Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Initial call handler #87

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open

Initial call handler #87

wants to merge 9 commits into from

Conversation

TomaszGol
Copy link
Contributor

@TomaszGol TomaszGol commented Oct 18, 2024

Summary by CodeRabbit

  • New Features

    • Introduced new smart contract functions for market operations, including creating, canceling, and closing orders, as well as managing deposits and withdrawals.
    • Added a new type system for handling order sides (Long and Short) in trading contexts.
    • Enhanced the structure for processing Ethereum transaction calls.
  • Bug Fixes

    • Updated Node.js version requirement for compatibility.
  • Documentation

    • Enhanced documentation regarding market-related functionalities and smart contract interactions.
  • Chores

    • Updated dependencies and development tools for improved performance and stability.

Copy link

coderabbitai bot commented Oct 18, 2024

Walkthrough

The pull request introduces significant updates across multiple files, primarily focusing on enhancing smart contract functionalities related to market operations. Key changes include the addition of various smart contract functions in abi.json, the introduction of type definitions in abi.ts, and updates to the package.json for dependency management. New files such as calls.ts and v6.ts establish structured types for market operations and order sides, respectively. Additionally, the getCall.ts file introduces functionality for processing Ethereum transaction calls, and the typegen.json file is updated to reflect new configurations for the Market pallet.

Changes

File Change Summary
package.json - Updated engines to require Node.js version >=20.
- Added dependency @subsquid/evm-typegen with version ^4.3.0.
- Updated typescript from ^4.9.5 to ^5.6.3.
src/abi/abi.json - Added functions: cancel_order, close_position, create_market, two overloads of create_order, delete_market, deposit, mark_to_market, oracle_price, withdraw, and withdraw_all.
src/abi/abi.ts - Introduced smart contract function definitions and types for the added functions, including a Contract class extending ContractBase and various type aliases for parameters and return types.
src/types/calls.ts - Added export statement to group exports from ./market/calls under the namespace market.
src/types/index.ts - Added exports for v6 and calls modules.
src/types/market/calls.ts - Introduced exports for market-related actions, defining structured call types for operations like createOrder, cancelOrder, closePosition, and others.
src/types/v6.ts - Defined a closed enumeration OrderSide with values Long and Short, and established a union type for type-safe handling of order sides.
src/utils/getCall.ts - Added functions decodeEvmCall and processCall for processing Ethereum transaction calls and decoding input data.
typegen.json - Added entry for Market pallet indicating it now includes calls: true.
src/eventprocessor/balances/reserveRepatriatedEventProcessor.ts - Updated process method to utilize processCall for handling Ethereum transaction calls, modifying how marketId is derived.
src/eventprocessor/market/marketCreatedEventProcessor.ts - Updated process method signature to include a new call parameter of type Call, allowing for enhanced event processing capabilities.

Possibly related PRs

  • Change id in aggregated order #60: Changes in src/eventprocessor/balances/reserveRepatriatedEventProcessor.ts involve processing Ethereum transaction calls, which may relate to the new smart contract functions introduced in the main PR.
  • 2TF Data #77: The modifications in src/eventprocessor/market/latestOraclePriceProcessor.ts and the GraphQL schema changes could be relevant due to the introduction of new market data types and the handling of market prices, which aligns with the updates in the main PR.
  • Market closed #78: The addition of the MarketClosedEventProcessor in src/eventprocessor/market/marketClosedEventProcessor.ts includes handling for market closure events, which could be relevant to the new market-related functions defined in the main PR.

"In the fields where markets grow,
New functions sprout, a vibrant show.
With orders to create and close,
Our smart contracts now compose.
From types to calls, all in a dance,
A rabbit's joy in each advance!" 🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 8398436 and ff2298b.

📒 Files selected for processing (1)
  • src/utils/getCall.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/utils/getCall.ts

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 8

🧹 Outside diff range and nitpick comments (9)
src/types/v6.ts (3)

1-1: Consider removing unused imports

