MultiConnectMultiConnectDocs Website home
MultiConnectSDK › SDK Apps

10. Economy

What the economy holds

Thing What it is
Currency A balance per player, in whole numbers: coins, gems. Never negative
Item Something a player owns, with a quantity: theme_gold, cue_fire
Timed item An item that lasts some hours, then expires: ad_free for 30 days
Ledger Every change to a balance, with its amount, the balance after, a reason and its source

Every change is made in one locked step on MultiConnectCloud, so two changes at the same moment can never lose one another or take a balance below zero.

Set it up

Open the app on SDK Apps and choose Economy.

  1. Under Currencies, add each currency:
    • Key, its name in code (coins);
    • Name;
    • Starting balance, which every new player gets;
    • Maximum (0 = none).
  2. Under Coin store, add the items players buy with currency:
    • Key;
    • Name;
    • Price and its Currency;
    • what Buying it gives (currencies, items, timed items);
    • Max per player (0 = any): 1 for a one-time unlock;
    • For sale or Hidden.
  3. Under Ad reward and the game's day, set the Time zone your game's day starts in. The daily bonus, daily tasks and the ad limit all reset at midnight there. The ad reward is in section 11.

Grants

A grant is what something gives. The dashboard edits grants for you; in code and in Store products (section 13) they are JSON:

{ "currencies": { "coins": 500 }, "items": { "theme_gold": 1 }, "timedItems": { "ad_free": 720 } }

timedItems are in hours: 720 is 30 days.

Change balances from your server

Two rules for server changes:

Call Use
McAppServer.GrantAsync(playerId, currency, amount, key, reason) Give currency
McAppServer.SpendAsync(playerId, currency, amount, key, reason) Take currency. Refused with InsufficientFunds, and nothing changes, if the balance is too low
McAppServer.EconomyAsync(key, reason, changes) Several changes, for one or many players, all or nothing
McAppServer.GetWalletAsync(playerId) A player's balances and items

Script 10.1: Server: take both entry fees in one step, then pay the winner

using System;
using System.Threading.Tasks;
using MultiConnect.App;

public static class MatchMoney
{
    public static async Task<bool> TakeEntryFees(string matchId, string playerA, string playerB, long fee)
    {
        var result = await McAppServer.EconomyAsync(matchId + ":entry", "Match entry", new[]
        {
            new McEconomyChange { playerId = playerA, currency = "coins", amount = -fee },
            new McEconomyChange { playerId = playerB, currency = "coins", amount = -fee }
        });

        // InsufficientFunds: one of them cannot pay, and neither was charged.
        if (!result.Ok) Console.WriteLine("Entry refused: " + result.Message);
        return result.Ok;
    }

    public static async Task PayWinner(string matchId, string winner, long prize)
    {
        var result = await McAppServer.GrantAsync(winner, "coins", prize, matchId + ":prize", "Match prize");
        if (!result.Ok) Console.WriteLine("Prize not paid, retry with the same key: " + result.Message);
    }
}

A change can also give or take items: set itemKey and quantity on the McEconomyChange, and hours for a timed item.

Bots and commission: the house wallet

What it is. Each app has one house wallet per currency, besides the players' wallets. Use it for money that belongs to the game rather than to a player:

How to use it. Pass McAppServer.House as the player id in an McEconomyChange. The house can then sit in the same all-or-nothing step as the players: fees, pot, commission and payouts are one call.

How it differs from a player's wallet:

The Economy page shows its balance next to each currency, its history, and Top up or take out.

Split a pot in whole coins. Balances are whole numbers, so a percentage commission needs a rounding rule. McPot.Split(pot, commissionPercent, winners) gives each winner the pot less the commission, divided equally and rounded down. The house gets everything else: the commission plus what rounding left over. The parts always add up to the pot. For example, a pot of 333 at 10% between 2 winners pays 149 each, and the house keeps 35.

Script 10.3: Server: a match against a bot, with commission

using System.Threading.Tasks;
using MultiConnect.App;

public static class BotMatch
{
    /// <summary>The player and a bot each pay the fee; the winner takes the pot less 10%.</summary>
    public static async Task<bool> Play(string matchId, string playerId, long fee, bool playerWon)
    {
        // The bot's fee comes from the house.
        var entry = await McAppServer.EconomyAsync(matchId + ":entry", "Match entry", new[]
        {
            new McEconomyChange { playerId = playerId, currency = "coins", amount = -fee },
            new McEconomyChange { playerId = McAppServer.House, currency = "coins", amount = -fee }
        });
        if (!entry.Ok) return false;

        var split = McPot.Split(fee * 2, 10m, 1);

        // The house keeps the commission either way, and the prize too when the bot wins.
        var payout = playerWon
            ? new[]
            {
                new McEconomyChange { playerId = playerId, currency = "coins", amount = split.PerWinner },
                new McEconomyChange { playerId = McAppServer.House, currency = "coins", amount = split.House }
            }
            : new[] { new McEconomyChange { playerId = McAppServer.House, currency = "coins", amount = fee * 2 } };

        var paid = await McAppServer.EconomyAsync(matchId + ":payout", "Match payout", payout);
        return paid.Ok;
    }
}

For a 2v2 match, call McPot.Split(pot, commission, 2) and pay PerWinner to each player on the winning team.

Read the wallet and buy in the game

Script 10.2: Client: show balances and buy a coin store item

using MultiConnect.App;
using UnityEngine;

public class CoinStoreScreen : MonoBehaviour
{
    private async void OnEnable()
    {
        var wallet = await McAppWallet.GetAsync();
        if (wallet.Ok && wallet.Value != null)
            Debug.Log($"Coins: {wallet.Value.Balance("coins")}, ad-free: {wallet.Value.Owns("ad_free")}");

        var store = await McAppWallet.GetStoreAsync();
        if (store.Ok && store.Value != null)
            foreach (var item in store.Value.items)
                Debug.Log($"{item.name}: {item.price} {item.currency} (bought {item.bought})");
    }

    public async void Buy(string itemKey)
    {
        var result = await McAppWallet.BuyItemAsync(itemKey);
        if (result.Ok && result.Value != null)
            Debug.Log("Bought. Coins left: " + result.Value.Balance("coins"));
        else if (result.Error == McAppError.InsufficientFunds)
            Debug.Log("Not enough coins.");
        else
            Debug.Log("Could not buy: " + result.Message);
    }
}

How buying works:

McAppWallet.GetHistoryAsync(currency, limit) returns the player's ledger, for a "coin history" screen.

Help a player from the dashboard

Under Players, open a player and choose Give or take back in Wallet. It needs a reason, and it is recorded in their ledger as a dashboard change.