Function Reference - TypeScript

The code runtime built into the server includes a module with functions to implement various logic and custom behavior, enabling you to define authoritative code and conditions on input received by clients. Learn more about it in the Server Framework documentation.

This page lists all functions available within Nakama and their respective parameters, with corresponding code samples for each. If you haven’t already, see the documentation on using the server framework.

Writing custom SQL is discouraged in favor of using the built-in features of the Storage Engine. If custom SQL is needed for your use case, please contact Heroic Labs before proceeding.
The creation of custom tables is strongly discouraged.

Accounts

accountDeleteId

Delete an account by user ID.

Parameters
NameDefaultDescription
userId string REQUIREDUser ID for the account to be deleted. Must be valid UUID.
recorded boolfalseWhether to record this deletion in the database.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
let userId = '4ec4f126-3f9d-11e7-84ef-b7c182b36521';

try {
    nk.accountDeleteId(userId, false);
} catch (error) {
    // handle error
}

accountExportId

Export account information for a specified user ID.

Parameters
NameDefaultDescription
userId string REQUIREDUser ID for the account to be exported. Must be valid UUID.
Returns
NameDescription
export stringAccount information for the provided user ID, in JSON format.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
let userId = '4ec4f126-3f9d-11e7-84ef-b7c182b36521';

try {
    let accountJson = nk.accountExportId(userId);
} catch (error) {
    // handle error
}

accountGetId

Fetch account information by user ID.

Parameters
NameDefaultDescription
userId string REQUIREDUser ID to fetch information for. Must be valid UUID.
Returns
NameDescription
account nkruntime.AccountAll account information including wallet, device IDs and more.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
let userId = '4ec4f126-3f9d-11e7-84ef-b7c182b36521';

try {
    let account = nk.accountGetId(userId);
} catch (error) {
    // handle error
}

accountsGetId

Fetch information for multiple accounts by user IDs.

Parameters
NameDefaultDescription
userIds REQUIREDArray of user IDs to fetch information for. Must be valid UUID.
Returns
NameDescription
account nkruntime.AccountsArray of accounts.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
let userIds = ['4ec4f126-3f9d-11e7-84ef-b7c182b36521', '6134d1cf-4b55-497f-b9e9-fc5090b76475'];

try {
    let accounts = nk.accountsGetId(userIds);
} catch (error) {
    // handle error
}

accountUpdateId

Update an account by user ID.

Parameters
NameDefaultDescription
userId string REQUIREDUser ID for which the information is to be updated. Must be valid UUID.
metadata objectThe metadata to update for this account.
username stringUsername to be set. Must be unique. Use null if it is not being updated.
displayName stringDisplay name to be updated. Use null if it is not being updated.
timezone stringTimezone to be updated. Use null if it is not being updated.
location stringLocation to be updated. Use null if it is not being updated.
language stringLang tag to be updated. Use null if it is not being updated.
avatarUrl stringUser's avatar URL. Use null if it is not being updated.
Returns
NameDescription
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
let userId = '4ec4f126-3f9d-11e7-84ef-b7c182b36521';
let username = null;
let metadata = {pro: true};
let displayName = 'new display name';
let timezone = null;
let location = null;
let langTag = null;
let avatarUrl = null;

try {
    nk.accountUpdateId(userId, username, displayName, timezone, location, langTag, avatarUrl, metadata);
} catch (error) {
    // handle error
}

Authenticate

authenticateApple

Authenticate user and create a session token using an Apple sign in token.

Parameters
NameDefaultDescription
token string REQUIREDApple sign in token.
username stringThe user's username. If left empty, one is generated.
create booltrueCreate user if one didn't exist previously.
Returns
NameDescription
userID stringThe user ID of the authenticated user.
username stringThe username of the authenticated user.
create boolValue indicating if this account was just created or already existed.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
let result = {} as nkruntime.AuthResult;

try {
    result = nk.authenticateApple('some-oauth-access-token', 'username', true);
} catch (error) {
    // Handle error
}

authenticateCustom

Authenticate user and create a session token using a custom authentication managed by an external service or source not already supported by Nakama.

Parameters
NameDefaultDescription
id string REQUIREDCustom ID to use to authenticate the user. Must be between 6-128 characters.
username stringThe user's username. If left empty, one is generated.
create booltrueCreate user if one didn't exist previously.
Returns
NameDescription
userID stringThe user ID of the authenticated user.
username stringThe username of the authenticated user.
create boolValue indicating if this account was just created or already existed.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
let result = {} as nkruntime.AuthResult;

try {
    result = nk.authenticateCustom('48656C6C6F20776F726C64', 'username', true);
} catch (error) {
    // Handle error
}

authenticateDevice

Authenticate user and create a session token using a device identifier.

Parameters
NameDefaultDescription
id string REQUIREDDevice ID to use to authenticate the user. Must be between 1-128 characters.
username stringThe user's username. If left empty, one is generated.
create booltrueCreate user if one didn't exist previously.
Returns
NameDescription
userID stringThe user ID of the authenticated user.
username stringThe username of the authenticated user.
create boolValue indicating if this account was just created or already existed.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
let result = {} as nkruntime.AuthResult;

try {
    result = nk.authenticateDevice('48656C6C6F20776F726C64', 'username', true);
} catch (error) {
    // Handle error
}

authenticateEmail

Authenticate user and create a session token using an email address and password.

Parameters
NameDefaultDescription
email string REQUIREDEmail address to use to authenticate the user. Must be between 10-255 characters.
password string REQUIREDPassword to set. Must be longer than 8 characters.
username stringThe user's username. If left empty, one is generated.
create booltrueCreate user if one didn't exist previously.
Returns
NameDescription
userID stringThe user ID of the authenticated user.
username stringThe username of the authenticated user.
create boolValue indicating if this account was just created or already existed.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
let result = {} as nkruntime.AuthResult;

try {
    result = nk.authenticateEmail('email@example.com', 'username', true);
} catch (error) {
    // Handle error
}

authenticateFacebook

Authenticate user and create a session token using a Facebook account token.

Parameters
NameDefaultDescription
token string REQUIREDAccess token.
import booltrueWhether to automatically import Facebook friends after authentication.
username stringThe user's username. If left empty, one is generated.
create booltrueCreate user if one didn't exist previously.
Returns
NameDescription
userID stringThe user ID of the authenticated user.
username stringThe username of the authenticated user.
create boolValue indicating if this account was just created or already existed.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
let result = {} as nkruntime.AuthResult;

try {
    result = nk.authenticateFacebook('some-oauth-access-token', 'username', true);
} catch (error) {
    // Handle error
}

authenticateFacebookInstantGame

Authenticate user and create a session token using a Facebook Instant Game.

Parameters
NameDefaultDescription
playerInfo string REQUIREDFacebook Player info.
username stringThe user's username. If left empty, one is generated.
create booltrueCreate user if one didn't exist previously.
Returns
NameDescription
userID stringThe user ID of the authenticated user.
username stringThe username of the authenticated user.
create boolValue indicating if this account was just created or already existed.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
let result = {} as nkruntime.AuthResult;

try {
    result = nk.authenticateFacebookInstantGame('player-info', 'username', true);
} catch (error) {
    // Handle error
}

authenticateGameCenter

Authenticate user and create a session token using Apple Game Center credentials.

Parameters
NameDefaultDescription
playerId string REQUIREDPlayerId provided by GameCenter.
bundleId string REQUIREDBundleId of your app on iTunesConnect.
timestamp int REQUIREDTimestamp at which Game Center authenticated the client and issued a signature.
salt string REQUIREDA random string returned by Game Center authentication on client.
signature string REQUIREDA signature returned by Game Center authentication on client.
publicKeyUrl string REQUIREDA URL to the public key returned by Game Center authentication on client.
username stringThe user's username. If left empty, one is generated.
create booltrueCreate user if one didn't exist previously.
Returns
NameDescription
userID stringThe user ID of the authenticated user.
username stringThe username of the authenticated user.
create boolValue indicating if this account was just created or already existed.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
let result = {} as nkruntime.AuthResult;

try {
    // Example assumes arguments are defined.
    result = nk.authenticateGameCenter(playerId, bundleId, timestamp, salt, signature, publicKeyUrl, username, create);
} catch (error) {
    // Handle error
}

authenticateGoogle

Authenticate user and create a session token using a Google ID token.

Parameters
NameDefaultDescription
token string REQUIREDGoogle OAuth access token.
username stringThe user's username. If left empty, one is generated.
create booltrueCreate user if one didn't exist previously.
Returns
NameDescription
userID stringThe user ID of the authenticated user.
username stringThe username of the authenticated user.
create boolValue indicating if this account was just created or already existed.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
let result = {} as nkruntime.AuthResult;

try {
    result = nk.authenticateGoogle('some-id-token', 'username', true);
} catch (error) {
    // Handle error
}

authenticateSteam

Authenticate user and create a session token using a Steam account token.

Parameters
NameDefaultDescription
token string REQUIREDSteam token.
username stringThe user's username. If left empty, one is generated.
import booltrueWhether to automatically import Steam friends after authentication.
create booltrueCreate user if one didn't exist previously.
Returns
NameDescription
userID stringThe user ID of the authenticated user.
username stringThe username of the authenticated user.
create boolValue indicating if this account was just created or already existed.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
let result = {} as nkruntime.AuthResult;

try {
    result = nk.authenticateSteam('steam-token', 'username', true);
} catch (error) {
    // Handle error
}

authenticateTokenGenerate

Generate a Nakama session token from a user ID.

Parameters
NameDefaultDescription
userId string REQUIREDUser ID to use to generate the token.
username stringThe user's username. If left empty, one is generated.
expiresAt numberUTC time in seconds when the token must expire. Defaults to server configured expiry time.
Returns
NameDescription
token stringThe Nakama session token.
validity numberThe period for which the token remains valid.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
let result = {} as nkruntime.TokenGenerateResult;

try {
    result = nk.authenticateTokenGenerate('steam-token', 'username', true);
} catch (error) {
    // Handle error
}

linkApple

Link Apple authentication to a user ID.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID to be linked.
token string REQUIREDApple sign in token.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
let userId = '<UserId>';
let token = '<Token>';

try {
  nk.linkApple(userId, token);
} catch (error) {
  // Handle error
}

linkCustom

Link custom authentication to a user ID.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID to be linked.
customId string REQUIREDCustom ID to be linked to the user.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
let userId = '<UserId>';
let customId = '<CustomId>';

try {
  nk.linkCustom(userId, customId);
} catch (error) {
  // Handle error
}

linkDevice

Link device authentication to a user ID.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID to be linked.
deviceId string REQUIREDDevice ID to be linked to the user.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
let userId = '<UserId>';
let deviceId = '<Deviceid>';

try {
  nk.linkDevice(userId, deviceId);
} catch (error) {
  // Handle error
}

linkEmail

Link email authentication to a user ID.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID to be linked.
email string REQUIREDAuthentication email to be linked to the user.
password string REQUIREDPassword to set. Must be longer than 8 characters.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
let userId = '<UserId>';
let email = 'test@heroiclabs.com';
let password = 'correct horse battery staple'

