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

[IND-498]: Add TradingRewardsHandler #902

Merged
merged 4 commits into from
Dec 22, 2023
Merged

Conversation

Christopher-Li
Copy link
Contributor

Changelist

Add support for Trading Rewards Handler

Test Plan

Unit tests

Author/Reviewer Checklist

  • If this PR has changes that result in a different app state given the same prior state and transaction list, manually add the state-breaking label.
  • If the PR has breaking postgres changes to the indexer add the indexer-postgres-breaking label.
  • If this PR isn't state-breaking but has changes that modify behavior in PrepareProposal or ProcessProposal, manually add the label proposal-breaking.
  • If this PR is one of many that implement a specific feature, manually label them all feature:[feature-name].
  • If you wish to for mergify-bot to automatically create a PR to backport your change to a release branch, manually add the label backport/[branch-name].
  • Manually add any of the following labels: refactor, chore, bug.

Copy link

linear bot commented Dec 21, 2023

Copy link
Contributor

coderabbitai bot commented Dec 21, 2023

Walkthrough

The recent updates involve the implementation of a trading rewards feature within a blockchain indexer system. The changes include database schema updates to handle new precision and scale for trading reward amounts, the addition of new constants and types to handle trading rewards data, and the creation of new SQL scripts and functions for processing trading rewards events. Moreover, a new TradingRewardsHandler class has been implemented to manage these events, and corresponding tests have been added to ensure correct functionality.

Changes

File(s) Change Summary
.../postgres/__tests__/helpers/constants.ts,
.../postgres/src/constants.ts
Added constants for wallet and trading rewards events.
.../postgres/src/db/migrations/.../update_trading_rewards_amount_scale.ts,
.../postgres/src/db/migrations/.../update_wallet_total_trading_rewards_scale.ts,
.../postgres/src/db/migrations/.../update_trading_reward_aggregations_amount_scale.ts
Updated precision and scale for trading reward amounts in database tables.
.../postgres/src/index.ts Exported new TradingRewardModel and TradingRewardAggregationModel.
.../postgres/src/stores/trading-reward-table.ts Modified findById function to accept id instead of address.
.../postgres/src/types/websocket-message-types.ts Added TradingRewardSubaccountMessageContents interface.
.../ender/__tests__/handlers/trading-rewards-handler.test.ts,
.../ender/src/handlers/trading-rewards-handler.ts
Added functionality and tests for trading rewards event handling.
.../ender/src/helpers/postgres/...,
.../ender/src/lib/block-processor.ts
Added SQL script references and updated event validation for trading rewards processing.
.../ender/src/lib/helper.ts,
.../ender/src/lib/types.ts
Updated types related to trading rewards events.
.../ender/src/scripts/handlers/.../dydx_block_processor_unordered_handlers.sql,
.../ender/src/scripts/handlers/dydx_trading_rewards_handler.sql,
.../ender/src/scripts/helpers/dydx_process_trading_reward_event.sql,
.../ender/src/scripts/helpers/dydx_uuid_from_trading_rewards_parts.sql
Introduced SQL functions and scripts for processing trading rewards and generating UUIDs.
.../ender/src/validators/trading-rewards-validator.ts Created TradingRewardsValidator class.

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 X ?


Tips

Chat with CodeRabbit Bot (@coderabbitai)

  • You can reply to a review comment made by CodeRabbit.
  • You can tag CodeRabbit on specific lines of code or files in the PR by tagging @coderabbitai in a comment.
  • You can tag @coderabbitai in a PR comment and ask one-off questions about the PR and the codebase. Use quoted replies to pass the context for follow-up questions.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • The JSON schema for the configuration file is available here.
  • 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/coderabbit-overrides.v2.json

@Christopher-Li Christopher-Li marked this pull request as ready for review December 21, 2023 22:03
Copy link
Contributor

@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.

Review Status

