@m3rcena/eco 0.0.0-stage → 14.28.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +119 -0
  2. package/DOCUMENTATION.md +869 -0
  3. package/LICENSE +191 -0
  4. package/README.md +182 -2
  5. package/assets/logo.png +0 -0
  6. package/dist/host-Bmld-WtZ.cjs +6163 -0
  7. package/dist/host-Bmld-WtZ.cjs.map +1 -0
  8. package/dist/host-XZmTzNyx.d.cts +1833 -0
  9. package/dist/host-XZmTzNyx.d.cts.map +1 -0
  10. package/dist/host-_xxHiG2p.d.mts +1833 -0
  11. package/dist/host-_xxHiG2p.d.mts.map +1 -0
  12. package/dist/host-qJNVzdDa.mjs +5894 -0
  13. package/dist/host-qJNVzdDa.mjs.map +1 -0
  14. package/dist/host.cjs +4 -0
  15. package/dist/host.d.cts +2 -0
  16. package/dist/host.d.mts +2 -0
  17. package/dist/host.mjs +2 -0
  18. package/dist/index.cjs +1440 -0
  19. package/dist/index.cjs.map +1 -0
  20. package/dist/index.d.cts +339 -0
  21. package/dist/index.d.cts.map +1 -0
  22. package/dist/index.d.mts +339 -0
  23. package/dist/index.d.mts.map +1 -0
  24. package/dist/index.mjs +1371 -0
  25. package/dist/index.mjs.map +1 -0
  26. package/dist/register.cjs +46 -0
  27. package/dist/register.cjs.map +1 -0
  28. package/dist/register.d.cts +6 -0
  29. package/dist/register.d.cts.map +1 -0
  30. package/dist/register.d.mts +6 -0
  31. package/dist/register.d.mts.map +1 -0
  32. package/dist/register.mjs +44 -0
  33. package/dist/register.mjs.map +1 -0
  34. package/dist/resolver.cjs +305 -0
  35. package/dist/resolver.cjs.map +1 -0
  36. package/dist/resolver.d.cts +40 -0
  37. package/dist/resolver.d.cts.map +1 -0
  38. package/dist/resolver.d.mts +40 -0
  39. package/dist/resolver.d.mts.map +1 -0
  40. package/dist/resolver.mjs +296 -0
  41. package/dist/resolver.mjs.map +1 -0
  42. package/dist/rolldown-runtime-CmQyd0Gu.cjs +27 -0
  43. package/dist/rolldown-runtime-D3PmRqjj.mjs +4 -0
  44. package/package.json +94 -4
