 Ecosystem Addon - Comprehensive Reference Guide

## Overview

The Ecosystem addon is a production-grade blockchain/cryptocurrency trading system supporting 17+ blockchains, token deployment, NFT management, real-time trading, and advanced order matching.

---

## 1. Database Models

Located at: `backend/models/ext/ecosystem/`

### 1.1 ecosystemBlockchain.ts
Stores blockchain configuration.

| Field | Type | Description |
|-------|------|-------------|
| id | UUID | Primary key |
| productId | STRING | Unique product identifier |
| name | STRING | Blockchain name |
| chain | STRING | Chain identifier |
| description | TEXT | Description |
| link | STRING | Documentation link |
| status | BOOLEAN | Active status |
| version | STRING | Version number |
| image | STRING | Icon/image path |

### 1.2 ecosystemToken.ts
ERC20/ERC1155/ERC721 token configurations.

| Field | Type | Description |
|-------|------|-------------|
| id | UUID | Primary key |
| contract | STRING | Contract address |
| name | STRING | Token name |
| currency | STRING | Currency symbol |
| chain | STRING | Blockchain chain |
| network | STRING | Network (mainnet/testnet) |
| type | STRING | Token type |
| decimals | INTEGER | Decimal places |
| contractType | ENUM | `PERMIT`, `NO_PERMIT`, `NATIVE` |
| status | BOOLEAN | Active status |
| precision | INTEGER | Display precision |
| limits | JSON | Min/max limits |
| fee | JSON | Fee configuration |
| icon | STRING | Token icon |

- Unique index on `(contract, chain)` pair
- Paranoid timestamps (soft deletes)

### 1.3 ecosystemMarket.ts
Trading pair configurations.

| Field | Type | Description |
|-------|------|-------------|
| id | UUID | Primary key |
| currency | STRING | Base currency |
| pair | STRING | Quote currency |
| isTrending | BOOLEAN | Trending flag |
| isHot | BOOLEAN | Hot market flag |
| metadata | JSON | `{precision, limits, taker, maker}` |
| status | BOOLEAN | Active status |

### 1.4 ecosystemMasterWallet.ts
Root wallet per chain/currency.

| Field | Type | Description |
|-------|------|-------------|
| id | UUID | Primary key |
| chain | STRING | Blockchain chain |
| currency | STRING | Currency symbol |
| address | STRING | Wallet address |
| balance | DECIMAL | Current balance |
| data | JSON | Additional data |
| status | ENUM | Wallet status |
| lastIndex | INTEGER | Last derivation index |

- One-to-many relationship with `ecosystemCustodialWallet`
- Unique index on `(chain, currency)` pair

### 1.5 ecosystemCustodialWallet.ts
User-specific wallets per chain.

| Field | Type | Description |
|-------|------|-------------|
| id | UUID | Primary key |
| masterWalletId | UUID | Foreign key to master wallet |
| address | STRING | Wallet address |
| chain | STRING | Blockchain chain |
| network | STRING | Network type |
| status | ENUM | `ACTIVE`, `INACTIVE`, `SUSPENDED` |

### 1.6 ecosystemUtxo.ts
UTXO (Bitcoin-style) transaction outputs.

| Field | Type | Description |
|-------|------|-------------|
| id | UUID | Primary key |
| walletId | UUID | Wallet reference |
| transactionId | STRING | Transaction hash |
| index | INTEGER | Output index |
| amount | DECIMAL | UTXO amount |
| script | STRING | Locking script |
| status | ENUM | UTXO status |

### 1.7 ecosystemPrivateLedger.ts
Off-chain ledger balances.

| Field | Type | Description |
|-------|------|-------------|
| id | UUID | Primary key |
| walletId | UUID | Wallet reference |
| index | INTEGER | Ledger index |
| currency | STRING | Currency symbol |
| chain | STRING | Blockchain chain |
| network | STRING | Network type |
| offchainDifference | DECIMAL | On-chain vs off-chain difference |

---

## 2. Backend API Routes

### 2.1 Public Routes (`backend/src/api/(ext)/ecosystem/`)

