npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@tokenbot-org/data-models

v1.2.0

Published

TypeScript data model library for TokenBot applications - single source of truth for database models

Downloads

35

Readme

@tokenbot/data-models

TypeScript data model library for TokenBot applications - the single source of truth for database models across all TokenBot services.

🎯 Purpose

This library serves as the centralized data model repository for the TokenBot ecosystem, ensuring consistency and maintainability across:

  • tokenbot-discord-bot-v2 - Discord bot integration
  • tokenbot-telegram-bot-v2 - Telegram bot integration
  • tokenbot-admin-dashboard - Administrative dashboard
  • tokenbot-dashboard-v2 - User dashboard
  • tokenbot-graphql-v2 - GraphQL API server

🚀 Installation

npm install @tokenbot/data-models

or

yarn add @tokenbot/data-models

📦 Features

  • Strong TypeScript typing - Full type safety with TypeScript
  • Zod validation - Runtime validation with detailed error messages
  • Multi-tenant support - Built-in organization-based data isolation
  • Comprehensive models - All core entities and relationships
  • Helper functions - Utility functions for common operations
  • Constants - Centralized configuration values
  • Validators - Custom validation rules and utilities

🏗️ Core Models

User & Authentication

  • User - Core user entity with authentication
  • Session - Session management
  • TwoFactorAuth - Two-factor authentication
  • PasswordReset - Password reset tokens
  • EmailVerification - Email verification tokens

Organization & Multi-tenancy

  • Organization - Multi-tenant organization
  • UserOrganization - User-organization relationships with roles

Trading & Strategy

  • ExchangeAccount - Exchange API integration
  • Strategy - Trading strategy configuration
  • StrategySelection - Per-channel strategy activation for Discord/Telegram bots
  • Copier - Strategy copy trading
  • Trade - Trade execution records
  • TradePair - Trading pair configuration

Rewards & Tokenomics

  • UserReward - User rewards and tokenomics
  • RewardType - Reward categories
  • Withdraw - Withdrawal management

System & Monitoring

  • AuditLog - Audit trail for compliance
  • Notification - User notifications
  • UserSetting - User preferences

📖 Usage Examples

Basic Model Usage

import { User, CreateUserSchema, UserHelpers } from '@tokenbot/data-models';

// Validate user creation input
const input = {
  email: '[email protected]',
  password: 'SecurePassword123!',
  referral_code: UserHelpers.generateReferralCode(),
};

const result = CreateUserSchema.safeParse(input);

if (result.success) {
  const userData = result.data;
  // Create user in database
} else {
  console.error('Validation errors:', result.error);
}

Working with Organizations

import { 
  Organization, 
  OrganizationHelpers,
  SubscriptionPlan 
} from '@tokenbot/data-models';

// Check organization limits
const org: Organization = {
  subscription_plan: SubscriptionPlan.PRO,
  max_users: 100,
  // ... other fields
};

const currentUserCount = 95;
if (OrganizationHelpers.hasReachedUserLimit(org, currentUserCount)) {
  console.log('Organization has reached user limit');
}

// Get plan limits
const limits = OrganizationHelpers.getPlanLimits(SubscriptionPlan.PRO);
console.log('Max strategies:', limits.max_strategies); // 200

Strategy Management

import { 
  Strategy, 
  StrategyHelpers,
  CreateStrategySchema 
} from '@tokenbot/data-models';

// Create a new strategy
const strategyInput = {
  user_id: 'user-uuid',
  organization_id: 'org-uuid',
  exchange_account_id: 'exchange-uuid',
  name: 'MACD Crossover Strategy',
  configuration: {
    entry_conditions: [
      {
        indicator: 'MACD',
        operator: '>',
        value: 0,
        timeframe: '1h',
      }
    ],
    exit_conditions: [
      {
        indicator: 'RSI',
        operator: '>',
        value: 70,
        timeframe: '1h',
      }
    ],
    stop_loss_percentage: 5,
    take_profit_percentage: 10,
  },
  risk_level: 5,
};

const validation = CreateStrategySchema.safeParse(strategyInput);

