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

[OTE-780] Add client code for affiliates #2252

Merged
merged 9 commits into from
Sep 16, 2024
Merged

Conversation

affanv14
Copy link
Contributor

@affanv14 affanv14 commented Sep 13, 2024

Changelist

Adds client code for queries and transactions

Test Plan

Adds unit tests for queries

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.

Summary by CodeRabbit

  • New Features

    • Introduced a new field for affiliate tiers in the Genesis state.
    • Added CLI commands for querying affiliate tiers, affiliate information, and referral information.
    • Implemented a command for registering affiliates through the CLI.
    • Enhanced the sample pregenesis configuration to include affiliate tiers.
    • Updated default genesis state to include affiliate tiers structure.
  • Bug Fixes

    • Simplified response handling in the ReferredBy function to return a valid response when no affiliate is found.
  • Tests

    • Added unit tests for the new CLI commands related to the affiliate module.
    • Improved error handling in tests for updating affiliate tiers.
    • Enhanced readability of test cases without altering functionality.
  • Chores

    • Improved the initialization and export of affiliate tiers in the module's genesis state.
    • Updated application version to reflect new features and improvements.

@affanv14 affanv14 requested a review from a team as a code owner September 13, 2024 15:37
Copy link

linear bot commented Sep 13, 2024

Copy link
Contributor

coderabbitai bot commented Sep 13, 2024

Walkthrough

The changes in this pull request enhance the affiliate module of the protocol by introducing a new field affiliate_tiers in the GenesisState message, allowing for better management of affiliate structures. Additionally, new CLI commands for querying and registering affiliates are added, along with unit tests to ensure functionality. The genesis state handling is improved for initialization and export, and modifications to the Keeper struct streamline error responses related to affiliate queries.

Changes

File Path Change Summary
proto/dydxprotocol/affiliates/genesis.proto Added affiliate_tiers field to GenesisState message, enhancing its functionality to manage affiliate tiers.
protocol/x/affiliates/genesis.go Modified InitGenesis and ExportGenesis functions to handle affiliate tiers correctly during initialization and export of the module's state.
protocol/x/affiliates/client/cli/query.go Introduced three new CLI commands: GetCmdQueryAffiliateTiers, GetCmdQueryAffiliateInfo, and GetCmdQueryReferredBy for querying affiliate data.
protocol/x/affiliates/client/cli/tx.go Added register-affiliate command to the CLI, allowing users to register affiliates with specific identifiers.
protocol/x/affiliates/client/cli/query_test.go Added unit tests for the new CLI commands to ensure correct functionality and response validation.
protocol/x/affiliates/keeper/grpc_query.go Updated ReferredBy function to return an empty response instead of an error if no affiliate is found, simplifying control flow.
protocol/x/affiliates/types/genesis.go Modified DefaultGenesis function to initialize GenesisState with an empty AffiliateTiers instance, ensuring a safer default state.
protocol/scripts/genesis/sample_pregenesis.json Updated sample_pregenesis.json to include affiliate_tiers object and incremented app_version, reflecting changes in the affiliate management system.
protocol/x/revshare/keeper/revshare_test.go Enhanced error handling in tests for UpdateAffiliateTiers function, improving robustness and reliability of test outcomes.
protocol/x/revshare/keeper/revshare_test.go Minor formatting adjustment in the TestKeeper_GetAllRevShares_Invalid test case for improved readability.

Possibly related PRs

Suggested labels

feature:indexer/affiliates

Poem

🐇 In the meadow where affiliates play,
New tiers bloom bright, guiding the way.
Commands now dance, queries take flight,
With tests in place, all feels just right.
So hop along, let’s celebrate,
A world of affiliates, oh, how great! 🌼


Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between c6c69e4 and 05c4163.

Files selected for processing (1)
  • protocol/x/affiliates/keeper/grpc_query_test.go (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • protocol/x/affiliates/keeper/grpc_query_test.go

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 generate interesting stats about this repository and render them as a table.
    -- @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
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.

Actionable comments posted: 4

Outside diff range and nitpick comments (1)
protocol/x/affiliates/genesis.go (1)

16-23: Enhance the error handling.

The changes to retrieve all affiliate tiers and include them in the exported genesis state are correct and provide a more complete representation of the module's state.

However, consider improving the error handling by returning the error instead of panicking. This allows the caller to handle the error gracefully.

Apply this diff to improve the error handling:

 affiliateTiers, err := k.GetAllAffiliateTiers(ctx)
 if err != nil {
-    panic(err)
+    return nil, err
 }
 
 return &types.GenesisState{
     AffiliateTiers: affiliateTiers,
-}
+}, nil

Also, update the function signature to return an error:

-func ExportGenesis(ctx sdk.Context, k keeper.Keeper) *types.GenesisState {
+func ExportGenesis(ctx sdk.Context, k keeper.Keeper) (*types.GenesisState, error) {
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between e5ec435 and 7fdb5c9.

Files ignored due to path filters (1)
  • protocol/x/affiliates/types/genesis.pb.go is excluded by !**/*.pb.go
Files selected for processing (7)
  • proto/dydxprotocol/affiliates/genesis.proto (1 hunks)
  • protocol/x/affiliates/client/cli/query.go (2 hunks)
  • protocol/x/affiliates/client/cli/query_test.go (1 hunks)
  • protocol/x/affiliates/client/cli/tx.go (2 hunks)
  • protocol/x/affiliates/genesis.go (1 hunks)
  • protocol/x/affiliates/keeper/grpc_query.go (1 hunks)
  • protocol/x/affiliates/types/genesis.go (1 hunks)
Additional context used
buf
proto/dydxprotocol/affiliates/genesis.proto

3-3: import "gogoproto/gogo.proto": file does not exist

(COMPILE)

Additional comments not posted (10)
protocol/x/affiliates/types/genesis.go (1)

5-7: LGTM!

The change to initialize the AffiliateTiers field with an empty AffiliateTiers instance in the default genesis state is a good improvement. It ensures that the field is explicitly initialized, which may be crucial for the correct functioning of the application that relies on this genesis state.

The overall logic of the function remains intact, but the initialization now provides a more complete and potentially safer default state.

proto/dydxprotocol/affiliates/genesis.proto (1)

10-13: LGTM!

The addition of the affiliate_tiers field to the GenesisState message is a valuable enhancement to the x/affiliates module. It allows for storing and managing different levels of affiliates within the protocol, which is crucial for the module's functionality.

The use of the gogoproto.nullable option to mark the field as non-nullable is also a good practice to ensure data integrity.

protocol/x/affiliates/genesis.go (1)

11-11: LGTM!

The change to call k.UpdateAffiliateTiers(ctx, genState.AffiliateTiers) is correct and ensures that the affiliate tiers are properly initialized during genesis.

protocol/x/affiliates/client/cli/tx.go (1)

27-46: LGTM!

The CmdRegisterAffiliate function is well-implemented and follows the expected patterns for creating a Cobra command in the Cosmos SDK. Here are the key observations:

  1. The command is clearly defined with the appropriate usage, description, and argument requirements.
  2. The transaction handling logic is correct, including retrieving the client context, constructing the MsgRegisterAffiliate message, and generating or broadcasting the transaction.
  3. The necessary transaction flags are added to the command using AddTxFlagsToCmd, allowing for transaction customization.
  4. The command is properly integrated into the parent command.

Overall, the code changes are sound and align with the module's functionality for registering affiliates.

protocol/x/affiliates/client/cli/query_test.go (2)

20-41: LGTM!

The setupNetwork function correctly initializes the genesis state with default values and adds test affiliate tiers. It returns the network and client context, which can be used in the test functions.


43-52: LGTM!

The TestQueryAffiliateTiers function correctly tests the GetCmdQueryAffiliateTiers CLI command. It sets up the network, executes the command, unmarshals the response, and asserts that the returned affiliate tiers match the default tiers.

protocol/x/affiliates/client/cli/query.go (4)

24-30: LGTM!

The function is correctly adding the new commands to the cmd variable and returning the updated cmd variable.


32-50: LGTM!

The function is correctly implementing the logic to query all affiliate tiers and print the response.


52-73: LGTM!

The function is correctly implementing the logic to query affiliate info for a given address and print the response.


75-94: LGTM!

The function is correctly implementing the logic to query the referee that referred the given address and print the response.

@@ -1,7 +1,13 @@
syntax = "proto3";
package dydxprotocol.affiliates;
import "gogoproto/gogo.proto";
Copy link
Contributor

Choose a reason for hiding this comment

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

Fix the missing import for "gogoproto/gogo.proto".

The static analysis tool buf reports a missing import for "gogoproto/gogo.proto". This issue needs to be resolved to ensure successful compilation of the code.

Please check the following:

  1. Ensure that the gogoproto library is properly installed and configured in your project's build system.
  2. Verify that the import path is correct and the "gogo.proto" file exists in the specified location.

If you need further assistance, I'd be happy to help you resolve this issue. Let me know if you'd like me to investigate further or provide more specific guidance.

Tools
buf

3-3: import "gogoproto/gogo.proto": file does not exist

(COMPILE)

"affiliate not found for address: %s",
req.GetAddress(),
)
return &types.ReferredByResponse{}, nil
Copy link
Contributor

Choose a reason for hiding this comment

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

Tip

Codebase Verification

Based on the analysis of the test cases, it appears that the tests for the ReferredBy function have not been updated to reflect the new behavior of returning an empty response instead of an error when no affiliate is found. This inconsistency could lead to potential issues and false negative test results.

To address this, we should recommend updating the test cases to align with the new implementation. Here's the final response:

Update test cases for ReferredBy function to expect empty response

The test cases for the ReferredBy function in protocol/x/affiliates/keeper/grpc_query_test.go need to be updated to reflect the new behavior of returning an empty response instead of an error when no affiliate is found. Specifically, the "Affiliate not found" test case should be modified as follows:

  • Remove the expectError: types.ErrAffiliateNotFound line.
  • Update the expected field to be an empty ReferredByResponse instead of nil.
  • Modify the assertion to check for an empty response rather than an error.

This update will ensure that the tests accurately reflect the new implementation and prevent potential false negative results.

Analysis chain

Verify the impact of returning an empty response on the calling code.

The change simplifies the control flow by removing the error handling when an affiliate is not found and returns an empty ReferredByResponse instead. This may impact how the calling code interprets the absence of an affiliate and may lead to different handling of the response in the broader application context.

Please verify that the calling code and the broader application can handle the empty response correctly. You can use the following script to search for the usage of the ReferredBy function and analyze the impact of the change:


To complete the verification process, we need to check if the test cases for the ReferredBy function have been updated to expect an empty response instead of an error when no affiliate is found. Let's examine the relevant test file.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the impact of returning an empty response on the calling code.

# Test: Search for the function usage. Expect: Analyze how the response is handled.
rg --type go -A 10 $'ReferredBy\('

Length of output: 18042


Script:

#!/bin/bash
# Description: Check if test cases for ReferredBy have been updated

# Test: Examine the test cases for ReferredBy function
cat protocol/x/affiliates/keeper/grpc_query_test.go

Length of output: 5723

Comment on lines +54 to +63
func TestQueryAffiliateInfo(t *testing.T) {
net, ctx := setupNetwork(t)

testAddress := constants.AliceAccAddress.String()
out, err := clitestutil.ExecTestCLICmd(ctx, cli.GetCmdQueryAffiliateInfo(), []string{testAddress})
require.NoError(t, err)

var resp types.AffiliateInfoResponse
require.NoError(t, net.Config.Codec.UnmarshalJSON(out.Bytes(), &resp))
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Add assertions for the returned affiliate info.

The TestQueryAffiliateInfo function correctly sets up the network and executes the GetCmdQueryAffiliateInfo CLI command with a test address. It also unmarshals the response into an AffiliateInfoResponse struct.

However, it does not assert anything about the returned affiliate info. Consider adding assertions to check that the returned affiliate info matches the expected values for the test address.

Comment on lines +65 to +74
func TestQueryReferredBy(t *testing.T) {
net, ctx := setupNetwork(t)

testAddress := constants.AliceAccAddress.String()
out, err := clitestutil.ExecTestCLICmd(ctx, cli.GetCmdQueryReferredBy(), []string{testAddress})
require.NoError(t, err)

var resp types.ReferredByResponse
require.NoError(t, net.Config.Codec.UnmarshalJSON(out.Bytes(), &resp))
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Add assertions for the returned referred-by info.

The TestQueryReferredBy function correctly sets up the network and executes the GetCmdQueryReferredBy CLI command with a test address. It also unmarshals the response into a ReferredByResponse struct.

However, it does not assert anything about the returned referred-by info. Consider adding assertions to check that the returned referred-by info matches the expected values for the test address.

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.

Actionable comments posted: 1

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 4e5599b and c6c69e4.

Files selected for processing (2)
  • protocol/x/affiliates/keeper/grpc_query_test.go (1 hunks)
  • protocol/x/revshare/keeper/revshare_test.go (1 hunks)
Files skipped from review due to trivial changes (1)
  • protocol/x/revshare/keeper/revshare_test.go

@@ -148,7 +148,7 @@ func TestReferredBy(t *testing.T) {
},
setup: func(ctx sdk.Context, k keeper.Keeper) {},
expected: nil,
expectError: types.ErrAffiliateNotFound,
expectError: nil,
Copy link
Contributor

Choose a reason for hiding this comment

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

Inconsistency between test case name and expected behavior.

The test case "Affiliate not found" implies that the test is checking the scenario where an affiliate is not found. However, setting expectError to nil suggests that the test is no longer expecting an error in this case.

This inconsistency could lead to confusion and potentially mask any issues related to handling the "Affiliate not found" scenario.

Consider either:

  1. Updating the test case name to reflect the new expected behavior, or
  2. Reverting the change and setting expectError to types.ErrAffiliateNotFound to align with the test case name and the scenario being tested.

For example:

-"Affiliate not found": {
+"Affiliate not registered": {
  req: &types.ReferredByRequest{
    Address: constants.DaveAccAddress.String(),
  },
  setup:       func(ctx sdk.Context, k keeper.Keeper) {},
  expected:    nil,
  expectError: nil,
},

or

 "Affiliate not found": {
  req: &types.ReferredByRequest{
    Address: constants.DaveAccAddress.String(),
  },
  setup:       func(ctx sdk.Context, k keeper.Keeper) {},
  expected:    nil,
-  expectError: nil,
+  expectError: types.ErrAffiliateNotFound,
},

Committable suggestion was skipped due to low confidence.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Development

Successfully merging this pull request may close these issues.

2 participants