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 {Number} syncType Sharing type of the currency. (0 = not shared with clients, 1 = shared with everyone, 2 = shared with just the wallet owner) * @return {Object} The added currency object. * @fires currencyDefined */ currencyAPI.addCurrency(key, name, syncType); /** * 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 iterator of all registered currency identifiers. * @return {Iterator.<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 the sync type of the specified currency. * @param {String} key Currency identifier. * @return {Number} Sync type of the currency. (0 = not shared with clients, 1 = shared with everyone, 2 = shared with just the wallet owner) */ currencyAPI.getCurrencySyncType(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 {Number} syncType Sharing type of the currency. (0 = not shared with clients, 1 = shared with everyone, 2 = shared with just the wallet owner) * @param {String} syncKey If the currency is shared, this string will be used with player.setVariable() or player.setOwnVariable() to transfer data to clientside. */ currencyAPI.on("currencyDefined", (key, name, syncType, 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"); const SYNC_TYPE_NONE = 0; const SYNC_TYPE_EVERYONE = 1; const SYNC_TYPE_PLAYER = 2; // Events currencyAPI.on("currencyDefined", (key, name, syncType, syncKey) => { const syncTypes = ["none", "everyone", "player"]; console.log(`Currency defined, key: ${key} | name: ${name} | syncType: ${syncTypes[syncType]} | syncKey: ${syncKey}`); }); 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", SYNC_TYPE_PLAYER); // So that we can use currency_cash shared variable on clientside currencyAPI.addCurrency("vip_tokens", "VIP Currency", SYNC_TYPE_NONE); // 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."); } }); // Do /currencies to get all registered currency identifiers and their names. mp.events.addCommand("currencies", (player) => { for (const key of currencyAPI.getAllCurrencies()) { player.outputChatBox(`${key} - Name: ${currencyAPI.getCurrencyName(key)}`); } });
// 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
Edited by rootcause
v2 changes
What's New in Version 2.0.0 See changelog
Released
Version 2.0.0
This version has some breaking changes.
- addCurrency throws errors instead of returning null on invalid/malformed data.
- getAllCurrencies returns an Iterator instead of an array of strings.
- The isShared boolean has been replaced with syncType number all around the library. (0 = not shared with clients, 1 = shared with everyone/using setVariable, 2 = shared with just the wallet owner/using setOwnVariable)
Everything affected by the isShared -> syncType change:
- addCurrency's isShared parameter is now called syncType and expects a number.
- getCurrencyIsShared is now getCurrencySyncType and returns a number.
- currencyDefined event's isShared parameter is now called syncType and is a number.