Waivio

Recommended Posts

Bitshares tutorial - Allocating gold to users based on their Bitshares balance!

0 comments

nftea.gallery1.3 K3 months agoHive.Blog3 min read

https://images.hive.blog/DQmSz7NPUhG1xCrJaNvXiM565HL7C1jj2HNGAMkVDBtUHfY/image.png

As you may have been following, I've recently been blogging about my efforts working with the rpg-js framework, check out my profile if you've missed out on this content.

I've got a new tutorial for you aspiring Bitshares game developers out there!

Allocating gold based on Bitshares balances

If you weren't aware, the RPG-JS framework offers a gold system!

Gold can be used to purchase items or to unlock new areas in game for example!

But, how are users supposed to earn gold? At the moment in my demo rpg-js implementation I have not implemented any means to earn gold whilst in game, like a traditional RPG game, so for the time being let's just give them an equal amount of gold as their chosen Bitshares account has Bitshares (BTS) in it!

Getting started - On join map

  async onJoinMap(player: RpgPlayer) {
    if (player.getVariable("AFTER_INTRO")) {
      return;
    }

    await player.gui("intro").open({}, {waitingAction: true});
    const usr = $currentUser.get();
    await playerGold(player, usr);
    player.setVariable("AFTER_INTRO", true);
  },

.
So this will launch our intro GUI, and fetch the user id & chain for the next step - fetching the user's balances!

In order to fetch the user's balances let's create the following nanostore query function:

import { nanoquery } from "@nanostores/query";
import Apis from "../bts/ws/ApiInstances.js";

//Fetch account balances
async function getAccountBalances(chain: String, accountID: String) {
  return new Promise(async (resolve, reject) => {
    const node =
      chain === "bitshares" ? "wss://node.xbts.io/ws" : "wss://eu.nodes.testnet.bitshares.ws";

    let currentAPI;
    try {
      currentAPI = await Apis.instance(node, true, 4000, { enableDatabase: true }, (error: Error) =>
        console.log({ error })
      );
    } catch (error) {
      console.log({ error });
      reject(error);
      return;
    }

    let balances;
    try {
      balances = await currentAPI
        .db_api()
        .exec("get_account_balances", [accountID, []])
        .then((results: Object[]) => {
          if (results && results.length) {
            return results;
          }
        });
    } catch (error) {
      console.log({ error });
      currentAPI.close();
      reject(error);
    }

    currentAPI.close();

    if (!balances) {
      return resolve([]);
    }

    return resolve(balances);
  });
}

// Create fetcher store for user balances
const [createUserBalancesStore] = nanoquery({
  fetcher: async (...args: unknown[]) => {
    const chain = args[0] as string;
    const accountID = args[1] as string;

    let response;
    try {
      response = await getAccountBalances(chain, accountID);
    } catch (error) {
      console.log({ error });
      return;
    }

    if (!response) {
      console.log(`Failed to fetch user balances`);
      return;
    }

    return response;
  },
});

export { createUserBalancesStore };

.
With this nanostore created, we can now easily subscribe to it to fetch the user's BTS balances then award the user an equal amount of gold to their BTS holdings!

async function playerGold(player: RpgPlayer, usr: User) {
  if (!usr || !usr.chain) {
    return;
  }

  const userBalanceStore = createUserBalancesStore([usr.chain, usr.id]);

  const unsub = userBalanceStore.subscribe((result) => {
    if (result.error) {
      console.error(result.error);
    }

    if (!result.loading) {
      if (result.data) {
        const res = result.data as any[];
        const btsBalance = res.filter((x) => x.asset_id === "1.3.0");
        if (btsBalance.length) {
          player.gold = parseInt(humanReadableFloat(btsBalance[0].amount, 5).toFixed(0));
        }
      }
    }
  });

  return () => {
    unsub();
  };
}

OK cool, so now we wait for the GUI, look up the user's balances, then set the user's gold to the amount of BTS they have!

Let's see it in action!

https://s10.gifyu.com/images/SYFRE.gif


Have any questions? Comment below!


These developments were brought to you by the NFTEA Gallery.

Consider collecting an NFTEA NFT to or donate to the following BTS or EOS blockchain accounts directly, to fund continued developments.

Comments

Sort byBest
AI
Waivio AI Assistant
How can I help you today?