Actionable comments generated: 1

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between ece92b4 and 9a66a81.
Files selected for processing (19)
  • indexer/packages/postgres/tests/helpers/constants.ts (1 hunks)
  • indexer/packages/postgres/src/constants.ts (2 hunks)
  • indexer/packages/postgres/src/db/migrations/migration_files/20231221153944_update_trading_rewards_amount_scale.ts (1 hunks)
  • indexer/packages/postgres/src/db/migrations/migration_files/20231221165820_update_wallet_total_trading_rewards_scale.ts (1 hunks)
  • indexer/packages/postgres/src/index.ts (1 hunks)
  • indexer/packages/postgres/src/stores/trading-reward-table.ts (1 hunks)
  • indexer/packages/postgres/src/types/websocket-message-types.ts (2 hunks)
  • indexer/services/ender/tests/handlers/trading-rewards-handler.test.ts (1 hunks)
  • indexer/services/ender/tests/helpers/constants.ts (2 hunks)
  • indexer/services/ender/src/handlers/trading-rewards-handler.ts (1 hunks)
  • indexer/services/ender/src/helpers/postgres/postgres-functions.ts (3 hunks)
  • indexer/services/ender/src/lib/block-processor.ts (3 hunks)
  • indexer/services/ender/src/lib/helper.ts (2 hunks)
  • indexer/services/ender/src/lib/types.ts (3 hunks)
  • indexer/services/ender/src/scripts/handlers/dydx_block_processor_unordered_handlers.sql (1 hunks)
  • indexer/services/ender/src/scripts/handlers/dydx_trading_rewards_handler.sql (1 hunks)
  • indexer/services/ender/src/scripts/helpers/dydx_process_trading_reward_event.sql (1 hunks)
  • indexer/services/ender/src/scripts/helpers/dydx_uuid_from_trading_rewards_parts.sql (1 hunks)
  • indexer/services/ender/src/validators/trading-rewards-validator.ts (1 hunks)
Files skipped from review due to trivial changes (1)
  • indexer/packages/postgres/src/index.ts
Additional comments: 26
indexer/services/ender/src/scripts/helpers/dydx_uuid_from_trading_rewards_parts.sql (1)
  • 1-10: The function dydx_uuid_from_trading_rewards_parts correctly concatenates the address and block height to generate a UUID. However, it's important to ensure that the dydx_uuid function it calls is designed to handle this specific concatenation format and that it generates a UUID that is unique across different addresses and block heights.
indexer/packages/postgres/src/db/migrations/migration_files/20231221153944_update_trading_rewards_amount_scale.ts (1)
  • 7-7: The migration alters the 'amount' column to have a precision and scale of 18, which means it can store values up to 18 digits long, all of which can be decimal. This is unusual as typically the scale (number of digits to the right of the decimal point) is less than the precision (total number of significant digits). Please verify that this is the intended behavior, as it would mean the 'amount' can only store values less than 1.
indexer/packages/postgres/src/db/migrations/migration_files/20231221165820_update_wallet_total_trading_rewards_scale.ts (1)
  • 7-7: Similar to the previous migration file, this migration also sets both precision and scale to 18 for the 'totalTradingRewards' column. This would allow only for values less than 1 to be stored, which might not be the intended behavior. Please confirm that this precision and scale setting is correct.
indexer/services/ender/src/validators/trading-rewards-validator.ts (1)
  • 20-26: The validation logic checks if denoms is zero, which is good for avoiding processing rewards with no value. However, it's important to ensure that bytesToBigInt correctly interprets the byte array from reward.denomAmount. If the byte array is not in the expected format, this could lead to incorrect validation.
indexer/services/ender/src/handlers/trading-rewards-handler.ts (2)
  • 23-33: The internalHandle function maps the resultRow.trading_rewards to TradingRewardFromDatabase objects using TradingRewardModel.fromJson. It's important to ensure that fromJson is robust and can handle any discrepancies in the trading_rewards data format to prevent runtime errors.

  • 45-65: The generateKafkaEvents function creates a Kafka event for each trading reward. It's good to see that the event includes the createdAtHeight and createdAt fields, which are important for event ordering and traceability. Ensure that the generateConsolidatedSubaccountKafkaEvent function properly handles the serialization of subaccountMessageContents.