#### Deposit & Withdrawal
| Route | Method | Description |
|-------|--------|-------------|
| `/deposit/index.ws.ts` | WS | Real-time deposit monitoring |
| `/deposit/unlock/index.get.ts` | GET | Unlock deposit |
| `/withdraw/` | POST | Withdrawal request |
| `/withdraw/min-withdrawal/` | GET | Minimum withdrawal limits |

#### Trading & Markets
| Route | Method | Description |
|-------|--------|-------------|
| `/market/index.get.ts` | GET | List all markets |
| `/market/index.ws.ts` | WS | Market updates |
| `/market/[id]/index.get.ts` | GET | Get specific market |
| `/order/index.get.ts` | GET | List orders |
| `/order/index.post.ts` | POST | Create order |
| `/order/index.ws.ts` | WS | Order updates |
| `/order/[id]/index.del.ts` | DELETE | Cancel order |
| `/order/all/index.del.ts` | DELETE | Bulk cancel orders |
| `/ticker/index.ws.ts` | WS | Ticker data |

#### Charts & Tokens
| Route | Method | Description |
|-------|--------|-------------|
| `/chart/index.get.ts` | GET | OHLCV chart data |
| `/token/index.get.ts` | GET | List tokens |
| `/token/[currency]/index.get.ts` | GET | Token by currency |
| `/wallet/index.get.ts` | GET | User's wallets |
| `/wallet/[currency]/index.get.ts` | GET | Wallet by currency |

### 2.2 Admin Routes (`backend/src/api/(ext)/admin/ecosystem/`)

#### Blockchain Management
| Route | Method | Description |
|-------|--------|-------------|
| `/blockchain/index.get.ts` | GET | List blockchains |
| `/blockchain/[id]/index.get.ts` | GET | Blockchain details |
| `/blockchain/[id]/status.put.ts` | PUT | Update status |
| `/blockchain/balance.get.ts` | GET | Get balances |
| `/blockchain/options.get.ts` | GET | Available options |

#### Token Management
| Route | Method | Description |
|-------|--------|-------------|
| `/token/index.get.ts` | GET | List tokens |
| `/token/index.post.ts` | POST | Create token |
| `/token/index.del.ts` | DELETE | Bulk delete |
| `/token/[id]/index.get.ts` | GET | Token details |
| `/token/[id]/index.put.ts` | PUT | Update token |
| `/token/[id]/index.del.ts` | DELETE | Delete token |
| `/token/[id]/status.put.ts` | PUT | Change status |
| `/token/[id]/holder.get.ts` | GET | Token holders |
| `/token/import.post.ts` | POST | Import tokens |

#### Market Management
| Route | Method | Description |
|-------|--------|-------------|
| `/market/index.get.ts` | GET | List markets |
| `/market/index.post.ts` | POST | Create market |
| `/market/[id]/index.put.ts` | PUT | Update market |
| `/market/[id]/status.put.ts` | PUT | Change status |

#### Wallet Management
| Route | Method | Description |
|-------|--------|-------------|
| `/wallet/custodial/` | GET | Custodial wallets |
| `/wallet/custodial/[id]/transfer` | POST | Transfer funds |
| `/wallet/master/` | GET | Master wallets |

#### Ledger & UTXO
| Route | Method | Description |
|-------|--------|-------------|
| `/ledger/index.get.ts` | GET | List ledger entries |
| `/ledger/[id]/index.get.ts` | GET | Ledger details |
| `/ledger/[id]/index.put.ts` | PUT | Update ledger |
| `/utxo/index.get.ts` | GET | List UTXOs |
| `/utxo/index.post.ts` | POST | Create UTXO |

---

## 3. Backend Utilities

Located at: `backend/src/api/(ext)/ecosystem/utils/`

### Core Utilities (23 files)

