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

fix: add token claims per network #4046

Merged
merged 2 commits into from
Oct 17, 2024
Merged

fix: add token claims per network #4046

merged 2 commits into from
Oct 17, 2024

Conversation

halaprix
Copy link
Member

@halaprix halaprix commented Oct 17, 2024

Update claimable ERC20 tokens by network

Changes πŸ‘·β€β™€οΈ

  • Replaced the static claimableErc20 array with a network-specific object claimableErc20
  • Added support for different claimable ERC20 tokens across various networks
  • Updated the ERC20 claims logic to use network-specific token lists

How to test πŸ§ͺ

  1. Check that ENA and SENA tokens are only claimable on the Mainnet network
  2. Verify that no tokens are claimable on other networks (Optimism, Arbitrum, Base, Polygon, etc.)
  3. Test the component on different networks to ensure it correctly uses the network-specific token list
  4. Confirm that the existing functionality for claiming rewards still works as expected

@pr (Diff with Main Branch)

// ... existing imports ...
import { NetworkIds } from 'blockchain/networks'

const claimableErc20: Record<NetworkIds, string[]> = {
  [NetworkIds.MAINNET]: ['ENA', 'SENA'],
  [NetworkIds.OPTIMISMMAINNET]: [],
  [NetworkIds.ARBITRUMMAINNET]: [],
  [NetworkIds.BASEMAINNET]: [],
  [NetworkIds.POLYGONMAINNET]: [],
  [NetworkIds.POLYGONMUMBAI]: [],
  [NetworkIds.BASEGOERLI]: [],
  [NetworkIds.EMPTYNET]: [],
  [NetworkIds.GOERLI]: [],
  [NetworkIds.HARDHAT]: [],
  [NetworkIds.ARBITRUMGOERLI]: [],
  [NetworkIds.OPTIMISMGOERLI]: [],
}

// ... existing code ...

useEffect(() => {
  if (dpmProxy) {
    // Existing ERC20 claims logic
    claimableErc20[networkId].forEach((token) => {
      // ... existing token balance and claim logic ...
    })

    // ... rest of the effect ...
  }
}, [dpmProxy, networkId, protocol, quoteAddress])

// ... rest of the component ...

This update introduces network-specific claimable ERC20 tokens, allowing for more granular control over which tokens can be claimed on different networks. The main changes are the introduction of the claimableErc20 object and the updated logic to use claimableErc20[networkId] instead of the previous static array.

Summary by CodeRabbit

  • New Features

    • Enhanced handling of claimable ERC20 tokens tailored for different networks.
    • Each network now has a dedicated array of claimable tokens, improving clarity and modularity.
  • Bug Fixes

    • Improved robustness in fetching rewards from Aave and Spark protocols based on network compatibility.

Copy link
Contributor

coderabbitai bot commented Oct 17, 2024

Walkthrough

The changes in this pull request primarily focus on the OmniDetailSectionRewardsClaims.tsx file, enhancing the management of claimable ERC20 tokens by transforming the claimableErc20 variable into a Record<NetworkIds, string[]>. This allows for network-specific arrays of claimable tokens, with MAINNET defined and others initialized as empty. The logic in the useEffect hook is updated to access the correct token array based on the current network, ensuring accurate token balance checks and reward fetching from Aave and Spark protocols.

Changes

File Change Summary
features/omni-kit/components/details-section/OmniDetailSectionRewardsClaims.tsx Updated claimableErc20 from string[] to Record<NetworkIds, string[]> for network-specific token management; modified useEffect to process claimable tokens based on networkId.

Possibly related PRs

  • feat: add aave and spark reward claimsΒ #4045: The changes in this PR involve the getAllUserRewards function, which is directly related to the updated logic for processing claimable tokens in the OmniDetailSectionRewardsClaims.tsx file, ensuring that the correct rewards are fetched based on the new structure of claimableErc20.

Suggested reviewers

  • piekczyk