try {
  nk.linkEmail(userId, email, password);
} catch (error) {
  // Handle error
}

linkFacebook

Link Facebook authentication to a user ID.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID to be linked.
username stringIf left empty, one is generated.
token string REQUIREDAccess token.
importFriends booltrueWhether to automatically import Facebook friends after authentication.
Returns
NameDescription
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
let userId = '<UserId>';
let username = '<Username>';
let token = '<Token>';
let importFriends = true;

try {
  nk.linkFacebook(userId, username, token, importFriends);
} catch (error) {
  // Handle error
}

linkFacebookInstantGame

Link Facebook Instant Game authentication to a user ID.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID to be linked.
playerInfo string REQUIREDFacebook player info.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
let userId = '<UserId>';
let signedPlayerInfo = '<SignedPlayerInfo>';

try {
  nk.linkFacebookInstantGame(userId, signedPlayerInfo);
} catch (error) {
  // Handle error
}

linkGameCenter

Link Apple Game Center authentication to a user ID.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID to be linked.
playerId string REQUIREDPlayer ID provided by Game Center.
bundleId string REQUIREDBundle ID of your app on iTunesConnect.
timestamp int REQUIREDTimestamp at which Game Center authenticated the client and issued a signature.
salt string REQUIREDA random string returned by Game Center authentication on client.
signature string REQUIREDA signature returned by Game Center authentication on client.
publicKeyUrl string REQUIREDA URL to the public key returned by Game Center authentication on client.
Returns
NameDescription
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
let userId = '<UserId>';
let playerId = '<PlayerId>';
let bundleId = '<BundleId>';
let timestamp = 0;
let salt = "<Salt>";
let signature = "<Signature>";
let publicKeyUrl = "<PublicKeyUrl>";

try {
  nk.linkGameCenter(userId, playerId, bundleId, timestamp, salt, signature, publicKeyUrl);
} catch (error) {
  // Handle error
}

linkGoogle

Link Google authentication to a user ID.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID to be linked.
token string REQUIREDGoogle OAuth access token.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
let userId = '<UserId>';
let token = '<Token>';

try {
  nk.linkGoogle(userId, token);
} catch (error) {
  // Handle error
}

linkSteam

Link Steam authentication to a user ID.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID to be linked.
username stringIf left empty, one is generated.
token string REQUIREDSteam access token.
importFriends booltrueWhether to automatically import Steam friends after authentication.
Returns
NameDescription
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
let userId = '<UserId>';
let username = '<Username>';
let token = '<Token>';
let importFriends = true;

try {
  nk.linkSteam(userId, username, token, importFriends);
} catch (error) {
  // Handle error
}

unlinkApple

Unlink Apple authentication from a user ID.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID to be unlinked.
token string REQUIREDApple sign in token.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
let userId = '<UserId>';
let token = '<Token>';

try {
  nk.unlinkApple(userId, token);
} catch (error) {
  // Handle error
}

unlinkCustom

Unlink custom authentication from a user ID.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID to be unlinked.
customId string REQUIREDCustom ID to be unlinked from the user.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
let userId = '<UserId>';
let customId = '<CustomId>';

try {
  nk.unlinkCustom(userId, customId);
} catch (error) {
  // Handle error
}

unlinkDevice

Unlink device authentication from a user ID.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID to be unlinked.
deviceId string REQUIREDDevice ID to be unlinked to the user.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
let userId = '<UserId>';
let deviceId = '<Deviceid>';

try {
  nk.unlinkDevice(userId, deviceId);
} catch (error) {
  // Handle error
}

unlinkEmail

Unlink email authentication from a user ID.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID to be unlinked.
email string REQUIREDEmail to be unlinked from the user.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
let userId = '<UserId>';
let email = 'test@heroiclabs.com';

try {
  nk.unlinkEmail(userId, email);
} catch (error) {
  // Handle error
}

unlinkFacebook

Unlink Facebook authentication from a user ID.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID to be unlinked.
token string REQUIREDAccess token.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
let userId = '<UserId>';
let token = '<Token>';

try {
  nk.unlinkFacebook(userId, token);
} catch (error) {
  // Handle error
}

unlinkFacebookInstantGame

Unlink Facebook Instant Game authentication from a user ID.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID to be unlinked.
playerInfo string REQUIREDFacebook player info.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
let userId = '<UserId>';
let signedPlayerInfo = '<SignedPlayerInfo>';

try {
  nk.unlinkFacebookInstantGame(userId, signedPlayerInfo);
} catch (error) {
  // Handle error
}

unlinkGameCenter

Unlink Apple Game Center authentication from a user ID.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID to be unlinked.
playerId string REQUIREDPlayer ID provided by Game Center.
bundleId string REQUIREDBundle ID of your app on iTunesConnect.
timestamp int REQUIREDTimestamp at which Game Center authenticated the client and issued a signature.
salt string REQUIREDA random string returned by Game Center authentication on client.
signature string REQUIREDA signature returned by Game Center authentication on client.
publicKeyUrl string REQUIREDA URL to the public key returned by Game Center authentication on client.
Returns
NameDescription
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
let userId = '<UserId>';
let playerId = '<PlayerId>';
let bundleId = '<BundleId>';
let timestamp = 0;
let salt = "<Salt>";
let signature = "<Signature>";
let publicKeyUrl = "<PublicKeyUrl>";

try {
  nk.unlinkGameCenter(userId, playerId, bundleId, timestamp, salt, signature, publicKeyUrl);
} catch (error) {
  // Handle error
}

unlinkGoogle

Unlink Google authentication from a user ID.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID to be unlinked.
token string REQUIREDGoogle OAuth access token.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
let userId = '<UserId>';
let token = '<Token>';

try {
  nk.unlinkGoogle(userId, token);
} catch (error) {
  // Handle error
}

unlinkSteam

Unlink Steam authentication from a user ID.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID to be unlinked.
token string REQUIREDSteam access token.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
let userId = '<UserId>';
let token = '<Token>';

try {
  nk.unlinkSteam(userId, token);
} catch (error) {
  // Handle error
}

Chat

channelIdBuild

Create a channel identifier to be used in other runtime calls. Does not create a channel.

Parameters
NameDefaultDescription
senderId string REQUIREDUserID of the message sender (when applicable). Defaults to the system user if void.
target string REQUIREDCan be the room name, group identifier, or another username.
chanType nkruntime.ChannelType REQUIREDThe type of channel, for example group or direct.
Returns
NameDescription
channelId stringThe generated ID representing a channel.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
let result: string;

try {
  result = nk.channelIdBuild('<TargetId>', nkruntime.ChanType.Room);
} catch (error) {
  // Handle error
}

channelMessageSend

Send a message on a realtime chat channel.

Parameters
NameDefaultDescription
channelId string REQUIREDThe ID of the channel to send the message on.
content object REQUIREDMessage content.
senderId string REQUIREDThe UUID for the sender of this message. If left empty, it will be assumed that it is a system message.
senderUsername string REQUIREDThe username of the user to send this message as. If left empty, it will be assumed that it is a system message.
persist booltrueWhether to record this message in the channel history.
Returns
NameDescription
channelMessageSend nkruntime.ChannelMessageAckMessage sent ack.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
let result: nkruntime.ChannelMessageSendAck;
let channelId = '<ChannelId>';
let content = { message: 'Hello world' };
let senderId = '<SenderId>';
let senderUsername = 'Someone';
let persist = true;

try {
  result = nk.channelMessageSend(channelId, content, senderId, senderUsername, persist);
} catch (error) {
  // Handle error
}

channelMessagesList

List messages from a realtime chat channel.

Parameters
NameDefaultDescription
channelId string REQUIREDThe ID of the channel to list messages from.
limit int100The number of messages to return per page.
forward booltrueWhether to list messages from oldest to newest, or newest to oldest.
cursor stringA pagination cursor to use for retrieving a next page of messages.
Returns
NameDescription
channelMessageList nkruntime.ChannelMessageListMessages from the specified channel.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
let messages = {} as nkruntime.ChannelMessageList;

try {
  let channelId = "<channelId>";
  messages = nk.channelMessagesList(channelId);
} catch (erroe) {
  // Handle error
}

channelMessageUpdate

Update a message on a realtime chat channel.

Parameters
NameDefaultDescription
channelId string REQUIREDThe ID of the channel to send the message on.
messageId string REQUIREDThe ID of the message to update.
content object REQUIREDMessage content.
senderId string REQUIREDThe UUID for the sender of this message. If left empty, it will be assumed that it is a system message.
senderUsername string REQUIREDThe username of the user to send this message as. If left empty, it will be assumed that it is a system message.
persist booltrueWhether to record this message in the channel history.
Returns
NameDescription
channelMessageUpdate nkruntime.ChannelMessageAckMessage updated ack.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
let result: nkruntime.ChannelMessageSendAck;
let channelId = '<ChannelId>';
let messageId = '<MessageId>';
let content = { message: 'Hello another world' };
let senderId = '<SenderId>';
let senderUsername = 'Someone';
let persist = true;

try {
  result = nk.channelMessageUpdate(channelId, messageId, content, senderId, senderUsername, persist);
} catch (error) {
  // Handle error
}

Events

event

Generate an event.

Parameters
NameDefaultDescription
event_name string REQUIREDThe name of the event to be created.
properties REQUIREDAn array of event properties.
ts intTimestamp for when event is created.
external boolfalseWhether the event is external.
Returns
NameDescription
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
let eventName = '<EventName>';
let properties = { pro: 'yes' };
let timestamp = 0;
let external = true;

try {
  nk.event(eventName, properties, timestamp, external);
} catch (error) {
  // Handle error
}

Friends

friendsAdd

Add friends to a user.

Parameters
NameDefaultDescription
userId string REQUIREDThe ID of the user to whom you want to add friends.
username string REQUIREDThe name of the user to whom you want to add friends.
ids REQUIREDTable array of IDs of the users you want to add as friends.
usernames REQUIREDTable array of usernames of the users you want to add as friends.
Returns
NameDescription
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
let userId = "b1aafe16-7540-11e7-9738-13777fcc7cd8";
let username = "username";
let userIds = ['9a51cf3a-2377-11eb-b713-e7d403afe081', 'a042c19c-2377-11eb-b7c1-cfafae11cfbc'];
let usernames = ["newfriend1", "newfriend2"];

try {
  nk.friendsAdd(userId, username, userIds, usernames);
} catch (error) {
  // Handle error
}

friendsBlock

Block friends for a user.

Parameters
NameDefaultDescription
userId string REQUIREDThe ID of the user from whom you want to block friends.
username string REQUIREDThe name of the user from whom you want to block friends.
ids REQUIREDTable array of IDs of the users you want to block as friends.
usernames REQUIREDTable array of usernames of the users you want to block as friends.
Returns
NameDescription
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
let userId = "b1aafe16-7540-11e7-9738-13777fcc7cd8";
let username = "username";
let userIds = ['9a51cf3a-2377-11eb-b713-e7d403afe081', 'a042c19c-2377-11eb-b7c1-cfafae11cfbc'];
let usernames = ["exfriend1", "exfriend2"];