The import statement includes several items that are not used in this file (Result, Option, Bytes, BitSequence). To improve code cleanliness and potentially reduce bundle size, consider removing these unused imports.

You can update the import statement as follows:

import {sts} from './support'

3-8: LGTM! Consider minor formatting improvement

The OrderSide constant is well-defined using sts.closedEnum. It correctly represents the two possible order sides (Long and Short) as simple flags.

For improved readability, consider removing the extra space after the arrow function:

export const OrderSide: sts.Type<OrderSide> = sts.closedEnum(() => ({
    Long: sts.unit(),
    Short: sts.unit(),
}))

12-18: LGTM! Consider minor consistency improvement

The OrderSide_Long and OrderSide_Short interfaces are well-defined and provide clear type information for the two possible order sides. The use of the __kind property with literal types is a good practice for discriminated unions in TypeScript.

For consistency with the rest of the file, consider adding a blank line between the two interface definitions:

export interface OrderSide_Long {
    __kind: 'Long'
}

export interface OrderSide_Short {
    __kind: 'Short'
}
src/abi/abi.json (1)

1-250: Overall, the ABI is well-structured with a comprehensive set of market operations.

The ABI defines a robust set of functions for managing markets, orders, and positions. The consistent use of parameter types (uint64 for market and position IDs, uint256 for prices and amounts, etc.) across functions is commendable.

General considerations for implementation:

  1. Ensure proper access control for critical functions (e.g., create_market, delete_market, oracle_price).
  2. Implement thorough input validation and error handling.
  3. Consider the gas implications of using string parameters (in create_market) and large integer types.
  4. Verify that the contract handles edge cases, such as market deletions with open positions or orders.
  5. Consider adding events for important state changes to facilitate off-chain tracking and UI updates.
src/utils/getCall.ts (1)

35-35: Provide more detailed error message when decoding fails

Include additional information in the error message to aid in debugging when decoding the EVM call fails.

Apply this diff to improve the error message:

-      console.error("Failed to decode the EVM call.");
+      console.error(`Failed to decode the EVM call for function ${functionName}.`);
src/abi/abi.ts (1)

102-115: Clarify type aliases for 'create_order' function overloads

The type aliases Create_orderParams_0 and Create_orderParams_1 use numeric suffixes, which may not clearly indicate the differences between the overloads.

For better readability and maintenance, consider renaming the type aliases to more descriptive names that reflect their specific use cases. For example:

  • CreateOrderParamsWithMargin and CreateOrderParamsWithoutMargin
  • CreateOrderParamsFull and CreateOrderParamsSimplified

This approach helps developers quickly understand the context and purpose of each type alias.

src/types/market/calls.ts (3)

129-129: Typo in comment: "positon" should be "position"

There's a typographical error in the comment on line 129. The word "positon" should be corrected to "position".

Apply this diff to fix the typo:

-    * Mark to market positon with oracle price
+    * Mark to market position with oracle price

143-143: Grammatical error in comment: "an user" should be "a user"

There's a grammatical error in the comment on line 143. "An user" should be corrected to "a user". Additionally, consider rephrasing for clarity.

Apply this diff to fix the grammatical error:

-    * Liquidate position of an user that has not sufficient margin
+    * Liquidate the position of a user who does not have sufficient margin

172-172: Typo in comment: "reduntant" should be "redundant"

There's a typographical error in the comment on line 172. The word "reduntant" should be corrected to "redundant".

Apply this diff to fix the typo:

-    * Withdraw reduntant funds from given market
+    * Withdraw redundant funds from the given market
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 8b99db9 and e5c054d.