// Calculate risk score
const strategy: Strategy = { /* ... */ };
const riskScore = StrategyHelpers.calculateRiskScore(strategy);

Trade Execution

import { 
  Trade, 
  TradeHelpers,
  TradeSide,
  TradeStatus 
} from '@tokenbot/data-models';

// Generate partition keys for trade storage
const partitionKeys = TradeHelpers.generatePartitionKeys(new Date());
console.log(partitionKeys); // { year_month: '2024-01', date_partition: '2024-01-15' }

// Calculate profit/loss
const profitLoss = TradeHelpers.calculateProfitLoss(
  100,    // entry price
  110,    // exit price
  10,     // quantity
  TradeSide.BUY,
  5       // fee
);
console.log('Profit:', profitLoss.profit_loss); // 95
console.log('Percentage:', profitLoss.profit_loss_percentage); // 9.5%

Strategy Selection (Bot Integration)

import {
  StrategySelection,
  StrategySelectionHelpers,
  CreateStrategySelectionSchema
} from '@tokenbot/data-models';

// Create a new strategy selection for a Discord/Telegram channel
const selectionInput = {
  user_id: 'user-uuid',
  strategy_id: 'strategy-uuid',
  strategy_name: 'Momentum Trading',
  channel_id: '123456789012345678', // Discord or Telegram channel ID
  channel_type: 'discord', // 'discord' or 'telegram'
  trades_enabled: false,
  nickname: StrategySelectionHelpers.generateNickname(), // Auto-generate nickname
};

const validation = CreateStrategySelectionSchema.safeParse(selectionInput);

if (validation.success) {
  // Enable trades for this channel
  const selection: StrategySelection = { /* ... */ };
  const newStatus = StrategySelectionHelpers.toggleTradesEnabled(selection.trades_enabled);

  // Format for display in Discord/Telegram
  const displayText = StrategySelectionHelpers.formatForChat(selection);
  console.log(displayText); // "[momentum01] Momentum Trading - Trades: ✅ ON"

  // Validate channel ID based on platform
  const validation = StrategySelectionHelpers.validateChannelId(
    '123456789012345678',
    'discord'
  );

  if (!validation.valid) {
    console.error('Invalid channel ID:', validation.error);
  }
}

User Rewards

import {
  UserReward,
  UserRewardHelpers,
  RewardTier
} from '@tokenbot/data-models';

// Get user tier based on volume
const tiers = UserRewardHelpers.getDefaultTiers();
const userVolume = 75000;
const userTier = UserRewardHelpers.getUserTier(userVolume, tiers);
console.log('User tier:', userTier.name); // 'Gold'

// Calculate trading reward
const tradingReward = UserRewardHelpers.calculateTradingReward(
  10000,    // volume
  userTier  // tier
);
console.log('Trading reward:', tradingReward); // 20 (0.2% of 10000)

Validation Utilities

import { 
  emailValidator,
  passwordValidator,
  safeParse,
  formatValidationErrors 
} from '@tokenbot/data-models';

// Use custom validators
const emailResult = emailValidator.safeParse('[email protected]');
const passwordResult = passwordValidator.safeParse('WeakPass');

// Safe parse with error formatting
import { UserSchema } from '@tokenbot/data-models';

const result = safeParse(UserSchema, userData);
if (!result.success) {
  console.log('Validation errors:', result.errors);
  // { 'email': ['Invalid email format'], 'password': ['Too short'] }
}

Using Constants

import { 
  DATABASE,
  SUBSCRIPTION_LIMITS,
  ERROR_CODES,
  TRADING 
} from '@tokenbot/data-models';

// Access database collection names
const userCollection = DATABASE.COLLECTIONS.USERS; // 'users_v2'

// Check subscription limits
const proLimits = SUBSCRIPTION_LIMITS.PRO;
console.log('Max strategies:', proLimits.MAX_STRATEGIES); // 200

// Use error codes
throw new Error(ERROR_CODES.INSUFFICIENT_BALANCE); // 'TRADE_4001'

// Trading limits
const minTrade = TRADING.LIMITS.MIN_TRADE_AMOUNT_USD; // 10

🧪 Testing

# Run tests
npm test

