How do you make a Discord economy bot with discord.js?
To make a Discord economy bot, register slash commands such as /balance, /daily, /pay and /leaderboard with discord.js v14, and store coins in a real database, not a JSON file or a Map. Every balance change is a row in a ledger table, and each daily claim or transfer runs inside one database transaction, so coins cannot be created or lost by a crash, a double click or two commands at once. Add cooldowns and transfer limits against alt accounts, and let members earn more coins on your website through an offerwall whose postbacks credit the same ledger.
This tutorial uses plain JavaScript with discord.js 14.27.0 and better-sqlite3 13.0.3, the latest versions on npm (checked on October 22, 2026). Every file was syntax-checked and the ledger was unit-tested. For the business side, read How to monetize a Discord bot.
What you build, and who does what
The bot has five commands. Sample values (the coin amounts, limits and cooldowns are yours to change):
| Command | What it does | Abuse guard |
|---|---|---|
/balance [member] | Shows your balance, or another member’s, privately | Bots have no wallets |
/daily | Gives 100 coins, plus 20 per day of streak, up to 220 on day 7 | One claim per 24 hours, checked inside the database transaction |
/pay member amount | Moves coins from you to another member, all or nothing | No self-pay, no bots, accounts at least 7 days old, linked site account, 5,000 coins per 24 hours |
/leaderboard | Lists the top 10 balances | Names without pings |
/earn | Sends a private button to the earn page on your website | Earning happens on the site account, never on the Discord ID |
Three parts share one database:
The bot answers commands and calls ledger functions. It never holds offerwall secrets.
The ledger module owns every coin.
Your website owns member accounts, shows the offerwall, and runs the postback endpoint that credits the same ledger.
Step 1: set up the project
You need Node.js 22 or newer: discord.js 14 asks for Node.js 18 or newer, but better-sqlite3 13 declares Node.js 22 as its minimum. Create the bot in the Discord Developer Portal, copy its token and application ID, invite it to your server with the applications.commands and bot scopes, then install the two packages:
mkdir economy-bot && cd economy-bot npm init -y npm install discord.js@14.27.0 better-sqlite3@13.0.3 mkdir src test Keep the token in an environment variable (DISCORD_TOKEN), never in the repository. Slash commands reach the bot as interactions, so it needs only the Guilds intent and no privileged intents such as Message Content.
Step 2: the ledger, with atomic transfers
An economy bot is a small bank, so design it like one. Two rules carry the whole design:
Integers only. Store coins as whole numbers. In floating point, 0.1 + 0.2 is 0.30000000000000004.
A ledger next to the balance.
walletskeeps a cached balance for fast reads, andledgergets one row for every change. A wallet’s ledger rows must always add up to its balance, which gives you an audit you can run any time.
SQLite or PostgreSQL?
| SQLite with better-sqlite3 | PostgreSQL with pg | |
|---|---|---|
| Setup | One file, no server | A database server or a managed service |
| Who can write | Processes on the same machine, one writer at a time | Many processes on many machines |
| API style | Synchronous; a transaction is a plain function | Asynchronous; every statement of a transaction must use one client from pool.connect() |
| Atomic transfer | db.transaction(fn).immediate() | BEGIN, UPDATE ... WHERE balance >= $1, COMMIT |
| Good fit | One bot and one website on the same server | A sharded bot, a website on another host, several services |
This guide uses SQLite. The same tables and the same WHERE balance >= ? pattern work in PostgreSQL; the node-postgres pattern for one-client transactions is in Offerwall postback in Node.js.
Save this as src/ledger.js:
const Database = require('better-sqlite3'); const { randomUUID } = require('node:crypto'); const DAY = 24 * 60 * 60 * 1000; const DAILY_BASE = 100; const DAILY_STEP = 20; const DAILY_MAX_STREAK = 7; const PAY_LIMIT_PER_DAY = 5000; class EconomyError extends Error { constructor(code, message) { super(message); this.code = code; } } function openLedger(file = 'economy.db') { const db = new Database(file); db.pragma('journal_mode = WAL'); db.pragma('busy_timeout = 5000'); db.pragma('foreign_keys = ON'); db.exec(` CREATE TABLE IF NOT EXISTS wallets ( id INTEGER PRIMARY KEY, discord_id TEXT UNIQUE, site_user_id TEXT UNIQUE, balance INTEGER NOT NULL DEFAULT 0, last_daily INTEGER, streak INTEGER NOT NULL DEFAULT 0 ); CREATE TABLE IF NOT EXISTS ledger ( id INTEGER PRIMARY KEY, wallet_id INTEGER NOT NULL REFERENCES wallets(id), amount INTEGER NOT NULL, kind TEXT NOT NULL, ref TEXT, created_at INTEGER NOT NULL ); CREATE INDEX IF NOT EXISTS ledger_wallet_kind ON ledger (wallet_id, kind, created_at); CREATE TABLE IF NOT EXISTS offer_tx ( transaction_id TEXT PRIMARY KEY, wallet_id INTEGER NOT NULL REFERENCES wallets(id), reward INTEGER NOT NULL, last_status INTEGER NOT NULL ); `); const q = { ensure: db.prepare('INSERT INTO wallets (discord_id) VALUES (?) ON CONFLICT (discord_id) DO NOTHING'), byDiscord: db.prepare('SELECT * FROM wallets WHERE discord_id = ?'), bySite: db.prepare('SELECT * FROM wallets WHERE site_user_id = ?'), add: db.prepare('UPDATE wallets SET balance = balance + ? WHERE id = ?'), take: db.prepare('UPDATE wallets SET balance = balance - ? WHERE id = ? AND balance >= ?'), setDaily: db.prepare('UPDATE wallets SET last_daily = ?, streak = ? WHERE id = ?'), entry: db.prepare('INSERT INTO ledger (wallet_id, amount, kind, ref, created_at) VALUES (?, ?, ?, ?, ?)'), sentToday: db.prepare("SELECT COALESCE(-SUM(amount), 0) FROM ledger WHERE wallet_id = ? AND kind = 'pay_out' AND created_at > ?").pluck(), top: db.prepare('SELECT discord_id, balance FROM wallets WHERE discord_id IS NOT NULL AND balance > 0 ORDER BY balance DESC, id LIMIT ?'), link: db.prepare('UPDATE wallets SET site_user_id = ? WHERE id = ? AND site_user_id IS NULL'), tx: db.prepare('SELECT * FROM offer_tx WHERE transaction_id = ?'), txNew: db.prepare('INSERT INTO offer_tx (transaction_id, wallet_id, reward, last_status) VALUES (?, ?, ?, ?)'), txSet: db.prepare('UPDATE offer_tx SET last_status = ? WHERE transaction_id = ?'), audit: db.prepare(`SELECT w.id, w.balance, COALESCE(SUM(l.amount), 0) AS total FROM wallets w LEFT JOIN ledger l ON l.wallet_id = w.id GROUP BY w.id HAVING w.balance != total`), }; function wallet(discordId) { q.ensure.run(discordId); return q.byDiscord.get(discordId); } function move(w, amount, kind, ref, now) { if (amount >= 0) q.add.run(amount, w.id); else if (q.take.run(-amount, w.id, -amount).changes === 0) { throw new EconomyError('insufficient', 'Not enough coins.'); } q.entry.run(w.id, amount, kind, ref, now); } const claimDaily = db.transaction((discordId, now) => { const w = wallet(discordId); if (w.last_daily !== null && now - w.last_daily < DAY) { return { ok: false, nextAt: w.last_daily + DAY }; } const keepsStreak = w.last_daily !== null && now - w.last_daily < 2 * DAY; const streak = keepsStreak ? Math.min(w.streak + 1, DAILY_MAX_STREAK) : 1; const amount = DAILY_BASE + DAILY_STEP * (streak - 1); move(w, amount, 'daily', null, now); q.setDaily.run(now, streak, w.id); return { ok: true, amount, streak, balance: w.balance + amount }; }); const pay = db.transaction((fromId, toId, amount, now) => { if (!Number.isSafeInteger(amount) || amount <= 0) throw new EconomyError('amount', 'Amount must be a whole number above 0.'); if (fromId === toId) throw new EconomyError('self', 'You cannot pay yourself.'); const from = wallet(fromId); const to = wallet(toId); if (q.sentToday.get(from.id, now - DAY) + amount > PAY_LIMIT_PER_DAY) { throw new EconomyError('limit', `You can send up to ${PAY_LIMIT_PER_DAY} coins per 24 hours.`); } const ref = randomUUID(); move(from, -amount, 'pay_out', ref, now); move(to, amount, 'pay_in', ref, now); return { balance: from.balance - amount }; }); const linkSiteAccount = db.transaction((discordId, siteUserId) => { const w = wallet(discordId); if (q.bySite.get(siteUserId)) throw new EconomyError('taken', 'That site account is already linked.'); if (q.link.run(siteUserId, w.id).changes === 0) throw new EconomyError('linked', 'This Discord account is already linked.'); }); const applyOfferEvent = db.transaction(({ tx, user, reward, status }, now) => { if (!/^\d+$/.test(reward)) throw new Error(`reward ${reward} is not a whole number`); const w = q.bySite.get(user); if (!w) throw new Error(`no wallet for site user ${user}`); const row = q.tx.get(tx); if (status === '1' && !row) { q.txNew.run(tx, w.id, Number(reward), 1); move(w, Number(reward), 'offer', tx, now); return 'credited'; } if (status === '2' && row && row.last_status === 1) { q.txSet.run(2, tx); q.add.run(-row.reward, row.wallet_id); q.entry.run(row.wallet_id, -row.reward, 'offer_reversal', tx, now); return 'reversed'; } if (status === '2' && !row) { q.txNew.run(tx, w.id, Number(reward), 2); return 'reversal_recorded'; } return 'ignored'; }); return { db, balance: (discordId) => wallet(discordId).balance, isLinked: (discordId) => wallet(discordId).site_user_id !== null, claimDaily: (discordId, now = Date.now()) => claimDaily.immediate(discordId, now), pay: (fromId, toId, amount, now = Date.now()) => pay.immediate(fromId, toId, amount, now), top: (limit = 10) => q.top.all(limit), linkSiteAccount: (discordId, siteUserId) => linkSiteAccount.immediate(discordId, String(siteUserId)), applyOfferEvent: (p, now = Date.now()) => applyOfferEvent.immediate(p, now), audit: () => q.audit.all(), }; } module.exports = { openLedger, EconomyError, DAY }; Why it is written this way
Transactions roll back on any error. The better-sqlite3 API docs say a function wrapped in
db.transaction()always runs inside a transaction, and if an exception is thrown, the transaction is rolled back. So when the receiver’s side of a transfer fails, the sender keeps their coins.The balance check is part of the update.
UPDATE ... SET balance = balance - ? WHERE id = ? AND balance >= ?either changes one row or none. Reading the balance first and subtracting later leaves a gap where two commands can both spend the same coins..immediate()takes the write lock at the start. The docs listdeferred,immediateandexclusiveversions of every transaction function. Immediate makes a second process (your website) wait atBEGINinstead of failing halfway, andbusy_timeoutsets how long it waits.No
asyncinside transactions. The same docs say transaction functions do not work with async functions. Do all Discord calls before or after the ledger call, never inside it.WAL mode. better-sqlite3’s performance guide recommends
journal_mode = WALbecause concurrent reads and writes can otherwise be slow.The daily cooldown lives in the database.
last_dailyis checked and set in the same transaction as the credit, so a restart cannot reset it and two quick/dailycalls cannot both pay. A claim within 48 hours of the last one keeps the streak; a longer gap starts again at day 1.
Step 3: register commands and handle them
Register the commands once with a deploy script. Guild commands update instantly, according to Discord’s application commands docs, so use them while you build; switch to Routes.applicationCommands (global commands) when the bot goes public. Integer options take a minimum and maximum, so Discord rejects a /pay of 0 before your code runs. Save this as src/deploy-commands.js and run it with node src/deploy-commands.js:
const { REST, Routes, SlashCommandBuilder } = require('discord.js'); const commands = [ new SlashCommandBuilder().setName('balance').setDescription('Show your coin balance') .addUserOption((o) => o.setName('member').setDescription('Someone else in this server')), new SlashCommandBuilder().setName('daily').setDescription('Claim your daily coins'), new SlashCommandBuilder().setName('pay').setDescription('Send coins to another member') .addUserOption((o) => o.setName('member').setDescription('Who gets the coins').setRequired(true)) .addIntegerOption((o) => o.setName('amount').setDescription('How many coins').setRequired(true).setMinValue(1).setMaxValue(5000)), new SlashCommandBuilder().setName('leaderboard').setDescription('Top 10 balances in this server'), new SlashCommandBuilder().setName('earn').setDescription('Earn more coins on our website'), ].map((c) => c.toJSON()); const rest = new REST().setToken(process.env.DISCORD_TOKEN); rest.put(Routes.applicationGuildCommands(process.env.DISCORD_CLIENT_ID, process.env.GUILD_ID), { body: commands }) .then((data) => console.log(`Registered ${data.length} commands`)) .catch(console.error); Then the bot, src/bot.js:
const { Client, Events, GatewayIntentBits, MessageFlags, ActionRowBuilder, ButtonBuilder, ButtonStyle, time, TimestampStyles, userMention, } = require('discord.js'); const { openLedger, EconomyError, DAY } = require('./ledger'); const ledger = openLedger(process.env.ECONOMY_DB || 'economy.db'); const client...