# C++

**URL:** https://heroiclabs.com/docs/nakama/client-libraries/cpp/
**Summary:** The official C++ client handles all communication in real-time with the server. It implements all features in the server. This guide will show you how to use the core Nakama features in Unity by showing you how to develop the Nakama specific parts of a game.
**Keywords:** c++ client guide, c++ client, nakama c++, authentication, user accounts, persistence, storage, wallet, status, groups, chat, dynamic chat, real-world example c++
**Categories:** nakama, cpp, client-libraries

---


# Nakama C++ Client Guide

This client library guide will show you how to use the core Nakama features in **C++** by showing you how to develop the Nakama specific parts (without full game logic or UI) of an [Among Us (external)](https://www.innersloth.com/games/among-us/) inspired game called Sagi-shi (Japanese for "Imposter").

<figure>
  <img src={{< fingerprint_image "/images/pages/nakama/client-libraries/gameplay.png" >}} alt="Sagi-shi gameplay screen">
  <figcaption>Sagi-shi gameplay</figcaption>
</figure>

{{< note "important" "Console Support" >}}
The C++ SDK includes [console support](../consoles/) for Sony, Microsoft, and Nintendo platforms. To obtain the C++ client for console platforms please [contact us](mailto:contact@heroiclabs.com).
![]({{< fingerprint_image "/images/pages/index/console_logos_min.png" >}})
{{< /note >}}


## Prerequisites

Before proceeding ensure that you have:

* [Installed Nakama server](../../getting-started/install/docker/)
* Installed the [Nakama C++ SDK](#installation)

### Full API documentation

For the full API documentation please visit the [API docs](https://heroiclabs.github.io/nakama-cpp/).

### Installation

The client is available from the:

* [Heroic Labs GitHub releases page](https://github.com/heroiclabs/nakama-cpp/releases)

For full instructions on how to setup your C++ project and install the Nakama C++ SDK please view the [Nakama C++ SDK README](https://github.com/heroiclabs/nakama-cpp) on GitHub.

#### Updates

New versions of the Nakama C++ Client and the corresponding improvements are documented in the [Changelog](https://github.com/heroiclabs/nakama-cpp/blob/master/CHANGELOG.md).


### Tick

The `tick` method pumps requests queue and executes callbacks in your thread. You must call it periodically (recommended every 50ms) in your thread.

```cpp
while(!done)
{
    client->tick();
    
    if (rtClient)
    {
        rtClient->tick();
    }
    
    this_thread::sleep_for(chrono::milliseconds(50));
}
```

Without this the default client and real-time client will not work, and you will not receive responses from the server.

### Asynchronous programming

Many of the Nakama APIs are asynchronous and non-blocking.

Sagi-shi calls these methods in a way which does not block the calling thread so that the game is responsive and efficient.

There are two ways that asynchronous calls can be made, the first is by using callbacks:

```cpp
bool done = false;

auto loginFailedCallback = [&done](const NError& error)
{
    cout << "Failed to login" << endl;
    cout << error.message << endl;
    done = true;
};

auto loginSucceededCallback = [&done, &rtClient](NSessionPtr session)
{
    cout << "Login successful" << endl;
    cout << session->getAuthToken() << endl;

    rtClient->connect(session, true);
};

string deviceId = "e872f976-34c1-4c41-88fe-fd6aef118782";

client->authenticateDevice(
        deviceId,
        opt::nullopt,
        opt::nullopt,
        {},
        loginSucceededCallback,
        loginFailedCallback);
```

The alternative method is to use the `std::future` version of the function (postfixed with `Async`):

```cpp
auto session = client->authenticateDeviceAsync(deviceId, opt::nullopt, opt::nullopt, {}).get();
```

For a full list of functions that support the `std::future` pattern see the [client interface source code](https://github.com/heroiclabs/nakama-cpp/blob/master/interface/include/nakama-cpp/NClientInterface.h). 

### Handling exceptions

Network programming requires additional safeguarding against connection and payload issues.

API calls in Sagi-shi gracefully handle errors:

```cpp
auto errorCallback = [](const NError& error)
{
    cout << "An error occurred: " << error.message << endl;

    if (error.code == ErrorCode::ConnectionError)
    {
        cout << "The server is currently unavailable. Check internet connection." << endl;
    }
};

client->getAccount(session, successCallback, errorCallback);
```

You can also handle errors when using futures:

```cpp
try
{
    auto account = client->getAccountAsync(session).get();
}
catch (const NException& e)
{
    cout << "An error occurred: " << e.error.message >> << endl;

    if (e.error.code == ErrorCode::ConnectionError)
    {
        cout << "The server is currently unavailable. Check internet connection." << endl;
    }
}
```


### Serializing and deserializing data

This guide makes use of JSON serialization and deserialization using the [nlohmann/json](https://github.com/nlohmann/json) library throughout.

## Getting started

Learn how to get started using the Nakama Client and Socket objects to start building Sagi-shi and your own game.


### Nakama Client

The Nakama Client connects to a Nakama Server and is the entry point to access Nakama features. It is recommended to have one client per server per game.

To create a client for Sagi-shi pass in your server connection details:

```cpp
NClientParameters params;
params.serverKey = "defaultkey";
params.host = "127.0.0.1";
params.port = DEFAULT_PORT;
auto client = createDefaultClient(params);
```

### Nakama Socket

The Nakama Socket is used for gameplay and real-time latency-sensitive features such as chat, parties, matches and RPCs.

From the client create a real time client:

```cpp
NRtClientPtr rtClient;
rtClient = client->createRtClient();

bool createStatus = true;
rtClient->connect(session, createStatus);
```

## Authentication

Nakama has many [authentication methods](../../concepts/authentication/) and supports creating [custom authentication](../../concepts/authentication/#custom) on the server.

Sagi-shi will use device and Facebook authentication, linked to the same user account so that players can play from multiple devices.

<figure>
  <img src={{< fingerprint_image "/images/pages/nakama/client-libraries/login.png" >}} alt="Sagi-shi login screen">
  <figcaption>Login screen and Authentication options</figcaption>
</figure>


### Device authentication

Nakama [Device Authentication](../../concepts/authentication/#device) uses the physical device's unique identifier to easily authenticate a user and create an account if one does not exist.

When using only device authentication, you don't need a login UI as the player can automatically authenticate when the game launches.

Authentication is an example of a Nakama feature accessed from a Nakama Client instance.

```cpp
// Typically you would get the system's unique device identifier here.
string deviceId = "e872f976-34c1-4c41-88fe-fd6aef118782";

auto loginFailedCallback = [&done](const NError& error)
{
    cout << "An error occurred: " << error.message << endl;
};

auto loginSucceededCallback = [&done, &rtClient](NSessionPtr session)
{
    cout << "Successfully authenticated: " << session->getAuthToken() << endl;
};

// Authenticate with the Nakama server using Device Authentication.
client->authenticateDevice(
        deviceId,
        opt::nullopt,
        opt::nullopt,
        {},
        loginSucceededCallback,
        loginFailedCallback);
```


### Facebook authentication

Nakama [Facebook Authentication](../../concepts/authentication/#facebook) is an easy to use authentication method which lets you optionally import the player's Facebook friends and add them to their Nakama Friends list.

```cpp
// Authenticate with the Nakama server using Facebook Authentication.
string accessToken = "<Token>";
bool importFriends = true;

client->authenticateFacebook(
        accessToken,
        "mycustomusername",
        true,
        importFriends,
        {},
        loginSucceededCallback,
        loginFailedCallback);
```

### Console authentication

See the [console authentication](../../concepts/authentication/#console) documentation for more information on how to authenticate players on consoles.

### Custom authentication

Nakama supports [Custom Authentication](../../concepts/authentication/#custom) methods to integrate with additional identity services.

See the [Itch.io custom authentication](../../client-libraries/snippets/custom-authentication/) recipe for an example.

### Linking authentication

Nakama allows players to [Link Authentication](../../concepts/authentication/#link-or-unlink) methods to their account once they have authenticated.


**Linking Device ID authentication**

```cpp
auto linkSuccessCallback = []()
{
    cout << "Successfully linked Device ID authentication to existing player account" << endl;    
};

auto linkErrorCallback = [](const NError& error)
{
    cout << "Error linking Device ID: " << error.message << endl;
};

// Link Device Authentication to existing player account.
client->linkDevice(
        session,
        deviceId,
        linkSuccessCallback,
        linkErrorCallback
        );
```


**Linking Facebook authentication**

```cpp
auto linkSuccessCallback = []()
{
    cout << "Successfully linked Facebook authentication to existing player account" << endl;    
};

auto linkErrorCallback = [](const NError& error)
{
    cout << "Error linking Facebook: " << error.message << endl;
};

client->linkFacebook(
        session,
        accessToken,
        importFriends,
        linkSuccessCallback,
        linkErrorCallback
        );
```


### Session variables

Nakama [Session Variables](../../concepts/session/#session-variables) can be stored when authenticating and will be available on the client and server as long as the session is active.

Sagi-shi uses session variables to implement analytics, referral and rewards programs and more.

Store session variables by passing them as an argument when authenticating:

```cpp
NStringMap vars = {
    { "DeviceOS", "<OperatingSystem>" },
    { "DeviceModel", "<DeviceModel>" },
    { "GameVersion", "<GameVersion>" },
    { "InviterUserId", "<SomeUserId>" },
};

/// ...

client->authenticateDevice(
        deviceId,
        opt::nullopt,
        opt::nullopt,
        vars,
        loginSucceededCallback,
        loginFailedCallback);

```

To access session variables:

```cpp
string deviceOs = session->getVariable("DeviceOS");
```


### Session lifecycle

Nakama [Sessions](../../concepts/session/) expire after a time set in your server [configuration](../../getting-started/configuration/#session). Expiring inactive sessions is a good security practice.

Nakama provides ways to restore sessions, for example when Sagi-shi players re-launch the game, or refresh tokens to keep the session active while the game is being played.

Use the auth and refresh tokens on the session object to restore or refresh sessions.

Store the tokens for use later:

```cpp
string authToken = session->getAuthToken();
string refreshToken = session->getRefreshToken();
```

Restore a session without having to re-authenticate:

```cpp
session = restoreSession(authToken, refreshToken);
```

Check if a session has expired or is close to expiring and refresh it to keep it alive:

```cpp
// Check whether a session has expired or is close to expiry.
if (session->isExpired() || session->isExpired(time(0) + 24*60*60))
{
    auto refreshSuccessCallback = [](NSessionPtr session)
    {
        cout << "Session successfully refreshed" << endl;
    };
    
    auto refreshErrorCallback = [](const NError& error)
    {
        // Couldn't refresh the session so reauthenticate.
        // client->authenticateDevice(...)
    };
    
    // Refresh the existing session
    client->authenticateRefresh(session, refreshSuccessCallback, refreshErrorCallback);
}
```

## User accounts

Nakama [User Accounts](../../concepts/user-accounts/) store user information defined by Nakama and custom developer metadata.

Sagi-shi allows players to edit their accounts and stores metadata for things like game progression and in-game items.

<figure>
  <img src={{< fingerprint_image "/images/pages/nakama/client-libraries/profile.png" >}} alt="Sagi-shi player profile screen">
  <figcaption>Player profile</figcaption>
</figure>


### Get the user account

Many of Nakama's features are accessible with an authenticated session, like [fetching a user account](../../concepts/user-accounts/#fetch-account).

Get a Sagi-shi player's full user account with their basic [user information](../../concepts/user-accounts/#fetch-account) and user id:

```cpp
auto successCallback = [](const NAccount& account)
{
    string username = account.user.username;
    string avatarUrl = account.user.avatarUrl;
    string userId = account.user.id;
};

auto errorCallback = [](const NError& error)
{
    cout << "Failed to get user account: " << error.message << endl;
};

client->getAccount(session, successCallback, errorCallback);
```


### Update the user account

Nakama provides easy methods to update server stored resources like user accounts.

Sagi-shi players need to be able to update their public profiles:

```cpp
auto successCallback = []()
{
    cout << "Account successfully updated" << endl;
};

auto errorCallback = [](const NError& error)
{
    cout << "Error updating account: " << error.message << endl;
};

client->updateAccount(
        session,
        newUsername,
        newDisplayName, 
        newAvatarYrl,
        newLangTag,
        newLocation,
        newTimezone,
        successCallback,
        errorCallback);
```


### Getting users

In addition to getting the current authenticated player's user account, Nakama has a convenient way to get a list of other players' public profiles from their ids or usernames.

Sagi-shi uses this method to display player profiles when engaging with other Nakama features:

```cpp
auto successCallback = [](const NUsers& users)
{
    cout << "Successfully retrieved " << users.users.size() << " users." << endl;
};

auto errorCallback = [](const NError& error)
{
    cout << "Error retrieving users: " << error.message << endl;
};

vector<string> userIds = { "<AnotherUserId" };
client->getUsers(session, userIds, {}, {}, successCallback, errorCallback);
```


### Storing metadata

Nakama [User Metadata](../../concepts/user-accounts/#user-metadata) allows developers to extend user accounts with public user fields.

User metadata can only be updated on the server. See the [updating user metadata](../snippets/user-metadata/) recipe for an example.

Sagi-shi will use metadata to store what in-game items players have equipped:


### Reading metadata

Define a class that describes the metadata and parse the JSON metadata:

```cpp
auto successCallback = [](const NAccount& account)
{
    struct metadata {
        string title;
        string hat;
        string skin;
    };

    // Parse the account user metadata (using nlohmann/json library).
    json j = json::parse(account.user.metadata);
    metadata m {
        j["title"].get<string>(),
        j["hat"].get<string>(),
        j["skin"].get<string>()
    };

    cout << "Title: " << m.title << endl;
    cout << "Hat: " << m.hat << endl;
    cout << "Skin: " << m.title << endl;
};

auto errorCallback = [](const NError& error)
{
    cout << "Error retrieving metadata: " << error.message << endl;
};

client->getAccount(session, successCallback, errorCallback);
```


### Wallets

Nakama [User Wallets](../../concepts/user-accounts/#virtual-wallet) can store multiple digital currencies as key/value pairs of strings/integers.

Players in Sagi-shi can unlock or purchase titles, skins and hats with a virtual in-game currency.


#### Accessing wallets

Parse the JSON wallet data from the user account:

```cpp
auto successCallback = [](const NAccount& account)
{
    // Parse the account user wallet (using nlohmann/json library).
    json j = json::parse(account.wallet);

    for (auto item = j.begin(); item != j.end(); item++)
    {
        cout << item.key() << ": " << item.value() << endl;
    }
};

auto errorCallback = [](const NError& error)
{
    cout << "Error retrieving wallet: " << error.message << endl;
};

client->getAccount(session, successCallback, errorCallback);
```


#### Updating wallets

Wallets can only be updated on the server. See the [user account virtual wallet](../../concepts/user-accounts/#virtual-wallet) documentation for an example.


## Storage Engine

The Nakama [Storage Engine](../../concepts/storage/collections/) is a distributed and scalable document-based storage solution for your game.

The Storage Engine gives you more control over how data can be [accessed](../../concepts/storage/permissions/#object-permissions) and [structured](../../concepts/storage/collections/#collections) in collections.

Collections are named, and store JSON data under a unique key and the user id.

By default, the player has full permission to create, read, update and delete their own storage objects.

Sagi-shi players can unlock or purchase many items, which are stored in the Storage Engine.

<figure>
  <img src={{< fingerprint_image "/images/pages/nakama/client-libraries/player-items.png" >}} alt="Sagi-shi player items screen">
  <figcaption>Player items</figcaption>
</figure>


### Reading storage objects

Define a class that describes the storage object and create a new storage object id with the collection name, key and user id. Finally, read the storage objects and parse the JSON data:

```cpp
struct hatsStorageObject
{
    vector<string> hats;
};

auto successCallback = [](const NStorageObjects& storageObjects)
{
    if (storageObjects.size() > 0)
    {
        NStorageObject storageObject = storageObjects[0];
        json j = json::parse(storageObject.value);

        hatsStorageObject h {
            j["hats"].get<vector<string>>()
        };

        cout << "Unlocked hats: " << endl;
        for (string hat : h.hats)
        {
            cout << hat << endl;
        }
    }
};

auto errorCallback = [](const NError& error)
{
    cout << "Error reading storage object: " << error.message << endl;
};

vector<NReadStorageObjectId> objectIds = {
        {
            collection: "Unlocks",
            key: "Hats",
            userId: session->getUserId()
        }
};

client->readStorageObjects(session, objectIds, successCallback, errorCallback);
```

To read other players' public storage objects use their `UserId` instead. Remember that players can only read storage objects they own or that are public (`PermissionRead` value of `2`).

### Writing storage objects

Nakama allows developers to write to the Storage Engine from the client and server.

Consider what adverse effects a malicious user can have on your game and economy when deciding where to put your write logic, for example data that should only be written authoritatively (i.e. game unlocks or progress).

Sagi-shi allows players to favorite items for easier access in the UI and it is safe to write this data from the client.

Create a write storage object with the collection name, key and JSON encoded data. Finally, write the storage objects to the Storage Engine:

```cpp
auto successCallback = [](const NStorageObjectAcks& storageObjectAcks)
{
    cout << "Success writing storage object" << endl;
};

auto errorCallback = [](const NError& error)
{
    cout << "Error writing storage object: " << error.message << endl;
};

hatsStorageObject favoriteHats {
    { "cowboy", "alien" }
};

json j;
j["hats"] = favoriteHats.hats;

NStorageObjectWrite writeObject {
    collection: "favorites",
    key: "hats",
    value: j.dump(),
    permissionRead: NStoragePermissionRead::OWNER_READ, // Only the server and owner can read
    permissionWrite: NStoragePermissionWrite::OWNER_WRITE // The server and owner can write
};

client->writeStorageObjects(session, { writeObject }, successCallback, errorCallback);
```

You can also pass multiple write objects:

```cpp
client->writeStorageObjects(session, { writeObject1, writeObject2, writeObject3 }, successCallback, errorCallback);
```


### Conditional writes

Storage Engine [Conditional Writes](../../concepts/storage/collections/#conditional-writes) ensure that write operations only happen if the object hasn't changed since you accessed it.

This gives you protection from overwriting data, for example the Sagi-shi server could have updated an object since the player last accessed it.

To perform a conditional write, add a version to the write storage object with the most recent object version:

```cpp
// Assuming we already have a storage object (storageObject).
NStorageObjectWrite writeObject {
    collection: "favorites",
    key: "hats",
    value: "<NewJsonValue>",
    permissionRead: NStoragePermissionRead::OWNER_READ, // Only the server and owner can read
    permissionWrite: NStoragePermissionWrite::OWNER_WRITE, // The server and owner can write
    version: storageObject.version
};

client->writeStorageObjects(session, { writeObject }, successCallback, errorCallback);
```


### Listing storage objects

Instead of doing multiple read requests with separate keys you can list all the storage objects the player has access to in a collection.

Sagi-shi lists all the player's unlocked or purchased titles, hats and skins:

```cpp
auto successCallback = [](NStorageObjectListPtr storageObjectList)
{
    for (NStorageObject storageObject : storageObjectList->objects)
    {
        json j = json::parse(storageObject.value);

        if (storageObject.key == "Titles")
        {
            titlesStorageObject o {
                j["titles"].get<vector<string>>()
            };
            // Display the unlocked titles
        }
        else if (storageObject.key == "Hats")
        {
            hatsStorageObject o {
                    j["hats"].get<vector<string>>()
            };
            // Display the unlocked hats
        }
        else if (storageObject.key == "Skins")
        {
            skinsStorageObject o {
                    j["skins"].get<vector<string>>()
            };
            // Display the unlocked skins
        }
    }
};

auto errorCallback = [](const NError& error)
{
    cout << "Error reading storage objects: " << error.message << endl;
};

int limit = 3;
string cursor = "";
client->listUsersStorageObjects(session, "Unlocks", session->getUserId(), limit, cursor, successCallback, errorCallback);
```


### Paginating results

Nakama methods that list results return a cursor which can be passed to subsequent calls to Nakama to indicate where to start retrieving objects from in the collection.

For example:
- If the cursor has a value of 5, you will get results from the fifth object.
- If the cursor is `null`, you will get results from the first object.

```cpp
client->listUsersStorageObjects(session, "Unlocks", session->getUserId(), limit, storageObjectList->cursor, successCallback, errorCallback);
```


### Protecting storage operations on the server

Nakama Storage Engine operations can be protected on the server to protect data the player shouldn't be able to modify (i.e.  game unlocks or progress). See the [writing to the Storage Engine authoritatively](../snippets/authoritative-write/) recipe.


## Remote Procedure Calls

The Nakama [Server](../../server-framework/) allows developers to write custom logic and expose it to the client as [RPCs](../../server-framework/introduction/#functionality).

Sagi-shi contains various logic that needs to be protected on the server, like checking if the player owns equipment before equipping it.


### Creating server logic

See the [handling player equipment authoritatively](../snippets/authoritative-read/) recipe for an example of creating a remote procedure to check if the player owns equipment before equipping it.


### Client RPCs

Nakama Remote Procedures can be called from the client and take optional JSON payloads.

The Sagi-shi client makes an RPC to securely equip a hat:

```cpp
auto successCallback = [](const NRpc& rpc)
{
    cout << "New hat equipped successfully" << endl;
};

auto errorCallback = [](const NError& error)
{
    cout << "Error calling RPC " << error.message << endl;
};

json j;
j["item"] = "cowboy";
string payload = j.dump();
client->rpc(session, "EquipHat", payload, successCallback, errorCallback);
```


### Socket RPCs

Nakama Remote Procedures can also be called from the socket when you need to interface with Nakama's real-time functionality.

```cpp
auto successCallback = [](const NRpc& rpc)
{
    cout << "Successfully called RPC" << endl;
};

auto errorCallback = [](const NRtError& error)
{
    cout << "Error calling RPC " << error.message << endl;
};

rtClient->rpc("<RpcId>", "<PayloadString>", successCallback, errorCallback);
```


## Friends

Nakama [Friends](../../concepts/friends/) offers a complete social graph system to manage friendships amongst players.

Sagi-shi allows players to add friends, manage their relationships and play together.

<figure>
  <img src={{< fingerprint_image "/images/pages/nakama/client-libraries/friends.png" >}} alt="Sagi-shi Friends screen">
  <figcaption>Friends screen</figcaption>
</figure>


### Adding friends

Adding a friend in Nakama does not immediately add a mutual friend relationship. An outgoing friend request is created to each user, which they will need to accept.

Sagi-shi allows players to add friends by their usernames or user ids:


```cpp
auto successCallback = []()
{
    cout << "Successfully added friends" << endl;
};

auto errorCallback = [](const NError& error)
{
    cout << "Error adding friends " << error.message << endl;
};

client->addFriends(session, {}, { "AlwaysTheImposter21", "SneakyBoi" }, successCallback, errorCallback);
client->addFriends(session, { "<SomeUserId>", "<AnotherUserId>" }, {}, successCallback, errorCallback);
```


### Friendship states

Nakama friendships are categorized with the following states:

| Value | State |
| 
----- | ----- |
| 0 | Mutual friends |
| 1 | An outgoing friend request pending acceptance |
| 2 | An incoming friend request pending acceptance |
| 3 | Blocked by the user |


### Listing friends

Nakama allows developers to list the player's friends based on their friendship state.

Sagi-shi lists the 20 most recent mutual friends:

```cpp
auto successCallback = [](NFriendListPtr friendList)
{
    for(NFriend f : friendList->friends)
    {
        cout << "ID: " << f.user.id << endl;
    }
};

auto errorCallback = [](const NError& error)
{
    cout << "Error retrieving friends " << error.message << endl;
};

int limit = 20; // Limit is capped at 1000
NFriend::State friendshipState = NFriend::State::FRIEND;
string cursor = "";
client->listFriends(session, limit, friendshipState, cursor, successCallback, errorCallback);
```


### Accepting friend requests

When accepting a friend request in Nakama the player adds a [bi-directional friend relationship](../../concepts/friends/best-practices/#modeling-relationships).

Nakama takes care of changing the state from pending to mutual for both.

In a complete game you would allow players to accept individual requests.

Sagi-shi just fetches and accepts all the incoming friend requests:

```cpp
auto successCallback = [client, session](NFriendListPtr friendList)
{
    for(NFriend f : friendList->friends)
    {
        client->addFriends(session, { f.user.id }, {}, nullptr, nullptr);
    }
};

auto errorCallback = [](const NError& error)
{
    cout << "Error retrieving friends " << error.message << endl;
};

int limit = 1000;
NFriend::State friendshipState = NFriend::State::INVITE_RECEIVED;
string cursor = "";
client->listFriends(session, limit, friendshipState, cursor, successCallback, errorCallback);
```


### Deleting friends

Sagi-shi players can decline friend requests and remove friends by their username or user id:

```cpp
auto successCallback = []()
{
    cout << "Successfully deleted friends" << endl;
};

auto errorCallback = [](const NError& error)
{
    cout << "Error deleting friends " << error.message << endl;
};

// Delete friends by User ID.
client->deleteFriends(session, { "<SomeUserId>", "<AnotherUserId>" }, {}, successCallback, errorCallback);

// Delete friends by Username.
client->deleteFriends(session, {}, { "<SomeUsername>", "<AnotherUsername>" }, successCallback, errorCallback);
```


### Blocking users

Sagi-shi players can block others by their username or user id:


```cpp
auto successCallback = []()
{
    cout << "Successfully blocked friends" << endl;
};

auto errorCallback = [](const NError& error)
{
    cout << "Error blocking friends " << error.message << endl;
};

// Block friends by User ID.
client->blockFriends(session, { "<SomeUserId>", "<AnotherUserId>" }, {}, successCallback, errorCallback);

// Block friends by Username.
client->blockFriends(session, {}, { "<SomeUsername>", "<AnotherUsername>" }, successCallback, errorCallback);
```


## Status & Presence

Nakama [Status](../../concepts/status/) is a real-time status and presence service that allows users to set their online presence, update their status message and follow other user's updates.

Players don't have to be friends with others they want to follow.

Sagi-shi uses status messages and online presences to notify players when their friends are online and share matches.

<figure>
  <img src={{< fingerprint_image "/images/pages/nakama/client-libraries/status.png" >}} alt="Sagi-shi status update screen">
  <figcaption>Updating player status</figcaption>
</figure>


### Follow users

The Nakama real-time APIs allow developers to subscribe to events on the socket, like a status presence change, and receive them in real-time.

The method to follow users also returns the current online users, known as presences, and their status.

Sagi-shi follows a player's friends and notifies them when they are online:

```cpp
// Subscribe to the Status event.
NRtDefaultClientListener listener;
rtClient->setListener(&listener);

listener.setStatusPresenceCallback([](const NStatusPresenceEvent& statusPresenceEvent) {
    for (NUserPresence presence : statusPresenceEvent.joins)
    {
        cout << presence.username << " is online with status: " << presence.status << endl;
    }

    for (NUserPresence presence : statusPresenceEvent.leaves)
    {
        cout << presence.username << "went offline" << endl;
    }
});

// Follow mutual friends and get the initial Status of any that are currently online.
auto successCallback = [&rtClient](NFriendListPtr friendList)
{
    auto followSuccessCallback = [](const NStatus& status)
    {
        for (NUserPresence presence : status.presences)
        {
            cout << presence.username << " is online with status: " << presence.status << endl;
        }
    };
    
    auto followErrorCallback = [](const NRtError& error)
    {
        cout << "Error following friends: " << error.message << endl;
    };
    
    for (NFriend f : friendList->friends)
    {
        rtClient->followUsers({ f.user.id }, followSuccessCallback, followErrorCallback);
    }
};

auto errorCallback = [](const NError& error)
{
    cout << "Error listing friends: " << error.message << endl;
};

// Follow mutual friends and get the initial Status of any that are currently online.
client->listFriends(session, 1000, NFriend::State::FRIEND, "", successCallback, errorCallback);
```


### Unfollow users

Sagi-shi players can unfollow others:

```cpp
auto successCallback = []()
{
    cout << "Successfully unfollowed users" << endl;
};

auto errorCallback = [](const NRtError& error)
{
    cout << "Error unfollowing users: " << error.message << endl;
};

rtClient->unfollowUsers({ "<UserId>" }, successCallback, errorCallback);
```


### Updating player status

Sagi-shi players can change and publish their status to their followers:

```cpp
auto successCallback = []()
{
    cout << "Successfully updated status" << endl;
};

auto errorCallback = [](const NRtError& error)
{
    cout << "Error updating status: " << error.message << endl;
};

rtClient->updateStatus("Viewing the Main Menu", successCallback, errorCallback);
```


## Groups

Nakama [Groups](../../concepts/groups/) is a group or clan system with public/private visibility, user memberships and permissions, metadata and group chat.

Sagi-shi allows players to form and join groups to socialize and compete.

<figure>
  <img src={{< fingerprint_image "/images/pages/nakama/client-libraries/groups-list.png" >}} alt="Sagi-shi groups screen">
  <figcaption>Groups list screen</figcaption>
</figure>


### Creating groups

Groups have a public or private "open" visibility. Anyone can join public groups, but they must request to join and be accepted by a superadmin/admin of a private group.

Sagi-shi players can create groups around common interests:

```cpp
auto successCallback = [](const NGroup& group)
{
    cout << "Successfully created group: " << group.id << endl;
};

auto errorCallback = [](const NError& error)
{
    cout << "Error creating group: " << error.message << endl;
};

string name = "Imposters R Us";
string description = "A group for people who love playing the imposter.";
string avatarUrl = "";
string langTag = "";
bool open = true; // public group
int maxSize = 100;

client->createGroup(session, name, description, avatarUrl, langTag, open, maxSize, successCallback, errorCallback);
```


### Update group visibility

Nakama allows group superadmin or admin members to update some properties from the client, like the open visibility:

```cpp
auto successCallback = []()
{
    cout << "Successfully updated group" << endl;
};

auto errorCallback = [](const NError& error)
{
    cout << "Error creating group: " << error.message << endl;
};

auto name = opt::nullopt;
auto description = opt::nullopt;
auto avatarUrl = opt::nullopt;
auto langTag = opt::nullopt;
bool open = false;
client->updateGroup(session, "<GroupId>", name, description, avatarUrl, langTag, open, successCallback, errorCallback);
```


### Update group size

Other properties, like the group's maximum member size, can only be changed on the server.

See the [updating group size](../../concepts/groups/#updating-group-size) recipe for an example, and the [Groups server function reference](../../server-framework/typescript-runtime/function-reference/#Groups) to learn more about updating groups on the server.

<figure>
  <img src={{< fingerprint_image "/images/pages/nakama/client-libraries/group-edit.png" >}} alt="Sagi-shi group edit screen">
  <figcaption>Sagi-shi group edit</figcaption>
</figure>


### Listing and filtering groups

Groups can be listed like other Nakama resources and also [filtered](../../concepts/groups/#list-and-filter-groups) with a wildcard group name.

Sagi-shi players use group listing and filtering to search for existing groups to join:


```cpp
auto successCallback = [&session](NGroupListPtr groupList)
{
    for (NGroup group : groupList->groups)
    {
        cout << group.name << ": " << (group.open ? "Public" : "Private") << endl;
    }
    
    // Get the next page of results using groupList->cursor.
};

auto errorCallback = [](const NError& error)
{
    cout << "Error listing groups: " << error.message << endl;
};

int limit = 20;
string cursor = "";
client->listGroups(session, "imposter%", limit, cursor, successCallback, errorCallback);
```


### Deleting groups

Nakama allows group superadmins to delete groups.

Developers can disable this feature entirely, see the [Guarding APIs guide](../../guides/server-framework/guarding-apis/) for an example on how to protect various Nakama APIs.

Sagi-shi players can delete groups which they are superadmins for:

```cpp
auto successCallback = []()
{
    cout << "Successfully deleted group" << endl;
};

auto errorCallback = [](const NError& error)
{
    cout << "Error deleting group: " << error.message << endl;
};

client->deleteGroup(session, "<GroupId>", successCallback, errorCallback);
```


### Group metadata

Like Users Accounts, Groups can have public metadata.

Sagi-shi uses group metadata to store the group's interests, active player times and languages spoken.

Group metadata can only be updated on the server. See the [updating group metadata](../snippets/group-metadata/) recipe for an example.

The Sagi-shi client makes an RPC with the group metadata payload:

```cpp
auto successCallback = [](const NRpc& rpc)
{
    cout << "Successfully updated group metadata" << endl;
};

auto errorCallback = [](const NError& error)
{
    cout << "Error updating group metadata: " << error.message << endl;
};

json j;
j["groupId"] = "<GroupId>";
j["interests"] = { "Deception", "Sabotage", "Cute Furry Bunnies" };
j["activeTimes"] = { "9am-2pm Weekdays", "9am-10pm Weekends" };
j["languages"] = { "English", "German" };

client->rpc(session, "UpdateGroupMetadata", j.dump(), successCallback, errorCallback);
```


### Group membership states

Nakama group memberships are categorized with the following states:

| Code | Purpose | |
| ---- | ------- | - |
|    0 | Superadmin | There must at least be 1 superadmin in any group. The superadmin has all the privileges of the admin and can additionally delete the group and promote admin members. |
|    1 | Admin | There can be one of more admins. Admins can update groups as well as accept, kick, promote, demote, ban or add members. |
|    2 | Member | Regular group member. They cannot accept join requests from new users. |
|    3 | Join request | A new join request from a new user. This does not count towards the maximum group member count. |


### Joining a group

If a player joins a public group they immediately become a member, but if they try and join a private group they must be accepted by a group admin.

Sagi-shi players can join a group:

```cpp
auto successCallback = []()
{
    cout << "Successfully joined group" << endl;
};

auto errorCallback = [](const NError& error)
{
    cout << "Error joining group: " << error.message << endl;
};

client->joinGroup(session, "<GroupId>", successCallback, errorCallback);
```


### Listing the user's groups

Sagi-shi players can list groups they are a member of:

```cpp
auto successCallback = [](NUserGroupListPtr userGroupList)
{
    for (NUserGroup userGroup : userGroupList->userGroups)
    {
        cout << userGroup.group.name << ": " << static_cast<int>(userGroup.state) << endl;
    }
};

auto errorCallback = [](const NError& error)
{
    cout << "Error listing user groups: " << error.message << endl;
};

auto limit = opt::nullopt;
auto state = opt::nullopt;
string cursor = "";
client->listUserGroups(session, limit, state, cursor, successCallback, errorCallback);
```


### Listing members

Sagi-shi players can list a group's members:

```cpp
auto successCallback = [](NGroupUserListPtr groupUserList)
{
    for (NGroupUser groupUser : groupUserList->groupUsers)
    {
        cout << groupUser.user.id << ": " << static_cast<int>(groupUser.state) << endl;
    }
};

auto errorCallback = [](const NError& error)
{
    cout << "Error listing group users: " << error.message << endl;
};

auto limit = opt::nullopt;
auto state = opt::nullopt;
string cursor = "";
client->listGroupUsers(session, "", limit, state, cursor, successCallback, errorCallback);
```


### Accepting join requests

Private group admins or superadmins can accept join requests by re-adding the user to the group.

Sagi-shi first lists all the users with a join request state and then loops over and adds them to the group:


```cpp
auto successCallback = [&client](NGroupUserListPtr groupUserList)
{
    for (NGroupUser groupUser : groupUserList->groupUsers)
    {
        client->addGroupUsers(session, "<GroupId>", { groupUser.user.id }, nullptr, nullptr);
    }
};

auto errorCallback = [](const NError& error)
{
    cout << "Error listing group users: " << error.message << endl;
};

auto limit = opt::nullopt;
NUserGroupState state = NUserGroupState::JOIN_REQUEST;
string cursor = "";
client->listGroupUsers(session, "", limit, state, cursor, successCallback, errorCallback);
```


### Promoting members

Nakama group members can be promoted to admin or superadmin roles to help manage a growing group or take over if members leave.

Admins can promote other members to admins, and superadmins can promote other members up to superadmins.

The members will be promoted up one level. For example:

- Promoting a member will make them an admin
- Promoting an admin will make them a superadmin

```cpp
auto successCallback = []()
{
    cout << "Successfully promoted group users" << endl;
};

auto errorCallback = [](const NError& error)
{
    cout << "Error promoting group users: " << error.message << endl;
};

client->promoteGroupUsers(session, "<GroupId>", { "<UserId>" }, successCallback, errorCallback);
```


### Demoting members

Sagi-shi group admins and superadmins can demote members:

```cpp
auto successCallback = []()
{
    cout << "Successfully demoted group users" << endl;
};

auto errorCallback = [](const NError& error)
{
    cout << "Error demoting group users: " << error.message << endl;
};

client->demoteGroupUsers(session, "<GroupId>", { "<UserId>" }, successCallback, errorCallback);
```


### Kicking members

Sagi-shi group admins and superadmins can remove group members:

```cpp
auto successCallback = []()
{
    cout << "Successfully kicked group users" << endl;
};

auto errorCallback = [](const NError& error)
{
    cout << "Error kicking group users: " << error.message << endl;
};

client->kickGroupUsers(session, "<GroupId>", { "<UserId>" }, successCallback, errorCallback);
```
<!-- Not available yet>
### Banning members

Sagi-shi group admins and superadmins can ban a user when demoting or kicking is not severe enough:

```cpp
auto successCallback = []()
{
    cout << "Successfully banned group users" << endl;
};

auto errorCallback = [](const NError& error)
{
    cout << "Error banning group users: " << error.message << endl;
};

client->banGroupUsers(session, "<GroupId>", { "<UserId>" }, successCallback, errorCallback);
```
-->

### Leaving groups

Sagi-shi players can leave a group:

```cpp
auto successCallback = []()
{
    cout << "Successfully left group" << endl;
};

auto errorCallback = [](const NError& error)
{
    cout << "Error leaving group: " << error.message << endl;
};

client->leaveGroup(session, "<GroupId>", successCallback, errorCallback);
```


## Chat

Nakama [Chat](../../concepts/chat/) is a real-time chat system for groups, private/direct messages and dynamic chat rooms.

Sagi-shi uses dynamic chat during matches, for players to mislead each other and discuss who the imposters are, group chat and private/direct messages.

<figure>
  <img src={{< fingerprint_image "/images/pages/nakama/client-libraries/chat.png" >}} alt="Sagi-shi chat screen">
  <figcaption>Sagi-shi Chat</figcaption>
</figure>


### Joining dynamic rooms

Sagi-shi matches have a non-persistent chat room for players to communicate in:

```cpp
auto successCallback = [](NChannelPtr channel)
{
    cout << "Connected to dynamic room channel: " << channel->id << endl;
};

auto errorCallback = [](const NRtError& error)
{
    cout << "Error connecting to channel: " << error.message << endl;
};

string roomName = "<MatchId>";
bool persistence = false;
bool hidden = false;
rtClient->joinChat(roomName, NChannelType::ROOM, persistence, hidden, successCallback, errorCallback);
```


### Joining group chat

Sagi-shi group members can have conversations that span play sessions in a persistent group chat channel:

```cpp
auto successCallback = [](NChannelPtr channel)
{
    cout << "Connected to group channel: " << channel->id << endl;
};

auto errorCallback = [](const NRtError& error)
{
    cout << "Error connecting to channel: " << error.message << endl;
};

string groupId = "<GroupId>";
bool persistence = false;
bool hidden = false;
rtClient->joinChat(groupId, NChannelType::GROUP, persistence, hidden, successCallback, errorCallback);
```


### Joining direct chat

Sagi-shi players can also chat privately one-to-one during or after matches and view past messages:

```cpp
auto successCallback = [](NChannelPtr channel)
{
    cout << "Connected to direct message channel: " << channel->id << endl;
};

auto errorCallback = [](const NRtError& error)
{
    cout << "Error connecting to channel: " << error.message << endl;
};

string userId = "<UserId>";
bool persistence = true;
bool hidden = false;
rtClient->joinChat(userId, NChannelType::DIRECT_MESSAGE, persistence, hidden, successCallback, errorCallback);
```


### Sending messages

Sending messages is the same for every type of chat channel. Messages contain chat text and emotes and are sent as JSON serialized data:

```cpp
auto successCallback = [](const NChannelMessageAck& messageAck)
{
    cout << "Successfully sent message: " << messageAck.messageId << endl;
};

auto errorCallback = [](const NRtError& error)
{
    cout << "Error sending message: " << error.message << endl;
};

string channelId = "<ChannelId>";

json j;
j["message"] = "I think Red is the imposter!";

rtClient->writeChatMessage(channelId, j.dump(), successCallback, errorCallback);

json j2;
j2["emote"] = "point";
j2["emoteTarget"] = "<RedPlayerUserId>";

rtClient->writeChatMessage(channelId, j2.dump(), successCallback, errorCallback);
```


### Listing message history

Message listing takes a parameter which indicates if messages are received from oldest to newest (forward) or newest to oldest.

Sagi-shi players can list a group's message history:

```cpp
auto successCallback = [](NChannelMessageListPtr messageList)
{
    for (NChannelMessage m : messageList->messages)
    {
        cout << m.username << ": " << m.content << endl;
    }
};

auto errorCallback = [](const NError& error)
{
    cout << "Error retrieving messages: " << error.message << endl;
};

int limit = 100;
bool forward = true;
string groupId = "<GroupId>";
string cursor = "";
client->listChannelMessages(session, groupId, limit, cursor, forward, successCallback, errorCallback);
```

Chat also has cacheable cursors to fetch the most recent messages. Read more about cacheable cursors in the [listing notifications](../../concepts/notifications/#list-notifications) documentation.

```cpp
string cursor = messageList->nextCursor;
client->listChannelMessages(session, groupId, limit, cursor, forward, successCallback, errorCallback);
```


### Updating messages

Nakama also supports updating messages. It is up to you whether you want to use this feature, but in a game of deception like Sagi-shi it can add an extra element of deception.

For example a player sends the following message:

```cpp
string channelId = "<ChannelId>";
json j;
j["message"] = "I think Red is the imposter!";

rtClient->writeChatMessage(channelId, j.dump(), successCallback, errorCallback);
```

They then quickly edit their message to confuse others:

```cpp
auto successCallback = [&rtClient](const NChannelMessageAck& messageAck)
{
    json j;
    j["message"] = "I think BLUE is the imposter!";
    rtClient->updateChatMessage(messageAck.channelId, messageAck.messageId, j.dump(), nullptr, nullptr);
};
```


## Matches

Nakama supports [Server Authoritative](../../concepts/multiplayer/authoritative/) and [Server Relayed](../../concepts/multiplayer/relayed/) multiplayer matches.

In server authoritative matches the server controls the gameplay loop and must keep all clients up to date with the current state of the game.

In server relayed matches the client is in control, with the server only relaying information to the other connected clients.

In a competitive game such as Sagi-shi, server authoritative matches would likely be used to prevent clients from interacting with your game in unauthorized ways.

For the simplicity of this guide, the server relayed model is used.

### Creating matches

Sagi-shi players can create their own matches and invite their online friends to join:

```cpp
auto errorRtCallback = [](const NRtError& error)
{
    cout << "Error: " << error.message << endl;
};

auto errorCallback = [](const NError& error)
{
    cout << "Error: " << error.message << endl;
};

auto listFriendsSuccessCallback = [&rtClient, &errorRtCallback, &match](NFriendListPtr friendList)
{
    for (NFriend f : friendList->friends)
    {
        if (!f.user.online)
        {
            continue;
        }
        
        auto joinChannelSuccessCallback = [&rtClient, &f, &match](NChannelPtr channel)
        {
            json j;
            j["message"] = "Hey " + f.user.username + ", join me for a match!";
            j["matchId"] = match.matchId;
            
            rtClient->writeChatMessage(channel->id, j.dump(), nullptr, nullptr);
        };
        
        bool persistence = false;
        bool hidden = false;
        rtClient->joinChat(f.user.id, NChannelType::DIRECT_MESSAGE, persistence, hidden, joinChannelSuccessCallback, errorRtCallback);
    }
};

int limit = 100;
NFriend::State state = NFriend::State::FRIEND;
string cursor = "";
client->listFriends(session, limit, state, cursor, listFriendsSuccessCallback, errorCallback);
```

### Joining matches

Sagi-shi players can try to join existing matches if they know the id:
```cpp
auto successCallback = [](const NMatch& match)
{
    cout << "Successfully joined match: " << match.matchId << endl;
};

auto errorCallback = [](const NRtError& error)
{
    cout << "Error: " << error.message << endl;
};

string matchId = "<MatchId>";
NStringMap metadata = {
        { "Region", "EU"}
};

rtClient->joinMatch(matchId, metadata, successCallback, errorCallback);
```

Or set up a real-time matchmaker listener and add themselves to the matchmaker:

```cpp
listener.setMatchmakerMatchedCallback([&rtClient](NMatchmakerMatchedPtr matchmakerMatched) {
    auto successCallback = [](const NMatch match)
    {
        cout << "Successfully joined match: " << match.matchId << endl;
    };
    
    auto errorCallback = [](const NRtError& error)
    {
        cout << "Error: " << error.message << endl;
    };
    
    rtClient->joinMatch(matchmakerMatched->matchId, {}, successCallback, errorCallback);
});

auto successCallback = [](const NMatchmakerTicket& matchmakerTicket)
{
    cout << "Successfully joined matchmaker: " << matchmakerTicket.ticket << endl;
};

auto errorCallback = [](const NRtError& error)
{
    cout << "Error: " << error.message << endl;
};

int minPlayers = 2;
int maxPlayers = 10;
string query = "";
NStringMap stringProperties = {};
NStringDoubleMap numericProperties = {};
auto countMultiple = opt::nullopt;
rtClient->addMatchmaker(minPlayers, maxPlayers, query, stringProperties, numericProperties, countMultiple, successCallback, errorCallback);
```

**Joining matches from player status**

Sagi-shi players can update their status when they join a new match:

```cpp
json j;
j["status"] = "Playing a match";
j["matchId"] = "<MatchID>";

rtClient->updateStatus(j.dump(), successCallback, errorCallback);
```

When their followers receive the real-time status event they can try and join the match:

```cpp
listener.setStatusPresenceCallback([&rtClient](const NStatusPresenceEvent& statusPresence) {
    for (NUserPresence presence : statusPresence.joins)
    {
        auto successCallback = [](const NMatch& match)
        {
            cout << "Successfully joined match: " << match.matchId << endl;
        };
        
        auto errorCallback = [](const NRtError& error)
        {
            cout << "Error: " << error.message << endl;
        };
        
        json j = json::parse(presence.status);
        if (j.contains("matchId"))
        {
            NStringMap metadata = {};
            rtClient->joinMatch(j["matchId"], metadata, successCallback, errorCallback);
        }
    }
});
```

### Listing matches

[Match Listing](../../concepts/multiplayer/match-listing/) takes a number of criteria to filter matches by including player count, a match label and an option to provide a more complex [search query](../../concepts/multiplayer/query-syntax/).

Sagi-shi matches start in a lobby state. The match exists on the server but the actual gameplay doesn't start until enough players have joined.

Sagi-shi can then list matches that are waiting for more players:

```cpp
auto successCallback = [](NMatchListPtr matchList)
{
    for (NMatch m : matchList->matches)
    {
        cout << m.matchId << ": " << m.size << "/10 players" << endl;
    }
};

auto errorCallback = [](const NError& error)
{
    cout << "Error: " << error.message << endl;
};

int minPlayers = 2;
int maxPlayers = 10;
int limit = 10;
bool authoritative = true;
string label = "";
client->listMatches(session, minPlayers, maxPlayers, limit, label, authoritative, successCallback, errorCallback);
```

To find a match that has a label of `"AnExactMatchLabel"`:

```cpp
string label = "AnExactMatchLabel";
```

**Advanced:**

In order to use a more complex structured query, the match label must be in JSON format.

To find a match where it expects player skill level to be `>100` and optionally has a game mode of `"sabotage"`:

```js
string query = "+label.skill:>100 label.mode:sabotage";
```

### Spawning players

The match object has a list of current online users, known as presences.

Sagi-shi uses the match presences to spawn players on the client:

```cpp
// Assuming a GameObject type
//class GameObject { };

map<string, GameObject*> players = {};
for (NUserPresence userPresence : match.presences)
{
    GameObject* gameObject = spawnPlayer(); // Instantiate player object
    players.insert({ userPresence.sessionId, gameObject });
}
```

Sagi-shi keeps the spawned players up-to-date as they leave and join the match using the match presence received event:

```cpp
listener.setMatchPresenceCallback([&players](const NMatchPresenceEvent matchPresence) {
    // For each player that has joined in this event...
    for (NUserPresence presence : matchPresence.joins)
    {
        // Spawn a player for this presence and store it in the dictionary by session id.
        GameObject* gameObject = spawnPlayer();
        players.insert({ presence.sessionId, gameObject });
    }

    // For each player that has left in this event...
    for (NUserPresence presence : matchPresence.leaves)
    {
        // Remove the player from the game if they've been spawned
        if (players.count(presence.sessionId) > 0)
        {
            players.erase(presence.sessionId);
        }
    }
});
```


### Sending match state

Nakama has real-time networking to [send](../../concepts/multiplayer/relayed/#send-data-messages) and [receive](../../concepts/multiplayer/relayed/#receive-data-messages) match state as players move and interact with the game world.

During the match, each Sagi-shi client sends match state to the server to be relayed to the other clients.

Match state contains an op code that lets the receiver know what data is being received so they can deserialize it and update their view of the game.

Example op codes used in Sagi-shi:
- 1: player position
- 2: player calling vote


**Sending player position**

Define a class to represent Sagi-shi player position states:

```cpp
struct positionState {
    float x;
    float y;
    float z;
};
```

Create an instance from the player's transform, set the op code and send the JSON encoded state:

```cpp
// Assuming a position variable
json j;
j["x"] = position.x;
j["y"] = position.y;
j["z"] = position.z;

int opCode = 1;

rtClient->sendMatchData(match.matchId, opCode, j.dump());
```


**Op Codes as a static class**

Sagi-shi has many networked game actions. Using a static class of constants for op codes will keep your code easier to follow and maintain:

```cpp
class OpCodes
{
public:
    static const int POSITION = 1;
    static const int VOTE = 2;
};

// ...

rtClient->sendMatchData(match.matchId, OpCodes::POSITION, j.dump());
```


### Receiving match state

Sagi-shi players can receive match data from the other connected clients by subscribing to the match state received event:

```cpp
listener.setMatchDataCallback([&players](const NMatchData& matchData) {
    switch (matchData.opCode)
    {
        case OpCodes::POSITION:
        {
            // Get the updated position data
            json j = json::parse(matchData.data);

            positionState position {
                    j["x"].get<float>(),
                    j["y"].get<float>(),
                    j["z"].get<float>()
            };

            // Update the GameObject associated with that player.
            if (players.count(matchData.presence.sessionId) > 0)
            {
                // Here we would normally do something like smoothly interpolate to the new position, but for this example let's just set the position directly.
                players[matchData.presence.sessionId].position = new Vector3(position.x, position.y, position.z);
            }
        }
        default:
            cout << "Unsupported opcode";
            break;
    }
});
```


## Matchmaker

Developers can find matches for players using Match Listing or the Nakama [Matchmaker](../../concepts/multiplayer/matchmaker/), which enables players join the real-time matchmaking pool and be notified when they are matched with other players that match their specified criteria.

Matchmaking helps players find each other, it does not create a match. This decoupling is by design, allowing you to use matchmaking for more than finding a game match. For example, if you were building a social experience you could use matchmaking to find others to chat with.


### Add matchmaker

Matchmaking criteria can be simple, find 2 players, or more complex, find 2-10 players with a minimum skill level interested in a specific game mode.

Sagi-shi allows players to join the matchmaking pool and have the server match them with other players:

```cpp
auto successCallback = [](const NMatchmakerTicket& matchmakerTicket)
{
    cout << "Received a matchmaker ticket: " << matchmakerTicket.ticket << endl;
};

auto errorCallback = [](const NRtError& error)
{
    cout << "Error: " << error.message << endl;
};

int minPlayers = 2;
int maxPlayers = 10;
string query = "+skill:>100 mode:sabotage";
NStringMap stringProperties = { { "mode", "sabotage" }};
NStringDoubleMap numericProperties = { { "skill", 125 }};
auto countMultiple = opt::nullopt;
rtClient->addMatchmaker(minPlayers, maxPlayers, query, stringProperties, numericProperties, countMultiple, successCallback, errorCallback);

```

## Parties

Nakama [Parties](../../concepts/parties/) is a real-time system that allows players to form short lived parties that don't persist after all players have disconnected.

Sagi-shi allows friends to form a party and matchmake together.


### Creating parties

The player who creates the party is the party's leader. Parties have maximum number of players and can be open to automatically accept players or closed so that the party leader can accept incoming join requests.

Sagi-shi uses closed parties with a maximum of 4 players:

```cpp
auto successCallback = [](const NParty& party)
{
    cout << "Successfully created party: " << party.id << endl;
};

auto errorCallback = [](const NRtError& error)
{
    cout << "Error: " << error.message << endl;
};

bool open = false;
int maxPlayers = 4;
rtClient->createParty(open, maxPlayers, successCallback, errorCallback);
```

Sagi-shi shares party ids with friends via private/direct messages:

```cpp
auto successCallback = [&rtClient](NFriendListPtr friendList)
{
    for (NFriend f : friendList->friends)
    {
        if (!f.user.online)
        {
            continue;
        }

        auto joinChatSuccessCallback = [&rtClient, &f, &party](NChannelPtr channel)
        {
            json j;
            j["message"] = "Hey" + f.user.username + ", wanna join the party?!";
            j["partyId"] = party.id;

            rtClient->writeChatMessage(channel->id, j.dump(), nullptr, nullptr);
        };

        auto joinChatErrorCallback = [](const NRtError& error)
        {
            cout << "Error: " << error.message << endl;
        };

        auto persistence = true;
        auto hidden = false;
        rtClient->joinChat(f.user.id, NChannelType::DIRECT_MESSAGE, persistence, hidden, joinChatSuccessCallback, joinChatErrorCallback);
    }
};

auto errorCallback = [](const NError& error)
{
    cout << "Error: " << error.message << endl;
};

int limit = 100;
NFriend::State state = NFriend::State::FRIEND;
string cursor = "";
client->listFriends(session, limit, state, cursor, successCallback, errorCallback);
```


### Joining parties

Safi-shi players can join parties from chat messages by checking for the party id in the message:

```cpp
listener.setChannelMessageCallback([&rtClient](const NChannelMessage& channelMessage) {
    auto successCallback = []()
    {
        cout << "Successfully joined party" << endl;
    };

    auto errorCallback = [](const NRtError& error)
    {
        cout << "Error: " << error.message << endl;
    };

    json j = json::parse(channelMessage.content);
    if (j.contains("partyId"))
    {
        rtClient->joinParty(j["partyId"], successCallback, errorCallback);
    }
});
```


### Promoting a member

Sagi-shi party members can be promoted to the party leader:

```cpp
auto successCallback = []()
{
    cout << "Successfully promoted party member" << endl;
};

auto errorCallback = [](const NRtError& error)
{
    cout << "Error: " << error.message << endl;
};

for (NUserPresence presence : party.presences)
{
    if (presence.sessionId != party.leader.sessionId)
    {
        rtClient->promotePartyMember(party.id, presence, successCallback, errorCallback);
    }
}
```

### Leaving parties

Sagi-shi players can leave parties:

```cpp
auto successCallback = []()
{
    cout << "Successfully left party" << endl;
};

auto errorCallback = [](const NRtError& error)
{
    cout << "Error: " << error.message << endl;
};

rtClient->leaveParty(party.id, successCallback, errorCallback);
```


### Matchmaking with parties

One of the main benefits of joining a party is that all the players can join the matchmaking pool together.

Sagi-shi players can listen to the the matchmaker matched event and join the match when one is found:

```cpp
listener.setMatchmakerMatchedCallback([&rtClient](NMatchmakerMatchedPtr matchmakerMatched) {
    auto successCallback = [](const NMatch& match)
    {
        cout << "Successfully joined match: " << match.matchId << endl;
    };

    auto errorCallback = [](const NRtError& error)
    {
        cout << "Error: " << error.message << endl;
    };
    
    rtClient->joinMatch(matchmakerMatched->matchId, {}, successCallback, errorCallback);
});
```

The party leader will start the matchmaking for their party:

```cpp
auto successCallback = [](const NPartyMatchmakerTicket& partyMatchmakerTicket)
{
    cout << "Successfully joined matchmaker as party: " << partyMatchmakerTicket.ticket << endl;
};

auto errorCallback = [](const NRtError& error)
{
    cout << "Error: " << error.message << endl;
};

int minPlayers = 2;
int maxPlayers = 10;
string query = "";
NStringMap stringProperties = {};
NStringDoubleMap numericProperties = {};
auto countMultiple = opt::nullopt;
rtClient->addMatchmakerParty(party.id, query, minPlayers, maxPlayers, stringProperties, numericProperties, countMultiple, successCallback, errorCallback);
```


### Sending party data

Sagi-shi players can send data to other members of their party to indicate they wish to start a vote.

```cpp
json j;
j["username"] = "<Username>"
j["reason"] = "Emergency";

rtClient->sendPartyData(partyId, OpCodes::PARTY_CALL_VOTE, j.dump());
```


### Receiving party data

Sagi-shi players can receive party data from other party members by subscribing to the party data event.

```cpp
listener.setPartyDataCallback([](const NPartyData& partyData) {
    switch (partyData.opCode)
    {
        case OpCodes::PARTY_CALL_VOTE:
        {
            // Get the username of the player calling the vote and the reason
            json j = json::parse(partyData.data);
            string username = j["username"].get<string>();
            string reason = j["reason"].get<string>();

            // Show a UI dialogue - "<username> has proposed to call a vote for <reason>. Do you agree? Yes/No"
        }
        default:
            cout << "Unsupported opcode";
            break;
    }
});
```


## Leaderboards

Nakama [Leaderboards](../../concepts/leaderboards/) introduce a competitive aspect to your game and increase player engagement and retention.

Sagi-shi has a leaderboard of weekly imposter wins, where player scores increase each time they win, and similarly a leaderboard for weekly crew member wins.

<figure>
  <img src={{< fingerprint_image "/images/pages/nakama/client-libraries/leaderboard.png" >}} alt="Sagi-shi leaderboard screen">
  <figcaption>Sagi-shi Leaderboard</figcaption>
</figure>


### Creating leaderboards

Leaderboards have to be created on the server, see the [leaderboard](../../concepts/leaderboards/#create-a-leaderboard) documentation for details on creating leaderboards.


### Submitting scores

When players submit scores, Nakama will increment the player's existing score by the submitted score value.

Along with the score value, Nakama also has a subscore, which can be used for ordering when the scores are the same.

Sagi-shi players can submit scores to the leaderboard with contextual metadata, like the map the score was achieved on:

```cpp
auto successCallback = [](const NLeaderboardRecord& leaderboardRecord)
{
    cout << "Successfully submitted leaderboard record" << endl;
};

auto errorCallback = [](const NError& error)
{
    cout << "Error: " << error.message << endl;
};

int score = 1;
int subscore = 0;
json j;
j["map"] = "space_station";
client->writeLeaderboardRecord(session, "weekly_imposter_wins", score, subscore, j.dump(), successCallback, errorCallback);
```

### Listing the top records

Sagi-shi players can list the top records of the leaderboard:

```cpp
auto successCallback = [](NLeaderboardRecordListPtr leaderboardRecordList)
{
    for (NLeaderboardRecord record : leaderboardRecordList->records)
    {
        cout << record.ownerId << ":" << record.score << endl;
    }
};

auto errorCallback = [](const NError& error)
{
    cout << "Error: " << error.message << endl;
};

int limit = 20;
string leaderboardName = "weekly_imposter_wins";
vector<string> ownerIds = {};
string cursor = "";
client->listLeaderboardRecords(session, leaderboardName, ownerIds, limit, cursor, successCallback, errorCallback);
```


**Listing records around the user**

Nakama allows developers to list leaderboard records around a player.

Sagi-shi gives players a snapshot of how they are doing against players around them:

```cpp
auto successCallback = [](NLeaderboardRecordListPtr leaderboardRecordList)
{
    for (NLeaderboardRecord record : leaderboardRecordList->records)
    {
        cout << record.ownerId << ":" << record.score << endl;
    }
};

auto errorCallback = [](const NError& error)
{
    cout << "Error: " << error.message << endl;
};

int limit = 5;
string leaderboardName = "weekly_imposter_wins";
string cursor = "";
client->listLeaderboardRecordsAroundOwner(session, leaderboardName, session->getUserId(), limit, successCallback, errorCallback);
```
For example, if the leaderboard contains 100 records and the ownerId = "player123" with limit = 5, the result will include the specified user along with nearby records:

```json
{
  "records": [
    { "ownerId": "player120", "rank": 48, "score": 1500 },
    { "ownerId": "player121", "rank": 49, "score": 1480 },
    { "ownerId": "player123", "rank": 50, "score": 1450 },  // Your ownerId
    { "ownerId": "player125", "rank": 51, "score": 1430 },
    { "ownerId": "player127", "rank": 52, "score": 1400 }
  ]
}
```

**Listing records for a list of users**

Sagi-shi players can get their friends' scores by supplying their user ids to the owner id parameter:

```cpp
auto successCallback = [&client, &session](NFriendListPtr friendList)
{
    vector<string> friendIds = {};

    for (NFriend f : friendList->friends)
    {
        friendIds.push_back(f.user.id);
    }

    auto successCallback = [](NLeaderboardRecordListPtr leaderboardRecordList)
    {
        for (NLeaderboardRecord record : leaderboardRecordList->records)
        {
            cout << record.username << " scored " << record.score << endl;
        }
    };

    auto errorCallback = [](const NError& error)
    {
        cout << "Error: " << error.message << endl;
    };

    int limit = 20;
    string leaderboardName = "weekly_imposter_wins";
    string cursor = "";
    client->listLeaderboardRecords(session, leaderboardName, friendIds, limit, cursor, successCallback, errorCallback);
};

auto errorCallback = [](const NError& error)
{
    cout << "Error: " << error.message << endl;
};

int limit = 100;
NFriend::State state = NFriend::State::FRIEND;
string cursor = "";
client->listFriends(session, limit, state, cursor, successCallback, errorCallback);
```

The same approach can be used to get group member's scores by supplying their user ids to the owner id parameter:

```cpp
auto successCallback = [&client, &session](NGroupUserListPtr groupUserList)
{
    vector<string> memberIds = {};

    for (NGroupUser g : groupUserList->groupUsers)
    {
        memberIds.push_back(g.user.id);
    }

    auto successCallback = [](NLeaderboardRecordListPtr leaderboardRecordList)
    {
        for (NLeaderboardRecord record : leaderboardRecordList->records)
        {
            cout << record.username << " scored " << record.score << endl;
        }
    };

    auto errorCallback = [](const NError& error)
    {
        cout << "Error: " << error.message << endl;
    };

    int limit = 20;
    string leaderboardName = "weekly_imposter_wins";
    string cursor = "";
    client->listLeaderboardRecords(session, leaderboardName, memberIds, limit, cursor, successCallback, errorCallback);
};

auto errorCallback = [](const NError& error)
{
    cout << "Error: " << error.message << endl;
};

int limit = 100;
auto state = opt::nullopt;
string cursor = "";
client->listGroupUsers(session, "<GroupId>", limit, state, cursor, successCallback, errorCallback);
```


### Deleting records

Sagi-shi players can delete their own leaderboard records:

```cpp
auto successCallback = []()
{
    cout << "Successfully deleted leaderboard record" << endl;
};

auto errorCallback = [](const NError& error)
{
    cout << "Error: " << error.message << endl;
};

client->deleteLeaderboardRecord(session, "<LeaderboardId>", successCallback, errorCallback);
```


## Tournaments

Nakama [Tournaments](../../concepts/tournaments/) are short lived competitions where players compete for a prize.

Sagi-shi players can view, filter and join running tournaments.

<figure>
  <img src={{< fingerprint_image "/images/pages/nakama/client-libraries/tournaments.png" >}} alt="Sagi-shi tournaments screen">
  <figcaption>Sagi-shi Tournaments</figcaption>
</figure>


### Creating tournaments

Tournaments have to be created on the server, see the [tournament](../../concepts/tournaments/#create-tournament) documentation for details on how to create a tournament.

Sagi-shi has a weekly tournament which challenges players to get the most correct imposter votes. At the end of the week the top players receive a prize of in-game currency.


### Joining tournaments

By default in Nakama players don't have to join tournaments before they can submit a score, but Sagi-shi makes this mandatory:

```cpp
auto successCallback = []()
{
    cout << "Successfully joined tournament" << endl;
};

auto errorCallback = [](const NError& error)
{
    cout << "Error: " << error.message << endl;
};

client->joinTournament(session, "<TournamentId>", successCallback, errorCallback);
```

### Listing tournaments

Sagi-shi players can list and filter tournaments with various criteria:

```cpp
auto successCallback = [](NTournamentListPtr tournamentList)
{
    for (NTournament t : tournamentList->tournaments)
    {
        cout << t.id << ":" << t.title << endl;
    }
};

auto errorCallback = [](const NError& error)
{
    cout << "Error: " << error.message << endl;
};

int categoryStart = 1;
int categoryEnd = 2;
auto startTime = opt::nullopt;
auto endTime = opt::nullopt;
int limit = 100;
string cursor = "";
client->listTournaments(session, categoryStart, categoryEnd, startTime, endTime, limit, cursor, successCallback, errorCallback);
```

For performance reasons categories are filtered using a range, not individual numbers. Structure your categories to take advantage of this (e.g. all PVE tournaments in the 1XX range, all PVP tournaments in the 2XX range, etc.).

### Listing records

Sagi-shi players can list tournament records:

```cpp
auto successCallback = [](NTournamentRecordListPtr tournamentRecordList)
{
    for (NLeaderboardRecord record : tournamentRecordList->records)
    {
        cout << record.ownerId << ":" << record.score << endl;
    }
};

auto errorCallback = [](const NError& error)
{
    cout << "Error: " << error.message << endl;
};

int limit = 20;
string tournamentName = "weekly_top_detective";
string cursor = "";
vector<string> ownerIds = {};
client->listTournamentRecords(session, tournamentName, limit, cursor, ownerIds, successCallback, errorCallback);
```


**Listing records around a user**

Similarly to leaderboards, Sagi-shi players can get other player scores around them:

```cpp
auto successCallback = [](NTournamentRecordListPtr tournamentRecordList)
{
    for (NLeaderboardRecord record : tournamentRecordList->records)
    {
        cout << record.ownerId << ":" << record.score << endl;
    }
};

auto errorCallback = [](const NError& error)
{
    cout << "Error: " << error.message << endl;
};

int limit = 20;
string tournamentName = "weekly_top_detective";
string cursor = "";
client->listTournamentRecordsAroundOwner(session, tournamentName, session->getUserId(), limit, successCallback, errorCallback);
```


### Submitting scores

Sagi-shi players can submit scores, subscores and metadata to the tournament:

```cpp
auto successCallback = [](const NLeaderboardRecord& leaderboardRecord)
{
    cout << "Successfully submit tournament score" << endl;
};

auto errorCallback = [](const NError& error)
{
    cout << "Error: " << error.message << endl;
};

string tournamentName = "weekly_top_detective";
int score = 1;
int subscore = 0;
json j;
j["map"] = "space_station";
client->writeTournamentRecord(session, tournamentName, score, subscore, j.dump(), successCallback, errorCallback);
```


## Notifications

Nakama [Notifications](../../concepts/notifications/) can be used for the game backend to broadcast real-time messages to players.

Notifications can be either persistent (remaining until a player has viewed it) or transient (received only if the player is currently online).

Sagi-shi uses Notifications to notify tournament winners about their winnings.

<figure>
  <img src={{< fingerprint_image "/images/pages/nakama/client-libraries/notifications.png" >}} alt="Sagi-shi notification screen">
  <figcaption>Sagi-shi notifications</figcaption>
</figure>


### Receiving notifications

Notifications have to be sent from the server.

Nakama uses a code to differentiate notifications. Codes of `0` and below are [system reserved](../../concepts/notifications/#notification-codes) for Nakama internals.

Sagi-shi players can subscribe to the notification received event. Sagi-shi uses a code of `100` for tournament winnings:

```cpp
listener.setNotificationsCallback([](const NNotificationList& notificationList) {
    const int rewardCode = 100;
    
    for (NNotification n : notificationList.notifications)
    {
        switch (n.code)
        {
            case rewardCode:
                cout << "Congratulations, you won the tournament!" << endl << n.subject << endl << n.content << endl;
                break;
            default:
                cout << "Other notification:" << endl << n.subject << endl << n.content << endl;
                break;
        }
    }
});
```


### Listing notifications

Sagi-shi players can list the notifications they received while offline:

```cpp
auto successCallback = [](NNotificationListPtr notificationList)
{
    for (NNotification n : notificationList->notifications)
    {
        cout << "Notification:" << endl << n.subject << endl << n.content << endl;
    }
};

auto errorCallback = [](const NError& error)
{
    cout << "Error: " << error.message << endl;
};

int limit = 100;
string cursor = "";
client->listNotifications(session, limit, cursor, successCallback, errorCallback);
```


**Pagination and cacheable cursors**

Like other listing methods, notification results can be paginated using a cursor or cacheable cursor from the result.

```cpp
string cacheableCursor = notificationList->cacheableCursor;
```

The next time the player logs in the cacheable cursor can be used to list unread notifications.

```cpp
client->listNotifications(session, limit, cacheableCursor, successCallback, errorCallback);
```


### Deleting notifications

Sagi-shi players can delete notifications once they've read them:

```cpp
auto successCallback = []()
{
    cout << "Successfully deleted notifications" << endl;
};

auto errorCallback = [](const NError& error)
{
    cout << "Error: " << error.message << endl;
};

vector<string> notificationIds = { "<NotificationId>" };
client->deleteNotifications(session, notificationIds, successCallback, errorCallback);
```