indexer/services/ender/src/scripts/helpers/dydx_process_trading_reward_event.sql (1)
  • 22-44: The function dydx_process_trading_reward_event performs several operations, including updating wallets and inserting into the trading_rewards table. It's important to ensure that the dydx_trim_scale and dydx_from_serializable_int functions are well-tested and handle edge cases, as they are critical to calculating the correct amount_in_human_readable.
indexer/packages/postgres/src/stores/trading-reward-table.ts (1)
  • 98-107: The findById function has been updated to use an id instead of an address. This change aligns with the new UUID generation strategy and should be reflected in all places where findById is used. Ensure that all references to this function have been updated accordingly.
indexer/services/ender/src/scripts/handlers/dydx_trading_rewards_handler.sql (1)
  • 1-67: The dydx_trading_rewards_handler function processes trading reward events and returns a JSON object with the processed rewards. It's important to ensure that the dydx_process_trading_reward_event function is called with the correct parameters and that the array indexing is handled correctly, considering PostgreSQL arrays are 1-indexed.
indexer/services/ender/src/helpers/postgres/postgres-functions.ts (3)
  • 42-45: The addition of dydx_trading_rewards_handler.sql to the HANDLER_SCRIPTS array is correct. Ensure that the script is placed in the correct directory and that the path resolution in newScript function correctly locates the script file.

  • 71-74: Similarly, the addition of dydx_process_trading_reward_event.sql to the HELPER_SCRIPTS array is correct. Verify that the script is properly managed in the source directory and that it's accessible during runtime.

  • 86-89: The inclusion of dydx_uuid_from_trading_rewards_parts.sql in the HELPER_SCRIPTS array is appropriate. Confirm that the function is correctly implemented and available for use by other scripts or functions that require UUID generation for trading rewards.

indexer/services/ender/src/scripts/handlers/dydx_block_processor_unordered_handlers.sql (1)
  • 63-64: The addition of the dydx_trading_rewards_handler call in the CASE statement is correct. Ensure that the dydx_trading_rewards_handler function is thoroughly tested to handle all possible event data structures it may receive.
indexer/packages/postgres/src/constants.ts (1)
  • 103-103: The inclusion of TradingRewardModel in the SQL_TO_JSON_DEFINED_MODELS array is correct. This ensures that the model is recognized for SQL to JSON conversion processes. Confirm that the TradingRewardModel has the necessary SQL to JSON conversion logic implemented.
indexer/services/ender/src/lib/types.ts (2)
  • 53-53: The addition of TRADING_REWARD to the DydxIndexerSubtypes enum is correct. This will allow the system to recognize and handle trading reward events appropriately.

  • 139-143: The extension of the EventProtoWithTypeAndVersion union type to include TradingRewardsEventV1 is correct. This ensures that the event handling system can process trading reward events with the new structure.

indexer/packages/postgres/src/types/websocket-message-types.ts (2)
  • 39-39: The addition of the tradingReward field to the SubaccountMessageContents interface is correct. This will allow the system to include trading reward information in the subaccount messages sent over websockets.

  • 167-171: The new interface TradingRewardSubaccountMessageContents is well-defined with appropriate fields for the trading reward, creation height, and creation time. Ensure that all systems consuming this message type are updated to handle the new structure.

indexer/services/ender/__tests__/handlers/trading-rewards-handler.test.ts (1)
  • 1-238: The unit tests for the TradingRewardsHandler are well-structured and cover the creation and update of trading rewards and wallets. The use of Big for precision, toISO for date formatting, and bigIntToBytes for handling binary data is appropriate. The asynchronous calls are correctly awaited, and the assertions using toEqual are suitable for the test cases.
indexer/services/ender/src/lib/helper.ts (2)
  • 26-26: The import of TradingRewardsEventV1 is correctly added to support the new trading rewards functionality.

  • 211-219: The addition of the DydxIndexerSubtypes.TRADING_REWARD case in the indexerTendermintEventToEventProtoWithType function is correctly implemented to handle the new event type.

indexer/services/ender/src/lib/block-processor.ts (2)
  • 25-25: The import of TradingRewardsValidator is correctly added to validate the new trading rewards events.

  • 50-50: The update to TXN_EVENT_SUBTYPE_VERSION_TO_VALIDATOR_MAPPING to include TradingRewardsValidator for DydxIndexerSubtypes.TRADING_REWARD is correctly implemented.

