Hu-Fi / Mr.Market

Mr. Market is the exchange oracle of HuFi, and a CeFi crypto bot on Mixin Messenger
https://mr-market-one.vercel.app
GNU Affero General Public License v3.0
1 stars 6 forks source link

Add initial version of spot module and tests #79

Closed zed-wong closed 4 months ago

zed-wong commented 4 months ago

User description

Add initial version of spot module and tests. Add message handler, controller, and tests. Add OKX and Gate.io in the market data module. Add a decoder that decodes different exchange data formats. Add a custom config module for dynamic configurations. Add JWT auth guard and tests for admin and protected endpoints. Add a withdrawal fee comparer for the withdrawal gateway. Add a skeleton loader and failure page for the candlestick page. Add a failure retry component for the home page. Add a message page for the admin page. Fix the NestJS socket gateway CORS error and combine listening ports.


Type

enhancement, bug_fix


Description


Changes walkthrough

Relevant files
Enhancement
23 files
exchange.service.ts
Implement Exchange Service for Trading Operations               

server/src/modules/mixin/exchange/exchange.service.ts
  • Added ExchangeService with methods for handling exchange operations.
  • Implemented API key loading, balance checking, and order placement
    functionalities.
  • Integrated with CCXT library for exchange interactions.
  • +331/-0 
    pairs.ts
    Update Supported Pairs and Add Exchange Mapping                   

    server/src/common/constants/pairs.ts
  • Updated SUPPORTED_PAIRS to include OKX and additional exchanges.
  • Added PAIRS_MAP and SYMBOL_ASSET_ID_MAP for memo decoding and asset ID
    mapping.
  • +79/-2   
    snapshots.service.ts
    Implement Snapshots Service for Mixin Integration               

    server/src/modules/mixin/snapshots/snapshots.service.ts
  • Implemented SnapshotsService for handling Mixin snapshots.
  • Added methods for fetching snapshots, processing them, and refunding.
  • +212/-0 
    socket.ts
    Update Socket Connections and Handlers for Market Data     

    interface/src/lib/helpers/hufi/socket.ts
  • Updated socket connection URLs and handlers for market data and
    candlestick pages.
  • Added error handling for candlestick data loading.
  • +24/-19 
    message.service.ts
    Implement Message Service for Mixin Messaging                       

    server/src/modules/mixin/message/message.service.ts
  • Added MessageService for handling Mixin messages.
  • Implemented methods for sending, broadcasting, and managing messages.
  • +164/-0 
    helpers.ts
    Update Helper Functions and Add New Exchange Icons             

    interface/src/lib/helpers/helpers.ts
  • Updated helper functions for finding exchange icons and coin icons.
  • Added new exchange icons and mappings.
  • +61/-14 
    exchange.listener.ts
    Implement ExchangeListener for Exchange Event Handling     

    server/src/modules/mixin/listeners/exchange.listener.ts
  • Implemented ExchangeListener for handling exchange-related events.
  • Added event handling for spot order placement and mixin release token
    processing.
  • +96/-0   
    utils.ts
    Add Utility Functions for Memo Decoding and Timestamp Handling

    server/src/common/helpers/utils.ts
  • Added utility functions for generating random sequences, decoding
    memos, and handling timestamps.
  • +84/-0   
    main.ts
    Simplify Main Application Setup and Update Logging             

    server/src/main.ts
  • Simplified main application setup and removed conditional HTTPS
    configuration.
  • Updated global request logging setup.
  • +16/-52 
    mixin.listener.ts
    Implement MixinListener for Mixin Event Handling                 

    server/src/modules/mixin/listeners/mixin.listener.ts
  • Implemented MixinListener for handling Mixin events.
  • Added event handling for token release and snapshot processing.
  • +90/-0   
    user.service.ts
    Implement UserService for Mixin User Management                   

    server/src/modules/mixin/user/user.service.ts
  • Added UserService for managing Mixin users.
  • Implemented user addition, removal, and existence checking.
  • +85/-0   
    customConfig.repository.ts
    Implement CustomConfigRepository for Configuration Management

    server/src/modules/customConfig/customConfig.repository.ts
  • Implemented CustomConfigRepository for managing custom configurations.
  • Added methods for reading and modifying spot fees and max balances.
  • +73/-0   
    marketDataDecoder.ts
    Update Market Data Decoder Functions                                         

    interface/src/lib/helpers/hufi/marketDataDecoder.ts
  • Updated market data decoder functions for handling order book,
    candlestick, and ticker data.
  • +10/-7   
    admin.controller.ts
    Update AdminController to Use JWT Authentication                 

    server/src/modules/admin/admin.controller.ts
  • Updated AdminController to use JWT authentication guard.
  • Added endpoints for admin and config data retrieval.
  • +12/-41 
    marketdata.service.ts
    Update MarketdataService to Include More Exchanges             

    server/src/modules/marketdata/marketdata.service.ts
  • Updated MarketdataService to include OKX and Gate.io exchanges.
  • Enhanced ticker data handling with a decoder function.
  • +16/-1   
    auth.service.ts
    Implement AuthService for Authentication Handling               

    server/src/modules/auth/auth.service.ts
  • Implemented AuthService for handling authentication and JWT token
    generation.
  • +45/-0   
    bigone.ts
    Define Types for BigOne Withdrawal Fee Responses                 

    server/src/common/types/withdrawal/bigone.ts - Defined types for handling BigOne withdrawal fee responses.
    +56/-0   
    logger.service.ts
    Update CustomLogger with Debug Logging and Refined Setup 

    server/src/modules/logger/logger.service.ts
  • Updated CustomLogger to include debug logging and refined file logging
    setup.
  • +15/-4   
    states.ts
    Define Mappings for Spot Order States and Codes                   

    server/src/common/types/orders/states.ts - Defined mappings for spot order states and codes.
    +32/-0   
    memo.ts
    Add Functions for Decoding Spot and Swap Memos                     

    server/src/common/helpers/mixin/memo.ts - Added functions for decoding spot and swap memos.
    +39/-0   
    constants.ts
    Update Supported Pairs and Add Configuration Variables     

    interface/src/lib/helpers/constants.ts
  • Updated supported pairs and added environment variables for
    application configuration.
  • +2/-3     
    spot.event.ts
    Define Event Classes for Spot Order and Mixin Events         

    server/src/modules/mixin/events/spot.event.ts
  • Defined event classes for spot order creation, exchange placement, and
    mixin release token events.
  • +43/-0   
    exchange.dto.ts
    Define DTO for Exchange Place Spot Event                                 

    server/src/modules/mixin/exchange/exchange.dto.ts - Defined DTO for exchange place spot event.
    +36/-0   
    Tests
    8 files
    mixin.listener.spec.ts
    Add Unit Tests for MixinListener                                                 

    server/src/modules/mixin/listeners/mixin.listener.spec.ts
  • Added unit tests for MixinListener to cover various scenarios
    including asset ID validation and release token handling.
  • +154/-0 
    exchange.listener.spec.ts
    Add Unit Tests for ExchangeListener                                           

    server/src/modules/mixin/listeners/exchange.listener.spec.ts
  • Added unit tests for ExchangeListener to verify spot order placement
    and API key selection.
  • +156/-0 
    spot.listener.spec.ts
    Add Unit Tests for SpotOrderListener                                         

    server/src/modules/mixin/listeners/spot.listener.spec.ts
  • Added unit tests for SpotOrderListener to validate spot order creation
    and event handling.
  • +108/-0 
    snapshots.service.spec.ts
    Add Unit Tests for SnapshotsService                                           

    server/src/modules/mixin/snapshots/snapshots.service.spec.ts
  • Added unit tests for SnapshotsService to cover snapshot fetching and
    processing.
  • +96/-0   
    message.service.spec.ts
    Add Unit Tests for MessageService                                               

    server/src/modules/mixin/message/message.service.spec.ts
  • Added unit tests for MessageService to cover message handling and
    repository interactions.
  • +83/-0   
    auth.service.spec.ts
    Add Unit Tests for AuthService                                                     

    server/src/modules/auth/auth.service.spec.ts
  • Added unit tests for AuthService to cover user validation and JWT
    generation.
  • +60/-0   
    withdrawal.service.spec.ts
    Add Unit Tests for WithdrawalService                                         

    server/src/modules/mixin/withdrawal/withdrawal.service.spec.ts
  • Added unit tests for WithdrawalService to compare fees between BigOne
    and Mixin for various assets.
  • +37/-0   
    marketdata.service.spec.ts
    Add Mock Implementations for Exchanges in Unit Tests         

    server/src/modules/marketdata/marketdata.service.spec.ts
  • Added mock implementations for OKX and Gate.io exchanges in unit
    tests.
  • +2/-4     

    PR-Agent usage: Comment /help on the PR to get a list of all available PR-Agent tools and their descriptions

    vercel[bot] commented 4 months ago

    The latest updates on your projects. Learn more about Vercel for Git ↗︎

    Name Status Preview Comments Updated (UTC)
    mr-market ✅ Ready (Inspect) Visit Preview 💬 Add feedback Mar 20, 2024 0:35am
    railway-app[bot] commented 4 months ago

    This PR is being deployed to Railway 🚅

    Mr.Market: ◻️ REMOVED

    github-actions[bot] commented 4 months ago

    PR Description updated to latest commit (https://github.com/Hu-Fi/Mr.Market/commit/cd2efefdb8895208cbe180152630f541ef79e607)

    github-actions[bot] commented 4 months ago

    PR Review

    ⏱️ Estimated effort to review [1-5] 5, due to the extensive amount of new functionality, changes across multiple modules, and the introduction of new entities and services. The PR adds significant features related to the Mixin exchange service, message handling, custom configurations, and various listeners for handling specific events. The complexity is further increased by the integration with external services like CCXT for cryptocurrency exchange operations and the need to ensure proper error handling, security considerations, especially around authentication and authorization, and the overall architectural fit within the existing system. The review requires a thorough understanding of the system's design, the Mixin API, and the CCXT library.
    🧪 Relevant tests No
    🔍 Possible issues Possible Bug: The `handleReleaseTokenEvent` method in `MixinListener` does not await the result of `readMixinReleaseHistory` before checking its value, which may lead to race conditions or incorrect logic flow.
    Security Concern: The `validateUser` method in `AuthService` uses SHA3-256 for password hashing, which, while secure, might not align with the latest recommendations for password storage strategies such as bcrypt or Argon2.
    Performance Concern: The `fetchAndProcessSnapshots` method in `SnapshotsService` fetches all snapshots and processes them in a loop without any form of pagination or rate limiting, which could lead to performance issues with a large number of snapshots.
    🔒 Security concerns JWT Secret Exposure: The `AuthService` retrieves the JWT secret directly from the environment variables without any form of encryption or secure storage, which might expose the secret in logs or to unauthorized access on the server.
    Code feedback:
    relevant fileserver/src/modules/mixin/listeners/mixin.listener.ts
    suggestion       Await the result of `readMixinReleaseHistory` before proceeding with the condition check to avoid potential race conditions or logic errors. [important]
    relevant lineif (!this.exchangeService.readMixinReleaseHistory(e.orderId)) {

    relevant fileserver/src/modules/auth/auth.service.ts
    suggestion       Consider using a more secure password storage strategy like bcrypt or Argon2 for hashing passwords instead of SHA3-256 to enhance security. [important]
    relevant lineconst hashedSuppliedPassword = createHash('sha3-256')

    relevant fileserver/src/modules/mixin/snapshots/snapshots.service.ts
    suggestion       Implement pagination or rate limiting in `fetchAndProcessSnapshots` to handle large volumes of snapshots efficiently and avoid potential performance bottlenecks. [medium]
    relevant linesnapshots.forEach(async (snapshot: SafeSnapshot) => {

    relevant fileserver/src/modules/auth/auth.service.ts
    suggestion       Securely manage the JWT secret used in `AuthService` by implementing encryption or a secure storage solution to prevent potential exposure. [important]
    relevant linethis.secret = this.configService.get('admin.jwt_secret');


    ✨ Review tool usage guide:
    **Overview:** The `review` tool scans the PR code changes, and generates a PR review. The tool can be triggered [automatically](https://pr-agent-docs.codium.ai/usage-guide/automations_and_usage/#github-app-automatic-tools-when-a-new-pr-is-opened) every time a new PR is opened, or can be invoked manually by commenting on any PR. When commenting, to edit [configurations](https://github.com/Codium-ai/pr-agent/blob/main/pr_agent/settings/configuration.toml#L19) related to the review tool (`pr_reviewer` section), use the following template: ``` /review --pr_reviewer.some_config1=... --pr_reviewer.some_config2=... ``` With a [configuration file](https://pr-agent-docs.codium.ai/usage-guide/configuration_options/), use the following template: ``` [pr_reviewer] some_config1=... some_config2=... ```
    Utilizing extra instructions
    The `review` tool can be configured with extra instructions, which can be used to guide the model to a feedback tailored to the needs of your project. Be specific, clear, and concise in the instructions. With extra instructions, you are the prompter. Specify the relevant sub-tool, and the relevant aspects of the PR that you want to emphasize. Examples for extra instructions: ``` [pr_reviewer] # /review # extra_instructions=""" In the 'possible issues' section, emphasize the following: - Does the code logic cover relevant edge cases? - Is the code logic clear and easy to understand? - Is the code logic efficient? ... """ ``` Use triple quotes to write multi-line instructions. Use bullet points to make the instructions more readable.
    How to enable\disable automation
    - When you first install PR-Agent app, the [default mode](https://pr-agent-docs.codium.ai/usage-guide/automations_and_usage/#github-app-automatic-tools-when-a-new-pr-is-opened) for the `review` tool is: ``` pr_commands = ["/review", ...] ``` meaning the `review` tool will run automatically on every PR, with the default configuration. Edit this field to enable/disable the tool, or to change the used configurations
    Auto-labels
    The `review` tool can auto-generate two specific types of labels for a PR: - a `possible security issue` label, that detects possible [security issues](https://github.com/Codium-ai/pr-agent/blob/tr/user_description/pr_agent/settings/pr_reviewer_prompts.toml#L136) (`enable_review_labels_security` flag) - a `Review effort [1-5]: x` label, where x is the estimated effort to review the PR (`enable_review_labels_effort` flag)
    Extra sub-tools
    The `review` tool provides a collection of possible feedbacks about a PR. It is recommended to review the [possible options](https://pr-agent-docs.codium.ai/tools/review/#enabledisable-features), and choose the ones relevant for your use case. Some of the feature that are disabled by default are quite useful, and should be considered for enabling. For example: `require_score_review`, `require_soc2_ticket`, `require_can_be_split_review`, and more.
    Auto-approve PRs
    By invoking: ``` /review auto_approve ``` The tool will automatically approve the PR, and add a comment with the approval. To ensure safety, the auto-approval feature is disabled by default. To enable auto-approval, you need to actively set in a pre-defined configuration file the following: ``` [pr_reviewer] enable_auto_approval = true ``` (this specific flag cannot be set with a command line argument, only in the configuration file, committed to the repository) You can also enable auto-approval only if the PR meets certain requirements, such as that the `estimated_review_effort` is equal or below a certain threshold, by adjusting the flag: ``` [pr_reviewer] maximal_review_effort = 5 ```
    More PR-Agent commands
    > To invoke the PR-Agent, add a comment using one of the following commands: > - **/review**: Request a review of your Pull Request. > - **/describe**: Update the PR title and description based on the contents of the PR. > - **/improve [--extended]**: Suggest code improvements. Extended mode provides a higher quality feedback. > - **/ask \**: Ask a question about the PR. > - **/update_changelog**: Update the changelog based on the PR's contents. > - **/add_docs** 💎: Generate docstring for new components introduced in the PR. > - **/generate_labels** 💎: Generate labels for the PR based on the PR's contents. > - **/analyze** 💎: Automatically analyzes the PR, and presents changes walkthrough for each component. >See the [tools guide](https://pr-agent-docs.codium.ai/tools/) for more details. >To list the possible configuration parameters, add a **/config** comment.
    See the [review usage](https://pr-agent-docs.codium.ai/tools/review/) page for a comprehensive guide on using this tool.
    github-actions[bot] commented 4 months ago

    PR Code Suggestions

    CategorySuggestions                                                                                                                                                       
    Best practice
    Remove or replace console.log for production readiness. ___ **It's generally not a good practice to use console.log in production code as it can expose
    sensitive information and clutter the console output. Consider using a more sophisticated
    logging mechanism that can be disabled in production or removing this line if it was used
    for debugging purposes.** [interface/src/lib/helpers/candle/candle.ts [9]](https://github.com/Hu-Fi/Mr.Market/pull/79/files#diff-5af359a89aaad696dbc30ecb68fd8f522fa2c1937741378093f7d9fd6ec8e97dR9-R9) ```diff -console.log(`fetchCandleChartData: ${pair.exchange}, ${pair.symbol}, ${timeFrame}`) +// Removed console.log for production readiness ```
    Validate URL formats to ensure they are correct. ___ **When defining constants that represent URLs, it's a good practice to validate the URL
    format to prevent typos and ensure the URLs are valid. Consider adding URL validation for
    AppURL and HUMAN_PROTOCOL_GROUP_URL.** [interface/src/lib/helpers/constants.ts [5]](https://github.com/Hu-Fi/Mr.Market/pull/79/files#diff-1d9500711f0f58654b9e0e95aa0e7fdc798a0b74f1c2310b09e52123e52d6bf2R5-R5) ```diff -export const AppURL = env.PUBLIC_APP_URL || "https://mr-market-one.vercel.app" +// Example URL validation (simplified) +const isValidUrl = (url) => { + try { + new URL(url); + return true; + } catch (_) { + return false; + } +}; +export const AppURL = isValidUrl(env.PUBLIC_APP_URL) ? env.PUBLIC_APP_URL : "https://mr-market-one.vercel.app"; ```
    Disable TypeORM synchronize in production for safer database management. ___ **Consider setting synchronize to false for production environments to avoid unintended
    database alterations. Use migrations to manage database changes more safely.** [server/src/app.module.ts [77]](https://github.com/Hu-Fi/Mr.Market/pull/79/files#diff-4e8033eb0f9fd87924c445b7ac0f1c1192d4890fc1589b2fad2679797d4f4ce0R77-R77) ```diff -synchronize: true, +synchronize: process.env.NODE_ENV !== 'production', ```
    Use more descriptive mock variable names for JWT and its secret. ___ **Use a more descriptive variable name than mock-jwt and mock-jwt-secret to reflect the
    purpose or context of the JWT and its secret in the tests, enhancing readability and
    maintainability.** [server/src/modules/auth/auth.service.spec.ts [19-26]](https://github.com/Hu-Fi/Mr.Market/pull/79/files#diff-a4aa529fbd3004f2485112cc226be5de73cf024074d5bc13c9a546b6bd307d68R19-R26) ```diff -sign: jest.fn(() => 'mock-jwt'), +sign: jest.fn(() => 'testAdminJwtToken'), ... -if (key === 'admin.jwt_secret') return 'mock-jwt-secret'; +if (key === 'admin.jwt_secret') return 'testJwtSecretForAdmin'; ```
    Add a teardown step to reset mocks after each test. ___ **Consider adding a teardown step after each test or at the end of your test suite to reset
    the mocks. This ensures that the state from one test does not inadvertently affect
    another, maintaining test isolation.** [server/src/modules/auth/auth.service.spec.ts [12-36]](https://github.com/Hu-Fi/Mr.Market/pull/79/files#diff-a4aa529fbd3004f2485112cc226be5de73cf024074d5bc13c9a546b6bd307d68R12-R36) ```diff -beforeEach(async () => { - const module: TestingModule = await Test.createTestingModule({ - providers: [ - AuthService, - ... - ], - }).compile(); - ... +afterEach(() => { + jest.resetAllMocks(); }); ```
    Enhancement
    Use descriptive error messages for better error handling. ___ **Instead of throwing a generic error, it's more helpful to provide a specific error message
    or create a custom error class. This can improve error handling and debugging. Consider
    creating a custom error class or using a more descriptive error message.** [interface/src/lib/helpers/hufi/coin.ts [41]](https://github.com/Hu-Fi/Mr.Market/pull/79/files#diff-256a64b9ed50e82ac22104895399dbc403c4aae9a4b3901816b45b49d91e499cR41-R41) ```diff -throw error('fetchOHLCV:', r.status) +throw new Error(`fetchOHLCV failed with status: ${r.status}`) ```
    Use a generic error page for unsupported exchanges or pairs instead of hardcoding a specific market page. ___ **Instead of hardcoding the redirection URL to a specific pair and exchange, consider using
    a more generic approach or redirecting to a generic error page. This would improve the
    user experience by not redirecting users to a potentially irrelevant market page.** [interface/src/routes/(secondary)/(candle)/market/candle/[exchange]/[pair]/+page.ts [19-24]](https://github.com/Hu-Fi/Mr.Market/pull/79/files#diff-cdcb797b71f48041884c0c2f0fa520b8d3aa611082a0b0b315bd6aa862a706ceR19-R24) ```diff -goto('/market/candle/okx/BTC-USDT') +goto('/error/unsupported-exchange-or-pair') ```
    Add type definition for the data parameter in decodeTicker function. ___ **Consider adding a type definition for the data parameter in decodeTicker function to
    improve type safety and code readability. TypeScript's type system can help ensure that
    the correct data structure is being passed and used within the function.** [server/src/common/helpers/marketdata/decoder.ts [1]](https://github.com/Hu-Fi/Mr.Market/pull/79/files#diff-2882795718f06a6172663455fdbc8ddcb255882d94c213903b48470f5ae351f3R1-R1) ```diff -export const decodeTicker = (exchangeName: string, data: any) => { +interface TickerData { + timestamp: number; + ask: number; +} +export const decodeTicker = (exchangeName: string, data: TickerData) => { ```
    Improve the robustness of ConfigService mocking in tests. ___ **Consider mocking ConfigService more comprehensively to cover all potential uses within the
    AuthService. This will ensure that your tests remain robust even if the implementation of
    AuthService evolves to use more configuration values.** [server/src/modules/auth/auth.service.spec.ts [23-29]](https://github.com/Hu-Fi/Mr.Market/pull/79/files#diff-a4aa529fbd3004f2485112cc226be5de73cf024074d5bc13c9a546b6bd307d68R23-R29) ```diff { provide: ConfigService, useValue: { get: jest.fn((key: string) => { - if (key === 'admin.jwt_secret') return 'mock-jwt-secret'; - if (key === 'admin.pass') return 'correctpassword'; + switch (key) { + case 'admin.jwt_secret': + return 'mock-jwt-secret'; + case 'admin.pass': + return 'correctpassword'; + default: + return null; // or a sensible default for other keys + } }), }, } ```
    Add a test case for unexpected but valid password inputs. ___ **Add a test case to verify the behavior of validateUser when a valid but unexpected
    password is provided. This ensures that your authentication logic behaves correctly across
    a wider range of inputs.** [server/src/modules/auth/auth.service.spec.ts [49-52]](https://github.com/Hu-Fi/Mr.Market/pull/79/files#diff-a4aa529fbd3004f2485112cc226be5de73cf024074d5bc13c9a546b6bd307d68R49-R52) ```diff -it('should throw an error if password is incorrect', async () => { - await expect(service.validateUser('incorrectpassword')).rejects.toThrow( +it('should throw an error if password is unexpected but valid format', async () => { + await expect(service.validateUser('unexpectedvalidpassword')).rejects.toThrow( UnauthorizedException, ); }); ```
    Security
    Ensure safer methods for opening external links to prevent security vulnerabilities. ___ **Directly manipulating the window's URL for opening links can lead to security
    vulnerabilities such as URL redirection attacks. Consider using a safer method to open
    external links, such as Svelte's built-in navigation functions or ensuring URL validation.** [interface/src/lib/helpers/hufi/socket.ts [39-43]](https://github.com/Hu-Fi/Mr.Market/pull/79/files#diff-69db56c5a1c3cee6870c22a54beed50d9fb897bca96979680cc4f2875eb43971R39-R43) ```diff -window.open(`mixin://send?category=app_card&data=${encodeURIComponent(btoa(JSON.stringify(data)))}`) -window.open(`mixin://pay?recipient=${BOT_ID}&asset=${p.asset_id}&amount=${p.amount}&memo=${p.memo}&trace=${p.trace_id}`) +// Ensure URL validation or use safer methods for opening external links ```
    Avoid storing sensitive information directly in the interface. ___ **For better security practices, consider not storing sensitive information like api_key and
    secret directly within the SuccessResponse interface. Instead, use environment variables
    or a secure vault service.** [server/src/common/types/exchange/exchange.ts [5-6]](https://github.com/Hu-Fi/Mr.Market/pull/79/files#diff-fb2181e873d268634613c516f1ad31287f1419ed32814bdbda79725c36d62084R5-R6) ```diff -api_key: string; -secret: string; +// Consider using environment variables or a secure vault service for sensitive information ```
    Use environment variables for sensitive configuration values. ___ **Ensure that sensitive configuration values like JWT_SECRET, MIXIN_SESSION_PRIVATE_KEY, and
    API keys are not hardcoded or committed to version control. Use environment variables to
    inject these values securely at runtime.** [server/src/config/configuration.ts [34]](https://github.com/Hu-Fi/Mr.Market/pull/79/files#diff-c2fef21ac50b82ee2bfddd0f8d6a23979cb586b4cff283642d567ac926bc1823R34-R34) ```diff -jwt_secret: process.env.JWT_SECRET, +// Ensure environment variables are used and not exposed or hardcoded ```
    Bug
    Correctly handle promises with async/await or promise chaining. ___ **Using await inside a non-async function will not work as expected. Ensure that the
    function handling the promise is marked as async or use promise chaining with .then() and
    .catch() for proper error handling and response processing.** [interface/src/lib/helpers/hufi/socket.ts [118]](https://github.com/Hu-Fi/Mr.Market/pull/79/files#diff-69db56c5a1c3cee6870c22a54beed50d9fb897bca96979680cc4f2875eb43971R118-R118) ```diff -return await fetchCandleChartData(); +// Correctly handle the promise +fetchCandleChartData().then(data => { + // Handle data +}).catch(error => { + // Handle error + CandleLoadingFailed.set(true); + console.error(error); +}); ```
    Add parameters to the load function to access URL parameters. ___ **The load function is missing its parameter. If the function intends to use URL parameters,
    it should include {params} in its definition to access them.** [interface/src/routes/(secondary)/(grow)/grow/arbitrage/[id]/+page.ts [4]](https://github.com/Hu-Fi/Mr.Market/pull/79/files#diff-28c632ace78a947611a63fdfbf33141c8bf9a9c42d91e46a97b285762f5a619cR4-R4) ```diff -export async function load() { +export async function load({params}) { ```
    Correct the typo in the import statement from TARDING_TYPE_MAP to TRADING_TYPE_MAP. ___ **There's a typo in the import statement TARDING_TYPE_MAP. It should be corrected to
    TRADING_TYPE_MAP to match the expected constant name and ensure the code functions as
    intended.** [server/src/common/helpers/mixin/memo.ts [2]](https://github.com/Hu-Fi/Mr.Market/pull/79/files#diff-996ebc0a0ef85b44a5c76b6f52e33e03b879f9bc3b8ef861205bb803d309b983R2-R2) ```diff import { - TARDING_TYPE_MAP, + TRADING_TYPE_MAP, ```
    Maintainability
    Rename the file to correct the typo in the file name. ___ **The file name mixin-message.eneity.ts seems to be a typo. Consider renaming it to
    mixin-message.entity.ts to maintain consistency and avoid confusion.** [server/src/common/entities/mixin-message.eneity.ts [1-47]](https://github.com/Hu-Fi/Mr.Market/pull/79/files#diff-284cd024599e53bbc106bb7b202a1a20aa6997f2c35d5803ede3e29b945e4b9aR1-R47) ```diff -export class MixinMessage { +// File renamed to mixin-message.entity.ts ```
    Define and export validation functions explicitly for better readability. ___ **Instead of exporting individual functions directly from an array, consider defining and
    exporting them explicitly. This improves readability and maintainability.** [server/src/common/helpers/checks/spotChecks.ts [29-31]](https://github.com/Hu-Fi/Mr.Market/pull/79/files#diff-149a7f6a722ed2b5d682d3cb8c1e228d5664c2540841e5056dc063ae9f3c754aR29-R31) ```diff -export const isTradingTypeValid = validators[0]; -export const isSpotOrderTypeValid = validators[1]; -export const isExchangeIndexValid = validators[2]; +export const isTradingTypeValid = (tradingType: string): boolean => { + const validTradingTypes: TradingType[] = Object.keys(TARDING_TYPE_MAP); + return validTradingTypes.includes(tradingType as TradingType); +}; +export const isSpotOrderTypeValid = (spotOrderType: string): boolean => { + const validSpotOrderTypes: SpotOrderType[] = Object.keys(SPOT_ORDER_TYPE_MAP); + return validSpotOrderTypes.includes(spotOrderType as SpotOrderType); +}; +export const isExchangeIndexValid = (exchangeIndex: string): boolean => { + const validExchangeIndexes: ExchangeIndex[] = Object.keys(SPOT_EXCHANGE_MAP); + return validExchangeIndexes.includes(exchangeIndex as ExchangeIndex); +}; ```
    Remove or uncomment unused code to maintain code cleanliness. ___ **Uncomment or remove the commented-out code related to configService if it's not being used
    in the tests to keep the codebase clean and maintainable.** [server/src/modules/auth/auth.service.spec.ts [36]](https://github.com/Hu-Fi/Mr.Market/pull/79/files#diff-a4aa529fbd3004f2485112cc226be5de73cf024074d5bc13c9a546b6bd307d68R36-R36) ```diff -// configService = module.get(ConfigService); + ```
    Performance
    Optimize the generateRandomSequence function by simplifying the loop logic. ___ **The generateRandomSequence function can be optimized by removing the unnecessary isLetter
    check inside the loop. Since the first character is always a letter, you can simplify the
    loop logic.** [server/src/common/helpers/utils.ts [29-30]](https://github.com/Hu-Fi/Mr.Market/pull/79/files#diff-cc4c047610df1eacdb7e7d23956b4158d0d99cbda2b182103ad2856771580d7bR29-R30) ```diff -const isLetter = i === 0 ? true : Math.random() > 0.5; -sequence += isLetter ? getRandomLetter() : getRandomDigit(); +if (i === 0) { + sequence += getRandomLetter(); +} else { + sequence += Math.random() > 0.5 ? getRandomLetter() : getRandomDigit(); +} ```

    ✨ Improve tool usage guide:
    **Overview:** The `improve` tool scans the PR code changes, and automatically generates suggestions for improving the PR code. The tool can be triggered [automatically](https://pr-agent-docs.codium.ai/usage-guide/automations_and_usage/#github-app-automatic-tools-when-a-new-pr-is-opened) every time a new PR is opened, or can be invoked manually by commenting on a PR. When commenting, to edit [configurations](https://github.com/Codium-ai/pr-agent/blob/main/pr_agent/settings/configuration.toml#L69) related to the improve tool (`pr_code_suggestions` section), use the following template: ``` /improve --pr_code_suggestions.some_config1=... --pr_code_suggestions.some_config2=... ``` With a [configuration file](https://pr-agent-docs.codium.ai/usage-guide/configuration_options/), use the following template: ``` [pr_code_suggestions] some_config1=... some_config2=... ```
    Enabling\disabling automation
    When you first install the app, the [default mode](https://pr-agent-docs.codium.ai/usage-guide/automations_and_usage/#github-app-automatic-tools-when-a-new-pr-is-opened) for the improve tool is: ``` pr_commands = ["/improve --pr_code_suggestions.summarize=true", ...] ``` meaning the `improve` tool will run automatically on every PR, with summarization enabled. Delete this line to disable the tool from running automatically.
    Utilizing extra instructions
    Extra instructions are very important for the `improve` tool, since they enable to guide the model to suggestions that are more relevant to the specific needs of the project. Be specific, clear, and concise in the instructions. With extra instructions, you are the prompter. Specify relevant aspects that you want the model to focus on. Examples for extra instructions: ``` [pr_code_suggestions] # /improve # extra_instructions=""" Emphasize the following aspects: - Does the code logic cover relevant edge cases? - Is the code logic clear and easy to understand? - Is the code logic efficient? ... """ ``` Use triple quotes to write multi-line instructions. Use bullet points to make the instructions more readable.
    A note on code suggestions quality
    - While the current AI for code is getting better and better (GPT-4), it's not flawless. Not all the suggestions will be perfect, and a user should not accept all of them automatically. - Suggestions are not meant to be simplistic. Instead, they aim to give deep feedback and raise questions, ideas and thoughts to the user, who can then use his judgment, experience, and understanding of the code base. - Recommended to use the 'extra_instructions' field to guide the model to suggestions that are more relevant to the specific needs of the project, or use the [custom suggestions :gem:](https://pr-agent-docs.codium.ai/tools/custom_suggestions/) tool - With large PRs, best quality will be obtained by using 'improve --extended' mode.
    More PR-Agent commands
    > To invoke the PR-Agent, add a comment using one of the following commands: > - **/review**: Request a review of your Pull Request. > - **/describe**: Update the PR title and description based on the contents of the PR. > - **/improve [--extended]**: Suggest code improvements. Extended mode provides a higher quality feedback. > - **/ask \**: Ask a question about the PR. > - **/update_changelog**: Update the changelog based on the PR's contents. > - **/add_docs** 💎: Generate docstring for new components introduced in the PR. > - **/generate_labels** 💎: Generate labels for the PR based on the PR's contents. > - **/analyze** 💎: Automatically analyzes the PR, and presents changes walkthrough for each component. >See the [tools guide](https://pr-agent-docs.codium.ai/tools/) for more details. >To list the possible configuration parameters, add a **/config** comment.
    See the [improve usage](https://pr-agent-docs.codium.ai/tools/improve/) page for a more comprehensive guide on using this tool.