Currency API 1.0.0

   (5 reviews)
Sign in to follow this  

1 Screenshot

About This File

This resource provides a currency API to server developers.

This resource will not save anything on its own. I'd also recommend you to not have over 2 billion of any currency.

 

Installing

  • Put the files you downloaded in their respective places
  • Check the documentation and examples
  • All done

 

Currency API

const currencyAPI = require("../currency-api");

 

/**
 * Adds a currency to the system.
 * @param {String}  key      Currency identifier. (such as vip_tokens)
 * @param {String}  name     Currency's human readable name. (such as VIP Tokens)
 * @param {Boolean} isShared Whether the currency will use shared data or not. Useful if you want to have a money HUD etc.
 * @return {Object} The added currency object, will be null if there were any mistakes.
 * @fires currencyDefined
 */
currencyAPI.addCurrency(key, name, isShared);

/**
 * Returns whether the specified key is a registered currency or not.
 * @param  {String}  key Currency identifier.
 * @return {Boolean}
 */
currencyAPI.hasCurrency(key);

/**
 * Returns the specified currency's object.
 * @param  {String} key Currency identifier.
 * @return {Object}     The currency object, will be undefined if the key isn't registered.
 */
currencyAPI.getCurrency(key);

/**
 * Returns an array of all registered currency identifiers.
 * @return {String[]}
 */
currencyAPI.getAllCurrencies();

/**
 * Returns the human readable name of the specified currency.
 * @param  {String} key Currency identifier.
 * @return {String}     Human readable name, will be Invalid Currency if the key isn't registered.
 */
currencyAPI.getCurrencyName(key);

/**
 * Returns whether the specified currency is shared or not.
 * @param  {String} key Currency identifier.
 * @return {Boolean}
 */
currencyAPI.getCurrencyIsShared(key);

/**
 * Returns the sync key of the specified currency. Sync key is used with player.setVariable()
 * @param  {String} key Currency identifier.
 * @return {String}     Sync key of the currency, will be null if the key isn't registered.
 */
currencyAPI.getCurrencySyncKey(key);

 

Currency API Events

/**
 * currencyDefined
 * This event is called when a currency is added to the system with currencyAPI.addCurrency
 * @param {String} key Currency identifier.
 * @param {String} name Human readable name of the currency.
 * @param {Boolean} isShared Whether the currency is shared or not.
 * @param {String} syncKey If the currency is shared, this string will be used with player.setVariable() to transfer data to clientside.
 */
currencyAPI.on("currencyDefined", (key, name, isShared, syncKey) => {
    // Your code here
});

/**
 * walletReplaced
 * This event is called when a player's wallet object gets replaced by player.setWallet()
 * @param {Player} player The player who had a wallet change.
 * @param {Object} oldWallet Old wallet object of the player.
 * @param {Object} newWallet New wallet object of the player.
 */
currencyAPI.on("walletReplaced", (player, oldWallet, newWallet) => {
    // Your code here
});

/**
 * currencyUpdated
 * This event is called when a player's wallet has a currency change.
 * @param {Player} player The player who had a currency change.
 * @param {String} currencyKey Currency identifier.
 * @param {Number} oldAmount The player's old amount of currency.
 * @param {Number} newAmount The player's new amount of currency.
 * @param {String} source Name of the function that triggered this update, will either be "setCurrency" or "changeCurrency".
 */
currencyAPI.on("currencyUpdated", (player, currencyKey, oldAmount, newAmount, source) => {
    // Your code here
});

 

Player API

/**
 * Returns the wallet object of the player.
 * @return {Object}
 */
player.getWallet();

/**
 * Replaces the wallet object of the player with the specified one.
 * @param {Object} newWallet
 * @return {Boolean} True if successful, false otherwise.
 * @fires walletReplaced
 */
player.setWallet(newWallet);

/**
 * Returns the amount of specified currency the player has in their wallet.
 * @param  {String} currencyKey Currency identifier.
 * @return {Number}
 */
player.getCurrency(currencyKey);

/**
 * Sets the amount of specified currency the player has in their wallet.
 * @param {String} currencyKey Currency identifier.
 * @param {Number} newAmount   New amount of specified currency.
 * @return {Boolean} True if successful, false otherwise.
 * @fires currencyUpdated
 */
player.setCurrency(currencyKey, newAmount);

/**
 * Changes the amount of specified currency the player has in their wallet by specified amount.
 * @param  {String} currencyKey Currency identifier.
 * @param  {Number} amount
 * @return {Boolean}            True if successful, false otherwise.
 */
player.changeCurrency(currencyKey, amount);

 

Examples

Full Test Script, will update GTAV money hud if you give yourself "cash" currency. (Used during development)

// SERVERSIDE CODE
const currencyAPI = require("../currency-api");

