Skip to content

Architecture

M3rcena edited this page Nov 1, 2026 · 3 revisions

🏗️ Architecture & Database Storage Handlers

This document details the internal system architecture, data models, persistence layers, and database migration tables for @m3rcena/eco.


🏛️ System Architecture

@m3rcena/eco is structured into decoupled financial domain modules orchestrated by EcoManager. All managers share the unified EcoStorageAdapter persistence layer, guaranteeing transactional consistency across all operations.

 ┌─────────────────────────────────────────────────────────────┐
 │                         EcoManager                          │
 └──────────────────────────────┬──────────────────────────────┘
                                │
        ┌───────────────────────┼───────────────────────┐
        ▼                       ▼                       ▼
 ┌──────────────┐        ┌──────────────┐        ┌──────────────┐
 │ Real Economy │        │ Progression  │        │ High Stakes  │
 │  • Bank      │        │  • Careers   │        │  • Casino    │
 │  • Vaults    │        │  • Shop      │        │  • Stocks    │
 │  • Loans     │        │  • Inventory │        │  • Heists    │
 │  • Bills/Tax │        │  • Business  │        │  • Pets      │
 └──────┬───────┘        └──────┬───────┘        └──────┬───────┘
        │                       │                       │
        └───────────────────────┼───────────────────────┘
                                │
                                ▼
 ┌─────────────────────────────────────────────────────────────┐
 │                     EcoDatabaseHandler                      │
 │    • SQLite (node:sqlite)  • Prisma ORM  • JSON  • Memory   │
 └─────────────────────────────────────────────────────────────┘

⚙️ EcoManagerOptions Reference

import { EcoManager } from "@m3rcena/eco";

const eco = new EcoManager({
  currencySymbol: "🪙",
  currencyName: "Coins",
  embedColor: "#F1C40F",
  defaultWalletBalance: 500,
  defaultBankCapacity: 10000,
  bankInterestRate: 0.01,
  transactionFeePercentage: 0.02,
  database: "sqlite",
  notifyUpdates: true,
});
Option Type Default Description
currencySymbol string "🪙" Display symbol for the primary currency.
currencyName string "Coins" Currency name used in descriptions and ledger statements.
embedColor any 0x5865f2 Primary embed accent color (Hex string or numeric code).
mode "guild" | "global" "guild" Scoping mode for player accounts and leaderboards.
defaultWalletBalance number 500 Initial pocket cash given to new player accounts.
defaultBankCapacity number 10000 Starting maximum bank deposit ceiling.
bankInterestRate number 0.01 Daily interest multiplier on bank holdings (1%).
transactionFeePercentage number 0 Percentage fee charged on peer-to-peer transfers (e.g. 0.02 for 2%).
database EcoDatabaseConfig "memory" Database storage mode: "sqlite", "prisma", "json", or configuration object.
storage EcoStorageAdapter MemoryEcoStorage Custom persistent storage adapter instance.
bridge M3rcenaBridge undefined Active @m3rcena/bridge instance for dashboard synchronization.
notifyUpdates boolean true Log styled update notification box in terminal on startup.
stockMarketTickIntervalMs number 60000 Milliseconds between simulated stock price fluctuations.
initialStocks StockConfig[] DEFAULT_STOCKS Initial stock & crypto asset list.
initialHeistTargets HeistTarget[] DEFAULT_HEIST_TARGETS Target vault parameters for multiplayer syndicate robberies.
initialPets PetConfig[] DEFAULT_PETS Companion pet catalog.
cooldowns object See below Cooldown overrides for daily, work, beg, crime, and rob.

💾 Database Handlers & Storage Architecture

@m3rcena/eco offers complete flexibility for persistence:

export type EcoDatabaseConfig =
  | "sqlite"
  | "memory"
  | "json"
  | { type: "sqlite"; path?: string }
  | { type: "prisma"; client: any; model?: string; autoMigrate?: boolean }
  | { type: "json"; path?: string }
  | { type: "memory" };

1. Built-in Native SQLite (node:sqlite) (Zero-Dependency)

Node.js 22+ native SQLite with WAL mode, indices, and transactional queries:

import { EcoManager } from "@m3rcena/eco";

const eco = new EcoManager({
  database: "sqlite", // Automatically creates ./eco.sqlite with tables & indexes
  // Or with custom path:
  database: {
    type: "sqlite",
    path: "./data/economy.sqlite",
  },
});

2. Built-in Prisma ORM Integration (PrismaEcoStorage)

