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 Basics documentation.
This page lists all functions available within layerG 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.
The creation of custom tables is strongly discouraged.
The context object represents information about the server and requester.
userId string OPTIONAL
User ID to fetch information for. Must be valid UUID.
onchainId string OPTIONAL
User wallet address to fetch information for Account. Must be a valid wallet address.
Returns
Name
Description
account *api.Account
All account information including wallet, device IDs and more.
error error
An optional error value if an error occurred.
Note: If both userId and onchainId are provided, userId will take precedence. Leave userId empty if you want to fetch account information by onchainId and vice versa.
account,err:= lg.AccountGetId(ctx,"8f4d52c7-bf28-4fcf-8af2-1d4fcf685592","0x1234567890123456789012345678901234567890") if err != nil { logger.WithField("err", err).Error("Get accounts error.") return } logger.Info("Wallet is: %v", account.Wallet)
List all friends, invites, invited, and blocked which belong to a user.
Parameters
Name
Default
Description
ctx context.Context REQUIRED
The context object represents information about the server and requester.
userId string REQUIRED
The ID of the user whose friends, invites, invited, and blocked you want to list.
limit int REQUIRED
The number of friends to retrieve in this page of results. No more than 100 limit allowed per result.
state int
The state of the friendship with the user. If unspecified this returns friends in all states for the user.
cursor string REQUIRED
Pagination cursor from previous result. Set to "" to start fetching from the beginning.
Returns
Name
Description
friends []*api.Friend
The user information for users that are friends of the current user.
cursor string
An optional next page cursor that can be used to retrieve the next page of records (if any). Will be set to "" or nil when fetching last available page.
error error
An optional error value if an error occurred.
userID:="b1aafe16-7540-11e7-9738-13777fcc7cd8" limit:=100 state:=0 cursor:="" friends,err:= lg.FriendsList(ctx, userID, limit,&state, cursor) if err != nil { logger.WithField("err", err).Error("lg.FriendsList error.") return } for _,friend:= range friends { // States are: friend(0), invite_sent(1), invite_received(2), blocked(3) logger.Info("Friend username %s has state %d", friend.GetUser().Username, friend.GetState()) }
The user information for users that are friends of friends the current user.
cursor string
An optional next page cursor that can be used to retrieve the next page of records (if any). Will be set to "" or nil when fetching last available page.
The context object represents information about the server and requester.
groupIds []string REQUIRED
An array of strings of the IDs for the groups to get.
Returns
Name
Description
getGroups []*api.Group
An array of groups with their fields.
error error
An optional error value if an error occurred.
groupID:="dcb891ea-a311-4681-9213-6741351c9994" groups,err:= lg.GroupsGetId(ctx,[] string { groupID }) if err != nil { logger.WithField("err", err).Error("Groups get by ID error.") return }
The context object represents information about the server and requester.
name string
Search for groups that contain this value in their name. Cannot be combined with any other filter.
langTag string
Filter based upon the entered language tag.
members int
Search by number of group members.
open bool
Filter based on whether groups are Open or Closed.
limit int
Return only the required number of groups denoted by this limit value.
cursor string
Pagination cursor from previous result. Don't set to start fetching from the beginning.
Returns
Name
Description
groups []*api.Group
A list of groups.
cursor string
An optional next page cursor that can be used to retrieve the next page of records (if any). Will be set to "" or nil when fetching last available page.
error error
An optional error value if an error occurred.
groupName:="LayerG" langTag:="en" members:=10 open:=true limit:=100 cursor:="" list, cursor,err:= lg.GroupsList(ctx, groupName, langTag,&members,&open, limit, cursor) if err != nil { logger.WithField("err", err).Error("Group list error.") }else{ for _,g:= range list { logger.Info("ID %s - open? %b cursor: %s", g.Id, g.Open, cursor) } }
List all members, admins and superadmins which belong to a group. This also lists incoming join requests.
Parameters
Name
Default
Description
ctx context.Context REQUIRED
The context object represents information about the server and requester.
groupId string REQUIRED
The ID of the group to list members for.
limit int REQUIRED
Return only the required number of users denoted by this limit value.
state int REQUIRED
Return only the users matching this state value, '0' for superadmins for example.
cursor string REQUIRED
Pagination cursor from previous result. Don't set to start fetching from the beginning.
Returns
Name
Description
error error
An optional error value if an error occurred.
groupID:="dcb891ea-a311-4681-9213-6741351c9994" groupUserList,err:= lg.GroupUsersList(ctx, groupID) if err != nil { logger.WithField("err", err).Error("Group users list error.") return } for _,member:= range groupUserList { // States are => 0: Superadmin, 1: Admin, 2: Member, 3: Requested to join logger.Info("Member username %s has state %d", member.GetUser().Username, member.GetState()) }
List all groups which a user belongs to and whether they've been accepted or if it's an invite.
Parameters
Name
Default
Description
ctx context.Context REQUIRED
The context object represents information about the server and requester.
userId string REQUIRED
The ID of the user to list groups for.
limit int REQUIRED
The maximum number of entries in the listing.
state int
The state of the user within the group. If unspecified this returns users in all states.
cursor string REQUIRED
Pagination cursor from previous result. Don't set to start fetching from the beginning.
Returns
Name
Description
cursor string
An optional next page cursor that can be used to retrieve the next page of records (if any). Will be set to "" or nil when fetching last available page.
error error
An optional error value if an error occurred.
userID:="dcb891ea-a311-4681-9213-6741351c9994" groups,err:= lg.UserGroupsList(ctx, userID) if err != nil { logger.WithField("err", err).Error("User groups list error.") return } for _,group:= range groups { logger.Printf("User has state %d in group %s.", group.GetState(), group.GetGroup().Name) }
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
Name
Default
Description
ctx context.Context REQUIRED
The context object represents information about the server and requester.
leaderboardID string REQUIRED
The unique identifier for the new leaderboard. This is used by clients to submit scores.
authoritative bool REQUIRED
false
Mark the leaderboard as authoritative which ensures updates can only be made via the Go runtime. No client can submit a score directly.
sortOrder string REQUIRED
The sort order for records in the leaderboard. Possible values are "asc" or "desc".
operator string REQUIRED
The operator that determines how scores behave when submitted. Possible values are "best", "set", or "incr".
resetSchedule string REQUIRED
The 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 map[string]interface REQUIRED
The metadata you want associated to the leaderboard. Some good examples are weather conditions for a racing game.
enableRanks bool REQUIRED
Whether to enable rank values for the leaderboard.
Returns
Name
Description
error error
An optional error value if an error occurred.
id:="4ec4f126-3f9d-11e7-84ef-b7c182b36521" authoritative:=false sortOrder:="desc" operator:="best" resetSchedule:="0 0 * * 1" metadata:= map[string]interface{}{ "weather_conditions":"rain", } enableRanks =false// Set to true to enable rank computation on leaderboard records. iferr:= lg.LeaderboardCreate(ctx, id, authoritative, sortOrder, operator, resetSchedule, metadata, enableRanks); err != nil { logger.WithField("err", err).Error("Leaderboard create error.") }
Find leaderboards which have been created on the server. Leaderboards can be filtered with categories.
Parameters
Name
Default
Description
limit int REQUIRED
Return only the required number of leaderboards denoted by this limit value.
cursor string
Pagination cursor from previous result. Don't set to start fetching from the beginning.
Returns
Name
Description
leaderboardList *api.LeaderboardList
A list of leaderboard results and possibly a cursor. If cursor is empty/nil there are no further results.
error error
An optional error value if an error occurred.
limit:=100// Number to list per page. cursor:="" list,err:= lg.LeaderboardList(ctx, limit, cursor) if err != nil { logger.WithField("err", err).Error("Leaderboard list error.") }else{ for _,l:= range list.Leaderboards{ logger.Info("ID %s - can enter? %b", l.Id, l.CanEnter) } }
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
Name
Default
Description
ctx context.Context REQUIRED
The context object represents information about the server and requester.
id string REQUIRED
The unique identifier for the leaderboard to list.
owners []string REQUIRED
Array of owners to filter to.
limit int REQUIRED
The maximum number of records to return (Max 10,000).
cursor string
Pagination cursor from previous result. Don't set to start fetching from the beginning.
overrideExpiry int REQUIRED
Records with expiry in the past are not returned unless within this defined limit. Must be equal or greater than 0.
Returns
Name
Description
records []*api.LeaderboardRecord
A page of leaderboard records.
ownerRecords []*api.LeaderboardRecord
A list of owner leaderboard records (empty if the owners input parameter is not set).
nextCursor string
An optional next page cursor that can be used to retrieve the next page of records (if any).
prevCursor string
An optional previous page cursor that can be used to retrieve the previous page of records (if any).
error error
An optional error value if an error occurred.
id:="4ec4f126-3f9d-11e7-84ef-b7c182b36521" ownerIDs:=[]string{} limit:=10 cursor:="" expiry:=int64(0) records, ownerRecords, prevCursor, nextCursor,err:= lg.LeaderboardRecordsList(ctx, id, ownerIDs, limit, cursor, expiry) if err != nil { logger.WithField("err", err).Error("Leaderboard record list error.") }
Build a cursor to be used with leaderboardRecordsList to fetch records starting at a given rank. Only available if rank cache is not disabled for the leaderboard.
Parameters
Name
Default
Description
leaderboardID string REQUIRED
The unique identifier of the leaderboard.
rank int REQUIRED
The rank to start listing leaderboard records from.
overrideExpiry int REQUIRED
Records with expiry in the past are not returned unless within this defined limit. Must be equal or greater than 0.
Returns
Name
Description
leaderboardListCursor string
A string cursor to be used with leaderboardRecordsList.
error error
An optional error value if an error occurred.
id:="4ec4f126-3f9d-11e7-84ef-b7c182b36521" rank:=int64(1) expiry:=int64(0) cursor,err:= lg.LeaderboardRecordsListCursorFromRank(ctx, id, rank, expiry) if err != nil { logger.WithField("err", err).Error("Leaderboard record list cursor from rank error.") }
Use the preconfigured operator for the given leaderboard to submit a score for a particular user.
Parameters
Name
Default
Description
ctx context.Context REQUIRED
The context object represents information about the server and requester.
id string REQUIRED
The unique identifier for the leaderboard to submit to.
owner string REQUIRED
The owner of this score submission.
username string REQUIRED
The owner username of this score submission, if it's a user.
score int REQUIRED
The score to submit.
subscore int
A secondary subscore parameter for the submission.
metadata map[string]interface
The metadata you want associated to this submission. Some good examples are weather conditions for a racing game.
overrideOperator *int REQUIRED
An override operator for the new record. The accepted values include: 0 (no override), 1 (best), 2 (set), 3 (incr), 4 (decr). Passing nil is the same as passing a pointer to 0 (no override), which uses the default leaderboard operator.
Returns
Name
Description
record *api.LeaderboardRecord
The newly created leaderboard record.
error error
An optional error value if an error occurred.
id:="4ec4f126-3f9d-11e7-84ef-b7c182b36521" ownerID:="4c2ae592-b2a7-445e-98ec-697694478b1c" username:="02ebb2c8" score:=int64(10) subscore:=int64(0) metadata:= map[string]interface{}{ "weather_conditions":"rain", } overrideOperator:=new(int)// Optional operator to override the one set in the leaderboard. nil or 0 means no override if record,err:= lg.LeaderboardRecordWrite(ctx, id, ownerID, username, score, subscore, metadata, overrideOperator); err != nil { logger.WithField("err", err).Error("Leaderboard record write error.") }
List currently running realtime multiplayer matches and optionally filter them by authoritative mode, label, and current participant count.
Parameters
Name
Default
Description
ctx context.Context REQUIRED
The context object represents information about the server and requester.
limit int
100
The maximum number of matches to list.
authoritative bool
false
Set true to only return authoritative matches, false to only return relayed matches.
label string REQUIRED
A label to filter authoritative matches by. Default "" means any label matches.
minSize int REQUIRED
Inclusive lower limit of current match participants.
maxSize int REQUIRED
Inclusive upper limit of current match participants.
query string REQUIRED
Additional query parameters to shortlist matches.
Returns
Name
Description
match []*api.Match
A list of matches matching the parameters criteria.
error error
An optional error value if an error occurred.
// List at most 10 matches, not authoritative, and that // have between 2 and 4 players currently participating. limit:=10 isAuthoritative:=false label:="" minSize:=2 maxSize:=4 matches,err:= lg.MatchList(ctx, limit, isAuthoritative, label, minSize, maxSize,"") if err != nil { logger.WithField("err", err).Error("Match list error.") }else{ for _,match:= range matches { logger.Info("Found match with id: %s", match.GetMatchId()) } }
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
Name
Default
Description
ctx context.Context REQUIRED
Context object represents information about the match and server for information purposes.
id string REQUIRED
The user ID or session ID to send a reservation signal for.
data string REQUIRED
An arbitrary input supplied by the runtime caller of the signal.
Returns
Name
Description
data string
Arbitrary data to return to the runtime caller of the signal. May be a string or nil.
error error
An optional error value if an error occurred.
matchId:="52f02f3e-5b48-11eb-b182-0f5058adfcc6" data:="<Data>" result,err:= lg.MatchSignal(ctx, matchId, data) if err != nil { logger.WithField("err", err).Error("Match signal error.") }else{ logger.Info("Match signal result: %s", result) }
User ID of the caller, will apply permissions checks of the user. If empty, defaults to system user and permissions are bypassed.
queryString string REQUIRED
Query to filter index entries.
limit int REQUIRED
Maximum number of results to be returned.
order []string
The storage object fields to sort the query results by. The prefix '-' before a field name indicates descending order. All specified fields must be indexed and sortable.
Write one or more objects by their collection/keyname and optional user.
Parameters
Name
Default
Description
ctx context.Context REQUIRED
The context object represents information about the server and requester.
objectIds []*runtime.StorageWrite REQUIRED
An array of object identifiers to be written.
Returns
Name
Description
acks []*api.StorageObjectAck
A list of acks with the version of the written objects.
error error
An optional error value if an error occurred.
userID:="4ec4f126-3f9d-11e7-84ef-b7c182b36521" objectIDs:=[]*runtime.StorageWrite{&runtime.StorageWrite{ Collection:"save", Key:"save1", UserID: userID, Value:"{}",// Value must be a valid encoded JSON object. },&runtime.StorageWrite{ Collection:"save", Key:"save2", UserID: userID, Value:"{}",// Value must be a valid encoded JSON object. },&runtime.StorageWrite{ Collection:"public", Key:"save3", UserID: userID, Value:"{}",// Value must be a valid encoded JSON object. PermissionRead:2, PermissionWrite:1, },&runtime.StorageWrite{ Collection:"public", Key:"save4", UserID: userID, Value:"{}",// Value must be a valid encoded JSON object. Version:"*", PermissionRead:2, PermissionWrite:1, }, } _,err:= lg.StorageWrite(ctx, objectIDs) if err != nil { logger.WithField("err", err).Error("Storage write error.") }
The Type of stream, '2' for a chat channel for example.
subject string REQUIRED
The primary stream subject, typically a user ID.
subcontext string REQUIRED
A secondary subject, for example for direct chat between two users.
label string REQUIRED
Meta-information about the stream, for example a chat room name.
data string REQUIRED
The data to send.
presences []runtime.Presence
all
Array of presences to receive the sent data.
reliable bool REQUIRED
Whether the sender has been validated prior.
Returns
Name
Description
error error
An optional error value if an error occurred.
mode:=uint8(123) label:="label" // Data does not have to be JSON, but it's a convenient format. data:="{\"some\":\"data\"}" lg.StreamSend(mode,"","", label, data, nil)
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
Name
Default
Description
ctx context.Context REQUIRED
The context object represents information about the server and requester.
id string REQUIRED
The unique identifier for the tournament to update.
owner string REQUIRED
The owner of the records to increment the count for.
count int REQUIRED
The number of attempt counts to increment. Can be negative to decrease count.
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
Name
Default
Description
ctx context.Context REQUIRED
The context object represents information about the server and requester.
id string REQUIRED
The unique identifier for the new tournament. This is used by clients to submit scores.
authoritative bool REQUIRED
Whether the tournament created is server authoritative.
sortOrder string REQUIRED
The sort order for records in the tournament. Possible values are "asc" or "desc".
operator string REQUIRED
The operator that determines how scores behave when submitted. The possible values are "best", "set", or "incr".
resetSchedule string REQUIRED
The 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 map[string]interface REQUIRED
The metadata you want associated to the tournament. Some good examples are weather conditions for a racing game.
title string REQUIRED
The title of the tournament.
description string REQUIRED
The description of the tournament.
category int REQUIRED
A category associated with the tournament. This can be used to filter different types of tournaments. Between 0 and 127.
startTime int
The start time of the tournament. Leave empty for immediately or a future time.
endTime int
never
The 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 int REQUIRED
The 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 int REQUIRED
Maximum size of participants in a tournament.
maxNumScore int REQUIRED
1000000
Maximum submission attempts for a tournament record.
joinRequired bool REQUIRED
false
Whether the tournament needs to be joined before a record write is allowed.
enableRanks bool REQUIRED
Whether to enable rank values for the tournament.
Returns
Name
Description
error error
An optional error value if an error occurred.
id:="4ec4f126-3f9d-11e7-84ef-b7c182b36521" authoritative:=false sortOrder:="desc"// One of: "desc", "asc". operator:="best"// One of: "best", "set", "incr". resetSchedule:="0 12 * * *"// Noon UTC each day. metadata:= map[string]interface{}{ "weather_conditions":"rain", } title:="Daily Dash" description:="Dash past your opponents for high scores and big rewards!" category:=1 startTime:=0// Start now. endTime:=0// Never end, repeat the tournament each day forever. duration:=3600// In seconds. maxSize:=10000// First 10,000 players who join. maxNumScore:=3// Each player can have 3 attempts to score. joinRequired:=true// Must join to compete. enableRanks:=true// Set to true to enable rank computation on leaderboard records. err:= lg.TournamentCreate(ctx, id, authoritative, sortOrder, operator, resetSchedule, metadata, title, description, category, startTime, endTime, duration, maxSize, maxNumScore, joinRequired, enableRanks) if err != nil { logger.WithField("err", err).Error("Tournament create error.") }
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
Name
Default
Description
ctx context.Context REQUIRED
The context object represents information about the server and requester.
Find tournaments which have been created on the server. Tournaments can be filtered with categories and via start and end times.
Parameters
Name
Default
Description
ctx context.Context REQUIRED
The context object represents information about the server and requester.
categoryStart int REQUIRED
Filter tournaments with categories greater or equal than this value.
categoryEnd int REQUIRED
Filter tournaments with categories equal or less than this value.
startTime int REQUIRED
Filter tournaments that start after this time.
endTime int REQUIRED
Filter tournaments that end before this time.
limit int REQUIRED
10
Return only the required number of tournament denoted by this limit value.
cursor string
Pagination cursor from previous result. Don't set to start fetching from the beginning.
Returns
Name
Description
tournamentList []*api.TournamentList
A list of tournament results and possibly a cursor. If cursor is empty/nil there are no further results.
error error
An optional error value if an error occurred.
categoryStart:=1 categoryEnd:=2 startTime:=int(time.Now().Unix()) endTime:=0// All tournaments from the start time. limit:=100// Number to list per page. cursor:="" list,err:= lg.TournamentList(ctx, categoryStart, categoryEnd, startTime, endTime, limit, cursor) if err != nil { logger.WithField("err", err).Error("Tournament list error.") }else{ for _,t:= range list.Tournaments{ logger.Info("ID %s - can enter? %b", t.Id, t.CanEnter) } }
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
Name
Default
Description
ctx context.Context REQUIRED
The context object represents information about the server and requester.
tournamentId string REQUIRED
The ID of the tournament to list records for.
ownerIds []string REQUIRED
Array of owner IDs to filter results by.
limit int REQUIRED
Return only the required number of tournament records denoted by this limit value. Max is 10000.
cursor string
Pagination cursor from previous result. Don't set to start fetching from the beginning.
overrideExpiry int REQUIRED
Records with expiry in the past are not returned unless within this defined limit. Must be equal or greater than 0.
Returns
Name
Description
records []*api.LeaderboardRecord
A page of tournament records.
ownerRecords []*api.LeaderboardRecord
A list of owner tournament records (empty if the owners input parameter is not set).
prevCursor string
An optional previous page cursor that can be used to retrieve the previous page of records (if any).
nextCursor string
An optional next page cursor that can be used to retrieve the next page of records (if any).
error error
An optional error value if an error occurred.
id:="4ec4f126-3f9d-11e7-84ef-b7c182b36521" limit:=100 overrideExpiry:=0 records,err:= lg.TournamentRecordsList(ctx, id, limit, overrideExpiry) if err != nil { logger.WithField("err", err).Error("Tournament records list error.") }else{ for _,r:= range records { logger.Info("Leaderboard: %s, score: %d, subscore: %d", r.GetLeaderboardId(), r.Score, r.Subscore) } }
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
Name
Default
Description
ctx context.Context REQUIRED
The context object represents information about the server and requester.
id string REQUIRED
The unique identifier for the tournament leaderboard to submit to.
owner string REQUIRED
The owner of this score submission.
username string REQUIRED
The owner username of this score submission, if it's a user.
score int REQUIRED
The score to submit.
subscore int
A secondary subscore parameter for the submission.
metadata map[string]interface
The metadata you want associated to this submission. Some good examples are weather conditions for a racing game.
overrideOperator *int REQUIRED
An override operator for the new record. The accepted values include: 0 (no override), 1 (best), 2 (set), 3 (incr), 4 (decr). Passing nil is the same as passing a pointer to 0 (no override), which uses the default leaderboard operator.
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
Name
Default
Description
ctx context.Context REQUIRED
The context object represents information about the server and requester.
updates []*runtime.WalletUpdate REQUIRED
The set of user wallet update operations to apply.
updateLedger bool REQUIRED
false
Whether to record this update in the ledger.
Returns
Name
Description
updateWallets []runtime.WalletUpdateResult
A list of wallet update results.
error error
An optional error value if an error occurred.
updates:=[]*runtime.WalletUpdate{ &runtime.WalletUpdate{ UserID:"8f4d52c7-bf28-4fcf-8af2-1d4fcf685592", Changeset: map[string]interface{}{ "coins":10,// Add 10 coins to the user's wallet. "gems":-5,// Remove 5 gems from the user's wallet. }, Metadata: map[string]interface{}{ "game_result":"won", }, }, } err:= lg.WalletsUpdate(ctx, updates,true) if err != nil { logger.WithField("err", err).Error("Wallets update error.") }