@@ -0,0 +1,869 @@
1
+ # 📖 @m3rcena/eco Comprehensive API Documentation
2
+
3
+ > 📚 **Official GitHub Wiki**: The full, categorized documentation, tutorials, and deep-dive guides are organized in the **[M3rcena Eco Official Wiki](https://github.com/M3rcena/m3rcena-eco/wiki)**:
4
+ > - **[Architecture & Database Handlers](https://github.com/M3rcena/m3rcena-eco/wiki/Architecture)**
5
+ > - **[Real Economy: Bank Vaults, Loans, Bills & Taxes](https://github.com/M3rcena/m3rcena-eco/wiki/Real-Economy)**
6
+ > - **[Careers, Jobs, Shop & Businesses](https://github.com/M3rcena/m3rcena-eco/wiki/Careers-and-Shop)**
7
+ > - **[Casino & Gambling Suite](https://github.com/M3rcena/m3rcena-eco/wiki/Casino-Suite)**
8
+ > - **[Stocks, Heists, Pets & Loot Crates](https://github.com/M3rcena/m3rcena-eco/wiki/Stocks-Heists-and-Pets)**
9
+ > - **[Dashboard Bridge Integration](https://github.com/M3rcena/m3rcena-eco/wiki/Bridge-Integration)**
10
+
11
+ Welcome to the definitive documentation for **`@m3rcena/eco`** (v14.28.1) — the ultimate enterprise-grade Discord.js v14 economy, progression, career, stock market, and casino engine.
12
+
13
+ ---
14
+
15
+ ## 📑 Table of Contents
16
+
17
+ 1. [Architecture & Design Principles](#1-architecture--design-principles)
18
+ 2. [Installation & Requirements](#2-installation--requirements)
19
+ 3. [Quickstart Setup](#3-quickstart-setup)
20
+ 4. [The Central Engine: `EcoManager`](#4-the-central-engine-ecomanager)
21
+ 5. [Database Handlers & Persistence Layer](#5-database-handlers--persistence-layer)
22
+ - [5.1. Zero-Config Local SQLite (`node:sqlite`)](#51-zero-config-local-sqlite-nodesqlite)
23
+ - [5.2. Enterprise Prisma ORM Integration](#52-enterprise-prisma-orm-integration)
24
+ - [5.3. Manual Prisma Migration Tables (PostgreSQL, MySQL, SQLite)](#53-manual-prisma-migration-tables)
25
+ - [5.4. JSON File Storage (`JsonEcoStorage`)](#54-json-file-storage-jsonecostorage)
26
+ - [5.5. In-Memory Ephemeral Storage (`MemoryEcoStorage`)](#55-in-memory-ephemeral-storage-memoryecostorage)
27
+ - [5.6. Custom Database Adapters (`EcoStorageAdapter`)](#56-custom-database-adapters-ecostorageadapter)
28
+ 6. [Core Banking & Dual-Currency System (`BankManager`)](#6-core-banking--dual-currency-system-bankmanager)
29
+ 7. [Daily Streaks, Work, Crime & Robbery (`RewardManager`)](#7-daily-streaks-work-crime--robbery-rewardmanager)
30
+ 8. [Career Progression & Jobs (`CareerManager`)](#8-career-progression--jobs-careermanager)
31
+ 9. [Shop, Inventory & Consumable Buffs (`ShopManager`)](#9-shop-inventory--consumable-buffs-shopmanager)
32
+ 10. [Passive Business Investment (`BusinessManager`)](#10-passive-business-investment-businessmanager)
33
+ 11. [Casino & High-Stakes Gambling Suite (`CasinoManager`)](#11-casino--high-stakes-gambling-suite-casinomanager)
34
+ - [11.1. Coinflip (`coinflip`)](#111-coinflip)
35
+ - [11.2. Dice Roll (`dice`)](#112-dice-roll)
36
+ - [11.3. Slot Machine (`slots`)](#113-slot-machine)
37
+ - [11.4. European Roulette (`roulette`)](#114-european-roulette)
38
+ - [11.5. Crash Multiplier (`crash`)](#115-crash-multiplier)
39
+ - [11.6. Blackjack Table (`blackjack`)](#116-blackjack-table)
40
+ 12. [Simulated Stock & Crypto Exchange (`StockMarketManager`)](#12-simulated-stock--crypto-exchange-stockmarketmanager)
41
+ 13. [Multiplayer Syndicate Heists (`HeistManager`)](#13-multiplayer-syndicate-heists-heistmanager)
42
+ 14. [Companion Pets & Foraging (`PetManager`)](#14-companion-pets--foraging-petmanager)
43
+ 15. [Mystery Loot Crates (`CrateManager`)](#15-mystery-loot-crates-cratemanager)
44
+ 16. [Real Economy: Bank Vaults & Compound Interest (`VaultManager`)](#16-real-economy-bank-vaults--compound-interest-vaultmanager)
45
+ 17. [Real Economy: Credit Score, Loans & Debt (`LoanManager`)](#17-real-economy-credit-score-loans--debt-loanmanager)
46
+ 18. [Real Economy: Municipal Bills, Taxes & Audits (`TaxManager`)](#18-real-economy-municipal-bills-taxes--audits-taxmanager)
47
+ 19. [Interactive Discord Components V2 UI Suite](#19-interactive-discord-components-v2-ui-suite)
48
+ 20. [High-Resolution Canvas Card Renderers](#20-high-resolution-canvas-card-renderers)
49
+ 21. [Cross-Platform Bridge Integration (`EcoBridgeRouter`)](#21-cross-platform-bridge-integration-ecobridgerouter)
50
+ 22. [Complete TypeScript Types Reference](#22-complete-typescript-types-reference)
51
+
52
+ ---
53
+
54
+ ## 1. Architecture & Design Principles
55
+
56
+ `@m3rcena/eco` is built with a modular, decoupled architecture where each financial domain is encapsulated within a dedicated manager class. All managers interact with the unified storage adapter to ensure atomic state updates and consistent user accounts.
57
+
58
+ ```
59
+ ┌───────────────────────────────────────────────┐
60
+ │ EcoManager │
61
+ └───────────────────────┬───────────────────────┘
62
+ │
63
+ ┌───────────────────┬────────────────────────┼────────────────────────┬───────────────────┐
64
+ │ │ │ │ │
65
+ ▼ ▼ ▼ ▼ ▼
66
+ ┌─────────────┐ ┌───────────────┐ ┌───────────────┐ ┌───────────────┐ ┌───────────────┐
67
+ │ BankManager │ │ RewardManager │ │ CareerManager │ │ ShopManager │ │BusinessManager│
68
+ └──────┬──────┘ └───────┬───────┘ └───────┬───────┘ └───────┬───────┘ └───────┬───────┘
69
+ │ │ │ │ │
70
+ ├───────────────────┼────────────────────────┼────────────────────────┼───────────────────┤
71
+ ▼ ▼ ▼ ▼ ▼
72
+ ┌─────────────┐ ┌───────────────┐ ┌───────────────┐ ┌───────────────┐ ┌───────────────┐
73
+ │CasinoManager│ │StockMarketMgr │ │ HeistManager │ │ PetManager │ │ CrateManager │
74
+ └──────┬──────┘ └───────┬───────┘ └───────┬───────┘ └───────┬───────┘ └───────┬───────┘
75
+ │ │ │ │ │
76
+ ├───────────────────┼────────────────────────┼────────────────────────┼───────────────────┤
77
+ ▼ ▼ ▼ ▼ ▼
78
+ ┌─────────────┐ ┌───────────────┐ ┌───────────────┐ ┌───────────────┐ ┌───────────────┐
79
+ │VaultManager │ │ LoanManager │ │ TaxManager │ │LeaderboardMgr │ │EcoBridgeRouter│
80
+ └──────┬──────┘ └───────┬───────┘ └───────┬───────┘ └───────┬───────┘ └───────┬───────┘
81
+ │ │ │ │ │
82
+ └───────────────────┴────────────────────────┼────────────────────────┴───────────────────┘
83
+ ▼
84
+ ┌─────────────────────────────┐
85
+ │ EcoStorageAdapter │
86
+ │ (SQLite / Prisma / JSON) │
87
+ └─────────────────────────────┘
88
+ ```
89
+
90
+ - **Dual-Currency Balance**: Cash on hand (Wallet) and protected funds (Bank).
91
+ - **Zero-Dependency Native SQLite**: Native `node:sqlite` storage for zero-hassle local databases.
92
+ - **Enterprise Prisma ORM**: Auto-migrating Prisma storage with direct delegates or raw SQL fallback.
93
+ - **Components V2 Powered**: Uses Discord's modern `flags: 32768` (Components V2) container structures.
94
+ - **Cross-Platform Bridge Ready**: Plugs into `@m3rcena/bridge` via `bridge.use(eco)` with live REST API and WebSocket events.
95
+
96
+ ---
97
+
98
+ ## 2. Installation & Requirements
99
+
100
+ ```bash
101
+ npm install @m3rcena/eco @m3rcena/bridge discord.js
102
+ ```
103
+
104
+ ### System Requirements
105
+ - **Node.js**: `>= 22.0.0` (Node 22, 24, or 26 recommended; supports native `node:sqlite`).
106
+ - **Discord.js**: `^14.0.0`.
107
+ - **Canvas (Optional)**: `@napi-rs/canvas` is bundled automatically for debit cards and stock charts.
108
+
109
+ ---
110
+
111
+ ## 3. Quickstart Setup
112
+
113
+ ```typescript
114
+ import { Client, GatewayIntentBits } from "discord.js";
115
+ import { EcoManager, EcoProfileUI, EcoShopUI, EcoStockMarketUI } from "@m3rcena/eco";
116
+
117
+ const client = new Client({
118
+ intents: [
119
+ GatewayIntentBits.Guilds,
120
+ GatewayIntentBits.GuildMessages,
121
+ GatewayIntentBits.MessageContent,
122
+ ],
123
+ });
124
+
125
+ // Initialize EcoManager with native SQLite
126
+ export const eco = new EcoManager({
127
+ currencySymbol: "🪙",
128
+ currencyName: "Coins",
129
+ embedColor: "#F1C40F",
130
+ database: "sqlite", // Zero configuration! Auto-creates ./eco.sqlite
131
+ });
132
+
133
+ client.on("messageCreate", async (message) => {
134
+ if (message.author.bot) return;
135
+
136
+ // 1. Balance Check
137
+ if (message.content === "!balance") {
138
+ const bal = await eco.getBalance(message.author.id, message.guildId ?? undefined);
139
+ return message.reply(`💰 Wallet: 🪙 ${bal.wallet.toLocaleString()} | Bank: 🪙 ${bal.bank.toLocaleString()} / ${bal.bankCapacity.toLocaleString()}`);
140
+ }
141
+
142
+ // 2. Daily Reward
143
+ if (message.content === "!daily") {
144
+ const res = await eco.daily(message.author.id, message.guildId ?? undefined);
145
+ if (!res.success) return message.reply(`⏳ Cooldown! Try again in ${Math.ceil((res.cooldownRemainingMs ?? 0) / 60000)}m.`);
146
+ return message.reply(`🎉 Claimed 🪙 ${res.amount.toLocaleString()}! Daily Streak: ${res.streak} 🔥`);
147
+ }
148
+
149
+ // 3. Interactive Components V2 Passport Profile
150
+ if (message.content === "!profile") {
151
+ return new EcoProfileUI(eco, { context: message }).start();
152
+ }
153
+
154
+ // 4. Interactive Components V2 Shop
155
+ if (message.content === "!shop") {
156
+ return new EcoShopUI(eco, { context: message }).start();
157
+ }
158
+ });
159
+
160
+ client.login("YOUR_BOT_TOKEN");
161
+ ```
162
+
163
+ ---
164
+
165
+ ## 4. The Central Engine: `EcoManager`
166
+
167
+ `EcoManager` is the unified orchestrator exposing high-level helper functions for all underlying modules.
168
+
169
+ ### Options (`EcoManagerOptions`)
170
+
171
+ | Option | Type | Default | Description |
172
+ | :--- | :--- | :--- | :--- |
173
+ | `currencySymbol` | `string` | `"🪙"` | Prefix symbol displayed across cards and messages. |
174
+ | `currencyName` | `string` | `"Coins"` | Plural name of the currency. |
175
+ | `embedColor` | `any` | `0x5865f2` | Primary embed accent color (Hex string or number). |
176
+ | `mode` | `"guild" \| "global"` | `"guild"` | Scoping mode for user accounts and leaderboards. |
177
+ | `defaultWalletBalance` | `number` | `500` | Starting cash granted to new accounts. |
178
+ | `defaultBankCapacity` | `number` | `10000` | Starting maximum bank deposit ceiling. |
179
+ | `bankInterestRate` | `number` | `0.01` | Daily interest multiplier on bank holdings (1%). |
180
+ | `transactionFeePercentage` | `number` | `0` | Fee percentage deducted on player transfers (e.g. `0.02` for 2%). |
181
+ | `database` | `EcoDatabaseConfig` | `"memory"` | Database storage configuration (`"sqlite"`, `"prisma"`, `"json"`, or object). |
182
+ | `storage` | `EcoStorageAdapter` | `MemoryEcoStorage` | Custom storage adapter instance. |
183
+ | `bridge` | `M3rcenaBridge` | `undefined` | Active `@m3rcena/bridge` instance for web dashboard synchronization. |
184
+ | `notifyUpdates` | `boolean` | `true` | Log styled update notification box when a newer version is on npm. |
185
+ | `stockMarketTickIntervalMs` | `number` | `60000` | Milliseconds between simulated market price fluctuations. |
186
+ | `initialStocks` | `StockConfig[]` | `DEFAULT_STOCKS` | Custom initial stock and crypto assets. |
187
+ | `initialHeistTargets` | `HeistTarget[]` | `DEFAULT_HEIST_TARGETS` | Custom heist target vaults. |
188
+ | `initialPets` | `PetConfig[]` | `DEFAULT_PETS` | Custom companion pets catalog. |
189
+ | `cooldowns` | `object` | *See below* | Cooldown duration overrides in milliseconds. |
190
+
191
+ ---
192
+
193
+ ## 5. Database Handlers & Persistence Layer
194
+
195
+ `@m3rcena/eco` features a zero-friction database system. Developers can choose between native SQLite, Prisma ORM, JSON files, or memory storage via the `database` configuration.
196
+
197
+ ```typescript
198
+ export type EcoDatabaseConfig =
199
+ | "sqlite"
200
+ | "memory"
201
+ | "json"
202
+ | { type: "sqlite"; path?: string }
203
+ | { type: "prisma"; client: any; model?: string; autoMigrate?: boolean }
204
+ | { type: "json"; path?: string }
205
+ | { type: "memory" };
206
+ ```
207
+
208
+ ---
209
+
210
+ ### 5.1. Zero-Config Local SQLite (`node:sqlite`)
211
+
212
+ Uses Node.js `>= 22.0.0` built-in `node:sqlite` (`DatabaseSync`). Zero npm compilation, zero C++ build tools, instant startup, WAL mode enabled by default, and indexed queries.
213
+
214
+ ```typescript
215
+ import { EcoManager } from "@m3rcena/eco";
216
+
217
+ const eco = new EcoManager({
218
+ // Auto-creates ./eco.sqlite with tables & indexes
219
+ database: "sqlite",
220
+
221
+ // Or with custom directory:
222
+ database: {
223
+ type: "sqlite",
224
+ path: "./data/economy.sqlite",
225
+ },
226
+ });
227
+ ```
228
+
229
+ ---
230
+
231
+ ### 5.2. Enterprise Prisma ORM Integration
232
+
233
+ Pass an existing `PrismaClient` instance. If your database hasn't compiled the `EcoAccount` delegate, `@m3rcena/eco` automatically runs DDL creation and executes queries via raw SQL:
234
+
235
+ ```typescript
236
+ import { PrismaClient } from "@prisma/client";
237
+ import { EcoManager, applyPrismaEcoModel } from "@m3rcena/eco";
238
+
239
+ const prisma = new PrismaClient();
240
+
241
+ // Optional: Automatically appends `model EcoAccount` to schema.prisma if missing:
242
+ applyPrismaEcoModel();
243
+
244
+ const eco = new EcoManager({
245
+ database: {
246
+ type: "prisma",
247
+ client: prisma,
248
+ autoMigrate: true, // Auto-creates table if missing
249
+ },
250
+ });
251
+ ```
252
+
253
+ ---
254
+
255
+ ### 5.3. Manual Prisma Migration Tables
256
+
257
+ If you prefer to manage database schemas manually or with `npx prisma migrate dev`, use the schema snippet below:
258
+
259
+ #### Prisma Schema Snippet (`schema.prisma`):
260
+ ```prisma
261
+ model EcoAccount {
262
+ userId String
263
+ guildId String @default("")
264
+ wallet Float @default(0)
265
+ bank Float @default(0)
266
+ level Int @default(1)
267
+ data String // Complete JSON payload of account state (inventory, businesses, etc.)
268
+ updatedAt DateTime @updatedAt
269
+
270
+ @@id([userId, guildId])
271
+ @@index([guildId])
272
+ @@index([wallet, bank])
273
+ }
274
+ ```
275
+
276
+ #### PostgreSQL Manual Migration SQL:
277
+ ```sql
278
+ CREATE TABLE IF NOT EXISTS "EcoAccount" (
279
+ "userId" VARCHAR(191) NOT NULL,
280
+ "guildId" VARCHAR(191) NOT NULL DEFAULT '',
281
+ "wallet" DOUBLE PRECISION NOT NULL DEFAULT 0,
282
+ "bank" DOUBLE PRECISION NOT NULL DEFAULT 0,
283
+ "level" INTEGER NOT NULL DEFAULT 1,
284
+ "data" TEXT NOT NULL,
285
+ "updatedAt" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
286
+ PRIMARY KEY ("userId", "guildId")
287
+ );
288
+
289
+ CREATE INDEX IF NOT EXISTS idx_eco_guild ON "EcoAccount" ("guildId");
290
+ CREATE INDEX IF NOT EXISTS idx_eco_networth ON "EcoAccount" ("wallet", "bank");
291
+ ```
292
+
293
+ #### MySQL Manual Migration SQL:
294
+ ```sql
295
+ CREATE TABLE IF NOT EXISTS `EcoAccount` (
296
+ `userId` VARCHAR(191) NOT NULL,
297
+ `guildId` VARCHAR(191) NOT NULL DEFAULT '',
298
+ `wallet` DOUBLE NOT NULL DEFAULT 0,
299
+ `bank` DOUBLE NOT NULL DEFAULT 0,
300
+ `level` INT NOT NULL DEFAULT 1,
301
+ `data` LONGTEXT NOT NULL,
302
+ `updatedAt` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
303
+ PRIMARY KEY (`userId`, `guildId`),
304
+ INDEX idx_eco_guild (`guildId`),
305
+ INDEX idx_eco_networth (`wallet`, `bank`)
306
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
307
+ ```
308
+
309
+ #### SQLite Manual Migration SQL:
310
+ ```sql
311
+ CREATE TABLE IF NOT EXISTS eco_accounts (
312
+ user_id TEXT NOT NULL,
313
+ guild_id TEXT NOT NULL DEFAULT '',
314
+ wallet REAL NOT NULL DEFAULT 0,
315
+ bank REAL NOT NULL DEFAULT 0,
316
+ level INTEGER NOT NULL DEFAULT 1,
317
+ data TEXT NOT NULL,
318
+ updated_at INTEGER NOT NULL,
319
+ PRIMARY KEY (user_id, guild_id)
320
+ );
321
+
322
+ CREATE INDEX IF NOT EXISTS idx_eco_guild ON eco_accounts (guild_id);
323
+ CREATE INDEX IF NOT EXISTS idx_eco_networth ON eco_accounts (wallet + bank DESC);
324
+ ```
325
+
326
+ ---
327
+
328
+ ### 5.4. JSON File Storage (`JsonEcoStorage`)
329
+
330
+ ```typescript
331
+ const eco = new EcoManager({
332
+ database: "json", // Defaults to ./eco-data.json
333
+ // Or:
334
+ database: {
335
+ type: "json",
336
+ path: "./data/economy.json",
337
+ },
338
+ });
339
+ ```
340
+
341
+ ---
342
+
343
+ ### 5.5. In-Memory Ephemeral Storage (`MemoryEcoStorage`)
344
+
345
+ Ideal for unit testing or ephemeral Discord bots with zero disk I/O:
346
+
347
+ ```typescript
348
+ const eco = new EcoManager({
349
+ database: "memory",
350
+ });
351
+ ```
352
+
353
+ ---
354
+
355
+ ### 5.6. Custom Database Adapters (`EcoStorageAdapter`)
356
+
357
+ Implement the `EcoStorageAdapter` interface for MongoDB, DynamoDB, or Redis:
358
+
359
+ ```typescript
360
+ import { EcoStorageAdapter, UserAccount } from "@m3rcena/eco";
361
+
362
+ export class CustomMongoStorage implements EcoStorageAdapter {
363
+ async getAccount(userId: string, guildId?: string): Promise<UserAccount | null> {
364
+ // Return UserAccount or null
365
+ }
366
+ async saveAccount(account: UserAccount): Promise<void> {
367
+ // Persist account
368
+ }
369
+ async getTopAccounts(sortBy: "netWorth" | "wallet" | "bank" | "level", limit?: number, guildId?: string): Promise<UserAccount[]> {
370
+ // Return sorted accounts
371
+ }
372
+ async getAllAccounts(guildId?: string): Promise<UserAccount[]> {
373
+ // Return all accounts
374
+ }
375
+ }
376
+ ```
377
+
378
+ ---
379
+
380
+ ## 6. Core Banking & Dual-Currency System (`BankManager`)
381
+
382
+ Manages player accounts, wallet funds, bank storage, deposits, withdrawals, and peer transfers.
383
+
384
+ ### Methods
385
+
386
+ #### `eco.getBalance(userId: string, guildId?: string): Promise<UserAccount>`
387
+ Returns the complete user account record with `wallet`, `bank`, `bankCapacity`, and computed `netWorth`.
388
+
389
+ #### `eco.deposit(userId: string, amount: number | "all", guildId?: string): Promise<TransferResult>`
390
+ Transfers funds from `wallet` to `bank`. Automatically caps deposits at `bankCapacity`.
391
+ ```typescript
392
+ const res = await eco.deposit(message.author.id, 500);
393
+ if (!res.success) message.reply(res.error);
394
+ ```
395
+
396
+ #### `eco.withdraw(userId: string, amount: number | "all", guildId?: string): Promise<TransferResult>`
397
+ Transfers funds from `bank` to `wallet`.
398
+
399
+ #### `eco.transfer(fromUserId: string, toUserId: string, amount: number, guildId?: string): Promise<TransferResult>`
400
+ Transfers funds between two users with optional percentage fees (`transactionFeePercentage`).
401
+
402
+ #### `eco.modifyWallet(userId: string, delta: number, guildId?: string): Promise<UserAccount>`
403
+ Directly increments or decrements cash in a user's wallet.
404
+
405
+ #### `eco.modifyBank(userId: string, delta: number, guildId?: string): Promise<UserAccount>`
406
+ Directly increments or decrements balance in a user's bank.
407
+
408
+ #### `eco.setBankCapacity(userId: string, newCap: number, guildId?: string): Promise<UserAccount>`
409
+ Sets maximum bank storage limit.
410
+
411
+ ---
412
+
413
+ ## 7. Daily Streaks, Work, Crime & Robbery (`RewardManager`)
414
+
415
+ Manages recurring player actions, time-gated reward claims, and high-risk criminal gameplay.
416
+
417
+ ### Default Cooldowns
418
+ - **Daily**: 24 hours (`86,400,000` ms)
419
+ - **Weekly**: 7 days (`604,800,000` ms)
420
+ - **Monthly**: 30 days (`2,592,000,000` ms)
421
+ - **Hourly**: 1 hour (`3,600,000` ms)
422
+ - **Work**: 30 minutes (`1,800,000` ms)
423
+ - **Beg**: 45 seconds (`45,000` ms)
424
+ - **Crime**: 15 minutes (`900,000` ms)
425
+ - **Rob**: 2 hours (`7,200,000` ms)
426
+
427
+ ### Methods
428
+
429
+ #### `eco.daily(userId, guildId?): Promise<RewardClaimResult>`
430
+ Claims daily cash reward with progressive streak bonuses.
431
+
432
+ #### `eco.work(userId, guildId?): Promise<WorkResult>`
433
+ Works a shift at the user's active career job. Awards career salary and character XP.
434
+
435
+ #### `eco.beg(userId, guildId?): Promise<BegResult>`
436
+ Begs from a randomized NPC (e.g. Elon Musk, MrBeast, Grandma) with custom dialogue quotes.
437
+
438
+ #### `eco.crime(userId, guildId?): Promise<CrimeResult>`
439
+ Attempts high-risk crime. 50% chance to earn 🪙 1,500 - 4,000; 50% chance to be fined by the police.
440
+
441
+ #### `eco.rob(robberId, victimId, guildId?): Promise<RobResult>`
442
+ Attempts to steal wallet cash from another player.
443
+ - **Titanium Padlock Shield**: If the victim owns a padlock, robbery fails and the padlock breaks.
444
+ - **Fail Penalty**: If caught, the robber pays a fine to the victim.
445
+
446
+ ---
447
+
448
+ ## 8. Career Progression & Jobs (`CareerManager`)
449
+
450
+ Provides a 10-tier career progression ladder with promotion mechanics and salary scaling.
451
+
452
+ ### Career Ladder (`DEFAULT_JOBS`)
453
+
454
+ | Tier | Job Title | Base Salary | Required Level | Required Shifts for Promotion |
455
+ | :---: | :--- | :---: | :---: | :---: |
456
+ | 1 | 🧹 Janitor | 🪙 150 | Lv 1 | 5 Shifts |
457
+ | 2 | ☕ Barista | 🪙 350 | Lv 2 | 10 Shifts |
458
+ | 3 | 📦 Delivery Courier | 🪙 650 | Lv 4 | 15 Shifts |
459
+ | 4 | 💻 Junior Software Dev | 🪙 1,200 | Lv 7 | 20 Shifts |
460
+ | 5 | 🔐 Cyber Security Analyst | 🪙 2,400 | Lv 12 | 25 Shifts |
461
+ | 6 | 📈 Wall Street Broker | 🪙 4,800 | Lv 18 | 30 Shifts |
462
+ | 7 | 🚀 Aerospace Engineer | 🪙 9,500 | Lv 25 | 35 Shifts |
463
+ | 8 | ⚖️ Corporate Law Partner | 🪙 18,000 | Lv 35 | 40 Shifts |
464
+ | 9 | 🏥 Chief Medical Officer | 🪙 35,000 | Lv 50 | 50 Shifts |
465
+ | 10 | 👑 Hedge Fund Managing Dir | 🪙 75,000 | Lv 75 | Max Tier |
466
+
467
+ ### Methods
468
+ - `eco.careers.getAvailableJobs()`: List all career options.
469
+ - `eco.careers.apply(userId, jobId, guildId?)`: Apply for a position.
470
+ - `eco.careers.getUserJob(userId, guildId?)`: Get active job details and promotion progress.
471
+
472
+ ---
473
+
474
+ ## 9. Shop, Inventory & Consumable Buffs (`ShopManager`)
475
+
476
+ Full player inventory management with interactive shopping and consumable buffs.
477
+
478
+ ### Default Item Catalog (`DEFAULT_SHOP_ITEMS`)
479
+
480
+ | ID | Name | Price | Type | Effect Description |
481
+ | :--- | :--- | :---: | :---: | :--- |
482
+ | `padlock` | 🔒 Titanium Padlock | 🪙 2,500 | Defense | Blocks 1 robbery attempt; breaks on protection. |
483
+ | `energy_drink` | ⚡ Cyber Energy Drink | 🪙 800 | Consumable | Instantly resets your work shift cooldown. |
484
+ | `lucky_clover` | 🍀 Four-Leaf Clover | 🪙 3,500 | Consumable | Grants +15% casino winning probability for 1 hour. |
485
+ | `swiss_key` | 🗝️ Swiss Vault Key | 🪙 15,000 | Permanent | Permanently expands maximum bank capacity by +🪙 25,000. |
486
+ | `crypto_miner` | ⛏️ ASIC Mining Rig | 🪙 30,000 | Business | Generates passive crypto yields into your wallet. |
487
+
488
+ ### Methods
489
+ - `eco.shop.getItems()`: Retrieve active shop catalog.
490
+ - `eco.shop.buy(userId, itemId, quantity, guildId?)`: Buy items with wallet cash.
491
+ - `eco.shop.sell(userId, itemId, quantity, guildId?)`: Sell items back for 70% refund.
492
+ - `eco.shop.use(userId, itemId, guildId?)`: Activate consumable buff.
493
+
494
+ ---
495
+
496
+ ## 10. Passive Business Investment (`BusinessManager`)
497
+
498
+ Allows players to purchase enterprises, upgrade facilities, hire staff, and collect passive income.
499
+
500
+ ### Business Catalog (`DEFAULT_BUSINESS_CATALOG`)
501
+
502
+ | ID | Enterprise | Base Cost | Hourly Revenue | Base Employees |
503
+ | :--- | :--- | :---: | :---: | :---: |
504
+ | `kiosk` | ☕ Coffee Kiosk | 🪙 10,000 | 🪙 400 / hr | 2 Baristas |
505
+ | `startup` | 💻 SaaS Tech Startup | 🪙 50,000 | 🪙 2,500 / hr | 5 Developers |
506
+ | `mining_rig` | ⛏️ Bitcoin Mining Farm | 🪙 150,000 | 🪙 9,000 / hr | 3 Engineers |
507
+ | `megacorp` | 🏢 Conglomerate Holding Corp | 🪙 1,000,000 | 🪙 75,000 / hr | 25 Executives |
508
+
509
+ ### Methods
510
+ - `eco.businesses.buy(userId, businessId, guildId?)`: Purchase enterprise.
511
+ - `eco.businesses.upgrade(userId, businessId, guildId?)`: Level up facility multiplier.
512
+ - `eco.businesses.hire(userId, businessId, count, guildId?)`: Hire employees for revenue boost.
513
+ - `eco.businesses.collect(userId, guildId?)`: Harvest accumulated revenue.
514
+
515
+ ---
516
+
517
+ ## 11. Casino & High-Stakes Gambling Suite (`CasinoManager`)
518
+
519
+ A complete, strictly audited casino suite with fair random math.
520
+
521
+ ### 11.1. Coinflip
522
+ ```typescript
523
+ const res = await eco.coinflip(userId, 500, "heads");
524
+ // res: { won: boolean, choice: "heads", outcome: "heads", payout: 1000 }
525
+ ```
526
+
527
+ ### 11.2. Dice Roll
528
+ ```typescript
529
+ // Prediction: "high" (4-6), "low" (1-3), or exact number (1-6)
530
+ const res = await eco.dice(userId, 250, "high");
531
+ ```
532
+
533
+ ### 11.3. Slot Machine
534
+ Spins 3 reels. Triple 7s award the 50x Mega Jackpot!
535
+ ```typescript
536
+ const res = await eco.slots(userId, 100);
537
+ // res: { reels: ["💎", "💎", "💎"], multiplier: 15, payout: 1500 }
538
+ ```
539
+
540
+ ### 11.4. European Roulette
541
+ Supports red, black, green (0), even, odd, or exact numbers (0-36).
542
+ ```typescript
543
+ const res = await eco.roulette(userId, 1000, "red");
544
+ ```
545
+
546
+ ### 11.5. Crash Multiplier
547
+ Simulates the popular crypto crash curve.
548
+ ```typescript
549
+ const res = await eco.crash(userId, 500, 2.5); // Target: 2.5x
550
+ ```
551
+
552
+ ### 11.6. Blackjack Table
553
+ Interactive dealer vs player blackjack:
554
+ ```typescript
555
+ const session = await eco.casino.startBlackjack(userId, 500);
556
+ // Hit or Stand
557
+ const updated = await eco.casino.stepBlackjack(userId, "hit");
558
+ ```
559
+
560
+ ---
561
+
562
+ ## 12. Simulated Stock & Crypto Exchange (`StockMarketManager`)
563
+
564
+ Simulates a live stock and crypto exchange with price fluctuations and market charts.
565
+
566
+ ### Assets Tracked
567
+ - `TECH`: Antigravity Technologies
568
+ - `CRYP`: Cyber Bitcoin
569
+ - `CORP`: Apex Conglomerate
570
+ - `AERO`: Orbital Aerospace
571
+
572
+ ### Methods
573
+ - `eco.stocks.getMarketOverview()`: Live prices, 24h change, and volume.
574
+ - `eco.stocks.buy(userId, symbol, shares, guildId?)`: Market buy order.
575
+ - `eco.stocks.sell(userId, symbol, shares, guildId?)`: Market sell order with realized PnL.
576
+ - `eco.stocks.getUserPortfolio(userId, guildId?)`: Portfolio holdings and valuation.
577
+
578
+ ---
579
+
580
+ ## 13. Multiplayer Syndicate Heists (`HeistManager`)
581
+
582
+ Assemble a crew of up to 4 players to rob high-security bank vaults.
583
+
584
+ ### Roles
585
+ - **Hacker**: Disables security lasers and firewall protocols.
586
+ - **Muscle**: Subdues bank guards and patrols.
587
+ - **Driver**: Accelerates getaway speeds and lowers arrest probability.
588
+ - **Infiltrator**: Cracks vault lock combinations.
589
+
590
+ ### Targets
591
+ 1. 🏦 Local Credit Union (Difficulty: Easy, Loot: 🪙 50,000)
592
+ 2. 🏛️ Central Federal Reserve (Difficulty: Hard, Loot: 🪙 250,000)
593
+ 3. 🌐 Global Cyber Vault (Difficulty: Insane, Loot: 🪙 1,000,000)
594
+
595
+ ---
596
+
597
+ ## 14. Companion Pets & Foraging (`PetManager`)
598
+
599
+ Adopt pets, feed them, level up companion loyalty, and dispatch them on timed expeditions for passive loot:
600
+ - `eco.pets.adopt(userId, petId, nickname)`
601
+ - `eco.pets.feed(userId, petId)`
602
+ - `eco.pets.startExpedition(userId, petId, durationMs)`
603
+ - `eco.pets.claimExpedition(userId, petId)`
604
+
605
+ ---
606
+
607
+ ## 15. Mystery Loot Crates (`CrateManager`)
608
+
609
+ Unbox mystery crates with animated reveals and rare item rewards:
610
+ - **Common Crate**: 🪙 1,500 (Small coins + Common consumables)
611
+ - **Rare Crate**: 🪙 5,000 (Coins + XP + Tools)
612
+ - **Epic Crate**: 🪙 25,000 (Large payouts + Swiss Keys)
613
+ - **Legendary Crate**: 🪙 100,000 (Huge jackpots + Permanent multipliers)
614
+
615
+ ---
616
+
617
+ ## 16. Real Economy: Bank Vaults & Compound Interest (`VaultManager`)
618
+
619
+ Upgrade bank vault security tiers to expand holding ceilings, protect funds against robbers, and earn compound daily interest:
620
+ - **Tiers**: Standard ➔ Bronze ➔ Silver ➔ Gold ➔ Platinum ➔ Diamond ➔ Swiss Titanium.
621
+ - `eco.vault.inspect(userId)`: Inspect current vault tier and interest rate.
622
+ - `eco.vault.upgrade(userId)`: Upgrade to the next security vault tier.
623
+
624
+ ---
625
+
626
+ ## 17. Real Economy: Credit Score, Loans & Debt (`LoanManager`)
627
+
628
+ A realistic credit scoring and lending engine:
629
+ - **FICO Score (300 - 850)**: Rated as `POOR`, `FAIR`, `GOOD`, or `EXCELLENT`.
630
+ - **Loan Tiers**: Starter Microloan, Small Business Loan, Commercial Mortgage, Megacorp Credit Line.
631
+ - **Credit Dynamics**: Timely loan repayments increase FICO scores and unlock larger credit lines; missed payments damage credit and trigger default penalties.
632
+ - `eco.loans.getCreditScore(userId)`
633
+ - `eco.loans.apply(userId, tierId)`
634
+ - `eco.loans.repay(userId, amount)`
635
+
636
+ ---
637
+
638
+ ## 18. Real Economy: Municipal Bills, Taxes & Audits (`TaxManager`)
639
+
640
+ Progressive taxation and municipal bills:
641
+ - **Public Utility Bills**: Periodic water, energy, and network infrastructure fees.
642
+ - **Progressive Wealth Tax**: Applied to accounts exceeding multi-million net-worth thresholds.
643
+ - **Municipal Audits**: Players who evade taxes face audits, asset freezes, and penalty fees.
644
+ - **Good Citizen Perks**: Paying bills on time grants tax discounts and XP bonuses.
645
+ - `eco.taxes.getPendingBills(userId)`
646
+ - `eco.taxes.payBill(userId, billId)`
647
+ - `eco.taxes.payAllBills(userId)`
648
+
649
+ ---
650
+
651
+ ## 19. Interactive Discord Components V2 UI Suite
652
+
653
+ `@m3rcena/eco` bundles 10 turn-key interactive user interfaces utilizing Discord Components V2:
654
+
655
+ ```typescript
656
+ import {
657
+ EcoProfileUI,
658
+ EcoShopUI,
659
+ EcoStockMarketUI,
660
+ EcoHeistUI,
661
+ EcoBlackjackUI,
662
+ EcoCrateUI,
663
+ EcoLeaderboardUI,
664
+ EcoVaultUI,
665
+ EcoLoanUI,
666
+ EcoBillsUI,
667
+ } from "@m3rcena/eco";
668
+
669
+ // 1. Digital Debit Card & Passport Profile
670
+ new EcoProfileUI(eco, { context: interaction }).start();
671
+
672
+ // 2. Interactive Storefront
673
+ new EcoShopUI(eco, { context: interaction }).start();
674
+
675
+ // 3. Stock Trader & Candle Chart
676
+ new EcoStockMarketUI(eco, { context: interaction }).start();
677
+
678
+ // 4. Syndicate Heist Recruitment Lobby
679
+ new EcoHeistUI(eco, { context: interaction }).start();
680
+
681
+ // 5. Interactive Blackjack Table
682
+ new EcoBlackjackUI(eco, { context: interaction, betAmount: 500 }).start();
683
+
684
+ // 6. Mystery Loot Crate Unboxing
685
+ new EcoCrateUI(eco, { context: interaction }).start();
686
+
687
+ // 7. Rich Paginated Net Worth Leaderboard
688
+ new EcoLeaderboardUI(eco, { context: interaction }).start();
689
+
690
+ // 8. Bank Vault Upgrades
691
+ new EcoVaultUI(eco, { context: interaction }).start();
692
+
693
+ // 9. Credit Score & Loan Terminal
694
+ new EcoLoanUI(eco, { context: interaction }).start();
695
+
696
+ // 10. Municipal Bills & Tax Ledger
697
+ new EcoBillsUI(eco, { context: interaction }).start();
698
+ ```
699
+
700
+ ---
701
+
702
+ ## 20. High-Resolution Canvas Card Renderers
703
+
704
+ Bundles native `@napi-rs/canvas` visual generators:
705
+
706
+ ### `RenderBankCard`
707
+ Generates a customized debit card complete with holographic microchip, holographic security foil, cardholder name, and bank balance:
708
+ ```typescript
709
+ import { RenderBankCard } from "@m3rcena/eco";
710
+
711
+ const buffer = await RenderBankCard.render({
712
+ username: "M3rcenaDev",
713
+ avatarUrl: "https://cdn.discordapp.com/avatars/...",
714
+ wallet: 25000,
715
+ bank: 150000,
716
+ netWorth: 175000,
717
+ bankName: "CYBER CREDIT UNION",
718
+ cardNumber: "4092 •••• •••• 8821",
719
+ });
720
+ ```
721
+
722
+ ### `RenderMarketChart`
723
+ Generates clean candlestick and sparkline price history charts with volume bars:
724
+ ```typescript
725
+ import { RenderMarketChart } from "@m3rcena/eco";
726
+
727
+ const chartBuffer = await RenderMarketChart.render({
728
+ symbol: "TECH",
729
+ name: "Antigravity Technologies",
730
+ currentPrice: 342.50,
731
+ change24h: 8.4,
732
+ history: [310, 315, 320, 318, 330, 342.50],
733
+ });
734
+ ```
735
+
736
+ ---
737
+
738
+ ## 21. Cross-Platform Bridge Integration (`EcoBridgeRouter`)
739
+
740
+ Connect `@m3rcena/eco` to `@m3rcena/bridge` in one line:
741
+
742
+ ```typescript
743
+ import { M3rcenaBridge } from "@m3rcena/bridge";
744
+ import { EcoManager } from "@m3rcena/eco";
745
+
746
+ const bridge = new M3rcenaBridge();
747
+ const eco = new EcoManager({ bridge });
748
+
749
+ // Fluent chaining also supported:
750
+ bridge.use(eco);
751
+ ```
752
+
753
+ ### Complete REST Route Reference (`/api/eco/*`)
754
+
755
+ | Method | Endpoint | Description |
756
+ | :--- | :--- | :--- |
757
+ | `GET` | `/api/eco/account/:userId` | Get full user account ledger (wallet, bank, net worth, vault, credit score). |
758
+ | `GET` | `/api/eco/cards/debit/:userId` | Returns rendered PNG buffer of user's holographic debit card. |
759
+ | `GET` | `/api/eco/market/overview` | Returns live prices and 24h metrics for all stocks and crypto. |
760
+ | `GET` | `/api/eco/market/chart/:symbol` | Returns rendered PNG sparkline / candlestick chart buffer. |
761
+ | `GET` | `/api/eco/leaderboard` | Returns top accounts ranked by net worth, wallet, or bank. |
762
+ | `GET` | `/api/eco/vault/:userId` | Returns current bank vault tier and upgrade pricing. |
763
+ | `GET` | `/api/eco/loans/:userId` | Returns FICO credit score, active debt, and loan offers. |
764
+ | `GET` | `/api/eco/bills/:userId` | Returns pending municipal utility bills and wealth taxes. |
765
+ | `POST` | `/api/eco/action/transfer` | Execute peer-to-peer money transfer. |
766
+ | `POST` | `/api/eco/action/gamble` | Place bets on coinflip, slots, dice, or roulette. |
767
+ | `POST` | `/api/eco/action/trade-stock` | Execute stock/crypto buy or sell orders. |
768
+
769
+ ### Live Bridge Audio Cues Dispatched
770
+ - `coin_drop`: Triggered on wallet modifications and cash earnings.
771
+ - `cash_register`: Triggered on shop purchases and bill settlements.
772
+ - `jackpot`: Triggered on slot machine 50x Mega Jackpots.
773
+ - `alarm`: Triggered on robbery attempts and bank heists.
774
+ - `upgrade_ding`: Triggered on vault tier expansions and job promotions.
775
+
776
+ ---
777
+
778
+ ## 22. Weky Minigames Integration (`EcoWekyConnector`)
779
+
780
+ Seamlessly connect `@m3rcena/eco` to `@m3rcena/weky` to disburse minigame rewards, escrow PvP bet pots, and reward tournament champions:
781
+
782
+ ```typescript
783
+ import { EcoManager } from "@m3rcena/eco";
784
+ import { WekyManager } from "@m3rcena/weky";
785
+
786
+ const eco = new EcoManager({ database: "sqlite" });
787
+ const weky = new WekyManager(client, { database: "sqlite" });
788
+
789
+ export const connector = eco.connectWeky(weky, {
790
+ defaultWinReward: 50, // Coins awarded on minigame victory
791
+ defaultLossPenalty: 0, // Coins deducted on defeat
792
+ defaultScoreMultiplier: 0.05, // Solo score multiplier (1000 pts = 50 coins)
793
+ streakBonus: 10, // +10 bonus coins per active win streak count
794
+ tournamentChampionPrize: 500, // Tournament champion prize
795
+ wagerHouseFee: 5, // 5% house fee taken from PvP bet pots
796
+ });
797
+
798
+ // Escrow a PvP wager duel:
799
+ await connector.createWager({
800
+ wagerId: interaction.channelId,
801
+ player1Id: player1.id,
802
+ player2Id: player2.id,
803
+ amount: 100, // 100 coins each = 200 pot
804
+ game: "fight",
805
+ });
806
+ ```
807
+
808
+ ---
809
+
810
+ ## 23. Complete TypeScript Types Reference
811
+
812
+ All types, configs, and adapters are exported from `@m3rcena/eco`:
813
+
814
+ ```typescript
815
+ export {
816
+ EcoManager,
817
+ BankManager,
818
+ RewardManager,
819
+ CareerManager,
820
+ ShopManager,
821
+ BusinessManager,
822
+ CasinoManager,
823
+ LeaderboardManager,
824
+ StockMarketManager,
825
+ HeistManager,
826
+ PetManager,
827
+ CrateManager,
828
+ VaultManager,
829
+ LoanManager,
830
+ TaxManager,
831
+ EcoBridgeRouter,
832
+ // Database Handlers
833
+ SqliteEcoStorage,
834
+ PrismaEcoStorage,
835
+ EcoDatabaseHandler,
836
+ resolveEcoStorage,
837
+ applyPrismaEcoModel,
838
+ PRISMA_ECO_MODEL,
839
+ // UI Suite
840
+ EcoProfileUI,
841
+ EcoShopUI,
842
+ EcoStockMarketUI,
843
+ EcoHeistUI,
844
+ EcoBlackjackUI,
845
+ EcoCrateUI,
846
+ EcoLeaderboardUI,
847
+ EcoVaultUI,
848
+ EcoLoanUI,
849
+ EcoBillsUI,
850
+ // Canvas Renderers
851
+ RenderBankCard,
852
+ RenderMarketChart,
853
+ // Types
854
+ type UserAccount,
855
+ type EcoDatabaseConfig,
856
+ type EcoStorageAdapter,
857
+ type TransferResult,
858
+ type RobResult,
859
+ type CasinoBetResult,
860
+ type StockConfig,
861
+ type StockTradeResult,
862
+ type HeistTarget,
863
+ type UserPet,
864
+ type BankVaultTier,
865
+ type CreditScoreData,
866
+ type LoanOffer,
867
+ type MunicipalBill,
868
+ };
869
+ ```