Pass your existing PrismaClient instance. If your database hasn't compiled models yet, @m3rcena/eco automatically runs DDL creation and executes queries seamlessly:

import { PrismaClient } from "@prisma/client";
import { EcoManager, applyPrismaEcoModel } from "@m3rcena/eco";

const prisma = new PrismaClient();

// Optional: Programmatically append EcoAccount model to your schema.prisma
applyPrismaEcoModel();

const eco = new EcoManager({
  database: {
    type: "prisma",
    client: prisma,
    autoMigrate: true, // Auto-creates table if missing
  },
});

3. Manual Prisma Migration Tables

If you prefer to run manual migrations or manage schemas with prisma migrate, use the definitions below:

Prisma Schema (schema.prisma):

model EcoAccount {
  userId    String
  guildId   String   @default("")
  wallet    Float    @default(0)
  bank      Float    @default(0)
  level     Int      @default(1)
  data      String   // Complete JSON payload of account state (inventory, businesses, etc.)
  updatedAt DateTime @updatedAt

  @@id([userId, guildId])
  @@index([guildId])
  @@index([wallet, bank])
}

PostgreSQL DDL SQL:

CREATE TABLE IF NOT EXISTS "EcoAccount" (
  "userId" VARCHAR(191) NOT NULL,
  "guildId" VARCHAR(191) NOT NULL DEFAULT '',
  "wallet" DOUBLE PRECISION NOT NULL DEFAULT 0,
  "bank" DOUBLE PRECISION NOT NULL DEFAULT 0,
  "level" INTEGER NOT NULL DEFAULT 1,
  "data" TEXT NOT NULL,
  "updatedAt" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY ("userId", "guildId")
);

CREATE INDEX IF NOT EXISTS idx_eco_guild ON "EcoAccount" ("guildId");
CREATE INDEX IF NOT EXISTS idx_eco_networth ON "EcoAccount" ("wallet", "bank");

MySQL DDL SQL:

CREATE TABLE IF NOT EXISTS `EcoAccount` (
  `userId` VARCHAR(191) NOT NULL,
  `guildId` VARCHAR(191) NOT NULL DEFAULT '',
  `wallet` DOUBLE NOT NULL DEFAULT 0,
  `bank` DOUBLE NOT NULL DEFAULT 0,
  `level` INT NOT NULL DEFAULT 1,
  `data` LONGTEXT NOT NULL,
  `updatedAt` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`userId`, `guildId`),
  INDEX idx_eco_guild (`guildId`),
  INDEX idx_eco_networth (`wallet`, `bank`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

SQLite DDL SQL:

CREATE TABLE IF NOT EXISTS eco_accounts (
  user_id TEXT NOT NULL,
  guild_id TEXT NOT NULL DEFAULT '',
  wallet REAL NOT NULL DEFAULT 0,
  bank REAL NOT NULL DEFAULT 0,
  level INTEGER NOT NULL DEFAULT 1,
  data TEXT NOT NULL,
  updated_at INTEGER NOT NULL,
  PRIMARY KEY (user_id, guild_id)
);

CREATE INDEX IF NOT EXISTS idx_eco_guild ON eco_accounts (guild_id);
CREATE INDEX IF NOT EXISTS idx_eco_networth ON eco_accounts (wallet + bank DESC);

4. Built-in JsonEcoStorage

Persists state safely to disk in a human-readable JSON database with atomic writes:

import { EcoManager } from "@m3rcena/eco";

const eco = new EcoManager({
  database: "json", // Defaults to ./eco-data.json
  // Or:
  database: {
    type: "json",
    path: "./data/economy.json",
  },
});

5. Custom Database Adapters (EcoStorageAdapter)

Implement the EcoStorageAdapter interface for MongoDB, DynamoDB, or Redis:

import { EcoStorageAdapter, UserAccount } from "@m3rcena/eco";

export class CustomMongoStorage implements EcoStorageAdapter {
  async getAccount(userId: string, guildId?: string): Promise<UserAccount | null> {
    // Return UserAccount or null
  }

  async saveAccount(account: UserAccount): Promise<void> {
    // Persist account
  }

  async getTopAccounts(
    sortBy: "netWorth" | "wallet" | "bank" | "level",
    limit?: number,
    guildId?: string
  ): Promise<UserAccount[]> {
    // Return sorted accounts
  }

  async getAllAccounts(guildId?: string): Promise<UserAccount[]> {
    // Return all accounts
  }
}

Clone this wiki locally