# Run tests with coverage
npm run test:coverage

# Run tests in watch mode
npm run test:watch

🏗️ Building

# Build the library
npm run build

# Build in watch mode for development
npm run build:watch

# Clean build artifacts
npm run clean

📦 Publishing to NPM

Prerequisites

  1. Ensure you have an npm account and are logged in:
npm login
  1. Verify you have publishing rights to the @tokenbot scope:
npm whoami
npm org ls @tokenbot

Publishing Process

  1. Ensure all tests pass and the build is clean:
npm test
npm run lint
npm run build
  1. Update the version number following semantic versioning:
# For patch releases (bug fixes)
npm version patch

# For minor releases (new features, backwards compatible)
npm version minor

# For major releases (breaking changes)
npm version major
  1. Review the changes before publishing:
git diff HEAD~1
npm pack --dry-run
  1. Publish to npm:
npm publish --access public
  1. Push the version tag to GitHub:
git push origin main --tags

Post-Publishing

After publishing a new version:

  1. Update dependent projects to use the new version:
# In each dependent project
npm update @tokenbot/data-models
  1. Create a GitHub release with changelog notes

  2. Notify the team about breaking changes if any

Automated Publishing (CI/CD)

For automated publishing via GitHub Actions, ensure the following secrets are configured in the repository:

  • NPM_TOKEN - npm authentication token with publish permissions

The CI/CD pipeline will automatically publish when:

  • A new tag is pushed following v* pattern
  • All tests pass
  • Build succeeds

📝 API Documentation

Model Schemas

All models are exported as Zod schemas with corresponding TypeScript types:

// Schema for validation
export const UserSchema = z.object({ /* ... */ });

// TypeScript type
export type User = z.infer<typeof UserSchema>;

// Input schemas for create/update operations
export const CreateUserSchema = /* ... */;
export const UpdateUserSchema = /* ... */;

// Helper class with utility functions
export class UserHelpers { /* ... */ }

Validation

The library provides comprehensive validation utilities:

  • safeParse() - Safe parsing with formatted errors
  • validateAsync() - Async validation wrapper
  • validatePartial() - Partial validation for updates
  • validateBatch() - Batch validation for multiple items

Utilities

Utility functions for common operations:

  • generateId() - Generate UUID
  • generateSlug() - Generate URL-safe slug
  • formatDate() - Format dates
  • formatCurrency() - Format currency values
  • paginate() - Paginate arrays
  • deepClone() - Deep clone objects
  • retry() - Retry async operations

🔒 Security

  • All sensitive data fields (API keys, secrets) should be encrypted before storage
  • Password fields are never included in public schemas
  • Session tokens are generated with cryptographically secure random values
  • Input validation prevents injection attacks
  • Rate limiting constants provided for API protection

🤝 Contributing

  1. Make changes to the models in src/models/
  2. Update corresponding tests in src/__tests__/
  3. Run tests to ensure everything passes
  4. Build the library to check for TypeScript errors
  5. Submit a pull request

📄 License

MIT

🔗 Links

🚀 Migration Guide

If you're migrating from inline models to this library:

  1. Install the package: npm install @tokenbot/data-models
  2. Replace local model definitions with imports from the library
  3. Update any custom validation to use the provided validators
  4. Replace magic strings with constants from the library
  5. Use helper functions instead of inline utility code

Before:

// Local model definition
interface User {
  id: string;
  email: string;
  // ...
}

const user: User = { /* ... */ };

After:

import { User, UserSchema } from '@tokenbot/data-models';

const user: User = UserSchema.parse(userData);

📊 Model Relationships

Organization
    ├── UserOrganization (many-to-many with User)
    ├── ExchangeAccount
    │   ├── Strategy
    │   │   └── Copier
    │   └── Trade
    └── UserReward

User
    ├── Session
    ├── TwoFactorAuth
    ├── UserOrganization
    ├── UserSetting
    └── Notification

🔄 Version History

  • 1.0.0 - Initial release with core models
    • Complete model definitions for all entities
    • Zod validation schemas
    • Helper functions and utilities
    • Constants and enums
    • Comprehensive documentation