| File | Purpose |
|------|---------|
| `blockchain.ts` | Chain config, block parsing, BigInt conversions |
| `chains.ts` | Chain configurations for all supported blockchains |
| `tokens.ts` | Token deployment, contract interactions |
| `wallet.ts` | Wallet creation, balance updates, address generation |
| `withdraw.ts` | EVM withdrawal logic |
| `utxo.ts` | UTXO management for Bitcoin-like chains |
| `transactions.ts` | Transaction fetching and validation |
| `matchingEngine.ts` | Order matching with Scylla integration |
| `matchmaking.ts` | Order matching algorithms |
| `orderbook.ts` | Order book management |
| `candles.ts` | OHLCV candle generation |
| `markets.ts` | Market information retrieval |
| `custodialWallet.ts` | Custodial wallet operations |
| `provider.ts` | Blockchain provider initialization |
| `smartContract.ts` | Smart contract interactions |
| `gas.ts` | Gas estimation |
| `emails.ts` | Email notifications |
| `cron.ts` | Scheduled tasks |
| `ws.ts` | WebSocket broadcasting |
| `withdrawalQueue.ts` | Withdrawal queue management |

### Deposit Monitors (`deposit/util/monitor/`)

| File | Blockchain |
|------|------------|
| `EVMDeposits.ts` | Ethereum-compatible chains |
| `UTXODeposits.ts` | Bitcoin-like chains |
| `SolanaDeposits.ts` | Solana |
| `TronDeposits.ts` | TRON |
| `MoneroDeposits.ts` | Monero |
| `TonDeposits.ts` | TON |
| `MODeposits.ts` | MO chain |
| `IDepositMonitor.ts` | Interface definition |

### Scylla Integration (`scylla/`)

| File | Purpose |
|------|---------|
| `client.ts` | Scylla DB connection |
| `queries.ts` | Order and candle queries |
| `chart.ts` | Chart data queries |
| `query.ts` | Query utilities |

---

## 4. Smart Contracts

Located at: `backend/ecosystem/smart-contracts/`

```
smart-contracts/
├── token/
│   ├── ERC20.sol          # Standard ERC20 token
│   ├── ERC20.json         # Compiled ABI
│   └── ERC20.bin          # Binary
├── wallet/
│   ├── CustodialWalletERC20.sol
│   └── CustodialWalletERC20.json
├── nft/
│   ├── contracts/
│   │   ├── ERC721NFT.sol      # NFT collection
│   │   ├── ERC1155NFT.sol     # Multi-token standard
│   │   └── NFTMarketplace.sol # NFT trading
│   ├── artifacts/
│   ├── scripts/
│   └── hardhat.config.js
├── gsn/
│   ├── MetaTransaction.sol    # GSN meta-transactions
│   └── MetaTransaction.json
└── proxy/
    ├── proxy.sol              # Upgradeable proxy
    ├── proxy.abi
    └── proxy.bin
```

### Contract Types
- **ERC20**: Standard tokens with PERMIT and NO_PERMIT variants
- **ERC721**: NFT collections with royalties
- **ERC1155**: Multi-token standard
- **NFTMarketplace**: NFT trading functionality
- **CustodialWallet**: Secure token holdings
- **GSN**: Gasless transactions
- **Proxy**: Upgradeable contracts

---

## 5. Frontend Admin Pages

Located at: `frontend/app/[locale]/(ext)/admin/ecosystem/`

| Route | Purpose |
|-------|---------|
| `/admin/ecosystem` | Dashboard (blockchains overview) |
| `/admin/ecosystem/blockchain/[productId]` | Install/configure blockchain |
| `/admin/ecosystem/token` | Token management |
| `/admin/ecosystem/token/create` | Token creation (4-step wizard) |
| `/admin/ecosystem/token/[id]` | Edit token |
| `/admin/ecosystem/market` | Market management |
| `/admin/ecosystem/market/create` | Market creation (4-step wizard) |
| `/admin/ecosystem/market/[id]` | Edit market |
| `/admin/ecosystem/ledger` | Private ledger view |
| `/admin/ecosystem/utxo` | UTXO management |
| `/admin/ecosystem/wallet/custodial` | Custodial wallets |
| `/admin/ecosystem/wallet/master` | Master wallets |

### Finance/Order Ecosystem
`frontend/app/[locale]/(dashboard)/admin/finance/order/ecosystem` - Trading order analytics

---

## 6. Supported Blockchains

### Base Chains (Built-in)

