Bicrypto - Crypto Trading Platform, Exchanges, KYC, Charting Library, Wallets, Binary Trading, News

Bicrypto - Crypto Trading Platform, Exchanges, KYC, Charting Library, Wallets, Binary Trading, News v5.7.2 + Addons

Update Notes - Core 5.7.2
Update Notes
Added

Ecosystem Trading

• Market Data WebSocket: Implemented real-time trades and OHLCV (candlestick) data streaming


• Live trade history showing recent buy/sell transactions with prices and amounts


• Real-time candlestick charts with configurable intervals (1m, 5m, 1h, 1d, etc.)


• Automatic updates only when new data is available to reduce bandwidth


• Supports custom data limits for different chart requirements


• Properly handles high-volume trading data from Scylla database

NFT Marketplace

• Auction Enhancements: Dynamic minimum bid increment functionality


• Admins can configure minimum bid increments per auction


• Ensures fair bidding with customizable increment requirements


• Prevents bid sniping with proper increment enforcement


• Collection Watchers: Watchers count tracking


• Users can watch/unwatch NFT collections they're interested in


• Real-time watcher count display on collection pages


• Helps gauge collection popularity and community interest


• Withdrawal Tracking: Proper pending withdrawal status


• Clear status indicators for NFT withdrawal requests


• Accurate tracking throughout the withdrawal process


• Better user experience for NFT transfers


• Collection Deployment: Seamless frontend to backend connection


• Smooth NFT collection deployment workflow


• Proper error handling and status updates during deployment


• Smart contract deployment integration


• Marketplace Pause Status: Emergency pause functionality


• Admins can pause/unpause marketplace trading when needed


• Emergency stop for security incidents or maintenance


• Clear UI indication when marketplace is paused

Improved

Ecosystem Operations

• Ledger Network Filtering: Enhanced admin ledger view


• Filters transactions by configured network (mainnet/testnet)


• Admins only see network-relevant transactions based on environment settings


• Reduces clutter and improves data accuracy for multi-network setups


• Withdrawal Notifications: Admin alerts for transaction failures


• Critical notifications when blockchain withdrawal verification fails


• System and individual admin notifications with transaction details


• Enables immediate manual review and intervention

Payment Processing

• DLocal Integration Enhancements:


• Deposit Notifications: Users receive immediate in-app notifications for deposit success or failure


• Clear success messages with deposit details


• Failure notifications with error explanations


• Email notifications ready for integration


• Refund Handling: Automated wallet deduction with user and admin notifications


• Detects full and partial refunds from payment provider


• Automatically adjusts user wallet balance


• Prevents negative balances with safety checks


• Notifies users and admins with refund details


• Chargeback Protection: Critical fraud detection and prevention system


• Automatically detects chargebacks from payment provider


• Deducts chargeback amount from user wallet


• Sends critical alerts to all admins for immediate review


• Detailed logging for compliance and audit requirements


• Special handling for missing wallet scenarios


• Paysafe Admin Profit Recording: Fixed profit tracking for deposit fees


• Admin profit now properly recorded for Paysafe deposit fees


• Consistent tracking across all payment providers


• Accurate fee revenue reporting

User Management

• Investment History: Enabled duration column sorting


• Users can now sort investment history by duration


• Better data organization and easier filtering


• Improved portfolio management experience


• User Import: Welcome notifications for imported users


• Newly imported users receive personalized welcome messages


• In-app greeting with account details


• Better onboarding experience for bulk-imported users

Code Quality

• OTP Recovery Codes: Verified correct implementation


• Accepts both hyphenated (XXXX-XXXX-XXXX) and plain (XXXXXXXXXXXX) formats


• Generates exactly 12 unique recovery codes per user


• Proper normalization and validation working as designed


• Code Cleanup: Comprehensive code audit completed


• All commented code serves legitimate documentation purposes


• No dead or unnecessary code found

Fixed

Build System

• TypeScript Compilation: Fixed type mismatches preventing successful builds


• Resolved async/await pattern errors


• Fixed property name mismatches in data structures


• Backend now compiles without errors

Database

• MySQL Compatibility: Fixed JSON syntax in P2P offer expiry handling


• Corrected JSON parsing for MySQL/MariaDB compatibility


• Proper offer expiration processing

Assets

• Missing Cryptocurrency Image: Added FDUSD (First Digital USD) stablecoin image


• Prevents broken image errors in crypto listings


• Maintains visual consistency across all supported cryptocurrencies

Migration Notes

No database migrations required. All changes are backward compatible and do not require schema updates.

Future Integration Points

The following infrastructure is ready with clear integration markers:

Email Service Integration:

• Deposit success/failure notifications


• User import welcome emails


• Simply implement email service and follow the TODO comments in code

Security Monitoring Integration:

• Frontend error reporting (Sentry, DataDog, etc.)


• Optional external monitoring for production environments
Update Notes - Core 5.7.1
Update Notes
Fixed


Binary Options Trading
• Investment Return on Wins: Fixed critical issue where winning trades only returned profit without the original investment
• Users were losing their investment amount on every winning trade
• Example: $100 investment with 87% profit should return $187, but only returned $87
• Balance calculations now correctly return investment + profit on winning trades
• Applies to all trading modes (demo and real)
• Profit Percentage Configuration: Fixed hardcoded 88% profit being used instead of configured duration-specific percentages
• System was ignoring admin-configured profit percentages in binary_duration table
• All durations showed 88% profit regardless of settings
• Profit percentages now dynamically loaded from database per duration
• Admins can now customize profit percentages for each time duration (1min, 5min, 15min, etc.)
• Profit percentage properly stored with each order for historical accuracy




P2P Trading
• Database Schema: Fixed "Can't create table p2p_trades (errno: 150 'Foreign key constraint is incorrectly formed')" error
• Root cause: Type mismatch between paymentMethod field (VARCHAR) and payment method ID reference (UUID)
• Updated paymentMethod field to use UUID type for proper foreign key constraint
• Enables proper relationship between trades and payment methods




Migration Notes




Database Migration Required


IMPORTANT: This update requires dropping and recreating the p2p_trades table due to schema changes.

Steps to perform migration:

Backup your database before proceeding
Run the following SQL commands (or use phpMyAdmin):
``sql

SET FOREIGN_KEY_CHECKS = 0;

DROP TABLE IF EXISTS p2p_trades;

SET FOREIGN_KEY_CHECKS = 1;

`

Alternative (phpMyAdmin):
• Open phpMyAdmin and select your database
• Find the p2p_trades table in the table list and click "Drop"
• When the confirmation dialog appears, uncheck the "Enable foreign key checks" checkbox
• Click "Yes" to confirm the drop operation
• Repeat for p2p_disputes and p2p_reviews` tables
Restart your backend application
The tables will be recreated automatically with the correct schema


Note: This migration will delete all existing P2P trades, disputes, and reviews.
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.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
  • Like
Reactions: gideonite
# 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
Top