indexer/services/ender/__tests__/helpers/constants.ts (2)
  • 31-31: The import of TradingRewardsEventV1 is correctly added to support the new trading rewards functionality in tests.

  • 392-399: The defaultTradingRewardsEvent constant is correctly defined to provide a default value for the TradingRewardsEventV1 type in tests.

indexer/packages/postgres/__tests__/helpers/constants.ts (1)
  • 106-109: The addition of defaultWallet2 with a totalTradingRewards value of '1' is consistent with the existing pattern of using strings for numeric fields in financial applications. Ensure that the new constant is integrated properly wherever it's needed in the codebase.

Comment on lines +28 to +33
if (reward.owner === undefined) {
return this.logAndThrowParseMessageError(
`TradingReward in TradingRewardEvent at index ${index} is missing an owner.`,
{ event: this.event, address: reward.owner },
);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

The check for reward.owner being undefined is crucial for data integrity. However, the error message uses reward.owner in the logging, which will not be informative if it is indeed undefined. Consider logging additional context, such as the index or other identifiable information from the reward object.

-        { event: this.event, address: reward.owner },
+        { event: this.event, index: index },

Committable suggestion

IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
if (reward.owner === undefined) {
return this.logAndThrowParseMessageError(
`TradingReward in TradingRewardEvent at index ${index} is missing an owner.`,
{ event: this.event, address: reward.owner },
);
}
if (reward.owner === undefined) {
return this.logAndThrowParseMessageError(
`TradingReward in TradingRewardEvent at index ${index} is missing an owner.`,
{ event: this.event, index: index },
);
}


(Note that no text should exist before the function declaration to ensure that exception line numbers are correct.)
DECLARE
trading_rewards_array trading_rewards%ROWTYPE;
Copy link
Contributor

Choose a reason for hiding this comment

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

what's this for? remove?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

oops my bad, this was when I was testing

Copy link
Contributor

@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.

Review Status

Actionable comments generated: 0

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 9a66a81 and 9660273.
Files selected for processing (13)
  • indexer/packages/postgres/tests/helpers/constants.ts (4 hunks)
  • indexer/packages/postgres/tests/helpers/conversion-helpers.ts (1 hunks)
  • indexer/packages/postgres/tests/stores/trading-reward-aggregation-table.test.ts (2 hunks)
  • indexer/packages/postgres/src/db/migrations/migration_files/20231221153944_update_trading_rewards_amount_scale.ts (1 hunks)
  • indexer/packages/postgres/src/db/migrations/migration_files/20231221165820_update_wallet_total_trading_rewards_scale.ts (1 hunks)
  • indexer/packages/postgres/src/db/migrations/migration_files/20231221233356_update_trading_reward_aggregations_amount_scale.ts (1 hunks)
  • indexer/packages/postgres/src/index.ts (2 hunks)
  • indexer/services/ender/tests/handlers/trading-rewards-handler.test.ts (1 hunks)
  • indexer/services/ender/tests/handlers/transfer-handler.test.ts (4 hunks)
  • indexer/services/ender/tests/helpers/conversion-helpers.ts (1 hunks)
  • indexer/services/ender/src/scripts/handlers/dydx_trading_rewards_handler.sql (1 hunks)
  • indexer/services/ender/src/scripts/helpers/dydx_process_trading_reward_event.sql (1 hunks)
  • indexer/services/ender/src/validators/trading-rewards-validator.ts (1 hunks)
Files skipped from review as they are similar to previous changes (6)
  • indexer/packages/postgres/src/db/migrations/migration_files/20231221153944_update_trading_rewards_amount_scale.ts
  • indexer/packages/postgres/src/index.ts
  • indexer/services/ender/tests/handlers/trading-rewards-handler.test.ts
  • indexer/services/ender/src/scripts/handlers/dydx_trading_rewards_handler.sql
  • indexer/services/ender/src/scripts/helpers/dydx_process_trading_reward_event.sql
  • indexer/services/ender/src/validators/trading-rewards-validator.ts
Additional comments: 14
indexer/services/ender/__tests__/helpers/conversion-helpers.ts (1)
  • 3-5: The function intToSerializedInt correctly converts a number to a Uint8Array. Ensure that the input number can safely be represented as a BigInt.
indexer/packages/postgres/__tests__/helpers/conversion-helpers.ts (1)
  • 6-8: The function denomToHumanReadableConversion correctly uses Big for conversion and formatting. Verify that the denom input is always a number that can be represented accurately in JavaScript.
indexer/packages/postgres/src/db/migrations/migration_files/20231221165820_update_wallet_total_trading_rewards_scale.ts (2)
  • 3-10: The up migration correctly alters the totalTradingRewards column with a precision of 27 and a scale of 18. Ensure this precision and scale are consistent with the application's requirements for representing trading rewards.

  • 12-17: The down migration reverts the totalTradingRewards column without specifying precision and scale. Confirm if this is the intended behavior or if the previous precision and scale should be restored.

indexer/packages/postgres/src/db/migrations/migration_files/20231221233356_update_trading_reward_aggregations_amount_scale.ts (2)
  • 3-10: The up migration correctly alters the amount column with a precision of 27 and a scale of 18. Ensure this precision and scale are consistent with the application's requirements for representing trading reward amounts.

  • 12-17: The down migration reverts the amount column without specifying precision and scale. Confirm if this is the intended behavior or if the previous precision and scale should be restored.

indexer/packages/postgres/__tests__/stores/trading-reward-aggregation-table.test.ts (2)
  • 12-12: The import of denomToHumanReadableConversion is correctly added to the test file.

  • 86-86: The use of denomToHumanReadableConversion(100000) replaces a hardcoded string, which is a good practice for maintainability and accuracy in tests.

indexer/packages/postgres/__tests__/helpers/constants.ts (2)
  • 104-104: The change to defaultWallet's totalTradingRewards field to use denomToHumanReadableConversion(0) ensures consistency and accuracy in representing trading rewards.

  • 107-109: The addition of defaultWallet2 with totalTradingRewards initialized using denomToHumanReadableConversion(1) is consistent and allows for varied test scenarios.

indexer/services/ender/__tests__/handlers/transfer-handler.test.ts (4)
  • 28-28: The import of testConversionHelpers is correctly added to the test file.

  • 308-308: Replacing hardcoded '0' with testConversionHelpers.denomToHumanReadableConversion(0) for the totalTradingRewards field in the test case is a good practice for maintainability and accuracy.

  • 360-360: Using testConversionHelpers.denomToHumanReadableConversion(0) for initializing totalTradingRewards in the test case ensures consistency and accuracy.

  • 413-413: The replacement of the hardcoded '0' with testConversionHelpers.denomToHumanReadableConversion(0) for the totalTradingRewards field in the test case is appropriate and improves test reliability.

Copy link
Contributor

@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.

Review Status

Actionable comments generated: 0

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 9660273 and 1840add.
Files selected for processing (3)
  • indexer/packages/postgres/src/db/migrations/migration_files/20231221153944_update_trading_rewards_amount_scale.ts (1 hunks)
  • indexer/packages/postgres/src/db/migrations/migration_files/20231221165820_update_wallet_total_trading_rewards_scale.ts (1 hunks)
  • indexer/packages/postgres/src/db/migrations/migration_files/20231221233356_update_trading_reward_aggregations_amount_scale.ts (1 hunks)
Files skipped from review due to trivial changes (1)
  • indexer/packages/postgres/src/db/migrations/migration_files/20231221233356_update_trading_reward_aggregations_amount_scale.ts
Files skipped from review as they are similar to previous changes (2)
  • indexer/packages/postgres/src/db/migrations/migration_files/20231221153944_update_trading_rewards_amount_scale.ts
  • indexer/packages/postgres/src/db/migrations/migration_files/20231221165820_update_wallet_total_trading_rewards_scale.ts

@Christopher-Li Christopher-Li merged commit b1ac285 into main Dec 22, 2023
11 checks passed
@Christopher-Li Christopher-Li deleted the cl_trading_rewards_handler branch December 22, 2023 19:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Development

Successfully merging this pull request may close these issues.

2 participants