Update Notes - Core 5.6.9
**Critical Model References**: Fixed all incorrect and non-existent database model usage across the backend that could cause runtime crashes
- Fixed `models.walletTransaction` → `models.transaction` in staking system (4 occurrences)
- Fixed `models.kyc` → `models.kycApplication` in user export functionality
- Fixed `models.blockchainTransaction` references in 18 NFT-related files
- Fixed `models.nftIpfsUpload` crash in IPFS service with null check
- Fixed `models.nftMetadataBackup` crashes in metadata backup service (4 occurrences)
- All incorrectly referenced models now properly handled with null checks or correct model names
### Staking System
- **Transaction Recording**: Fixed staking position creation failing with "Cannot read properties of undefined (reading 'create')" error
- Root cause: Attempting to use non-existent `walletTransaction` model
- Now correctly uses `transaction` model with proper STAKING transaction types
- Affected endpoints:
- Staking position creation (`/staking/position`)
- Staking reward claims (`/staking/position/[id]/claim`)
- Admin bulk position updates (`/admin/staking/position/bulk`)
- **Audit Trail**: All staking operations now properly create transaction records for complete audit history
- **Metadata Format**: Fixed metadata not being stringified - now properly uses `JSON.stringify()`
### NFT Marketplace
- **Blockchain Transaction Tracking**: Fixed NFT operations not recording blockchain transactions
- Auction bids now record `NFT_AUCTION_BID` transactions
- Auction settlements record `NFT_AUCTION_SETTLE` transactions
- NFT purchases record `NFT_PURCHASE` transactions with full fee breakdown
- NFT transfers record `NFT_TRANSFER` transactions
- All transactions include blockchain details (transaction hash, gas, block numbers)
- **Admin Profit Recording**: Fixed NFT marketplace fees not being tracked as admin profits
- Offer confirmations now create both transaction and adminProfit records
- Marketplace fees properly linked to profit tracking system
- Supports multiple currencies with wallet-based tracking
- **Optional Features**: Services gracefully handle missing optional models (IPFS upload tracking, metadata backup)
### Payment Gateway Metadata
- **Metadata Stringification**: Fixed 19 payment gateway files with non-stringified metadata
- All metadata fields now properly use `JSON.stringify()` before database storage
- Prevents data corruption and ensures proper JSON parsing on retrieval
### ICO Vesting System
- **Vesting Release Model**: Created missing `icoTokenVestingRelease` model for tracking individual vesting releases
- Enables proper recording of each scheduled token release
- Tracks release status (PENDING, RELEASED, FAILED, CANCELLED)
- Records blockchain transaction hashes for on-chain releases
- Supports failure tracking with detailed error reasons
## Added
### Database Models
- **NFT Price History Model**: New `nftPriceHistory` model for tracking NFT sale prices over time
- Records sale price, currency, and USD conversion at time of sale
- Tracks sale type (DIRECT, AUCTION, OFFER)
- Links to buyer, seller, token, and collection
- Enables historical price analysis and floor price tracking
- Includes blockchain transaction hash reference
- **ICO Token Vesting Release Model**: New `icoTokenVestingRelease` model
- File: `backend/models/ext/ico/icoTokenVestingRelease.ts`
- Tracks individual scheduled releases within a vesting plan
- Fields:
- `vestingId` - Parent vesting record reference
- `releaseDate` - Scheduled release date
- `releaseAmount` - Token amount to release
- `percentage` - Percentage of total vesting
- `status` - PENDING | RELEASED | FAILED | CANCELLED
- `transactionHash` - On-chain transaction hash
- `releasedAt` - Actual release timestamp
- `failureReason` - Error details if failed
- Includes database indexes for efficient queries
- Properly associated with parent `icoTokenVesting` model
### Transaction Types
- **NFT Transaction Types**: Added 8 new transaction types to support NFT marketplace operations
- `NFT_PURCHASE` - Direct NFT purchases
- `NFT_SALE` - NFT sales (seller receiving payment)
- `NFT_MINT` - NFT minting operations
- `NFT_BURN` - NFT burning operations
- `NFT_TRANSFER` - Direct NFT transfers between users
- `NFT_AUCTION_BID` - Auction bid placements
- `NFT_AUCTION_SETTLE` - Auction settlements
- `NFT_OFFER` - Offer-based purchases
- **Admin Profit Types**: Added 3 NFT-related admin profit types
- `NFT_SALE` - Marketplace fees from direct sales
- `NFT_AUCTION` - Fees from auction settlements
- `NFT_OFFER` - Fees from offer acceptances
## Improved
### Transaction Recording
- **Wallet Integration**: All NFT marketplace transactions now properly link to user wallets
- Enables accurate balance tracking across all transaction types
- Supports multi-currency operations
- Gracefully handles cases where wallets don't exist yet
### Code Quality
- **Error Handling**: Enhanced error handling for optional model features
- IPFS upload tracking gracefully disabled if model not created
- Metadata backup service continues operation without model
- Gas history tracking properly guarded with null checks
- System backup functionality safely disabled when model unavailable
### Model Associations
- **ICO Vesting Relationships**: Enhanced `icoTokenVesting` model with complete associations
- `hasMany` relationship with `icoTokenVestingRelease` (as "releases")
- `belongsTo` relationship with `icoTransaction` (as "transaction")
- `belongsTo` relationship with `user` (as "user")
- `belongsTo` relationship with `icoTokenOffering` (as "offering")
- Enables efficient queries with proper eager loading
Update Notes - Core 5.6.8
Core 5.6.8 - Latest updates and improvements.
Update Notes - Core 5.6.3
Fixed
Ecosystem Order Matching
• Partial Fill Fees: Fixed sellers being charged full order fee instead of proportional fee on partial fills - now correctly charges only for the filled amount
• Locked Funds Release: Fixed buyer's funds staying locked forever on partial fills - proportional cost and fee now properly released from locked balance
• Negative Balance: Fixed trade balance going negative due to wallet data type conversion issues - now explicitly converts Decimal types to numbers for accurate arithmetic
• Price Execution: Fixed unfair price matching where buyers always got their price - now properly uses maker's price (whoever placed order first)
• Unauthorized Credit: Fixed orders executing even when wallet updates failed due to insufficient funds - matching now properly aborts when validation fails
• Error Handling: Fixed order matching continuing after wallet update errors - failed matches are now skipped and orders remain available for retry
• Order Cancellation: Fixed partial fill cancellation refunding incorrect amounts - users receiving more than they should when cancelling partially filled orders - now correctly refunds only the remaining unfilled portion
Email Notifications
• Email Verification: Fixed email verification and deposit confirmation emails not being sent - added missing URL shortcode to template validation
Trading Interface
• Balance Display: Fixed trading page showing only available balance instead of total balance - now displays total balance, locked amount, and available balance separately for better clarity
• Chart Updates: Fixed OHLCV (candlestick) data not broadcasting to WebSocket subscribers when orders are matched - corrected subscription filter property order to match frontend subscription format
Improved
Fee Model
• Maker/Taker Fees: Improved fee assignment to use industry-standard maker/taker model
• Market orders now use taker fee (removes liquidity)
• Limit orders that cross spread use taker fee (removes liquidity)
• Limit orders that rest on book use maker fee (adds liquidity)
• Previous behavior incorrectly assigned fees based on buy/sell side only
Order Matching
• Proportional Fees: Enhanced fee calculations to properly handle partial fills
• 10% order fill now charges 10% of the fee (was charging 100% before)
• Locked funds released proportionally including fee portion
• All calculations maintain 18 decimal precision for accuracy
Wallet Operations
• Balance Integrity: Improved wallet update logic to prevent balance discrepancies
• Fresh wallet data fetched before each update to prevent stale data bugs
• Separate handling for order creation/cancellation vs order matching
• Both balance and locked funds (inOrder) validated before updates
Balance Display
• Wallet Information: Enhanced wallet endpoint to return comprehensive balance details
• Total balance (balance + inOrder)
• Amount locked in orders (inOrder)
• Available/spendable balance
• Trading Interface: Improved balance display with clear breakdown of all balance components
• Shows total owned balance prominently
• Displays locked funds with lock icon when applicable
• Highlights available balance in green for easy identification
Added
Trading Features
• Maker/Taker Detection: Added automatic detection of maker/taker status at order creation
• System checks if limit order will immediately match (taker) or rest on book (maker)
• Applies appropriate fee rate based on liquidity provision
• Encourages market depth with lower maker fees
Update Notes
Core 5.6.2 - Latest updates and improvements.
**Tags:** ECOSYSTEM TRADING, WEBSOCKET, ORDER MANAGEMENT, UI IMPROVEMENTS, REAL-TIME UPDATES
## Fixed
### Ecosystem Order Management
- **Order Cancellation Timestamp**: Fixed "Invalid date" error when canceling ecosystem orders - now correctly passes order's createdAt timestamp instead of Date.now()
- **Balance Updates**: Fixed spendable balance not updating in real-time after order cancellation - now broadcasts wallet update events
- **100% Orders**: Fixed 100% order placement failing due to fee not being subtracted from available balance
- **Sell Orders**: Fixed 100% SELL orders failing with "insufficient balance" error - now correctly calculates spendable balance (balance - inOrder)
- **Negative Balance**: Fixed asset balance going negative due to double-locking when creating orders - now properly uses spendable balance calculations
- **Amount Field Bug**: Fixed "untitled" text appearing in amount field after order submission - changed to empty string
### WebSocket Improvements
- **Orders WebSocket**: Created dedicated orders WebSocket service (`orders-ws.ts`) separate from market data WebSocket to prevent message routing conflicts
- **Connection IDs**: Fixed WebSocket messages being sent to wrong connections by using unique connection IDs (`orders-eco`, `orders-spot`, `orders-futures`)
- **Persistent Connection**: Moved orders WebSocket initialization to trading-layout level so connection stays alive even when orders panel is collapsed
- **Message Routing**: Fixed notifications and announcements being sent to all WebSocket connections - now only sent to `/api/user` connection using `sendToClientOnRoute()`
- **Partial Fills**: Fixed partial fills not appearing in real-time - now broadcasts order updates after each match in matchmaking
### Market Panel
- **isEco Flag**: Fixed eco market flag being lost when ticker data updates - now preserves all original market properties using spread operator pattern
- **Property Preservation**: Changed market update pattern from manual reconstruction to spread operator (`{...market, ...tickerUpdates}`) to prevent losing properties
## Improved
### Trading Interface
- **Fee Calculations**: Enhanced all order forms (limit, market, stop) to properly calculate fees for 100% orders
- BUY orders: `amount = availableBalance / (price * (1 + takerFee))`
- SELL orders: Use full balance (fee deducted from proceeds)
- **Fee Display**: Added trading fee display in order form UI showing fee percentage and estimated fee amount
- **Amount Precision**: Improved amount calculations using `Math.floor()` for proper rounding instead of hardcoded buffers
### Orders Panel - Fill Progress
- **Filled/Amount Display**: Enhanced Open Orders table to show "Filled / Amount" instead of just "Amount"
- **Visual Progress Bar**: Added color-coded progress bar (green for BUY, red for SELL) showing fill percentage
- **Real-time Updates**: Partial fills now update instantly via WebSocket without page reload
- **Compact Layout**: Optimized column width with `min-w-[120px]` for better space utilization
- **Percentage Indicator**: Shows fill percentage (e.g., "2%") next to progress bar for instant clarity
### Fee Handling
- **Taker/Maker Fees**: Properly passes market-specific taker and maker fees from market metadata to order forms
- **Dynamic Fee Rates**: Fees are now pulled from market configuration instead of being hardcoded
- **Fee Transparency**: Users can see exact fee amount before placing orders
## Added
### WebSocket Architecture
- **Orders WebSocket Service**: New dedicated service (`/services/orders-ws.ts`) for handling order updates
- Supports multiple market types (spot, eco, futures)
- Connection status tracking per market type
- Automatic reconnection handling
- Message caching for late subscribers
- **Message Broker Improvements**: Enhanced `sendToClientOnRoute()` method for route-specific WebSocket messaging
### Real-time Order Updates
- **Partial Fill Broadcasting**: Orders now broadcast updates after each match in the matching engine
- **Live Progress**: Users see their orders getting filled in real-time with visual progress indicators
- **Multi-user Updates**: Both buyer and seller receive instant updates when orders partially fill
## Technical Improvements
### Code Quality
- **Removed Debug Logs**: Cleaned up verbose console logging from production code:
- Ecosystem orders API logs
- Scylla query execution logs
- Orders WebSocket connection logs
- Trading layout initialization logs
- **Better Error Handling**: Kept only essential error logging for debugging real issues
### WebSocket Performance
- **Connection Management**: Single persistent connection per market type at layout level
- **Efficient Callbacks**: Panels register/unregister callbacks without affecting connection
- **No Duplicate Messages**: Fixed duplicate order broadcasts in matching engine
### Balance Calculations
- **Spendable Balance**: Wallet endpoint now returns `balance - inOrder` for accurate available balance
- **Order Validation**: Pre-flight checks use spendable balance to prevent insufficient balance errors
# Update Notes 5.6
Update Notes
Menu translation added
docs\MENU-TRANSLATION-IMPLEMENTATION.md
Important Note
• Before updating: Delete /frontend/middleware.ts if present to avoid build conflicts
Fixed
Trading Page - Ecosystem Markets
• Order Cancellation: Fixed "Failed to cancel order" error for Eco markets
• Batch Cancellation: Fixed "Failed to cancel all orders" error for Eco markets
• Order History: Fixed cancelled orders now appearing immediately in History tab without page reload
• Open Orders Display: Fixed new orders requiring page reload to appear in Open Orders tab - orders now appear instantly
• Order Book Prices: Fixed prices showing as 0.000000 for values below 0.01 (e.g., 0.001 now displays correctly)
• Total Calculations: Fixed Total column showing 0.00 for small price calculations
Payment Methods
• QR Code Support: Fixed QR Code option not appearing in Type dropdown when creating new deposit methods
Investment Management
• Duration Selection: Fixed duration saving error in AI Investment and Forex plans
• Menu Visibility: Fixed Investment Management section not appearing in Finance menu
Forex Trading
• Account Type Display: Fixed Forex account MT version always showing MT4 instead of selected MT5
Build System
•IMPORTANT: Before running pnpm updator, manually delete /frontend/middleware.ts file if it exists
• Next.js 16 Compatibility: Cleared middleware/proxy conflict causing build errors
Improved
Order Book Enhancements
• Amount Display: Improved amount column formatting to strip trailing zeros (e.g., 1.00000000 displays as "1")
• Price Grouping: Improved order book grouping with fine-grained aggregation levels supporting micro-cap tokens
• Aggregation Options: Expanded aggregation dropdown from 4 to 8 options for better flexibility
• Decimal Precision: Enhanced aggregation algorithm for floating-point precision
Trading Interface
• Smart Price Formatting: Prices now display with appropriate decimal places based on value magnitude
• Real-time Updates: Orders now appear instantly via WebSocket without requiring page refresh
• Better Precision: Support for micro-priced assets and meme coins with tiny prices
Added
Investment Features
• Duration Selection: Added multiselect duration field to AI Investment plans
• Forex Durations: Added multiselect duration field to Forex plans
• Multiple Durations: Investment and Forex plans can now select multiple durations when creating or editing
Payment Methods
• QR Code Fields: Added QR Code option to deposit method custom fields in Type dropdown
# Update Notes 5.5.9
Update Notes
Important Note
• Before updating: Delete /frontend/middleware.ts if present to avoid build conflicts
Fixed
Trading Page - Ecosystem Markets
• Order Cancellation: Fixed "Failed to cancel order" error for Eco markets
• Batch Cancellation: Fixed "Failed to cancel all orders" error for Eco markets
• Order History: Fixed cancelled orders now appearing immediately in History tab without page reload
• Open Orders Display: Fixed new orders requiring page reload to appear in Open Orders tab - orders now appear instantly
• Order Book Prices: Fixed prices showing as 0.000000 for values below 0.01 (e.g., 0.001 now displays correctly)
• Total Calculations: Fixed Total column showing 0.00 for small price calculations
Payment Methods
• QR Code Support: Fixed QR Code option not appearing in Type dropdown when creating new deposit methods
Investment Management
• Duration Selection: Fixed duration saving error in AI Investment and Forex plans
• Menu Visibility: Fixed Investment Management section not appearing in Finance menu
Forex Trading
• Account Type Display: Fixed Forex account MT version always showing MT4 instead of selected MT5
Build System
•IMPORTANT: Before running pnpm updator, manually delete /frontend/middleware.ts file if it exists
• Next.js 16 Compatibility: Cleared middleware/proxy conflict causing build errors
Improved
Order Book Enhancements
• Amount Display: Improved amount column formatting to strip trailing zeros (e.g., 1.00000000 displays as "1")
• Price Grouping: Improved order book grouping with fine-grained aggregation levels supporting micro-cap tokens
• Aggregation Options: Expanded aggregation dropdown from 4 to 8 options for better flexibility
• Decimal Precision: Enhanced aggregation algorithm for floating-point precision
Trading Interface
• Smart Price Formatting: Prices now display with appropriate decimal places based on value magnitude
• Real-time Updates: Orders now appear instantly via WebSocket without requiring page refresh
• Better Precision: Support for micro-priced assets and meme coins with tiny prices
Added
Investment Features
• Duration Selection: Added multiselect duration field to AI Investment plans
• Forex Durations: Added multiselect duration field to Forex plans
• Multiple Durations: Investment and Forex plans can now select multiple durations when creating or editing
Payment Methods
• QR Code Fields: Added QR Code option to deposit method custom fields in Type dropdown
Critical Fixes
Withdrawal Balance Calculation
- Fixed NATIVE EVM token withdrawal fee calculation - Gas fees are now correctly paid FROM the withdrawal amount instead of being added on top
- Affected chains: ETH, BSC, POLYGON, FTM, OPTIMISM, ARBITRUM, BASE, CELO, RSK, AVAX
- Previously: totalToDeduct = withdrawAmount + platformFee + gasFee (incorrect)
- Now: totalToDeduct = withdrawAmount + platformFee (gas paid from withdrawal itself)
Max Withdrawal Calculation
- Added gas fee estimation for NATIVE EVM tokens in max withdrawal endpoint
- Max withdrawal now subtracts estimated gas fee to prevent "Insufficient funds" errors
- Formula: maxAmount = availableBalance - platformFee - estimatedGas
String Concatenation Bugs
- Fixed critical string concatenation issues in balance calculations (7 locations)
- Database stores balances as strings, causing concatenation instead of addition
- Example bug: "0.00689273" + "0.0001" resulted in "0.006892730.0001" instead of 0.00699273
- Added parseFloat() before all arithmetic operations on wallet balances
Floating-Point Precision Errors
- Added EVM chains to balance precision function
- Fixed precision errors like 0.000890629999999999 displaying instead of 0.00089063
- Added chains: BSC, ETH, POLYGON, ARBITRUM, OPTIMISM, BASE, AVAX, FTM, CELO, RSK (all with 8 decimal precision)
Gas Fee Reconciliation
- Implemented gas fee reconciliation for NATIVE EVM withdrawals
- Compares estimated vs actual gas used after transaction confirms
- Refunds difference if overestimated, deducts if underestimated
- Keeps database balance synchronized with on-chain balance
Private Ledger Integration
- Fixed withdrawal balance checks to consider private ledger
- For PERMIT tokens, now checks: availableBalance = wallet_data.balance - offchainDifference
- Prevents users from withdrawing admin fees collected in cross-token exchanges
- Applied in both max withdrawal and withdrawal validation
Monero (XMR) Deposit Processing
- Fixed XMR deposit deadlock issue
- Created processMoneroTransactionDirect method to handle deposits when wallet is already open
- Prevents "0/120 attempt" stalling on deposits
Technical Improvements
Balance Checking Logic
- Changed from checking wallet.balance (total across all chains) to wallet_data.balance (chain-specific available balance)
- Ensures users can only withdraw what's actually available on the specific blockchain
Gas Estimation
- Implemented proper gas estimation for NATIVE EVM tokens before withdrawal
- Uses 21000 gas limit for standard transfers
- Fetches current gas price from blockchain
- Falls back to conservative estimates if estimation fails
Private Ledger Logic
- offchainDifference > 0: Admin fees collected (reduces available balance)
- offchainDifference < 0: User credited from exchange (increases available balance)
- Only applies to PERMIT contract type tokens