@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 integrationtokenbot-telegram-bot-v2- Telegram bot integrationtokenbot-admin-dashboard- Administrative dashboardtokenbot-dashboard-v2- User dashboardtokenbot-graphql-v2- GraphQL API server
🚀 Installation
npm install @tokenbot/data-modelsor
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 authenticationSession- Session managementTwoFactorAuth- Two-factor authenticationPasswordReset- Password reset tokensEmailVerification- Email verification tokens
Organization & Multi-tenancy
Organization- Multi-tenant organizationUserOrganization- User-organization relationships with roles
Trading & Strategy
ExchangeAccount- Exchange API integrationStrategy- Trading strategy configurationStrategySelection- Per-channel strategy activation for Discord/Telegram botsCopier- Strategy copy tradingTrade- Trade execution recordsTradePair- Trading pair configuration
Rewards & Tokenomics
UserReward- User rewards and tokenomicsRewardType- Reward categoriesWithdraw- Withdrawal management
System & Monitoring
AuditLog- Audit trail for complianceNotification- User notificationsUserSetting- 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); // 200Strategy 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
- Ensure you have an npm account and are logged in:
npm login- Verify you have publishing rights to the
@tokenbotscope:
npm whoami
npm org ls @tokenbotPublishing Process
- Ensure all tests pass and the build is clean:
npm test
npm run lint
npm run build- 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- Review the changes before publishing:
git diff HEAD~1
npm pack --dry-run- Publish to npm:
npm publish --access public- Push the version tag to GitHub:
git push origin main --tagsPost-Publishing
After publishing a new version:
- Update dependent projects to use the new version:
# In each dependent project
npm update @tokenbot/data-modelsCreate a GitHub release with changelog notes
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 errorsvalidateAsync()- Async validation wrappervalidatePartial()- Partial validation for updatesvalidateBatch()- Batch validation for multiple items
Utilities
Utility functions for common operations:
generateId()- Generate UUIDgenerateSlug()- Generate URL-safe slugformatDate()- Format datesformatCurrency()- Format currency valuespaginate()- Paginate arraysdeepClone()- Deep clone objectsretry()- 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
- Make changes to the models in
src/models/ - Update corresponding tests in
src/__tests__/ - Run tests to ensure everything passes
- Build the library to check for TypeScript errors
- Submit a pull request
📄 License
MIT
🔗 Links
🚀 Migration Guide
If you're migrating from inline models to this library:
- Install the package:
npm install @tokenbot/data-models - Replace local model definitions with imports from the library
- Update any custom validation to use the provided validators
- Replace magic strings with constants from the library
- 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