// Events
currencyAPI.on("currencyDefined", (key, name, isShared, syncKey) => {
    console.log(`Currency defined, key: ${key} | name: ${name} | isShared: ${isShared ? `yes, sync key: ${syncKey}` : "no"}`);
});

currencyAPI.on("walletReplaced", (player, oldWallet, newWallet) => {
    console.log("==============================");
    console.log(`${player.name} had their wallet replaced.`);
    console.log(`Old wallet currencies: ${Object.keys(oldWallet).join(",")}`);
    console.log(`New wallet currencies: ${Object.keys(newWallet).join(",")}`);
    console.log("==============================");
});

currencyAPI.on("currencyUpdated", (player, currencyKey, oldAmount, newAmount, source) => {
    const diff = newAmount - oldAmount;
    console.log(`${player.name} ${diff < 0 ? "lost" : "got"} ${Math.abs(diff)} ${currencyAPI.getCurrencyName(currencyKey)} (${currencyKey}). (caused by: ${source})`);
});

// Register currencies
currencyAPI.addCurrency("cash", "Money", true); // since isShared is true, we can use currency_cash shared variable on clientside
currencyAPI.addCurrency("vip_tokens", "VIP Currency", false);

// Test commands
const fs = require("fs");
const path = require("path");

// Do /savewallet to save your wallet to a JSON file. (file path will be printed to console)
mp.events.addCommand("savewallet", (player) => {
    const saveDir = path.join(__dirname, "wallets");
    if (!fs.existsSync(saveDir)) fs.mkdirSync(saveDir);

    const playerPath = path.join(saveDir, `${player.socialClub}.json`);
    fs.writeFileSync(playerPath, JSON.stringify(player.getWallet(), null, 2));

    player.outputChatBox("Wallet saved.");
    console.log(`Player ${player.name} saved their wallet. (${playerPath})`);
});

// Do /loadwallet to load your wallet from a JSON file.
mp.events.addCommand("loadwallet", (player) => {
    const playerPath = path.join(__dirname, "wallets", `${player.socialClub}.json`);

    if (fs.existsSync(playerPath)) {
        player.setWallet(JSON.parse(fs.readFileSync(playerPath)));
        player.outputChatBox("Wallet loaded.");
    } else {
        player.outputChatBox("Wallet file not found.");
    }
});

// Do /mytokens to see your VIP tokens currency amount.
mp.events.addCommand("mytokens", (player) => {
    player.outputChatBox(`Your VIP tokens: ${player.getCurrency("vip_tokens")}`);
});

// Do /wallet to list the currencies you have.
mp.events.addCommand("wallet", (player) => {
    const wallet = player.getWallet();

    player.outputChatBox("Your wallet:");
    for (const [key, value] of Object.entries(wallet)) player.outputChatBox(`${currencyAPI.getCurrencyName(key)}: ${value}`);
});

// Do /setcurrency [key] [amount] to set your currency amount.
mp.events.addCommand("setcurrency", (player, _, currencyKey, amount) => {
    amount = Number(amount);

    if (player.setCurrency(currencyKey, amount)) {
        player.outputChatBox(`Set ${currencyAPI.getCurrencyName(currencyKey)} (${currencyKey}) to ${amount}.`);
    } else {
        player.outputChatBox("Failed to set currency.");
    }
});

// Do /changecurrency [key] [amount] to change your currency amount by specified value.
mp.events.addCommand("changecurrency", (player, _, currencyKey, amount) => {
    amount = Number(amount);

    if (player.changeCurrency(currencyKey, amount)) {
        player.outputChatBox(`${currencyAPI.getCurrencyName(currencyKey)} (${currencyKey}) changed by ${amount}.`);
    } else {
        player.outputChatBox("Failed to change currency.");
    }
});
// CLIENTSIDE CODE
mp.events.addDataHandler("currency_cash", (entity, value) => {
    if (entity.handle === mp.players.local.handle) {
        mp.game.stats.statSetInt(mp.game.joaat("SP0_TOTAL_CASH"), value, false);
        mp.gui.chat.push(`(clientside) currency_cash updated, new value: ${value}`);
    }
});

Source code is available on GitHub in case you don't want to download: https://github.com/root-cause/ragemp-currency-api

Thanks to Lorc for providing the resource icon: https://game-icons.net/1x1/lorc/cash.html

  • Like 2



User Feedback

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest

SotaRex

   0 of 1 member found this review helpful 0 / 1 member

I dont know how to use it for clientside scripts.

Ok, i have inserted the DataHanlder, but how can i let me show my Value in an HUD or anything other ?

Share this review


Link to review
ragempdev

   0 of 1 member found this review helpful 0 / 1 member

* hands api

Share this review


Link to review
MrPancakers

  

better than money api

Share this review


Link to review
rgnbgnhnd

  

waow

Share this review


Link to review
Kar

  

Haha cool

Share this review


Link to review