Quickstart
Quickstart
Put your game code in separate .js files. Add storage to capabilities in game.json for this example.
// game.js, loaded with <script type="module" src="./game.js">
const session = await uniplays.ready()
console.log('Playing version', session.version)
if (uniplays.can('storage')) {
try {
const save = await uniplays.storage.get('progress')
const progress = save.value ?? { level: 1 }
await uniplays.storage.set('progress', progress, {
ifMatch: save.etag
})
} catch (error) {
// version_conflict means a newer save exists: reload it, merge, and save again.
console.warn('Could not save:', error.code)
}
}Reward pool, item buy offers and chance
Reward pool, item buy offers and chance
Optional features. Chance is closed for now. When a network does not offer a feature, the call fails with an error that names what is missing instead of hanging, so catch it and keep playing.
can('economy') and can('chance') only tell you what game.json declares, not what the network offers. A game that declares neither can skip this section. chance.verify() recomputes a result on the player’s device from the numbers a round published. It checks no signature, so never present its result as verified randomness.
economy.treasury: Read the reward pool: its balance, the current limits and the maximums.economy.awards: Read the awards already paid to this player and what today’s limit allows.npc.offers: Read the standing offers to buy items, with the units left today.npc.sell: Sell items the player owns into a standing offer. The player signs in their wallet.chance.rounds: List open chance rounds, with the rules table set at launch.chance.result: Read one entry’s state and the record needed to check its outcome.chance.enter: Enter an open round at its published entry price.chance.claim: Collect the prize or the refund a finished entry is owed.
Getting ready
3 methodsCall ready() first, before anything else. can() and session.on() answer at once; every other method returns a promise, so use await.
uniplays.ready()Waits for UniPlays to connect your game, then returns the session: gameId, version, bundleHash, locale, isGuest, capabilities, entitlements, protocol, and your published game.json.
SessionWaits for UniPlays to connect your game, then returns the session: gameId, version, bundleHash, locale, isGuest, capabilities, entitlements, protocol, and your published game.json.
uniplays.can(capability)Checks whether your game.json declares a capability.
booleanChecks whether your game.json declares a capability. Throws not_ready before ready() resolves. A declaration is not a promise the call will succeed: a declared method the network does not serve refuses by name rather than answering an empty result.
uniplays.game.version()The version of your game that is running now, with its release notes.
{ version, bundleHash, publishedAt, changelog }The version of your game that is running now, with its release notes.
Players
4 methodsuniplays.player.id()A stable ID for this player in your game.
stringplayer.identityA stable ID for this player in your game. The same person has a different ID in another game.
uniplays.player.displayName()The player’s display name, or null for a guest.
string | nullplayer.identityThe player’s display name, or null for a guest.
uniplays.player.wallet()The player’s wallet address, after UniPlays asks the player to agree.
stringplayer.walletThe player’s wallet address, after UniPlays asks the player to agree. Handle consent_required (they said no) and wallet_required (they have no wallet).
uniplays.player.token()A short-lived sign-in token (JWT) your own server can use to trust who the player is.
{ token, expiresAt }player.identityA short-lived sign-in token (JWT) your own server can use to trust who the player is. On your server, check its signature, issuer, audience (your gameId), and expiry.
Saves & progress
5 methodsAccount storage allows 64 keys and 256 KiB per player per game; guest storage allows 16 keys and 64 KiB, kept for 30 days. A key is one named save.
uniplays.storage.get(key)Reads one save and its etag, a version tag you pass back when saving so an old copy cannot overwrite a newer one.
{ value, savedAtVersion, etag, rev }storageReads one save and its etag, a version tag you pass back when saving so an old copy cannot overwrite a newer one. A missing key has a null value.
uniplays.storage.set(key, value, { ifMatch? })Write JSON data.
{ etag, rev, savedAtVersion }storageWrite JSON data. Pass the last etag as ifMatch, and omit ifMatch while the etag is null, because UniPlays refuses a null one. On version_conflict, reload and reconcile before writing again.
uniplays.storage.list({ prefix?, limit? })Lists the player’s save keys, optionally only those starting with a prefix.
StorageEntry[]storageLists the player’s save keys, optionally only those starting with a prefix. Use storage.get for a key’s etag and savedAtVersion.
uniplays.storage.remove(key, { ifMatch? })Deletes a save, optionally only if its etag still matches.
booleanstorageDeletes a save, optionally only if its etag still matches.
uniplays.storage.migrate(fromVersion, { key? })Re-tags saves with the running version.
numberstorageRe-tags saves with the running version. This does not change the data: read, convert, and save the new shape yourself.
Leaderboards
4 methodsScores submitted from the browser are unverified, so label them that way.
uniplays.leaderboard.submit(score, { seasonId?, board? })Submits a score as an integer; fractional values are cut off.
{ accepted, best, rank, verification }leaderboardSubmits a score as an integer; fractional values are cut off. It goes to the selected season. Name the board with board when the game declares several.
uniplays.leaderboard.top(limit?, { seasonId?, board? })The top scores for a season and board.
{ seasonId, board, order, verification, entries }leaderboardThe top scores for a season and board. Before the game has a season, seasonId is null and entries is empty.
uniplays.leaderboard.boards()The boards your game.json declares, first board first, each with its order and bound.
LeaderboardBoard[]leaderboardThe boards your game.json declares, first board first, each with its order and bound. A game without a leaderboards block has one board, default, highest first.
uniplays.leaderboard.seasons()List this game’s leaderboard seasons.
Season[]leaderboardList this game’s leaderboard seasons. The developer starts a new one from the manage page or with a publish-scoped key, so a rebalanced game does not compete with its old scores.
Game token
5 methodsThese methods are about your game’s own token.
uniplays.token.price()The token’s price in ETH.
{ eth, usd, source, updatedAt }The token’s price in ETH. The usd field is null.
uniplays.token.symbol()The token’s ticker, such as COMET.
stringThe token’s ticker, such as COMET.
uniplays.token.decimals()How many decimal places the token uses: 18.
numberHow many decimal places the token uses: 18.
uniplays.token.balance()How many whole tokens the player holds.
stringtoken.gateHow many whole tokens the player holds.
uniplays.token.gate(id)Checks a holder rule you declared in token.gates.
booleantoken.gateChecks a holder rule you declared in token.gates. This is advisory and locally bypassable; enforce valuable access on your backend.
Shop & rewards
4 methodsuniplays.store.items()Your shop catalog as published in game.json.
{ pricing, items }storeYour shop catalog as published in game.json. Needs the store block.
uniplays.store.quote(itemId)An expiring price quote for a declared item.
{ itemId, priceUsd, priceTokens, tokenSymbol, expiresAt, pricedAt, source }storeAn expiring price quote for a declared item. Show each USD item as its dollar price beside the token amount, for example '$2.00 · 480 PLAY', and quote again when expiresAt passes. A USD amount is exactly what the chain charges for the priced minute, pricedAt, until expiresAt; source names the market it was averaged over.
uniplays.store.purchase(itemId)Opens the purchase window: the player reviews the checkout terms, approves if needed, and confirms the payment.
PurchaseReceiptstoreOpens the purchase window: the player reviews the checkout terms, approves if needed, and confirms the payment. A quote is not a receipt.
uniplays.rewards.grant(amount, { reason?, authorization })Redeems a signed reward from your server for this player, after the player reviews it in their wallet.
{ granted, remainingToday, txHash, awardHash, status }rewardsRedeems a signed reward from your server for this player, after the player reviews it in their wallet. authorization holds the award and its signature; without it the call refuses before any wallet prompt. This never gives the game permission to issue rewards itself.
Items & marketplace
9 methodsRead your game’s items and listings. Anything that moves value needs the player’s review and wallet approval. One manifest version declares at most 256 item types and a collection holds at most 4,096 over the game’s life.
uniplays.assets.inventory({ cursor?, limit? })The items this player owns in your game.
{ items, cursor }assetsThe items this player owns in your game.
uniplays.assets.item(type)The details of one item type.
AssetTypeassetsThe details of one item type.
uniplays.assets.balance(type)How many of one item type the player owns.
stringassetsHow many of one item type the player owns.
uniplays.assets.burn({ purpose, items })Destroys items the player owns, for a purpose you declared in assets.burns, such as crafting.
AssetBurnReceiptassets.burnDestroys items the player owns, for a purpose you declared in assets.burns, such as crafting. Only the purpose and each tokenId and amount are sent. UniPlays shows its own review window and sends the burn once the player approves it. It answers not_available when the network has no item collection configured, item burns are turned off or its checks cannot be read, so branch on can('assets.burn') and handle not_available. Recipes change only through a game update; grant the reward from your server once it has verified the burn.
uniplays.market.listings({ type?, cursor?, limit? })Items listed for sale, optionally for one item type, a page at a time.
{ listings, cursor, tokenSymbol }marketItems listed for sale, optionally for one item type, a page at a time.
uniplays.market.quote(listingId)The price, the royalty, and what the seller receives for one listing.
ListingQuotemarketThe price, the royalty, and what the seller receives for one listing.
uniplays.market.list({ tokenId, amount, price, expiresIn? })Puts one of the player’s items up for sale.
ListingReceiptmarketPuts one of the player’s items up for sale. The market capability also requires assets.
uniplays.market.buy(listingId, { maxTotal, amount? })Buys a listed item with the game’s token.
MarketPurchaseReceiptmarketBuys a listed item with the game’s token. maxTotal is the most the player will pay.
uniplays.market.cancel(listingId)Takes the player’s listing down.
CancelReceiptmarketTakes the player’s listing down.
Pause, audio & online players
4 methodsuniplays.presence.count()How many players are online in your game right now.
{ signedIn, guests }presenceHow many players are online in your game right now. An unavailable service refuses with not_available rather than inventing zero counts.
uniplays.session.state()Pause when paused is true or visible is false, never on focused: a tap into the game can move focus into the frame.
{ visible, focused, paused }Pause when paused is true or visible is false, never on focused: a tap into the game can move focus into the frame.
uniplays.session.on(event, callback)Listen for pause, resume, visibility, entitlements, or audio events.
() => voidListen for pause, resume, visibility, entitlements, or audio events. Returns a function that stops listening. Pause on pause, never on focused. Resume audio on resume with activation true and again from the game's own first pointerup, touchend or keydown, because only the in-frame gesture always counts.
uniplays.session.audioPolicy()Whether the browser lets your game play audio on its own.
allowed | allowed-muted | disallowed | unknownWhether the browser lets your game play audio on its own. Audio may still require a user gesture.
Hosted backend (optional)
1 methodShort server-side functions that UniPlays runs for your game, with protected state and prepaid usage.
uniplays.backend.call(name, input, { idempotencyKey })Runs one of your hosted functions.
Promise<{ result, replayed }>backendRuns one of your hosted functions. Create a UUID for each action and reuse it on every retry, so a retry never repeats the action. UniPlays ties the call to your game and its frontend version. hosting_suspended means the online service is unavailable; the developer dashboard offers a top-up. Your backend receives the verified player. NFT rewards you sign need the player’s consent plus your explicit permission for the signing key.
Reward pool & awards
2 methodsReads only: the limits, the split and the rates belong to the reward pool (the treasury), and nothing here moves a token. If a network does not serve the reward pool, these reads refuse by name rather than answering a zero balance.
uniplays.economy.treasury()The pot’s balance, how purchases are split now, the limits in force, what today’s limit still allows, and the open rounds.
TreasuryStateeconomyThe pot’s balance, how purchases are split now, the limits in force, what today’s limit still allows, and the open rounds. The game fee that funds the pot is fixed at launch.
uniplays.economy.awards({ limit? })Awards already paid to this player, what the per-player limit still allows today, and the most one signed award may carry.
AwardHistoryeconomyAwards already paid to this player, what the per-player limit still allows today, and the most one signed award may carry.
Item buy offers
2 methodsStanding offers from the reward pool to buy items you have declared. A sale opens a confirmation window: the player approves the exact terms and their own wallet signs.
uniplays.npc.offers(type?)Every standing offer, or the offers for one declared item type, with the units left today, the expiry and whether the offer is firm (it cannot be made worse while firm).
NpcOfferListeconomyEvery standing offer, or the offers for one declared item type, with the units left today, the expiry and whether the offer is firm (it cannot be made worse while firm). An offer is not a price floor, and reading it does not reserve a sale for a seller.
uniplays.npc.sell(tokenId, { amount, minUnitPrice })Sells items the player owns into a standing offer.
NpcSaleReceipteconomySells items the player owns into a standing offer. tokenId is an id from assets.inventory, not an item type name. minUnitPrice is required: it is the unit price the player was shown, the same reason market.buy requires maxTotal.
Paid prize draws
4 methodsThe draws your game.json declares, priced in whole tokens, or in dollars converted at the token’s 30-minute average price. play and refund open a confirmation window with the exact token amount; the other calls are reads. Only draws created through UniPlays are listed, and a holder rewards contract counts only when it is where your game fee is sent; a lookalike is never read from or paid.
uniplays.draws.status(id?)Each declared draw with its state, the price for the current minute, the odds, the prizes left, and this wallet’s plays and pending plays.
DrawStatusListdrawsEach declared draw with its state, the price for the current minute, the odds, the prizes left, and this wallet’s plays and pending plays. A draw not created yet is listed with state notCreated and no price.
uniplays.draws.play({ id, maxTokens? })Pays the amount the player approved, burned or split as game.json declares.
DrawPlayReceiptdrawsPays the amount the player approved, burned or split as game.json declares. maxTokens is an optional ceiling the game sets. The outcome comes from a later drand round (a public random number), after the play confirms.
uniplays.draws.result(id, playId)Whether a play has settled, whether it won, its prize, and whether that prize still waits to be claimed.
DrawResultdrawsWhether a play has settled, whether it won, its prize, and whether that prize still waits to be claimed. The platform claims every win for its player, who can also claim it on the game page.
uniplays.draws.refund(id, playId)Returns the price paid for a play whose random number never arrived, once its refund time has passed, or at once for a play that draws.status lists in myPending with refundOnly true.
DrawRefundReceiptdrawsReturns the price paid for a play whose random number never arrived, once its refund time has passed, or at once for a play that draws.status lists in myPending with refundOnly true.
Chance rounds
6 methodsChance is closed: no round exists, so rounds lists none and enter and claim answer not_available for the round they name. Rounds follow a table of outcomes set at launch. rounds, result, verify and verifyPool only read; enter and claim open a confirmation window, which shows the player the rules before their first entry.
uniplays.chance.rounds(id?)Open rounds, or the rounds of one declared chance game, with the entry price, the entries left, the close time and the rules hash of the table armed at launch.
ChanceRoundListchanceOpen rounds, or the rounds of one declared chance game, with the entry price, the entries left, the close time and the rules hash of the table armed at launch. The round carries the hash, not the table itself.
uniplays.chance.result(roundId, entryIndex)One entry’s state and amount, with the record that verify() recomputes from.
ChanceResultchanceOne entry’s state and amount, with the record that verify() recomputes from. A pending entry has no outcome yet, and none is made up.
uniplays.chance.enter({ id, roundId, rulesHash, maxEntryPrice })All four fields are required.
ChanceEntryReceiptchanceAll four fields are required. rulesHash names the table of rules the player agreed to, and maxEntryPrice is the most they will pay. UniPlays fills in neither for you.
uniplays.chance.claim(roundId, entryIndex)Collects the prize or the refund that a finished entry is owed.
ChanceClaimReceiptchanceCollects the prize or the refund that a finished entry is owed.
uniplays.chance.verify(transcript)Recomputes one entry’s outcome from a chance.result record, on the player’s device with no network call.
ChanceVerificationRecomputes one entry’s outcome from a chance.result record, on the player’s device with no network call. It recomputes; it does not prove: pairingChecked is always false, so never present the answer as verified randomness.
uniplays.chance.verifyPool(transcript)The same recomputation for a pool round, where one winner is drawn over the entries.
ChancePoolVerificationThe same recomputation for a pool round, where one winner is drawn over the entries. A pool round reads no row of the armed table, so verify() refuses it and this call answers for it.
Staked matches
6 methodsPlayers each put in a stake. Signed terms and trusted results are required. Anything that moves value needs wallet review; creating a match or reporting a result without a signature returns authorization_required.
uniplays.match.create({ stake, maxPlayers, authorization })Creates a match.
{ id, stake, maxPlayers, txHash, status }matchCreates a match. authorization holds the complete terms, the authorizer and a signature. The player reviews the approval and the deposit separately. Never use creation to test whether matches are available.
uniplays.match.join(id)Joins an open match using its current signed terms and a separately reviewed stake deposit.
{ id, txHash, status }matchJoins an open match using its current signed terms and a separately reviewed stake deposit.
uniplays.match.report(id, result)Reports a match result.
{ id, accepted, txHash, status }matchReports a match result. result holds the outcome, resultHash, the resolver’s signature (the account that signs match results) and the winner for a win. A claim from the browser alone cannot settle a match.
uniplays.match.state(id)Reads a match: its terms, who has joined, what the player can claim, and the next action.
MatchStatematchReads a match: its terms, who has joined, what the player can claim, and the next action. Settling a match and withdrawing the money are separate steps.
uniplays.match.cancel(id)Cancels an eligible open match.
{ id, txHash, status }matchCancels an eligible open match. Use claim separately to withdraw refund credit.
uniplays.match.claim(id)Withdraws what the player is owed.
{ id, amount, txHash, refundTxHash, status }matchWithdraws what the player is owed. The player reviews any timeout refund step and the withdrawal separately. Pending transactions keep their original hashes so they can be recovered.