@usherlabs/cex-broker 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright © 2024 Usher Labs Pty Ltd
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,576 @@
1
+ # CEX Broker
2
+
3
+ A high-performance gRPC-based cryptocurrency exchange broker service that provides unified access to multiple centralized exchanges (CEX) through the CCXT library. Built with TypeScript, Bun, and designed for reliable trading operations with policy enforcement, real-time streaming, and zero-knowledge proof integration.
4
+
5
+ ## 🚀 Features
6
+
7
+ - **Multi-Exchange Support**: Unified API to any CEX supported by [CCXT](https://github.com/ccxt/ccxt) (100+ exchanges)
8
+ - **gRPC Interface**: High-performance RPC communication with type safety
9
+ - **Real-time Streaming**: Live orderbook, trades, ticker, OHLCV, balance, and order updates
10
+ - **Policy Enforcement**: Configurable trading and withdrawal limits with real-time policy updates
11
+ - **IP Authentication**: Security through IP whitelisting
12
+ - **Zero-Knowledge Proofs**: Optional Verity integration for privacy-preserving operations
13
+ - **Secondary Broker Support**: Multiple API keys per exchange for load balancing and redundancy
14
+ - **Real-time Policy Updates**: Hot-reload policy changes without server restart
15
+ - **Type Safety**: Full TypeScript support with generated protobuf types
16
+ - **Comprehensive Logging**: Built-in logging with tslog
17
+ - **CLI Support**: Command-line interface for easy management
18
+ - **Deposit Address Management**: Fetch deposit addresses for supported networks
19
+ - **Advanced Order Management**: Create, fetch, and cancel orders with full details
20
+
21
+ ## 📋 Prerequisites
22
+
23
+ - [Bun](https://bun.sh) (v1.2.17 or higher)
24
+ - API keys for supported exchanges (e.g., Binance, Bybit, etc.)
25
+ - Optional: Verity prover URL for zero-knowledge proof integration
26
+
27
+ ## 🛠️ Installation
28
+
29
+ 1. **Clone the repository:**
30
+ ```bash
31
+ git clone <repository-url>
32
+ cd fietCexBroker
33
+ ```
34
+
35
+ 2. **Install dependencies:**
36
+ ```bash
37
+ bun install
38
+ ```
39
+
40
+ 3. **Generate protobuf types:**
41
+ ```bash
42
+ bun run proto-gen
43
+ ```
44
+
45
+ ## ⚙️ Configuration
46
+
47
+ ### Environment Variables
48
+
49
+ The broker loads configuration from environment variables with the `CEX_BROKER_` prefix:
50
+
51
+ ```env
52
+ # Server Configuration
53
+ PORT_NUM=8086
54
+
55
+ # Primary Exchange API Keys (format: CEX_BROKER_<EXCHANGE>_API_KEY/SECRET)
56
+ CEX_BROKER_BINANCE_API_KEY=your_binance_api_key
57
+ CEX_BROKER_BINANCE_API_SECRET=your_binance_api_secret
58
+ CEX_BROKER_BYBIT_API_KEY=your_bybit_api_key
59
+ CEX_BROKER_BYBIT_API_SECRET=your_bybit_api_secret
60
+ CEX_BROKER_KRAKEN_API_KEY=your_kraken_api_key
61
+ CEX_BROKER_KRAKEN_API_SECRET=your_kraken_api_secret
62
+
63
+ # Secondary Exchange API Keys (for load balancing and redundancy)
64
+ CEX_BROKER_BINANCE_API_KEY_1=your_secondary_binance_api_key
65
+ CEX_BROKER_BINANCE_API_SECRET_1=your_secondary_binance_api_secret
66
+ CEX_BROKER_BINANCE_API_KEY_2=your_tertiary_binance_api_key
67
+ CEX_BROKER_BINANCE_API_SECRET_2=your_tertiary_binance_api_secret
68
+ ```
69
+
70
+ **Note**: Only configure API keys for exchanges you plan to use. The system will automatically detect and initialize configured exchanges.
71
+
72
+ ### Policy Configuration
73
+
74
+ Configure trading policies in `policy/policy.json`:
75
+
76
+ ```json
77
+ {
78
+ "withdraw": {
79
+ "rule": {
80
+ "networks": ["BEP20", "ARBITRUM", "ETHEREUM"],
81
+ "whitelist": ["0x9d467fa9062b6e9b1a46e26007ad82db116c67cb"],
82
+ "amounts": [
83
+ {
84
+ "ticker": "USDC",
85
+ "max": 100000,
86
+ "min": 1
87
+ },
88
+ {
89
+ "ticker": "USDT",
90
+ "max": 100000,
91
+ "min": 1
92
+ }
93
+ ]
94
+ }
95
+ },
96
+ "deposit": {},
97
+ "order": {
98
+ "rule": {
99
+ "markets": [
100
+ "BINANCE:ARB/USDT",
101
+ "BYBIT:ARB/USDC",
102
+ "BINANCE:ETH/USDT",
103
+ "BINANCE:BTC/ETH"
104
+ ],
105
+ "limits": [
106
+ { "from": "USDT", "to": "ETH", "min": 1, "max": 100000 },
107
+ { "from": "ETH", "to": "USDT", "min": 0.5, "max": 5 },
108
+ { "from": "ARB", "to": "USDC", "min": 1, "max": 1000 },
109
+ { "from": "USDC", "to": "ARB", "min": 1, "max": 10000 }
110
+ ]
111
+ }
112
+ }
113
+ }
114
+ ```
115
+
116
+ ## 🚀 Usage
117
+
118
+ ### Starting the Server
119
+
120
+ ```bash
121
+ # Using the CLI (recommended)
122
+ bun run start-broker --policy policy/policy.json --port 8086 --whitelist 127.0.0.1 192.168.1.100 --verityProverUrl http://localhost:8080
123
+
124
+ # Development mode
125
+ bun run start
126
+
127
+ # Production build
128
+ bun run build:ts
129
+ bun run ./build/index.js
130
+ ```
131
+
132
+ ### CLI Options
133
+
134
+ ```bash
135
+ cex-broker --help
136
+
137
+ Options:
138
+ -p, --policy <path> Policy JSON file (required)
139
+ --port <number> Port number (default: 8086)
140
+ -w, --whitelist <addresses...> IPv4 address whitelist (space-separated list)
141
+ -vu, --verityProverUrl <url> Verity Prover URL for zero-knowledge proofs
142
+ ```
143
+
144
+ ### Available Scripts
145
+
146
+ ```bash
147
+ # Start the server
148
+ bun run start
149
+
150
+ # Build for production
151
+ bun run build:ts
152
+
153
+ # Run tests
154
+ bun test
155
+
156
+ # Generate protobuf types
157
+ bun run proto-gen
158
+
159
+ # Format code
160
+ bun run format
161
+
162
+ # Lint code
163
+ bun run lint
164
+
165
+ # Check code (format + lint)
166
+ bun run check
167
+ ```
168
+
169
+ ## 📡 API Reference
170
+
171
+ The service exposes a gRPC interface with two main methods:
172
+
173
+ ### ExecuteAction
174
+
175
+ Execute trading operations on supported exchanges.
176
+
177
+ **Request:**
178
+ ```protobuf
179
+ message ActionRequest {
180
+ Action action = 1; // The action to perform
181
+ map<string, string> payload = 2; // Parameters for the action
182
+ string cex = 3; // CEX identifier (e.g., "binance", "bybit")
183
+ string symbol = 4; // Trading pair symbol if needed
184
+ }
185
+ ```
186
+
187
+ **Response:**
188
+ ```protobuf
189
+ message ActionResponse {
190
+ string result = 2; // JSON string of the result data or ZK proof
191
+ }
192
+ ```
193
+
194
+ **Available Actions:**
195
+ - `NoAction` (0): No operation
196
+ - `Deposit` (1): Confirm deposit transaction
197
+ - `Transfer` (2): Transfer/withdraw funds
198
+ - `CreateOrder` (3): Create a new order
199
+ - `GetOrderDetails` (4): Get order information
200
+ - `CancelOrder` (5): Cancel an existing order
201
+ - `FetchBalance` (6): Get account balance
202
+ - `FetchDepositAddresses` (7): Get deposit addresses for a token/network
203
+
204
+ **Example Usage:**
205
+
206
+ ```typescript
207
+ // Fetch balance
208
+ const balanceRequest = {
209
+ action: 6, // FetchBalance
210
+ payload: {},
211
+ cex: "binance",
212
+ symbol: "USDT"
213
+ };
214
+
215
+ // Create order
216
+ const orderRequest = {
217
+ action: 3, // CreateOrder
218
+ payload: {
219
+ orderType: "limit",
220
+ amount: "0.001",
221
+ fromToken: "BTC",
222
+ toToken: "USDT",
223
+ price: "50000"
224
+ },
225
+ cex: "binance",
226
+ symbol: "BTC/USDT"
227
+ };
228
+
229
+ // Fetch deposit addresses
230
+ const depositAddressRequest = {
231
+ action: 7, // FetchDepositAddresses
232
+ payload: {
233
+ chain: "BEP20"
234
+ },
235
+ cex: "binance",
236
+ symbol: "USDT"
237
+ };
238
+ ```
239
+
240
+ ### Subscribe (Streaming)
241
+
242
+ Real-time streaming of market data and account updates.
243
+
244
+ **Request:**
245
+ ```protobuf
246
+ message SubscribeRequest {
247
+ string cex = 1; // CEX identifier
248
+ string symbol = 2; // Trading pair symbol
249
+ SubscriptionType type = 3; // Type of subscription
250
+ map<string, string> options = 4; // Additional options (e.g., timeframe)
251
+ }
252
+ ```
253
+
254
+ **Response Stream:**
255
+ ```protobuf
256
+ message SubscribeResponse {
257
+ string data = 1; // JSON string of the streaming data
258
+ int64 timestamp = 2; // Unix timestamp
259
+ string symbol = 3; // Trading pair symbol
260
+ SubscriptionType type = 4; // Type of subscription
261
+ }
262
+ ```
263
+
264
+ **Available Subscription Types:**
265
+ - `ORDERBOOK` (0): Real-time order book updates
266
+ - `TRADES` (1): Live trade feed
267
+ - `TICKER` (2): Ticker information updates
268
+ - `OHLCV` (3): Candlestick data (configurable timeframe)
269
+ - `BALANCE` (4): Account balance updates
270
+ - `ORDERS` (5): Order status updates
271
+
272
+ **Example Usage:**
273
+
274
+ ```typescript
275
+ // Subscribe to orderbook updates
276
+ const orderbookRequest = {
277
+ cex: "binance",
278
+ symbol: "BTC/USDT",
279
+ type: 0, // ORDERBOOK
280
+ options: {}
281
+ };
282
+
283
+ // Subscribe to OHLCV with custom timeframe
284
+ const ohlcvRequest = {
285
+ cex: "binance",
286
+ symbol: "BTC/USDT",
287
+ type: 3, // OHLCV
288
+ options: {
289
+ timeframe: "1h"
290
+ }
291
+ };
292
+ ```
293
+
294
+ ## 🔒 Security
295
+
296
+ ### IP Authentication
297
+
298
+ All API calls require IP authentication. Configure allowed IPs via CLI or broker initialization:
299
+
300
+ ```bash
301
+ # Via CLI
302
+ cex-broker --policy policy.json --whitelist 127.0.0.1 192.168.1.100
303
+
304
+ # Via code
305
+ const config = {
306
+ port: 8086,
307
+ whitelistIps: [
308
+ "127.0.0.1", // localhost
309
+ "::1", // IPv6 localhost
310
+ "192.168.1.100", // Your allowed IP
311
+ ]
312
+ };
313
+ ```
314
+
315
+ ### Secondary Broker Support
316
+
317
+ For high-availability and load balancing, you can configure multiple API keys per exchange:
318
+
319
+ ```env
320
+ # Primary keys
321
+ CEX_BROKER_BINANCE_API_KEY=primary_key
322
+ CEX_BROKER_BINANCE_API_SECRET=primary_secret
323
+
324
+ # Secondary keys (numbered)
325
+ CEX_BROKER_BINANCE_API_KEY_1=secondary_key_1
326
+ CEX_BROKER_BINANCE_API_SECRET_1=secondary_secret_1
327
+ CEX_BROKER_BINANCE_API_KEY_2=secondary_key_2
328
+ CEX_BROKER_BINANCE_API_SECRET_2=secondary_secret_2
329
+ ```
330
+
331
+ To use secondary brokers, include the `use-secondary-key` metadata in your gRPC calls:
332
+
333
+ ```typescript
334
+ const metadata = new grpc.Metadata();
335
+ metadata.set('use-secondary-key', '1'); // Use secondary broker 1
336
+ metadata.set('use-secondary-key', '2'); // Use secondary broker 2
337
+ ```
338
+
339
+ ### Zero-Knowledge Proof Integration
340
+
341
+ Enable privacy-preserving operations with Verity integration:
342
+
343
+ ```bash
344
+ # Start with Verity integration
345
+ cex-broker --policy policy.json --verityProverUrl http://localhost:8080
346
+ ```
347
+
348
+ When Verity is enabled, responses include zero-knowledge proofs instead of raw data:
349
+
350
+ ```typescript
351
+ // With Verity enabled
352
+ const response = await client.ExecuteAction(request, metadata);
353
+ // response.result contains ZK proof instead of raw data
354
+ ```
355
+
356
+ ### API Key Management
357
+
358
+ - Store API keys securely in environment variables
359
+ - Use read-only API keys when possible
360
+ - Regularly rotate API keys
361
+ - Monitor API usage and set appropriate rate limits
362
+ - Use secondary brokers for redundancy and load distribution
363
+
364
+ ## 🏗️ Architecture
365
+
366
+ ### Project Structure
367
+
368
+ ```
369
+ fietCexBroker/
370
+ ├── src/ # Source code
371
+ │ ├── commands/ # CLI commands
372
+ │ │ └── start-broker.ts # Broker startup command
373
+ │ ├── helpers/ # Utility functions
374
+ │ │ ├── index.ts # Policy validation helpers
375
+ │ │ └── logger.ts # Logging configuration
376
+ │ ├── index.ts # Main broker class
377
+ │ ├── server.ts # gRPC server implementation
378
+ │ ├── cli.ts # CLI entry point
379
+ │ └── types.ts # TypeScript type definitions
380
+ ├── proto/ # Protocol buffer definitions
381
+ │ ├── node.proto # Service definition
382
+ │ └── node.ts # Type exports
383
+ ├── policy/ # Policy configuration
384
+ │ └── policy.json # Trading and withdrawal rules
385
+ ├── scripts/ # Build scripts
386
+ ├── test/ # Test files
387
+ ├── patches/ # Dependency patches
388
+ ├── build.ts # Build configuration
389
+ └── package.json # Dependencies and scripts
390
+ ```
391
+
392
+ ### Core Components
393
+
394
+ - **CEXBroker**: Main broker class that manages exchange connections and policy enforcement
395
+ - **Policy System**: Real-time policy validation and enforcement
396
+ - **gRPC Server**: High-performance RPC interface with streaming support
397
+ - **CCXT Integration**: Unified access to 100+ cryptocurrency exchanges
398
+ - **Verity Integration**: Zero-knowledge proof generation for privacy
399
+ - **Secondary Broker Management**: Load balancing and redundancy support
400
+
401
+ ## 🧪 Development
402
+
403
+ ### Adding New Exchanges
404
+
405
+ The broker automatically supports all exchanges available in CCXT. To add a new exchange:
406
+
407
+ 1. Add your API credentials to environment variables:
408
+ ```env
409
+ CEX_BROKER_<EXCHANGE>_API_KEY=your_api_key
410
+ CEX_BROKER_<EXCHANGE>_API_SECRET=your_api_secret
411
+ ```
412
+
413
+ 2. Update policy configuration if needed for the new exchange
414
+
415
+ 3. The broker will automatically detect and initialize the exchange
416
+
417
+ ### Using Secondary Brokers
418
+
419
+ Secondary brokers provide redundancy and load balancing:
420
+
421
+ 1. Configure secondary API keys:
422
+ ```env
423
+ CEX_BROKER_BINANCE_API_KEY_1=secondary_key_1
424
+ CEX_BROKER_BINANCE_API_SECRET_1=secondary_secret_1
425
+ ```
426
+
427
+ 2. Use secondary brokers in your gRPC calls:
428
+ ```typescript
429
+ const metadata = new grpc.Metadata();
430
+ metadata.set('use-secondary-key', '1'); // Use secondary broker
431
+ ```
432
+
433
+ ### Querying Supported Networks
434
+
435
+ To understand which networks each exchange supports for deposits and withdrawals, you can query the exchange's currency information:
436
+
437
+ ```typescript
438
+ import ccxt from 'ccxt';
439
+
440
+ // Initialize the exchange (no API keys needed for public data)
441
+ const exchange = new ccxt.binance(); // or any other exchange like ccxt.bybit()
442
+
443
+ // Fetch all currencies and their network information
444
+ const currencies = await exchange.fetchCurrencies();
445
+
446
+ // Example: Check USDT networks on Binance
447
+ const usdtInfo = currencies['USDT'];
448
+ console.log("USDT Networks on Binance:");
449
+ console.log(usdtInfo?.networks);
450
+
451
+ // Example output:
452
+ // {
453
+ // 'BEP20': {id: 'BSC', network: 'BSC', active: true, deposit: true, withdraw: true, fee: 1.0},
454
+ // 'ETH': {id: 'ETH', network: 'ETH', active: true, deposit: true, withdraw: true, fee: 15.0},
455
+ // 'TRC20': {id: 'TRX', network: 'TRX', active: true, deposit: true, withdraw: true, fee: 1.0}
456
+ // }
457
+
458
+ // Check all available currencies
459
+ for (const [currency, info] of Object.entries(currencies)) {
460
+ if ('networks' in info) {
461
+ console.log(`\n${currency} networks:`);
462
+ for (const [network, networkInfo] of Object.entries(info.networks)) {
463
+ console.log(` ${network}:`, networkInfo);
464
+ }
465
+ }
466
+ }
467
+ ```
468
+
469
+ **Common Network Identifiers:**
470
+ - `BEP20` / `BSC`: Binance Smart Chain
471
+ - `ETH` / `ERC20`: Ethereum
472
+ - `TRC20`: Tron
473
+ - `ARBITRUM`: Arbitrum One
474
+ - `POLYGON`: Polygon
475
+ - `AVALANCHE`: Avalanche C-Chain
476
+ - `OPTIMISM`: Optimism
477
+
478
+ **Using this information in your policy:**
479
+
480
+ ```json
481
+ {
482
+ "withdraw": {
483
+ "rule": {
484
+ "networks": ["BEP20", "ARBITRUM", "ETH"], // Networks supported by your exchanges
485
+ "whitelist": ["0x9d467fa9062b6e9b1a46e26007ad82db116c67cb"],
486
+ "amounts": [
487
+ {
488
+ "ticker": "USDT",
489
+ "max": 100000,
490
+ "min": 1
491
+ }
492
+ ]
493
+ }
494
+ }
495
+ }
496
+ ```
497
+
498
+ ### Testing
499
+
500
+ ```bash
501
+ # Run all tests
502
+ bun test
503
+
504
+ # Run tests with watch mode
505
+ bun test --watch
506
+
507
+ # Run tests with coverage
508
+ bun test --coverage
509
+ ```
510
+
511
+ ### Code Quality
512
+
513
+ ```bash
514
+ # Format code
515
+ bun run format
516
+
517
+ # Lint code
518
+ bun run lint
519
+
520
+ # Check code (format + lint)
521
+ bun run check
522
+ ```
523
+
524
+ ## 📦 Dependencies
525
+
526
+ ### Core Dependencies
527
+
528
+ - `@grpc/grpc-js`: gRPC server implementation
529
+ - `@grpc/proto-loader`: Protocol buffer loading
530
+ - `@usherlabs/ccxt`: Enhanced CCXT library with Verity support
531
+ - `commander`: CLI framework
532
+ - `joi`: Configuration validation
533
+ - `tslog`: TypeScript logging
534
+
535
+ ### Development Dependencies
536
+
537
+ - `@biomejs/biome`: Code formatting and linting
538
+ - `@types/bun`: Bun type definitions
539
+ - `bun-plugin-dts`: TypeScript declaration generation
540
+ - `bun-types`: Additional Bun types
541
+ - `husky`: Git hooks
542
+
543
+ ## 🤝 Contributing
544
+
545
+ 1. Fork the repository
546
+ 2. Create a feature branch (`git checkout -b feature/amazing-feature`)
547
+ 3. Make your changes
548
+ 4. Add tests for new functionality
549
+ 5. Ensure all tests pass (`bun test`)
550
+ 6. Run code quality checks (`bun run check`)
551
+ 7. Commit your changes (`git commit -m 'Add amazing feature'`)
552
+ 8. Push to the branch (`git push origin feature/amazing-feature`)
553
+ 9. Open a Pull Request
554
+
555
+ ## 📄 License
556
+
557
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
558
+
559
+ ## 🆘 Support
560
+
561
+ For issues and questions:
562
+
563
+ - Open an issue on the repository
564
+ - Contact the development team
565
+ - Check the [CCXT documentation](https://docs.ccxt.com/) for exchange-specific information
566
+
567
+ ## 🙏 Acknowledgments
568
+
569
+ - [CCXT](https://github.com/ccxt/ccxt) for providing unified access to cryptocurrency exchanges
570
+ - [Bun](https://bun.sh) for the fast JavaScript runtime
571
+ - [gRPC](https://grpc.io/) for high-performance RPC communication
572
+ - [Verity](https://usher.so/) for zero-knowledge proof integration
573
+
574
+ ---
575
+
576
+ **Built with ❤️ by Usher Labs**
@@ -0,0 +1,3 @@
1
+ // Generated by dts-bundle-generator v9.5.1
2
+
3
+ export {};