#### UTXO-based
- BTC (Bitcoin)
- LTC (Litecoin)
- DOGE (Dogecoin)
- DASH

#### EVM-compatible
- ETH (Ethereum)
- BSC (Binance Smart Chain)
- POLYGON
- FTM (Fantom)
- OPTIMISM
- ARBITRUM
- BASE
- CELO

#### Others
- SOL (Solana)
- TRON
- XMR (Monero)
- MO
- TON

### Network Support
- Mainnet and testnet for most chains
- Custom RPC endpoints
- Explorer API integration

---

## 7. Cron Jobs

Located at: `backend/src/utils/crons/`

| File | Purpose |
|------|---------|
| `btc-deposit-scanner.ts` | Bitcoin deposit monitoring |
| `wallet.ts` | Wallet-related tasks |
| `ecosystem/utils/cron.ts` | Ecosystem-specific scheduled tasks |

---

## 8. Data Flows

### Deposit Flow
```
1. User deposits to custodial wallet address
2. Deposit monitor (WebSocket) watches blockchain
3. verifyPendingTransactions worker validates deposit
4. Transaction stored in Redis and broadcasted
5. Private ledger updated
6. Wallet balance updated
```

### Trading Flow
```
1. User creates order via /api/ecosystem/order POST
2. Order stored in Scylla database
3. Matching engine processes order queue
4. Matches with counter-orders
5. Broadcasts via WebSocket
6. Updates orderbook in Scylla
7. Generates candles for chart data
```

### Withdrawal Flow
```
1. User requests withdrawal
2. Backend validates amount and fees
3. Initializes EVM/UTXO contract
4. Executes transaction (PERMIT/NO_PERMIT/NATIVE)
5. Updates wallet balance
6. Broadcasts confirmation
```

### Token Deployment Flow
```
1. Admin creates token via form
2. System gets master wallet for chain
3. Deploys contract (ERC20, SPL, etc.)
4. Stores token metadata in DB
5. Updates Scylla cache
```

---

## 9. Type Definitions

Located at: `backend/types/ecosystem.d.ts`

### Core Types
```typescript
// Market Types
EcosystemMarket
EcosystemMarketMetaData
EcosystemMarketLimits

// Order Types
EcosystemOrder
EcosystemOrderStatus
EcosystemOrderType
EcosystemOrderSide
EcosystemTimeInForce  // GTC, IOC, FOK, PO

// Token Types
EcosystemToken
EcosystemTokenContractType  // PERMIT, NO_PERMIT, NATIVE

// Wallet Types
EcosystemMasterWallet
EcosystemCustodialWallet
EcosystemPrivateLedger

// Transaction Types
TradeDetail
ParsedTransaction
```

---

## 10. Technology Stack

| Technology | Purpose |
|------------|---------|
| **Scylla DB** | High-performance orders, candles, orderbook |
| **Redis** | Caching and transaction broadcasting |
| **ethers.js** | EVM blockchain interactions |
| **Sequelize** | SQL ORM for PostgreSQL |
| **WebSockets** | Real-time market data, orders, deposits |
| **Hardhat** | Smart contract compilation and deployment |
| **OpenZeppelin** | Standard contract libraries |

---

## 11. File Statistics

- **73 API route files** in ecosystem
- **7 database models**
- **23+ utility files**
- **4 WebSocket endpoints**
- **Multiple smart contracts** (ERC20, ERC721, ERC1155, NFTMarketplace)
- **Full admin frontend** with CRUD operations

---

## 12. Conventions & Patterns

### Naming
- All models prefixed with `ecosystem` (e.g., `ecosystemToken`)
- Table names use snake_case (e.g., `ecosystem_token`)
- API routes follow REST conventions
- WebSocket routes end in `.ws.ts`
- Admin routes grouped under `/admin/ecosystem/`
- User routes under `/ecosystem/`

### Architecture
- Separation of concerns (models, routes, utilities)
- Service-layer approach (utilities do heavy lifting)
- Event-driven updates via WebSocket
- Database-agnostic utilities (Sequelize & Scylla)
- Paranoid mode for soft deletes on user-facing data