try {
  nk.friendsBlock(userId, username, userIds, usernames);
} catch (error) {
  // Handle error
}

friendsDelete

Delete friends from a user.

Parameters
NameDefaultDescription
userId string REQUIREDThe ID of the user from whom you want to delete friends.
username string REQUIREDThe name of the user from whom you want to delete friends.
ids REQUIREDTable array of IDs of the users you want to delete as friends.
usernames REQUIREDTable array of usernames of the users you want to delete as friends.
Returns
NameDescription
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
let userId = "b1aafe16-7540-11e7-9738-13777fcc7cd8";
let username = "username";
let userIds = ['9a51cf3a-2377-11eb-b713-e7d403afe081', 'a042c19c-2377-11eb-b7c1-cfafae11cfbc'];
let usernames = ["exfriend1", "exfriend2"];

try {
  nk.friendsDelete(userId, username, userIds, usernames);
} catch (error) {
  // Handle error
}

friendsList

List all friends, invites, invited, and blocked which belong to a user.

Parameters
NameDefaultDescription
userId string REQUIREDThe ID of the user whose friends, invites, invited, and blocked you want to list.
limit number100The number of friends to retrieve in this page of results. No more than 100 limit allowed per result.
state numberThe state of the friendship with the user. If unspecified this returns friends in all states for the user.
cursor stringThe cursor returned from a previous listing request. Used to obtain the next page of results.
Returns
NameDescription
friends nkruntime.FriendListThe user information for users that are friends of the current user.
cursor stringAn optional next page cursor that can be used to retrieve the next page of records (if any).
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
let friends = {} as nkruntime.FriendList;

try {
  let userId = 'b1aafe16-7540-11e7-9738-13777fcc7cd8';
  let limit = 100;
  let state = 0;
  friends = nk.friendsList(userId, limit, state);
} catch (error) {
  // Handle error
}

Groups

groupCreate

Setup a group with various configuration settings. The group will be created if they don't exist or fail if the group name is taken.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID to be associated as the group superadmin.
name string REQUIREDGroup name, must be unique.
creatorId stringThe user ID to be associated as creator. If not set or nil/null, system user will be set.
langTag stringGroup language.
description stringGroup description, can be left empty as nil/null.
avatarUrl stringURL to the group avatar, can be left empty as nil/null.
open boolfalseWhether the group is for anyone to join, or members will need to send invitations to join.
metadata objectCustom information to store for this group. Can be left empty as nil/null.
maxCount number100Maximum number of members to have in the group.
Returns
NameDescription
createGroup nkruntime.GroupThe groupId of the newly created group.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
let userId = 'dcb891ea-a311-4681-9213-6741351c9994';
let creatorId = 'dcb891ea-a311-4681-9213-6741351c9994';
let name = 'Some unique group name';
let description = 'My awesome group.';
let lang = 'en';
let open = true;
let avatarURL = 'url://somelink';
let metadata = { custom_field: 'some_value' };
let maxCount = 100;

let group = {} as nkruntime.Group;
try {
  group = nk.groupCreate(userId, name, creatorId, lang, description, avatarURL, open, metadata, maxCount);
} catch (error) {
  // Handle error
}

groupDelete

Delete a group.

Parameters
NameDefaultDescription
groupId string REQUIREDThe ID of the group to delete.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
try {
  nk.groupdDelete('f00fa79a-750f-11e7-8626-0fb79f45ff97');
} catch (error) {
  // Handle error
}

groupsGetId

Fetch one or more groups by their ID.

Parameters
NameDefaultDescription
groupIds string REQUIREDAn array of strings of the IDs for the groups to get.
Returns
NameDescription
getGroups nkruntime.Group[]An array of groups with their fields.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
let groups: nkruntime.Group[];

try {
  let groupIds = ['dcb891ea-a311-4681-9213-6741351c9994'];
  groups = nk.groupsGetId(groupIds);
} catch (error) {
  // Handle error
}

groupsList

Find groups based on the entered criteria.

Parameters
NameDefaultDescription
name string REQUIREDSearch for groups that contain this value in their name.
langTag stringFilter based upon the entered language tag.
members numberSearch by number of group members.
open boolFilter based on whether groups are Open or Closed.
limit number100Return only the required number of groups denoted by this limit value.
cursor stringCursor to paginate to the next result set. If this is empty/null there is no further results.
Returns
NameDescription
groups nkruntime.GroupListA list of groups.
cursor stringAn optional next page cursor that can be used to retrieve the next page of records (if any).
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
let groupName = "Heroic";
let langTag = "en";
let members = 10;
let open = true;
let limit = 100;

let results: nkruntime.GroupList = {};
try {
  results = nk.groupsList(groupName, langTag, open, members, limit);
} catch (error) {
  // Handle error
}

groupUpdate

Update a group with various configuration settings. The group which is updated can change some or all of its fields.

Parameters
NameDefaultDescription
groupId string REQUIREDThe ID of the group to update.
userId string REQUIREDUser ID calling the update operation for permission checking. Set as nil to enact the changes as the system user.
name stringGroup name, can be empty if not changed.
creatorId stringThe user ID to be associated as creator. Can be empty if not changed.
langTag stringGroup language. Empty if not updated.
description stringGroup description, can be left empty if not updated.
avatarUrl stringURL to the group avatar, can be left empty if not updated.
open boolWhether the group is for anyone to join or not.
metadata objectCustom information to store for this group. Use nil if field is not being updated.
maxCount numberMaximum number of members to have in the group. Use 0, nil/null if field is not being updated.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
let metadata = { someField: 'some value' };
let groupId = 'f00fa79a-750f-11e7-8626-0fb79f45ff97';
let description = 'An updated description';

try {
  nk.groupUpdate(groupId, nil, null, null, null, description, null, true, metadata);
} catch (error) {
  // Handle error.
}

groupUserJoin

Join a group for a particular user.

Parameters
NameDefaultDescription
groupId string REQUIREDThe ID of the group to join.
userId string REQUIREDThe user ID to add to this group.
username string REQUIREDThe username of the user to add to this group.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
let groupId = 'dcb891ea-a311-4681-9213-6741351c9994';
let userId = '9a51cf3a-2377-11eb-b713-e7d403afe081';
let username = 'myusername';

try {
  nk.groupUserJoin(groupId, userId, username);
} catch (error) {
  // Handle error
}

groupUserLeave

Leave a group for a particular user.

Parameters
NameDefaultDescription
groupId string REQUIREDThe ID of the group to leave.
userId string REQUIREDThe user ID to remove from this group.
username string REQUIREDThe username of the user to remove from this group.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
let groupId = 'dcb891ea-a311-4681-9213-6741351c9994';
let userId = '9a51cf3a-2377-11eb-b713-e7d403afe081';
let username = 'myusername';

try {
  nk.groupUserLeave(groupId, userId, username);
} catch (error) {
  // Handle error
}

groupUsersAdd

Add users to a group.

Parameters
NameDefaultDescription
groupId string REQUIREDThe ID of the group to add users to.
userIds string REQUIREDTable array of user IDs to add to this group.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
let groupId = 'dcb891ea-a311-4681-9213-6741351c9994';
let userIds = ['9a51cf3a-2377-11eb-b713-e7d403afe081', 'a042c19c-2377-11eb-b7c1-cfafae11cfbc'];

try {
  nk.groupUsersAdd(groupId, userIds);
} catch (error) {
  // Handle error
}

groupUsersBan

Ban users from a group.

Parameters
NameDefaultDescription
groupId REQUIREDThe ID of the group to ban users from.
userIds REQUIREDTable array of user IDs to ban from this group.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
let groupId = 'dcb891ea-a311-4681-9213-6741351c9994';
let userIds = ['9a51cf3a-2377-11eb-b713-e7d403afe081', 'a042c19c-2377-11eb-b7c1-cfafae11cfbc'];
let callerId = '6ffededc-bfec-4ea1-a070-274a05825a47';

try {
  nk.groupUsersBan(groupId, userIds, callerId);
} catch (error) {
  // Handle error
}

groupUsersDemote

Demote users in a group.

Parameters
NameDefaultDescription
groupId string REQUIREDThe ID of the group whose members are being demoted.
userIds string REQUIREDTable array of user IDs to demote.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
let groupId = 'dcb891ea-a311-4681-9213-6741351c9994';
let userIds = ['9a51cf3a-2377-11eb-b713-e7d403afe081', 'a042c19c-2377-11eb-b7c1-cfafae11cfbc'];

try {
  nk.groupUsersDemote(groupId, userIds);
} catch (error) {
  // Handle error
}

groupUsersKick

Kick users from a group.

Parameters
NameDefaultDescription
groupId string REQUIREDThe ID of the group to kick users from.
userIds string REQUIREDTable array of user IDs to kick.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
let groupId = 'dcb891ea-a311-4681-9213-6741351c9994';
let userIds = ['9a51cf3a-2377-11eb-b713-e7d403afe081', 'a042c19c-2377-11eb-b7c1-cfafae11cfbc'];

try {
  nk.groupUsersKick(groupId, userIds);
} catch (error) {
  // Handle error
}

groupUsersList

List all members, admins and superadmins which belong to a group. This also list incoming join requests.

Parameters
NameDefaultDescription
groupId string REQUIREDThe ID of the group to list members for.
Returns
NameDescription
groupUsers nkruntime.GroupUserListThe user information for members, admins and superadmins for the group. Also users who sent a join request.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
let groupId = 'dcb891ea-a311-4681-9213-6741351c9994';
let groupUsers = {} as nkruntime.GroupUserList;

try {
  groupUsers = nk.groupUsersList(groupId);
} catch (error) {
  // Handle error
}

groupUsersPromote

Promote users in a group.

Parameters
NameDefaultDescription
groupId string REQUIREDThe ID of the group whose members are being promoted.
userIds string REQUIREDTable array of user IDs to promote.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
let groupId = 'dcb891ea-a311-4681-9213-6741351c9994';
let userIds = ['9a51cf3a-2377-11eb-b713-e7d403afe081', 'a042c19c-2377-11eb-b7c1-cfafae11cfbc'];

try {
  nk.groupUsersPromote(groupId, userIds);
} catch (error) {
  // Handle error
}

userGroupsList

List all groups which a user belongs to and whether they've been accepted or if it's an invite.

Parameters
NameDefaultDescription
userId string REQUIREDThe ID of the user to list groups for.
Returns
NameDescription
userGroups nkruntime.UserGroupListA table of groups with their fields.
cursor stringAn optional next page cursor that can be used to retrieve the next page of records (if any).
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
let userId = '64ef6cb0-7512-11e7-9e52-d7789d80b70b';
let groups: nkruntime.UserGroupList;

try {
    groups = nk.userGroupsList(userId);
} catch (error) {
    // Handle error
}