⛔ Files ignored due to path filters (2)
  • package-lock.json is excluded by !**/package-lock.json
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (9)
  • package.json (3 hunks)
  • src/abi/abi.json (1 hunks)
  • src/abi/abi.ts (1 hunks)
  • src/types/calls.ts (1 hunks)
  • src/types/index.ts (1 hunks)
  • src/types/market/calls.ts (1 hunks)
  • src/types/v6.ts (1 hunks)
  • src/utils/getCall.ts (1 hunks)
  • typegen.json (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • src/types/calls.ts
🧰 Additional context used
🔇 Additional comments (20)
src/types/index.ts (1)

2-2: Verify the existence and contents of the v6 module.

The addition of the v6 module export is a good practice for versioning and organizing type definitions. However, please ensure that:

  1. The v6.ts file exists in the same directory.
  2. The exports from v6.ts are intended to be exposed through this index file.
  3. There's appropriate documentation for the new v6 types, especially if they introduce breaking changes compared to previous versions.

To verify the existence and contents of the v6 module, please run the following script:

src/types/v6.ts (1)

10-10: LGTM! Type definition is correct

The OrderSide type is correctly defined as a union of OrderSide_Long and OrderSide_Short. This aligns with the constant defined earlier and provides a TypeScript-friendly way to use the OrderSide type in the rest of the codebase.

typegen.json (1)

31-33: LGTM! Verify type generation output.

The addition of the Market pallet with "calls": true is correct and aligns with the PR objective of implementing an initial call handler. This change will enable the generation of call types for the Market pallet.

To ensure the change has the intended effect, please verify the type generation output after this change. Run the following script to check for newly generated Market call types:

If no results are found, it may indicate that the type generation process needs to be re-run or that additional configuration might be required.

package.json (3)

5-5: Approved: Broadened Node.js version compatibility

Updating the minimum Node.js version to 20 is a good decision. It allows the project to run on the current LTS version and improves compatibility while still leveraging modern features.


Line range hint 1-39: Summary of package.json changes

The changes to package.json are well-considered and beneficial:

  1. Broadened Node.js compatibility improves deployment flexibility.
  2. Addition of @subsquid/evm-typegen expands the project's blockchain capabilities.
  3. Upgrade to TypeScript 5 brings new features and improvements.

These updates enhance the project's capabilities and keep it up-to-date with current best practices. Please ensure to run the suggested verification scripts to confirm proper integration of these changes.


37-37: Approved: Updated TypeScript to version 5.6.3

Updating to TypeScript 5.6.3 is a significant improvement that brings new features and enhancements. However, as this is a major version update, it's crucial to ensure compatibility with the existing codebase.

To verify compatibility and identify any necessary adjustments, please run the following script:

After running these checks, review any errors or warnings and make necessary adjustments to ensure full compatibility with TypeScript 5.

src/abi/abi.json (11)

1-19: LGTM: cancel_order function definition is appropriate.

The cancel_order function is well-defined with appropriate parameter types (uint64) for market and order_id. The nonpayable state mutability is correct for a function that modifies the contract state without accepting Ether.


20-47: LGTM: close_position function definition is well-structured.

The close_position function is correctly defined with appropriate parameter types. The use of uint64 for market and position_id, uint256 for price, and uint32 for quantity provides a good balance between range and gas efficiency.


48-90: LGTM: create_market function is well-defined, with a minor consideration.

The create_market function is correctly structured with appropriate parameter types for creating a new market. The use of string for market name and various uint types for other parameters is suitable.

Note: The use of uint8 for initial_margin, maintenance_margin, and contract_unit_decimals is sufficient for most cases but might be limiting if you need to represent values greater than 255. Consider if uint16 would be more appropriate for future-proofing.


91-123: LGTM: First create_order function is well-defined, with a note on enum representation.

The function parameters are appropriately typed for creating a new order. The use of uint64 for market, uint256 for price, uint32 for quantity, and uint8 for margin provides a good balance between range and gas efficiency.

Note: The order_side parameter is defined as an enum Market.OrderSide but represented as uint8 in the ABI. This is correct as Solidity enums are represented as uint8 in the ABI, but ensure that the enum values in the contract match the expected uint8 values (0, 1, etc.) to avoid any confusion.


124-151: LGTM: Second create_order function provides a useful overload.

This version of create_order is well-defined and consistent with the first version. The omission of the margin parameter provides a useful overload, likely using a default margin value in the contract implementation.

Ensure that the contract logic handles the absence of the margin parameter appropriately, possibly by using a default value.


152-164: LGTM: delete_market function is correctly defined, but consider its implications.

The delete_market function is properly defined with a uint64 parameter for the market ID, consistent with other functions.

Note: Deleting a market is a significant operation. Ensure that the contract implementation includes appropriate checks and balances, such as:

  1. Verifying that the caller has the necessary permissions to delete a market.
  2. Handling any existing orders or positions in the market before deletion.
  3. Considering whether a "soft delete" (marking as inactive) might be more appropriate than a hard delete in some cases.

183-200: LGTM: mark_to_market function is well-defined.

The mark_to_market function is correctly structured with appropriate parameter types. The use of uint64 for both market and position_id is consistent with other functions and suitable for the purpose.

Ensure that the contract implementation handles the mark-to-market process correctly, including updating position values and handling any resulting actions (e.g., liquidations if the position falls below maintenance margin).


201-218: LGTM: oracle_price function is correctly defined, but consider access control.

The oracle_price function is well-structured with appropriate parameter types. The use of uint64 for market and uint256 for price provides sufficient range for most use cases.

Note: Updating oracle prices is a critical operation that can significantly impact the system. Ensure that the contract implementation includes robust access control mechanisms to restrict this function to authorized oracle(s) only.


219-236: LGTM: withdraw function is correctly defined.

The withdraw function is well-structured with appropriate parameter types. The use of uint64 for market and uint256 for amount provides sufficient range for most use cases.

Ensure that the contract implementation includes necessary checks, such as:

  1. Verifying that the user has sufficient balance to withdraw.
  2. Handling any open positions or orders that might be affected by the withdrawal.
  3. Implementing appropriate access control to ensure only authorized users can withdraw funds.

237-249: LGTM: withdraw_all function is correctly defined, but consider its implications.

The withdraw_all function is properly defined with a uint64 parameter for the market ID, consistent with other functions.

Note: Withdrawing all funds from a market is a significant operation. Ensure that the contract implementation includes appropriate checks and balances, such as:

  1. Verifying that the user has no open positions or orders in the market before allowing a full withdrawal.
  2. Implementing appropriate access control to ensure only authorized users can withdraw all funds.
  3. Considering whether partial withdrawals might be more appropriate in some cases to maintain market liquidity.

165-182: ⚠️ Potential issue

Consider changing deposit function to payable.

The deposit function is well-defined with appropriate parameter types. However, it's currently marked as nonpayable, which is unusual for a deposit function in Ethereum smart contracts.

Suggestion: Consider changing the state mutability to payable if the function is intended to receive Ether. If it's designed to handle token deposits, ensure that the contract has appropriate methods to handle the token transfer.

src/abi/abi.ts (1)

1-144: Well-structured and type-safe ABI definitions

The ABI definitions and associated type aliases are comprehensively set up, providing a clear and type-safe interface for interacting with the smart contract functions.

src/types/market/calls.ts (2)

178-178: Verify if amount in withdraw should be optional

The amount parameter in the withdraw function is defined as optional (sts.option(() => sts.bigint())), whereas in the deposit function, amount is required (sts.bigint()). Please confirm if it is intentional for amount to be optional in withdraw. If not, consider making it consistent with deposit.


205-205: ⚠️ Potential issue

Undefined v7 used in closeMarket export

The v7 variable is used in the closeMarket export but is neither imported nor defined. This will cause a ReferenceError at runtime. Please ensure that v7 is correctly imported or that the appropriate version variable is used.

Apply this diff to fix the issue:

+import * as v7 from '../v7'

...
-    v7: new CallType(
+    v7: new CallType(

Alternatively, if v7 is a typo and should refer to an existing version like v2 or v6, update it accordingly.

Likely invalid or redundant comment.

src/types/index.ts Show resolved Hide resolved
src/types/v6.ts Show resolved Hide resolved
package.json Show resolved Hide resolved
src/utils/getCall.ts Outdated Show resolved Hide resolved
src/utils/getCall.ts Outdated Show resolved Hide resolved
src/utils/getCall.ts Outdated Show resolved Hide resolved
src/utils/getCall.ts Show resolved Hide resolved
src/abi/abi.ts Show resolved Hide resolved
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (1)
src/eventprocessor/balances/reserveRepatriatedEventProcessor.ts (1)

35-52: Consider implementing structured logging and error monitoring.

The new Ethereum transaction handling introduces additional complexity. To improve maintainability and debugging:

  1. Consider using a structured logging library (e.g., Winston, Pino) instead of console.log/error
  2. Add transaction tracing with correlation IDs
  3. Implement metrics collection for success/failure rates

Example structured logging implementation:

interface LogContext {
  eventId: string;
  callName?: string;
  marketId?: string;
  error?: Error;
}

function logError(message: string, context: LogContext) {
  // Integration with your logging infrastructure
  console.error({
    message,
    timestamp: new Date().toISOString(),
    ...context,
  });
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between e5c054d and a81412e.

📒 Files selected for processing (4)
  • package.json (2 hunks)
  • src/eventprocessor/balances/reserveRepatriatedEventProcessor.ts (2 hunks)
  • src/eventprocessor/market/marketCreatedEventProcessor.ts (2 hunks)
  • src/utils/getCall.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • package.json
  • src/utils/getCall.ts
🔇 Additional comments (5)
src/eventprocessor/market/marketCreatedEventProcessor.ts (2)

Line range hint 27-49: Consider handling call data for market creation.

The method processes market creation events but doesn't utilize the newly added call parameter. If the call contains relevant data for market creation (e.g., transaction details, caller information), it should be processed and stored.

Let's check how other processors handle the call parameter:

#!/bin/bash
# Description: Check how other processors utilize the call parameter

# Search for patterns of call parameter usage
rg -A 10 "async process.*call: Call.*?\{" 

22-25: Verify the usage of the new call parameter.

The process method has been updated to accept a call parameter, but it's not being utilized in the method implementation. This could indicate:

  1. Missing implementation of call processing logic
  2. Potential inconsistency with the event processor interface

Let's verify the interface implementation and usage across other event processors:

✅ Verification successful

Let me gather more information about the actual implementation of the MarketCreatedEventProcessor to see if it uses the call parameter.


Let me try one more verification to check the interface and other implementations with a corrected path:


The call parameter is correctly implemented according to the interface

The call parameter is optional in the EventProcessor interface (call?: Call<any>), and while it's not actively used in the MarketCreatedEventProcessor, this is acceptable. Some processors like ReserveRepatriatedEventProcessor do utilize the call parameter for specific logic, showing that its presence in the interface and implementations is intentional and properly handled where needed.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check EventProcessor interface definition and its implementations
# to verify if the `call` parameter is consistently handled

# Check the EventProcessor interface definition
echo "Checking EventProcessor interface definition:"
ast-grep --pattern 'interface EventProcessor {
  $$$
  process($$$): $$$
  $$$
}'

# Check other implementations of process method
echo "Checking other event processor implementations:"
rg -A 5 "implements EventProcessor.*?\{" 

Length of output: 9901


Script:

#!/bin/bash
# Check the implementation of MarketCreatedEventProcessor's process method
rg -A 20 "async process\(" "src/eventprocessor/market/marketCreatedEventProcessor.ts"

# Check if any other processors are using the call parameter
rg -A 5 "call\?" "src/eventprocessor/**/*.ts"

Length of output: 974


Script:

#!/bin/bash
# Check if any other processors are using the call parameter
rg -A 5 "call\?" src/eventprocessor/

# Check for actual usage of call parameter in process methods
rg -B 2 -A 10 "call: Call" src/eventprocessor/

Length of output: 3935

src/eventprocessor/balances/reserveRepatriatedEventProcessor.ts (3)

20-20: LGTM: Import statement is correctly added.

The new import is necessary for the Ethereum transaction processing functionality.


52-52: ⚠️ Potential issue

Verify market ID extraction and add validation.

The market ID extraction has changed from event arguments to call arguments, which could be a breaking change.

Let's verify the market ID format and usage:

#!/bin/bash
# Search for market ID usage patterns
rg "args\.market" 

# Search for Market type definitions
ast-grep --pattern 'interface Market {
  $$$
}'

Consider adding validation:

-      const marketId = processedCall.args.market;
+      const marketId = processedCall.args.market;
+      if (!marketId || typeof marketId !== 'string') {
+        console.error(`Invalid market ID in processed call: ${JSON.stringify(processedCall.args)}`);
+        return;
+      }

35-48: ⚠️ Potential issue

Add error handling and validation for Ethereum transaction processing.

The current implementation has several potential issues:

  1. Missing error handling for processCall
  2. No validation for event names
  3. Implicit type handling with undefined values

Consider applying these improvements:

-    let ethCall;
+    let ethCall: ReturnType<typeof processCall> | undefined;

     if (call.name === "Ethereum.transact") {
       let callName: string | undefined;
       if (event.name === "Market.PositionMarkedToMarket") {
         callName = "mark_to_market";
       } else if (event.name === "Market.PositionClosed") {
         callName = "close_position";
       }
-      ethCall = processCall(call, callName);
+      try {
+        if (!callName) {
+          console.warn(`Unsupported event type: ${event.name}`);
+          return;
+        }
+        ethCall = processCall(call, callName);
+      } catch (error) {
+        console.error(`Failed to process Ethereum call: ${error}`);
+        throw error;
+      }
     }

-    const processedCall = ethCall ? ethCall : call;
+    const processedCall = ethCall ?? call;

Let's verify the event names are consistent with the contract:

src/eventprocessor/market/marketCreatedEventProcessor.ts Outdated Show resolved Hide resolved
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between a81412e and 8398436.

📒 Files selected for processing (3)
  • src/eventprocessor/balances/reserveRepatriatedEventProcessor.ts (2 hunks)
  • src/eventprocessor/market/marketCreatedEventProcessor.ts (2 hunks)
  • src/utils/getCall.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/eventprocessor/balances/reserveRepatriatedEventProcessor.ts
  • src/eventprocessor/market/marketCreatedEventProcessor.ts
🔇 Additional comments (2)
src/utils/getCall.ts (2)

1-1: LGTM: Clean imports section

The import is properly used throughout the code.


6-8: Verify ABI function selectors

Let's ensure all function selectors in the ABI are properly formatted.

✅ Verification successful

Let me gather more information about the actual selectors in the ABI file to better understand their format.


Let me try a different approach to locate and examine the ABI definitions.


Let's examine the content of the ABI files to understand the actual structure.


ABI function selectors are properly formatted

All function selectors in src/abi/abi.ts follow the correct format of "0x" followed by 8 hexadecimal characters (e.g., "0x9c5f444f", "0xf051c5da", etc.). The selectors are properly defined and match the function signatures in the ABI JSON. The code in getCall.ts that uses these selectors is correctly implemented.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that all function selectors in the ABI are 10 characters long (0x + 8 chars)

# Test: Search for selector definitions in abi.ts
rg -A 1 'selector:' src/abi/abi.ts | grep -E '"0x[a-fA-F0-9]{8}"' || echo "Invalid selectors found"

Length of output: 122


Script:

#!/bin/bash
# Let's see the actual content of selector definitions
rg -A 1 'selector:' src/abi/abi.ts

Length of output: 34


Script:

#!/bin/bash
# First, let's find all potential ABI-related files
fd abi

# Then let's look for any files that might contain function selectors
rg -l "selector"

Length of output: 87


Script:

#!/bin/bash
# Check the content of abi.json
cat src/abi/abi.json

# Check the content of abi.ts
cat src/abi/abi.ts

Length of output: 9083

src/utils/getCall.ts Outdated Show resolved Hide resolved
src/utils/getCall.ts Outdated Show resolved Hide resolved
@Klapeyron Klapeyron linked an issue Nov 5, 2024 that may be closed by this pull request
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Context call information
2 participants