πŸ‡ In the land of tokens, where networks play,
Claimable treasures come out to stay.
With MAINNET shining, the others align,
A structured approach makes everything fine.
So hop along, let the rewards flow,
In this code garden, watch the tokens grow! 🌼


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
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 df5e33f and c9482bd.

πŸ“’ Files selected for processing (1)
  • features/omni-kit/components/details-section/OmniDetailSectionRewardsClaims.tsx (2 hunks)
🧰 Additional context used
πŸ”‡ Additional comments (2)
features/omni-kit/components/details-section/OmniDetailSectionRewardsClaims.tsx (2)

18-18: Necessary Import of NetworkIds

The addition of import { NetworkIds } from 'blockchain/networks' is appropriate and required for defining claimableErc20.


20-33: Correct Implementation of Network-Specific claimableErc20 Mapping

Defining claimableErc20 as a Record<NetworkIds, string[]> allows for network-specific claimable tokens, enhancing the flexibility and scalability of the code.

@@ -36,7 +50,7 @@
useEffect(() => {
if (dpmProxy) {
// Existing ERC20 claims logic
claimableErc20.forEach((token) => {
claimableErc20[networkId].forEach((token) => {
Copy link
Contributor

@coderabbitai coderabbitai bot Oct 17, 2024

Choose a reason for hiding this comment

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

⚠️ Potential issue

Handle Undefined claimableErc20[networkId] to Prevent Runtime Errors

If networkId is not a key in the claimableErc20 object, accessing claimableErc20[networkId] will return undefined, leading to a runtime error when calling forEach.

Apply this diff to ensure safe access and prevent potential runtime errors:

-          claimableErc20[networkId].forEach((token) => {
+          (claimableErc20[networkId] || []).forEach((token) => {

This modification defaults to an empty array when claimableErc20[networkId] is undefined, ensuring that the forEach method always functions correctly, even for unrecognized networks.

πŸ“ 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. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
claimableErc20[networkId].forEach((token) => {
(claimableErc20[networkId] || []).forEach((token) => {

Copy link
Member Author

Choose a reason for hiding this comment

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

ok I'll agree. But don't get cocky. Thats only because I like you. If somone modifies the NetwrokIds and there's a cese we use it as index - that should be caught by ts

Copy link
Contributor

Choose a reason for hiding this comment

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

@halaprix, glad to hear that you've agreed to the change! You're absolutely right, TypeScript should catch such cases if someone modifies the NetworkIds. Thank you!

🐰😊


✏️ Learnings added
Learnt from: halaprix
PR: OasisDEX/oasis-borrow#4046
File: features/omni-kit/components/details-section/OmniDetailSectionRewardsClaims.tsx:53-53
Timestamp: 2024-10-17T18:29:27.516Z
Learning: In TypeScript code, we rely on TypeScript's type checking to catch cases where `NetworkIds` are modified and used as an index, ensuring that accessing `claimableErc20[networkId]` is safe.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!

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: 0

🧹 Outside diff range and nitpick comments (3)
features/omni-kit/components/details-section/OmniDetailSectionRewardsClaims.tsx (3)

7-7: LGTM! Consider using a constant for the MAINNET tokens.

The changes to claimableErc20 align well with the PR objectives, providing a clear structure for network-specific claimable tokens. This implementation allows for easy management of claimable tokens across different networks.

Consider defining a constant for the MAINNET tokens to improve maintainability:

const MAINNET_CLAIMABLE_TOKENS = ['ENA', 'SENA'] as const;

const claimableErc20: Record<NetworkIds, readonly string[]> = {
  [NetworkIds.MAINNET]: MAINNET_CLAIMABLE_TOKENS,
  // ... other networks
};

This approach would make it easier to update the list of claimable tokens for MAINNET in the future if needed.

Also applies to: 20-33


Line range hint 74-136: LGTM! Consider extracting protocol-specific logic.

The new Aave and Spark rewards check logic is well-implemented and aligns with the PR objectives. It correctly handles different protocols and networks, with proper error handling and logging.

To improve code organization and maintainability, consider extracting the protocol-specific logic into separate functions:

function getAaveV3Addresses(network: Network): { rewardsController: string, poolDataProvider: string } {
  if (network !== Network.HARDHAT && network !== Network.LOCAL && network !== Network.TENDERLY) {
    return {
      rewardsController: ADDRESSES[network].aave.v3.RewardsController,
      poolDataProvider: ADDRESSES[network].aave.v3.PoolDataProvider
    };
  }
  throw new Error(`Unsupported network for AaveV3: ${network}`);
}

function getSparkV3Addresses(network: Network): { rewardsController: string, poolDataProvider: string } {
  if (network !== Network.HARDHAT && network !== Network.LOCAL && network !== Network.TENDERLY) {
    return {
      rewardsController: ADDRESSES[network].spark.RewardsController,
      poolDataProvider: ADDRESSES[network].spark.PoolDataProvider
    };
  }
  throw new Error(`Unsupported network for SparkV3: ${network}`);
}

// In the useEffect hook:
let { rewardsControllerAddress, poolDataProviderAddress } = 
  protocol === LendingProtocol.AaveV3 ? getAaveV3Addresses(network) :
  protocol === LendingProtocol.SparkV3 ? getSparkV3Addresses(network) :
  (() => { throw new Error(`Unsupported protocol: ${protocol}`) })();

This refactoring would make the code more modular and easier to maintain, especially if more protocols are added in the future.


Line range hint 168-180: LGTM! Consider using a configuration object for eligibility.

The updates to the OmniDetailSectionRewardsClaims component correctly expand the eligibility for rewards claiming to include more protocols and tokens, aligning with the PR objectives.

To improve flexibility and maintainability, consider using a configuration object for eligibility:

const REWARDS_ELIGIBILITY = {
  protocols: [
    LendingProtocol.MorphoBlue,
    LendingProtocol.Ajna,
    LendingProtocol.AaveV3,
    LendingProtocol.SparkV3,
  ],
  tokens: ['SUSDE', 'USDE', 'WETH', 'ETH'],
};

const isEligible =
  REWARDS_ELIGIBILITY.protocols.includes(protocol) &&
  (REWARDS_ELIGIBILITY.tokens.includes(collateralToken) || REWARDS_ELIGIBILITY.tokens.includes(quoteToken));

This approach would make it easier to update the list of eligible protocols and tokens in the future without modifying the component logic.

πŸ“œ Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

πŸ“₯ Commits

Files that changed from the base of the PR and between c9482bd and b3f953e.

πŸ“’ Files selected for processing (1)
  • features/omni-kit/components/details-section/OmniDetailSectionRewardsClaims.tsx (3 hunks)
🧰 Additional context used
πŸ”‡ Additional comments (2)
features/omni-kit/components/details-section/OmniDetailSectionRewardsClaims.tsx (2)

53-53: Improved network-specific token claiming, but consider error handling.

The updated logic correctly uses the network-specific array of claimable tokens, which aligns with the PR objectives. This change ensures that only the appropriate tokens are considered for claiming on each network.

As mentioned in a previous review comment, consider handling the case where claimableErc20[networkId] might be undefined to prevent potential runtime errors. The suggestion to use (claimableErc20[networkId] || []).forEach(...) is still valid and would improve the robustness of this code.


Line range hint 1-180: Overall, excellent implementation with room for minor improvements.

The changes in this file successfully implement network-specific token claiming and expand the rewards claiming functionality as per the PR objectives. The code is well-structured and includes proper error handling. The suggestions provided in the review comments, if implemented, would further enhance the code's maintainability and robustness.

Great job on this implementation!

@halaprix halaprix merged commit d23c231 into dev Oct 17, 2024
25 of 26 checks passed
@halaprix halaprix deleted the kk/fix-token-claims branch October 17, 2024 18:31
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.

2 participants