Leaderboards

leaderboardCreate

Setup a new dynamic leaderboard with the specified ID and various configuration settings. The leaderboard will be created if it doesn't already exist, otherwise its configuration will not be updated.

Parameters
NameDefaultDescription
leaderboardID string REQUIREDThe unique identifier for the new leaderboard. This is used by clients to submit scores.
authoritative bool REQUIREDfalseMark the leaderboard as authoritative which ensures updates can only be made via the Go runtime. No client can submit a score directly.
sortOrder stringThe sort order for records in the leaderboard. Possible values are "asc" or "desc".
operator stringThe operator that determines how scores behave when submitted. Possible values are "best", "set", or "incr".
resetSchedule stringThe cron format used to define the reset schedule for the leaderboard. This controls when a leaderboard is reset and can be used to power daily/weekly/monthly leaderboards.
metadata objectThe metadata you want associated to the leaderboard. Some good examples are weather conditions for a racing game.
Returns
NameDescription
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
let id = '4ec4f126-3f9d-11e7-84ef-b7c182b36521';
let authoritative = false;
let sort = nkruntime.SortOrder.DESCENDING;
let operator = nkruntime.Operator.BEST;
let reset = '0 0 * * 1';

let metadata = {
  weatherConditions: 'rain',
};

try {
    nk.leaderboardCreate(id, authoritative, sort, operator, reset, metadata);
} catch(error) {
    // Handle error
}

leaderboardDelete

Delete a leaderboard and all scores that belong to it.

Parameters
NameDefaultDescription
id string REQUIREDThe unique identifier for the leaderboard to delete.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
let id = '4ec4f126-3f9d-11e7-84ef-b7c182b36521';

try {
    nk.leaderboardDelete(id);
} catch(error) {
    // Handle error
}

leaderboardList

Find leaderboards which have been created on the server. Leaderboards can be filtered with categories.

Parameters
NameDefaultDescription
categoryStart number REQUIREDFilter leaderboards with categories greater or equal than this value.
categoryEnd number REQUIREDFilter leaderboards with categories equal or less than this value.
limit number10Return only the required number of leaderboards denoted by this limit value.
cursor stringCursor to paginate to the next result set. If this is empty/null there are no further results.
Returns
NameDescription
leaderboardList nkruntime.LeaderboardListA list of leaderboard results and possibly a cursor.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
let categoryStart = 1;
let categoryEnd = 2;
let limit = 100  // Number to list per page.
let results: nkruntime.LeaderboardList = {};

try {
    results = nk.leaderboardList(categoryStart, categoryEnd, limit);
} catch (error) {
    // Handle error
}

leaderboardRecordDelete

Remove an owner's record from a leaderboard, if one exists.

Parameters
NameDefaultDescription
id string REQUIREDThe unique identifier for the leaderboard to delete from.
owner string REQUIREDThe owner of the score to delete. Mandatory field.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
let id = '4ec4f126-3f9d-11e7-84ef-b7c182b36521';
let owner = '4c2ae592-b2a7-445e-98ec-697694478b1c';

try {
    nk.leaderboardRecordDelete(id, owner);
} catch(error) {
    // Handle error
}

leaderboardRecordsHaystack

Fetch the list of leaderboard records around the owner.

Parameters
NameDefaultDescription
id string REQUIREDThe unique identifier for the leaderboard.
owner string REQUIREDThe owner of the score to list records around. Mandatory field.
limit number REQUIREDReturn only the required number of leaderboard records denoted by this limit value.
overrideExpiry number REQUIREDRecords with expiry in the past are not returned unless within this defined limit. Must be equal or greater than 0.
Returns
NameDescription
records nkruntime.LeaderboardRecordListThe leaderboard records according to ID.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
let id = '4ec4f126-3f9d-11e7-84ef-b7c182b36521';
let owner = '4c2ae592-b2a7-445e-98ec-697694478b1c';
let limit = 10;
let overrideExpiry = 3600;
let results: nkruntime.Leaderboard[] = [];

try {
  results = nk.leaderboardRecordsHaystack(id, owner, limit, overrideExpiry);
} catch (error) {
  // Handle error
}

leaderboardRecordsList

List records on the specified leaderboard, optionally filtering to only a subset of records by their owners. Records will be listed in the preconfigured leaderboard sort order.

Parameters
NameDefaultDescription
id string REQUIREDThe unique identifier for the leaderboard to list. Mandatory field.
owners string REQUIREDArray of owners to filter to.
limit number REQUIREDThe maximum number of records to return (Max 10,000).
cursor stringCursor to paginate to the next result set. If this is empty/null there are no further results.
Returns
NameDescription
records nkruntime.LeaderboardRecordA page of leaderboard records.
ownerRecords nkruntime.LeaderboardRecordA list of owner leaderboard records (empty if the owners input parameter is not set).
nextCursor stringAn optional next page cursor that can be used to retrieve the next page of records (if any).
prevCursor stringAn optional previous page cursor that can be used to retrieve the previous page of records (if any).
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
let result: nkruntime.LeaderboardRecordList;
let id = '4ec4f126-3f9d-11e7-84ef-b7c182b36521';
let ownerIds: string[] = [];

try {
    result = nk.leaderboardRecordsList(id, ownerIds);
} catch(error) {
    // Handle error
}

leaderboardRecordWrite

Use the preconfigured operator for the given leaderboard to submit a score for a particular user.

Parameters
NameDefaultDescription
id string REQUIREDThe unique identifier for the leaderboard to submit to.
owner string REQUIREDThe owner of this score submission.
username stringThe owner username of this score submission, if it's a user.
score number0The score to submit.
subscore number0A secondary subscore parameter for the submission.
metadata objectThe metadata you want associated to this submission. Some good examples are weather conditions for a racing game.
Returns
NameDescription
record nkruntime.LeaderboardRecordThe newly created leaderboard record.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
let id = '4ec4f126-3f9d-11e7-84ef-b7c182b36521';
let ownerID = '4c2ae592-b2a7-445e-98ec-697694478b1c';
let username = '02ebb2c8';
let score = 10;
let subscore = 0;

let metadata = {
  weatherConditions: 'rain',
};

let result: nkruntime.LeaderboardRecord;

try {
  result = nk.leaderboardRecordWrite(id, ownerID, username, score, subscore, metadata);
} catch(error) {
  // Handle error
}

leaderboardsGetId

Fetch one or more leaderboards by ID.

Parameters
NameDefaultDescription
ids string REQUIREDThe table array of leaderboard ids.
Returns
NameDescription
leaderboards nkruntime.LeaderboardThe leaderboard records according to ID.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
let leaderboardIds = [
  '3ea5608a-43c3-11e7-90f9-7b9397165f34',
  '447524be-43c3-11e7-af09-3f7172f05936',
]

let leaderboards: nkruntime.Leaderboard[];

try {
  leaderboards = nk.leaderboardsGetId(leaderboardIds);
} catch (error) {
  // Handle error
}

Matches

matchCreate

Create a new authoritative realtime multiplayer match running on the given runtime module name. The given params are passed to the match's init hook.

Parameters
NameDefaultDescription
module string REQUIREDThe name of an available runtime module that will be responsible for the match. This was registered in InitModule.
params Any value to pass to the match init hook.
Returns
NameDescription
matchId stringThe match ID of the newly created match. Clients can immediately use this ID to join the match.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
let module = 'some.folder.module';
let params = {
  some: 'data',
}

let matchId: string;

try {
  matchId = nk.matchCreate(module, params);
} catch(error) {
  // Handle error
}

matchGet

Get information on a running match.

Parameters
NameDefaultDescription
id string REQUIREDThe ID of the match to fetch.
Returns
NameDescription
match nkruntime.MatchInformation for the running match.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
let matchId = '52f02f3e-5b48-11eb-b182-0f5058adfcc6';
let match: nkruntime.Match;

try {
  match = nk.matchGet(matchId);
} catch(error) {
  // Handle error
}

matchList

List currently running realtime multiplayer matches and optionally filter them by authoritative mode, label, and current participant count.

Parameters
NameDefaultDescription
limit number1The maximum number of matches to list.
authoritative boolfalseSet true to only return authoritative matches, false to only return relayed matches.
label stringA label to filter authoritative matches by. Default "" meaning any label matches.
minSize numberInclusive lower limit of current match participants.
maxSize numberInclusive upper limit of current match participants.
query stringAdditional query parameters to shortlist matches.
Returns
NameDescription
match nkruntime.Match[]A list of matches matching the parameters criteria.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
let limit = 10;
let isAuthoritative = false;
let label = '';
let minSize = 2;
let maxSize = 4;
let matches: nkruntime.Match[] = [];

try {
  matches = nk.matchList(limit, isAuthoritative, label, minSize, maxSize);
} catch(error) {
  // Handle error
}

matchSignal

Allow the match handler to be sent a reservation signal to mark a user ID or session ID into the match state ahead of their join attempt and eventual join flow. Called when the match handler receives a runtime signal.

Parameters
NameDefaultDescription
id string REQUIREDThe user ID or session ID to send a reservation signal for.
data string REQUIREDAn arbitrary input supplied by the runtime caller of the signal.
Returns
NameDescription
data stringArbitrary data to return to the runtime caller of the signal. May be a string or nil.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
let matchId = '<MatchId>';
let data = '<Data>';
let result: string;

try {
  result = nk.matchSignal(matchId, data);
} catch(error) {
  // Handle error
}  

Metrics

metricsCounterAdd

Add a custom metrics counter.

Parameters
NameDefaultDescription
name string REQUIREDThe name of the custom metrics counter.
tags map REQUIREDThe metrics tags associated with this counter.
delta number REQUIREDAn integer value to update this metric with.
Returns
NameDescription
1
2
3
4
5
6
7
8
9
let name = "metricName";
let tags = new Map<string, string>(); // Metrics tags for this counter.
let delta = 100;

try {
  nk.metricsCounterAdd(name, tags, delta);
} catch(error) {
  // handle error
}

metricsGaugeSet

Add a custom metrics gauge.

Parameters
NameDefaultDescription
name string REQUIREDThe name of the custom metrics gauge.
tags map REQUIREDThe metrics tags associated with this gauge.
value number REQUIREDA value to update this metric with.
Returns
NameDescription
1
2
3
4
5
6
7
8
9
let name = "metricName";
let tags = new Map<string, string>(); // Metrics tags for this gauge.
let value = 3.14

try {
    nk.metricsGaugeSet(name, tags, value);
} catch(error) {
    // handle error
}

metricsTimerRecord

Add a custom metrics timer.

Parameters
NameDefaultDescription
name string REQUIREDThe name of the custom metrics timer.
tags map REQUIREDThe metrics tags associated with this timer.
value number REQUIREDAn integer value to update this metric with (in nanoseconds).
Returns
NameDescription
1
2
3
4
5
6
7
8
9
let name = "metricName";
let tags = new Map<string, string>(); // Metrics tags for this gauge.
let value = 100000000000;

try {
  nk.metricsTimerRecord(name, tags, value)
} catch(error) {
  // handle error
}

Notifications

notificationSend

Send one in-app notification to a user.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID of the user to be sent the notification.
subject string REQUIREDNotification subject.
content object REQUIREDNotification content. Must be set but can be empty object.
code number REQUIREDNotification code to use. Must be equal or greater than 0.
sender stringThe sender of this notification. If left empty, it will be assumed that it is a system notification.
persistent boolfalseWhether to record this in the database for later listing.
Returns
NameDescription
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
let receiverId = '4c2ae592-b2a7-445e-98ec-697694478b1c';
let subject = "You've unlocked level 100!";

let content = {
  rewardCoins: 1000,
}

let code = 101;
let senderId = 'dcb891ea-a311-4681-9213-6741351c9994'
let persistent = true;

try {
  nk.notificationSend(receiverId, subject, content, code, senderId, persistent);
} catch (error) {
  // Handle error
}

notificationSendAll

Send an in-app notification to all users.

Parameters
NameDefaultDescription
subject string REQUIREDNotification subject.
content object REQUIREDNotification content. Must be set but can be an empty object.
code number REQUIREDNotification code to use. Must be greater than or equal to 0.
persistent boolfalseWhether to record this in the database for later listing.
Returns
NameDescription
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
let subject = "You've unlocked level 100!";

let content = {
  rewardCoins: 1000,
}

let code = 101;
let persistent = true;

try {
  nk.notificationSendAll(subject, content, code, persistent);
} catch (error) {
  // Handle error
}

notificationsSend

Send one or more in-app notifications to a user.

Parameters
NameDefaultDescription
notifications any REQUIREDA list of notifications to be sent together.
Returns
NameDescription
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
let notifications: nkruntime.NotificationRequest[] = [
  {
    userId: '4c2ae592-b2a7-445e-98ec-697694478b1c',
    subject: "You've unlocked level 100!",
    content: { rewardCoins: 1000 },
    code: 101,
    persistent: true,
  },
  {
    userId: '69769447-b2a7-445e-98ec-8b1c4c2ae592',
    subject: "You've unlocked level 100!",
    content: { rewardCoins: 1000 },
    code: 101,
    persistent: true,
  },
];

try {
  nk.notificationsSend(notifications);
} catch (error) {
  // Handle error
}

Purchases

purchaseGetByTransactionId

Look up a purchase receipt by transaction ID.

Parameters
NameDefaultDescription
transactionId string REQUIREDTransaction ID of the purchase to look up.
Returns
NameDescription
owner stringThe owner of the purchase.
purchase nkruntime.ValidatedPurchaseAroundOwnerA validated purchase.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
let transactionId = '809346e9-3d71-4aa8-9938-0ea566a0ed11';
let result: nkruntime.ValidatedPurchaseOwner;

try {
  result = nk.purchaseGetByTransactionId(transactionId);
} catch(error) {
    // Handle error
}

purchasesList

List stored validated purchase receipts.

Parameters
NameDefaultDescription
userId stringFilter by user ID. Can be an empty string to list purchases for all users.
limit number100Limit number of records retrieved.
cursor stringPagination cursor from previous result. If none available set to nil or "" (empty string).
Returns
NameDescription
listPurchases nkruntime.ValidatedPurchaseListA page of stored validated purchases.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
let userId = '4c2ae592-b2a7-445e-98ec-697694478b1c';
let validation: nkruntime.ValidatedPurchaseList;

try {
  validation = nk.purchasesList(userId);
} catch(error) {
  // Handle error
}

purchaseValidateApple

Validates and stores the purchases present in an Apple App Store Receipt.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID of the owner of the receipt.
receipt string REQUIREDBase-64 encoded receipt data returned by the purchase operation itself.
persist booltruePersist the purchase so that seenBefore can be computed to protect against replay attacks.
passwordOverride stringOverride the iap.apple.shared_password provided in your configuration.
Returns
NameDescription
validation nkruntime.ValidatePurchaseResponseThe resulting successfully validated purchases. Any previously validated purchases are returned with a seenBefore flag.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
let userId = '4c2ae592-b2a7-445e-98ec-697694478b1c';
let receipt = '<base64-receipt-data>';
let validation: nkruntime.ValidatePurchaseResponse;

try {
  validation = nk.purchaseValidateApple(userId, receipt);
} catch(error) {
  // Handle error
}

purchaseValidateGoogle

Validates and stores a purchase receipt from the Google Play Store.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID of the owner of the receipt.
receipt string REQUIREDJSON encoded Google receipt.
persist booltruePersist the purchase so that seenBefore can be computed to protect against replay attacks.
Returns
NameDescription
validation nkruntime.ValidatePurchaseResponseThe resulting successfully validated purchases. Any previously validated purchases are returned with a seenBefore flag.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
let userId = '4c2ae592-b2a7-445e-98ec-697694478b1c';
let receipt = '{\"json\":{\"orderId \":\"..\",\"packageName \":\"..\",\"productId \":\"..\",\"purchaseTime\":1607721533824,\"purchaseState\":0,\"purchaseToken\":\"..\",\"acknowledged\":false},\"signature \":\"..\",\"skuDetails \":{\"productId\":\"..\",\"type\":\"inapp\",\"price\":\"u20ac82.67\",\"price_amount_micros\":82672732,\"price_currency_code\":\"EUR\",\"title\":\"..\",\"description\":\"..\",\"skuDetailsToken\":\"..\"}}';
let validation: nkruntime.ValidatePurchaseResponse;

try {
  validation = nk.purchaseValidateGoogle(userId, receipt);
} catch(error) {
  // Handle error
}

purchaseValidateHuawei

Validates and stores a purchase receipt from the Huawei App Gallery.

Parameters
NameDefaultDescription
userId string REQUIREDThe user ID of the owner of the receipt.
receipt string REQUIREDThe Huawei receipt data.
signature string REQUIREDThe receipt signature.
persist booltruePersist the purchase so that seenBefore can be computed to protect against replay attacks.
Returns
NameDescription
validation nkruntime.ValidatePurchaseResponseThe resulting successfully validated purchases. Any previously validated purchases are returned with a seenBefore flag.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
let userId = '4c2ae592-b2a7-445e-98ec-697694478b1c';
let receipt = '<receipt-data>';
let signature = '<signature-data>';
let validation: nkruntime.ValidatePurchaseResponse;

try {
  validation = nk.purchaseValidateHuawei(userId, receipt, signature);
} catch(error) {
  // Handle error
}

Sessions

sessionDisconnect

Disconnect a session.

Parameters
NameDefaultDescription
sessionId string REQUIREDThe ID of the session to be disconnected.
reason nkruntime.PresenceReason REQUIREDThe reason for the session disconnect.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
const sessionId = "81550806-a751-45c3-a667-574c916e06aa";
const reason = nkruntime.PresenceReason.PresenceReasonDisconnect;
nk.sessionDisconnect(sessionId, reason);

sessionLogout

Log out a user from their current session.

Parameters
NameDefaultDescription
userId string REQUIREDThe ID of the user to be logged out.
token stringThe current session authentication token. If the current auth and refresh tokens are not provided, all user sessions will be logged out.
refreshToken stringThe current session refresh token. If the current auth and refresh tokens are not provided, all user sessions will be logged out.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
const userId = "1467c4f5-df88-43df-98c5-6bd09723aa70";
const token = "<Token>";
const refreshToken = "<RefreshToken>";
nk.sessionLogout(userId, token, refreshToken);

Storage

storageDelete

Remove one or more objects by their collection/keyname and optional user.

Parameters
NameDefaultDescription
objectIds nkruntime.StorageDeleteRequest REQUIREDAn array of object identifiers to be deleted.
Returns
NameDescription
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
let userId = '4ec4f126-3f9d-11e7-84ef-b7c182b36521';
let friendUserId = '8d98ee3f-8c9f-42c5-b6c9-c8f79ad1b820';

let objectIds: nkruntime.StorageDeleteRequest[] = [
  { collection: 'save', key: 'save1', userId },
  { collection: 'save', key: 'save2', userId },
  { collection: 'public', key: 'progress', userId: friendUserId },
];

try {
    nk.storageDelete(objectIds);
} catch (error) {
    // Handle error
}

storageList

List records in a collection and page through results. The records returned can be filtered to those owned by the user or "" for public records.

Parameters
NameDefaultDescription
userId string REQUIREDUser ID to list records for or "" (empty string) for public records.
collection string REQUIREDCollection to list data from.
limit number100Limit number of records retrieved.
cursor string REQUIREDPagination cursor from previous result. If none available set to nil or "" (empty string).
Returns
NameDescription
objects nkruntime.StorageObjectListA list of storage objects.
cursor stringPagination cursor.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
let user_id = '4ec4f126-3f9d-11e7-84ef-b7c182b36521';
let result: nkruntime.StorageObjectList = {};

try {
    let result = nk.storageList(user_id, 'collection', 10);
} catch (error) {
    // Handle error
}

storageRead

Fetch one or more records by their bucket/collection/keyname and optional user.

Parameters
NameDefaultDescription
objectIds nkruntime.StorageReadRequest REQUIREDAn array of object identifiers to be fetched.
Returns
NameDescription
objects nkruntime.StorageObject[]A list of matches matching the parameters criteria.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
let userId = '4ec4f126-3f9d-11e7-84ef-b7c182b36521';

let objectIds: nkruntime.StorageReadRequest[] = [
  { collection: 'save', key: 'save1', userId: userId },
  { collection: 'save', key: 'save2', userId },
  { collection: 'save', key: 'save3', userId },
];

let results: nkruntime.StorageObject[] = [];

try {
    results = nk.storageRead(objectIds);
} catch (error) {
    // Handle error

storageWrite

Write one or more objects by their collection/keyname and optional user.

Parameters
NameDefaultDescription
objectIds nkruntime.StorageWriteRequest REQUIREDAn array of object identifiers to be written.
Returns
NameDescription
acks nkruntime.StorageWriteAcksA list of acks with the version of the written objects.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
// Storage Write
let userId = '4ec4f126-3f9d-11e7-84ef-b7c182b36521';

let newObjects: nkruntime.StorageWriteRequest[] = [
  { collection: 'save', key: 'save1', userId, value: {} },
  { collection: 'save', key: 'save2', userId, value: {} },
  { collection: 'save', key: 'save3', userId, value: {}, permissionRead: 2, permissionWrite: 1 },
  { collection: 'save', key: 'save3', userId, value: {}, version: '<some_version>', permissionRead: 1, permissionWrite: 1 }
];

try {
    nk.storageWrite(newObjects);
} catch (error) {
    // Handle error
}

Streams

streamClose

Close a stream and remove all presences on it.

Parameters
NameDefaultDescription
stream nkruntime.Stream REQUIREDA stream object.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
try {
  let stream: nkruntime.Stream; // An existing stream object
  nk.streamClose(stream);
} catch (err) {
  // Handle error
}

streamCount

Get a count of stream presences.

Parameters
NameDefaultDescription
stream nkruntime.Stream REQUIREDA stream object.
Returns
NameDescription
countByStream numberNumber of current stream presences.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
try {
  let stream: nkruntime.Stream; // An existing stream object
  const count = nk.streamCount(stream);
} catch (err) {
  // Handle error
}

streamSend

Send data to presences on a stream.

Parameters
NameDefaultDescription
stream nkruntime.Stream REQUIREDA stream object.
data string REQUIREDThe data to send.
presences nkruntime.PresenceArray of presences to receive the sent data. If not set, will be sent to all presences.
reliable booltrueWhether the sender has been validated prior.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
try {
  let stream: nkruntime.Stream; // An existing stream object
  let presences: nkruntime.Presence[]; // An existing presences array
  const data = "<Data>";
  const reliable = true;
  nk.streamSend(stream, data, presences, reliable);
} catch (err) {
  // Handle error
}

streamSendRaw

Send a message to presences on a stream.

Parameters
NameDefaultDescription
stream nkruntime.Stream REQUIREDA stream object.
msg REQUIREDThe message to send.
presences nkruntime.Presence REQUIREDArray of presences to receive the sent data. If not set, will be sent to all presences.
reliable booltrueWhether the sender has been validated prior.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
try {
  let stream: nkruntime.Stream; // An existing stream object
  let presences: nkruntime.Presence[]; // An existing presences array
  const envelope = {}; // A data object
  const reliable = true;
  nk.streamSendRaw(stream, envelope, presences, reliable);
} catch (err) {
  // Handle error
}

streamUserGet

Retreive a stream presence and metadata by user ID.

Parameters
NameDefaultDescription
stream nkruntime.Stream REQUIREDA stream object.
userId string REQUIREDThe user ID to fetch information for.
sessionId string REQUIREDThe current session ID for the user.
Returns
NameDescription
meta nkruntime.PresencePresence for the user.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
try {
  let stream: nkruntime.Stream; // An existing stream object
  const userId = "7d8252ef-8bc7-4d7d-a828-e99733046355";
  const sessionId = "ef54eece-ddd1-4c62-b567-6d6c8c902c9c";
  const presence = nk.streamUserGet(userId, sessionId, stream);
} catch (err) {
  // Handle error
}

streamUserJoin

Add a user to a stream.

Parameters
NameDefaultDescription
stream nkruntime.Stream REQUIREDA stream object.
userId string REQUIREDThe user ID to be added.
sessionId string REQUIREDThe current session ID for the user.
hidden bool REQUIREDWhether the user will be marked as hidden.
persistence bool REQUIREDWhether message data should be stored in the database.
status string REQUIREDUser status message.
Returns
NameDescription
success boolWhether the user was successfully added.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
try {
  let stream: nkruntime.Stream; // An existing stream object
  const userId = "7d8252ef-8bc7-4d7d-a828-e99733046355";
  const sessionId = "ef54eece-ddd1-4c62-b567-6d6c8c902c9c";
  const hidden = false;
  const persistence = true;
  const status = "Some Status";
  nk.streamUserJoin(userId, sessionId, stream, hidden, persistence, status);
} catch (err) {
  // Handle error
}

streamUserKick

Kick a user from a stream.

Parameters
NameDefaultDescription
stream nkruntime.Stream REQUIREDA stream object.
presence nkruntime.Presence REQUIREDThe presence to be kicked.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
try {
  let stream: nkruntime.Stream; // An existing stream object
  let presence: nkruntime.Presence; // An existing presence object
  nk.streamUserKick(presence, stream);
} catch (err) {
  // Handle error
}

streamUserLeave

Remove a user from a stream.

Parameters
NameDefaultDescription
stream nkruntime.Stream REQUIREDA stream object.
userId string REQUIREDThe user ID to be removed.
sessionId string REQUIREDThe current session ID for the user.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
try {
  let stream: nkruntime.Stream; // An existing stream object
  const userId = "7d8252ef-8bc7-4d7d-a828-e99733046355";
  const sessionId = "ef54eece-ddd1-4c62-b567-6d6c8c902c9c";
  nk.streamUserLeave(userId, sessionId, stream);
} catch (err) {
  // Handle error
}

streamUserList

List all users currently online and connected to a stream.

Parameters
NameDefaultDescription
stream nkruntime.Stream REQUIREDA stream object.
includeHidden boolInclude stream presences marked as hidden in the results.
includeNotHidden boolInclude stream presences not marked as hidden in the results.
Returns
NameDescription
presences nkruntime.Presences[]Array of stream presences and their information.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
try {
  let stream: nkruntime.Stream; // An existing stream object
  const includeHidden = true;
  const includeNotHidden = true;
  const presences = nk.streamUserList(stream, includeHidden, includeNotHidden);
} catch (err) {
  // Handle error
}

streamUserUpdate

Update a stream user by ID.

Parameters
NameDefaultDescription
stream nkruntime.Stream REQUIREDA stream object.
userId string REQUIREDThe user ID to be updated.
sessionId string REQUIREDThe current session ID for the user.
hidden bool REQUIREDWhether the user will be marked as hidden.
persistence bool REQUIREDWhether message data should be stored in the database.
status string REQUIREDUser status message.
Returns
NameDescription
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
try {
  let stream: nkruntime.Stream; // An existing stream object
  const userId = "7d8252ef-8bc7-4d7d-a828-e99733046355";
  const sessionId = "ef54eece-ddd1-4c62-b567-6d6c8c902c9c";
  const hidden = true;
  const persistence = true;
  nk.streamUserUpdate(userId, sessionId, stream, hidden, persistence);
} catch (err) {
  // Handle error
}

Tournaments

tournamentAddAttempt

Add additional score attempts to the owner's tournament record. This overrides the max number of score attempts allowed in the tournament for this specific owner.

Parameters
NameDefaultDescription
id string REQUIREDThe unique identifier for the tournament to update.
owner string REQUIREDThe owner of the records to increment the count for.
count number REQUIREDThe number of attempt counts to increment. Can be negative to decrease count.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
let id = '4ec4f126-3f9d-11e7-84ef-b7c182b36521';
let owner = 'leaderboard-record-owner';
let count = -10;

try {
  nk.tournamentAddAttempt(id, owner, count);
} catch (error) {
  // Handle error
}

tournamentCreate

Setup a new dynamic tournament with the specified ID and various configuration settings. The underlying leaderboard will be created if it doesn't already exist, otherwise its configuration will not be updated.

Parameters
NameDefaultDescription
id string REQUIREDThe unique identifier for the new tournament. This is used by clients to submit scores.
authoritative booltrueWhether the tournament created is server authoritative.
sortOrder stringThe sort order for records in the tournament. Possible values are "asc" or "desc".
operator stringThe operator that determines how scores behave when submitted. The possible values are "best", "set", or "incr".
resetSchedule stringThe cron format used to define the reset schedule for the tournament. This controls when the underlying leaderboard resets and the tournament is considered active again.
metadata objectThe metadata you want associated to the tournament. Some good examples are weather conditions for a racing game.
title stringThe title of the tournament.
description stringThe description of the tournament.
category numberA category associated with the tournament. This can be used to filter different types of tournaments. Between 0 and 127.
startTime numberThe start time of the tournament. Leave empty for immediately or a future time.
endTime numberneverThe end time of the tournament. When the end time is elapsed, the tournament will not reset and will cease to exist. Must be greater than startTime if set.
duration number REQUIREDThe active duration for a tournament. This is the duration when clients are able to submit new records. The duration starts from either the reset period or tournament start time whichever is sooner. A game client can query the tournament for results between end of duration and next reset period.
maxSize numberMaximum size of participants in a tournament.
maxNumScore numberMaximum submission attempts for a tournament record.
joinRequired boolfalseWhether the tournament needs to be joined before a record write is allowed.
Returns
NameDescription
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
let id = '4ec4f126-3f9d-11e7-84ef-b7c182b36521';
let authoritative = false
let sortOrder = nkruntime.SortOrder.DESCENDING;
let operator = nkruntime.Operator.BEST;
let duration = 3600;     // In seconds.
let resetSchedule = '0 12 * * *'; // Noon UTC each day.

let metadata = {
    weatherConditions: 'rain',
};

let title = 'Daily Dash';
let description = "Dash past your opponents for high scores and big rewards!";
let category = 1;
let startTime = 0;       // Start now.
let endTime = 0;         // Never end, repeat the tournament each day forever.
let maxSize = 10000;     // First 10,000 players who join.
let maxNumScore = 3;     // Each player can have 3 attempts to score.
let joinRequired = true; // Must join to compete.

try {
  nk.tournamentCreate(id, authoritative, sortOrder, operator, duration, resetSchedule, metadata, title, description, category, startTime, endTime, maxSize, maxNumScore, joinRequired);
} catch (error) {
  // Handle error
}

tournamentDelete

Delete a tournament and all records that belong to it.

Parameters
NameDefaultDescription
id string REQUIREDThe unique identifier for the tournament to delete.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
let id = '4ec4f126-3f9d-11e7-84ef-b7c182b36521';

try {
  nk.tournamentDelete(id);
} catch (error) {
  // Handle error
}

tournamentJoin

A tournament may need to be joined before the owner can submit scores. This operation is idempotent and will always succeed for the owner even if they have already joined the tournament.

Parameters
NameDefaultDescription
id string REQUIREDThe unique identifier for the tournament to join.
ownerId string REQUIREDThe owner of the record.
username string REQUIREDThe username of the record owner.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
let id = '4ec4f126-3f9d-11e7-84ef-b7c182b36521';
let owner = 'leaderboard-record-owner';
let username = 'myusername';

try {
  nk.tournamentJoin(id, owner, username);
} catch (error) {
  // Handle error
}

tournamentList

Find tournaments which have been created on the server. Tournaments can be filtered with categories and via start and end times.

Parameters
NameDefaultDescription
categoryStart number REQUIREDFilter tournament with categories greater or equal than this value.
categoryEnd number REQUIREDFilter tournament with categories equal or less than this value.
startTime numberFilter tournament with that start after this time.
endTime numberFilter tournament with that end before this time.
limit number10Return only the required number of tournament denoted by this limit value.
cursor stringCursor to paginate to the next result set. If this is empty/null there is no further results.
Returns
NameDescription
tournamentList nkruntime.TournamentList[]A list of tournament results and possibly a cursor.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
let categoryStart = 1;
let categoryEnd = 2;
let startTime = 1538147711M;
let endTime = 0 // All tournaments from the start time.
let limit = 100  // Number to list per page.
let results: nkruntime.TournamentList = {};

try {
  results = nk.tournamentList(categoryStart, categoryEnd, startTime, endTime, limit);
} catch (error) {
  // Handle error
}

tournamentRecordsHaystack

Fetch the list of tournament records around the owner.

Parameters
NameDefaultDescription
id string REQUIREDThe ID of the tournament to list records for.
ownerId string REQUIREDThe owner ID around which to show records.
limit numberReturn only the required number of tournament records denoted by this limit value. Between 1-100.
expiry numberTime since epoch in seconds. Must be greater than 0.
Returns
NameDescription
tournamentRecordsHaystack nkruntime.LeaderboardRecordA list of tournament records.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
let id = '4ec4f126-3f9d-11e7-84ef-b7c182b36521';
let owner = '4c2ae592-b2a7-445e-98ec-697694478b1c';
let results: nkruntime.Tournament[] = [];

try {
  results = nk.tournamentRecordsHaystack(id, owner);
} catch (error) {
  // Handle error
}

tournamentRecordsList

List records on the specified tournament, optionally filtering to only a subset of records by their owners. Records will be listed in the preconfigured tournament sort order.

Parameters
NameDefaultDescription
tournamentId string REQUIREDThe ID of the tournament to list records for.
ownerIds stringArray of owner IDs to filter results by. Optional.
cursor stringCursor to paginate to the next result set. If this is empty/null there are no further results.
overrideExpiry numberRecords with expiry in the past are not returned unless within this defined limit. Must be equal or greater than 0.
Returns
NameDescription
records nkruntime.LeaderboardRecordA page of tournament records.
ownerRecords nkruntime.LeaderboardRecordA list of owner tournament records (empty if the owners input parameter is not set).
prevCursor stringAn optional previous page cursor that can be used to retrieve the previous page of records (if any).
nextCursor stringAn optional next page cursor that can be used to retrieve the next page of records (if any).
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
let tournamentId = '809346e9-3d71-4aa8-9938-0ea566a0ed11';
let tournamentOwners = ['385ad06e-95a5-4a1e-811a-d7ef242a3ea2', 'f8f55fd8-2ca8-46d1-9f39-82f72fe4e2c4'];
let limit = 10;
let cursor = null;
let overrideExpiry = null;
let result: nkruntime.TournamentRecordList;

try {
  result = nk.tournamentRecordsList(tournamentId, tournamentOwners, limit, cursor, overrideExpiry);
} catch(error) {
    // Handle error
}

tournamentRecordWrite

Submit a score and optional subscore to a tournament leaderboard. If the tournament has been configured with join required this will fail unless the owner has already joined the tournament.

Parameters
NameDefaultDescription
id string REQUIREDThe unique identifier for the tournament leaderboard to submit to.
owner string REQUIREDThe owner of this score submission. Mandatory field.
username stringThe owner username of this score submission, if it's a user.
score number0The score to submit.
Returns
NameDescription
metadata objectThe metadata you want associated to this submission. Some good examples are weather conditions for a racing game.
result nkruntime.LeaderboardRecordThe newly created leaderboard record.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
let id = '4ec4f126-3f9d-11e7-84ef-b7c182b36521';
let owner = '4c2ae592-b2a7-445e-98ec-697694478b1c';
let username = '02ebb2c8';
let score = 10;
let subscore = 0;

let metadata = {
  weather_conditions = 'rain',
};

try {
  nk.tournamentRecordWrite(categoryStart, categoryEnd, startTime, endTime, limit);
} catch (error) {
  // Handle error
}

tournamentsGetId

Fetch one or more tournaments by ID.

Parameters
NameDefaultDescription
ids string REQUIREDThe table array of tournament ids.
Returns
NameDescription
result nkruntime.Tournament[]Array of tournament records.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
let tournamentIds = [
  '3ea5608a-43c3-11e7-90f9-7b9397165f34',
  '447524be-43c3-11e7-af09-3f7172f05936',
]

let owner = 'leaderboard-record-owner';
let username = 'myusername';
let tournaments: nkruntime.Tournament[];

try {
  tournaments = nk.tournamentsGetId(id, owner, username);
} catch (error) {
  // Handle error
}

Users

multiUpdate

Update account, storage, and wallet information simultaneously.

Parameters
NameDefaultDescription
accountUpdates nkruntime.AccountUpdate REQUIREDArray of account information to be updated.
storageWrites nkruntime.StorageWriteRequest REQUIREDArray of storage objects to be updated.
walletUpdates nkruntime.WalletUpdate REQUIREDArray of wallet updates to be made.
updateLedger boolfalseWhether to record this wallet update in the ledger.
Returns
NameDescription
storageWriteAcks nkruntime.StorageWriteAckA list of acks with the version of the written objects.
walletUpdateAcks nkruntime.WalletUpdateResultA list of wallet updates results.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
let accountUpdates: nkruntime.UserUpdateAccount[];
let storageWrites: nkruntime.StorageWriteRequest[];
let walletUpdates: nkruntime.WalletUpdate[];
let updateLedger = true;

try {
  const result = nk.multiUpdate(accountUpdates, storageWrites, walletUpdates, updateLedger);
  logger.info("Storage Acks: " + result.storageWriteAcks.length);
  logger.info("Wallet Acks: " + result.walletUpdateAcks.length);
} catch (error) {
  // handle error
}

usersBanId

Ban one or more users by ID.

Parameters
NameDefaultDescription
userIds string REQUIREDAn array of user IDs to ban.
Returns
NameDescription
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
let userIds = [
  '3ea5608a-43c3-11e7-90f9-7b9397165f34',
  '447524be-43c3-11e7-af09-3f7172f05936',
];

try {
  nk.usersBanId(userIds);
} catch (error) {
  // Handle error
}

usersGetId

Fetch one or more users by ID.

Parameters
NameDefaultDescription
userIds REQUIREDAn array of user IDs to fetch.
Returns
NameDescription
users nkruntime.User[]A list of user record objects.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
let userIds = [
  '3ea5608a-43c3-11e7-90f9-7b9397165f34',
  '447524be-43c3-11e7-af09-3f7172f05936',
];

let users: nkruntime.Users[];

try {
  users = nk.usersGetId(userIds);
} catch (error) {
  // Handle error
}

usersGetRandom

Fetch one or more users randomly.

Parameters
NameDefaultDescription
count number REQUIREDThe number of users to fetch.
Returns
NameDescription
users nkruntime.User[]A list of user record objects.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
let users: nkruntime.Users[];

try {
  users = nk.usersGetRandom(100);
} catch (error) {
  // Handle error
}

usersGetUsername

Fetch one or more users by username.

Parameters
NameDefaultDescription
usernames REQUIREDAn array of usernames to fetch.
Returns
NameDescription
users nkruntime.User[]A list of user record objects.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
let usernames = [
  'b7865e7e',
  'c048ba7a',
];

let users: nkruntime.Users[];

try {
  users = nk.usersGetUsername(usernames);
} catch (error) {
  // Handle error
}

usersUnbanId

Unban one or more users by ID.

Parameters
NameDefaultDescription
userIds string REQUIREDAn array of user IDs to unban.
Returns
NameDescription
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
let userIds = [
  '3ea5608a-43c3-11e7-90f9-7b9397165f34',
  '447524be-43c3-11e7-af09-3f7172f05936',
];

try {
  nk.usersUnbanId(userIds);
} catch (error) {
  // Handle error
}

Utils

aes128Decrypt

Decrypt an aes128 encrypted string.

Parameters
NameDefaultDescription
input string REQUIREDThe string to be decrypted.
key string REQUIREDThe 16 Byte decryption key.
Returns
NameDescription
clearText stringThe deciphered input.
error errorAn optional error value if an error occurred.
1
2
3
4
5
try {
  let clearText = nk.aes128Decrypt('48656C6C6F20776F726C64', 'goldenbridge_key');
} catch (error) {
  // Handle error
}

aes128Encrypt

aes128 encrypt a string input.

Parameters
NameDefaultDescription
input string REQUIREDThe string which will be aes128 encrypted.
key string REQUIREDThe 16 Byte encryption key.
Returns
NameDescription
cipherText stringThe ciphered input.
error errorAn optional error value if an error occurred.
1
2
3
4
5
try {
  let cipherText = nk.aes128Encrypt('Hello world', 'goldenbridge_key');
} catch (error) {
  // Handle error
}

aes256Decrypt

Decrypt an aes256 encrypted string.

Parameters
NameDefaultDescription
input string REQUIREDThe string to be decrypted.
key string REQUIREDThe 32 Byte decryption key.
Returns
NameDescription
clearText stringThe deciphered input.
error errorAn optional error value if an error occurred.
1
2
3
4
5
try {
  let clearText = nk.aes256Decrypt('48656C6C6F20776F726C64', 'goldenbridge_key');
} catch (error) {
  // Handle error
}

aes256Encrypt

aes256 encrypt a string input.

Parameters
NameDefaultDescription
input string REQUIREDThe string which will be aes256 encrypted.
key string REQUIREDThe 32 Byte encryption key.
Returns
NameDescription
cipherText stringThe ciphered input.
error errorAn optional error value if an error occurred.
1
2
3
4
5
try {
  let cipherText = nk.aes256Encrypt('Hello world', 'goldenbridge_key');
} catch (error) {
  // Handle error
}

aesDecrypt

aes decrypt a base 64 encoded string input.

Parameters
NameDefaultDescription
keySize int REQUIREDThe size in bytes of the decryption key.
input string REQUIREDThe string which will be decrypted.
key string REQUIREDThe encryption key.
Returns
NameDescription
clearText stringThe deciphered and decoded input.
error errorAn optional error value if an error occurred.
1
2
3
4
5
try {
  let clearText = nk.aesDecrypt(16, '48656C6C6F20776F726C64', 'goldenbridge_key');
} catch (error) {
  // Handle error
}

aesEncrypt

aes encrypt a string input and return the cipher text base64 encoded.

Parameters
NameDefaultDescription
keySize int REQUIREDThe size in bytes of the encryption key.
input string REQUIREDThe string which will be encrypted.
key string REQUIREDThe encryption key.
Returns
NameDescription
cipherText stringThe ciphered and base64 encoded input.
error errorAn optional error value if an error occurred.
1
2
3
4
5
try {
  let cipherText = nk.aesEncrypt(16, 'Hello world', 'goldenbridge_key');
} catch (error) {
  // Handle error
}

base16Decode

Decode a base16 encoded string.

Parameters
NameDefaultDescription
input string REQUIREDThe string to be decoded.
Returns
NameDescription
out stringDecoded string.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
let result: string;

try {
  result = nk.base16Decode('48656C6C6F20776F726C64');
} catch (error) {
  // Handle error
}

base16Encode

base16 encode a string input.

Parameters
NameDefaultDescription
input string REQUIREDThe string to be encoded.
Returns
NameDescription
out stringEncoded string.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
let result: string;

try {
  result = nk.base16Encode('Hello World');
} catch (error) {
  // Handle error
}

base64Decode

Decode a base64 encoded string.

Parameters
NameDefaultDescription
input string REQUIREDThe string which will be base64 decoded.
Returns
NameDescription
out stringDecoded string.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
let result: string;

try {
  result = nk.base64Decode('SGVsbG8gd29ybGQ=');
} catch (error) {
  // Handle error
}

base64Encode

Base64 encode a string input.

Parameters
NameDefaultDescription
input string REQUIREDThe string which will be base64 encoded.
Returns
NameDescription
out stringEncoded string.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
let result: string;

try {
  result = nk.base64Encode('Hello World');
} catch (error) {
  // Handle error
}

base64UrlDecode

Decode a base64 URL encoded string.

Parameters
NameDefaultDescription
input string REQUIREDThe string to be decoded.
Returns
NameDescription
out stringDecoded string.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
let result: string;

try {
  result = nk.base64UrlDecode('SGVsbG8gd29ybGQ=');
} catch (error) {
  // Handle error
}

base64UrlEncode

Base64 URL encode a string input.

Parameters
NameDefaultDescription
input string REQUIREDThe string which will be base64 URL encoded.
Returns
NameDescription
out stringEncoded string.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
let result: string;

try {
  result = nk.base64UrlEncode('Hello World');
} catch (error) {
  // Handle error
}

bcryptCompare

Compare hashed input against a plaintext input.

Parameters
NameDefaultDescription
input string REQUIREDThe bcrypted input string.
plaintext string REQUIREDPlaintext input to compare against.
Returns
NameDescription
result boolTrue if they are the same, false otherwise.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
let result: boolean;

try {
  result = nk.bcryptCompare('$2a$04$bl3tac7Gwbjy04Q8H2QWLuUOEkpoNiAeTxazxi4fVQQRMGbMaUHQ2', '123456');
} catch (error) {
  // Handle error
}

bcryptHash

Generate one-way hashed string using bcrypt.

Parameters
NameDefaultDescription
input string REQUIREDThe input string to bcrypt.
Returns
NameDescription
hash stringHashed string.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
let result: string;

try {
  result = nk.bcryptHash('Hello World');
} catch (error) {
  // Handle error
}

binaryToString

Convert binary data to string.

Parameters
NameDefaultDescription
data Uint REQUIREDThe binary data to be converted.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
let result: string;

try {
  result = nk.binaryToString('\x48\x65\x72\x6F\x69\x63\x4C\x61\x62\x73');
} catch (error) {
  // Handle error
}

cronNext

Parses a CRON expression and a timestamp in UTC seconds, and returns the next matching timestamp in UTC seconds.

Parameters
NameDefaultDescription
expression string REQUIREDA valid CRON expression in standard format, for example "0 0 * * *" (meaning at midnight).
timestamp number REQUIREDA time value expressed as UTC seconds.
Returns
NameDescription
next_ts numberThe next UTC seconds timestamp (number) that matches the given CRON expression, and is immediately after the given timestamp.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
let result: number;

try {
  let expr = '0 0 * * 1';
  let ts = Math.floor(Date.now() / 1000);
  result = nk.cronNext(expr, ts);
} catch (error) {
  // Handle error
}

fileRead

Read file from user device.

Parameters
NameDefaultDescription
relPath string REQUIREDRelative path to the file to be read.
Returns
NameDescription
fileRead stringThe read file contents.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
let result: string;
let relativePath = '<RelativePath>';

try {
  result = nk.fileRead(relativePath);
} catch (error) {
  // Handle error
}

hmacSHA256Hash

Create a HMAC-SHA256 hash from input and key.

Parameters
NameDefaultDescription
input string REQUIREDThe input string to hash.
key string REQUIREDThe hashing key.
Returns
NameDescription
mac stringHashed input as a string using the key.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
let hash: string;

try {
  hash = nk.hmacSha256Hash('some input text to hash', 'some_key');
} catch (error) {
  // Handle error
}

httpRequest

Send a HTTP request that returns a data type containing the result of the HTTP response.

Parameters
NameDefaultDescription
url string REQUIREDThe URL of the web resource to request.
method string REQUIREDThe HTTP method verb used with the request.
headers string REQUIREDA table of headers used with the request.
content string REQUIREDThe bytes to send with the request.
timeout number5000Timeout of the request in milliseconds.
Returns
NameDescription
returnVal nkruntime.httpResponseCode, Headers, and Body response values for the HTTP response.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
let method: nkruntime.RequestMethod = 'get';

let headers = {
  'Content-Type': 'application/json',
  'Accept': 'application/json',
};

let body = JSON.stringify({});
let res = {} as nkruntime.HttpResponse;

try {
  res = nk.httpRequest('https://google.com', method, headers, body);
} catch (error) {
  // Handle error
}

jwtGenerate

Generate a JSON Web Token.

Parameters
NameDefaultDescription
signingMethod string REQUIREDThe signing method to be used, either HS256 or RS256.
claims REQUIREDThe JWT payload.
Returns
NameDescription
signedToken stringThe newly generated JWT.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
let result: string
let signingKey = 'goldenbridge_key';
let claims = { email: 'test@heroiclabs.com' }

try {
  result = nk.jwtGenerate('HS256', signingKey, claims);
} catch (error) {
  // Handle error
}

md5Hash

Create an md5 hash from the input.

Parameters
NameDefaultDescription
input string REQUIREDThe input string to hash.
Returns
NameDescription
hash stringA string with the md5 hash of the input.
error errorAn optional error value if an error occurred.
1
2
let input = 'somestring';
let hashed = nk.md5Hash(input);

rsaSHA256Hash

Create a RSA encrypted SHA256 hash from the input.

Parameters
NameDefaultDescription
input string REQUIREDThe input string to hash.
key string REQUIREDThe RSA private key.
Returns
NameDescription
signature stringA string with the RSA encrypted SHA256 hash of the input.
error errorAn optional error value if an error occurred.
1
const cipherText = nk.rsaSha256Hash("Hello world", "<RSAPrivateKey>")

sha256Hash

Create an SHA256 hash from the input.

Parameters
NameDefaultDescription
input string REQUIREDThe input string to hash.
Returns
NameDescription
hash stringA string with the SHA256 hash of the input.
error errorAn optional error value if an error occurred.
1
const cipherText = nk.sha256Hash("Hello world");

sqlExec

Execute an arbitrary SQL query and return the number of rows affected. Typically an "INSERT", "DELETE", or "UPDATE" statement with no return columns.

Parameters
NameDefaultDescription
query string REQUIREDA SQL query to execute.
parameters any REQUIREDArbitrary parameters to pass to placeholders in the query.
Returns
NameDescription
rowsAffected numberA list of matches matching the parameters criteria.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
let query = 'DELETE FROM leaderboard_record WHERE expires_at > 0 AND expires_at <= $1';
let parameters = [ Math.floor(Date.now() / 1000) ];
let result: nkruntime.SqlExecResult;

try {
  result = nk.sqlExec(query, parameters);
} catch (error) {
  // Handle error
}

sqlQuery

Execute an arbitrary SQL query that is expected to return row data. Typically a "SELECT" statement.

Parameters
NameDefaultDescription
query string REQUIREDA SQL query to execute.
parameters any REQUIREDArbitrary parameters to pass to placeholders in the query.
Returns
NameDescription
result nkruntime.SqlQueryResultAn array of rows and the respective columns and values.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
let query = 'SELECT username, create_time FROM users ORDER BY create_time DESC LIMIT 100';
let parameters: any[] = [];
let rows: nkruntime.SqlQueryResult = [];

try {
  rows = nk.sqlQuery(query, parameters);
} catch (error) {
  // Handler error
}

stringToBinary

Convert string data to binary.

Parameters
NameDefaultDescription
str string REQUIREDThe string to be converted.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
let result: Uint8Array

try {
  result = nk.stringToBinary('HeroicLabs');
} catch (error) {
  // Handle error
}

uuidV4

Generate a version 4 UUID in the standard 36-character string representation.

Parameters
NameDefaultDescription
Returns
NameDescription
uuid stringThe newly generated version 4 UUID identifier string.
error errorAn optional error value if an error occurred.
1
let uuid = nk.uuidV4();

Wallets

walletLedgerList

List all wallet updates for a particular user from oldest to newest.

Parameters
NameDefaultDescription
userId string REQUIREDThe ID of the user to list wallet updates for.
limit number100Limit number of results.
cursor string REQUIREDPagination cursor from previous result. If none available set to nil or "" (empty string).
Returns
NameDescription
runtimeItems nkruntime.WalletLedgerItem[]A JavaScript Object containing wallet entries with Id, UserId, CreateTime, UpdateTime, Changeset, Metadata parameters.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
let userId = '8f4d52c7-bf28-4fcf-8af2-1d4fcf685592';
let results: nkruntime.WalletLedgerList[];

try {
    results = nk.walletLedgerList(userId);
} catch (error) {
    // Handle error
}

walletLedgerUpdate

Update the metadata for a particular wallet update in a user's wallet ledger history. Useful when adding a note to a transaction for example.

Parameters
NameDefaultDescription
itemId string REQUIREDThe ID of the wallet ledger item to update.
metadata object REQUIREDThe new metadata to set on the wallet ledger item.
Returns
NameDescription
updateWalletLedger nkruntime.WalletLedgerItemThe updated wallet ledger item.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
let id = '2745ba53-4b43-4f83-ab8f-93e9b677f33a';

let metadata = {
  gameResult: 'loss'
};

let result: nkruntime.WalletLedgerResult;

try {
    result = nk.walletLedgerUpdate(id, metadata);
} catch (error) {
    // Handle error
}

walletsUpdate

Update one or more user wallets with individual changesets. This function will also insert a new wallet ledger item into each user's wallet history that tracks their update.

Parameters
NameDefaultDescription
updates nkruntime.WalletUpdate REQUIREDThe set of user wallet update operations to apply.
updateLedger boolfalseWhether to record this update in the ledger.
Returns
NameDescription
updateWallets nkruntime.WallateUpdateResultA list of wallet update results.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
let updates: nkruntime.WalletUpdate[] = [
  {
    userId: '8f4d52c7-bf28-4fcf-8af2-1d4fcf685592',
    changeset: {
      coins: 10, // Add 10 coins to the user's wallet.
      gems: -5,  // Remove 5 gems from the user's wallet.
    },
    metadata: {
      gameResult: 'won',
    }
  }
];
  
let results: nkruntime.WalletUpdateResult[];

try {
    results = nk.walletsUpdate(updates);
} catch (error) {
    // Handle error
}

walletUpdate

Update a user's wallet with the given changeset.

Parameters
NameDefaultDescription
userId string REQUIREDThe ID of the user whose wallet to update.
changeset REQUIREDThe set of wallet operations to apply.
metadata objectAdditional metadata to tag the wallet update with.
updateLedger boolfalseWhether to record this update in the ledger.
Returns
NameDescription
result nkruntime.WalletUpdateResultThe changeset after the update and before to the update, respectively.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
let user_id = '8f4d52c7-bf28-4fcf-8af2-1d4fcf685592';

let changeset = {
  coins: 10, // Add 10 coins to the user's wallet.
  gems: -5,   // Remove 5 gems from the user's wallet.
};

let metadata = {
  gameResult: 'won'
};

let result: nkruntime.WalletUpdateResult;

try {
    result = nk.walletUpdate(user_id, changeset, metadata, true);
} catch (error) {
    // Handle error
}