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(vapordex): incorrect startblock and make address lowercase DEV-723 #8

Merged
merged 14 commits into from
Jun 28, 2024

Conversation

iHiteshAgrawal
Copy link
Member

@iHiteshAgrawal iHiteshAgrawal commented May 14, 2024

Summary by CodeRabbit

  • New Features

    • Added new fields to record user actions and introduced new table definitions for enhanced tracking.
    • Introduced new points sources for user activity.
  • Enhancements

    • Improved address consistency by converting user addresses to lowercase before processing.
    • Added a new entry for DexAggregatorV2 with a corresponding address mapping for the AVALANCHE chain.
    • Updated database operations with additional logging for better traceability.
  • Configuration

    • Added ORACLE_PRIVATE_KEY to .env.example for better configuration management.
  • Sync and Merkle Logic

    • Introduced new sync logic and Merkle root generation with enhanced logging and smart contract interactions.

Copy link

swarmia bot commented May 14, 2024

✅  Linked to Task DEV-723 · Some numbers are off in ponder.

Copy link

coderabbitai bot commented May 14, 2024

Warning

Review failed

The pull request is closed.

Walkthrough

The recent updates address several areas: adding boolean fields to the schema for user action tracking, new point sources, and wallet tier management, reflecting chain-related user operations in helper functions, normalizing user addresses, and ABI management for DexAggregatorV2. Additionally, environmental variables for private key storage and a complete synchronization logic are introduced, featuring Merkle Root generation and contract interaction.

Changes

Files/Paths Change Summary
ponder.schema.ts Added fields to schema for tracking user actions, new points sources, and table for wallet tiers.
src/config/constants.ts Added new DexAggregatorV2 address for the AVALANCHE chain.
src/helpers.ts Introduced handleChainFirstWallet, modified queryQuote, created getOrUpdateWalletsPerTier.
src/index.ts Updated code to use lowercase user addresses, added new helper functions.
src/types.ts Added new fields to the UserHistory interface.
abis/DexAggregatorV2.ts Introduced DexAggregatorV2ABI with relevant smart contract details.
.env.example Added ORACLE_PRIVATE_KEY configuration variable.
src/sync/merkle.cjs Exported getMerkleRoot function and added a console log.
src/sync/sync.js Added synchronization logic involving wallet client creation and Merkle root syncing.
src/sync/utils.cjs Updated database operations and logging, adjusted SQL query variable names.
tsconfig.json Included new sync file and changed extensions for existing files.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Application
    participant Blockchain
    participant Database

    User->>Application: Perform First Wallet Action
    Application->>Database: Log firstWalletInVPNDLM/firstWalletInVAPELM
    Application->>Blockchain: Interact using DexAggregatorV2
    Blockchain->>Application: Response with transaction details
    Application->>User: Confirmation of first wallet action
Loading

Poem

🐇 In the code, a rabbit hops with glee,
🎉 New fields added, true as can be!
First wallet and swaps, tracked with care,
Merkle root whispers, syncing here and there.
🌐 On Avalanche’s chain, we stake our name,
🎩 Cheers to the magic in this coding game! 🌟


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>.
    • 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 show all the console.log statements in this repository.
    • @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 as 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.

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

Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between df0778e and 59f20ad.
Files selected for processing (5)
  • ponder.config.ts (2 hunks)
  • ponder.schema.ts (1 hunks)
  • src/helpers.ts (2 hunks)
  • src/index.ts (24 hunks)
  • src/types.ts (1 hunks)
Additional comments not posted (8)
src/types.ts (1)

45-46: New boolean fields added to UserHistory interface.

The additions of firstWalletInVPNDLM, firstWalletInVAPELM, and firstSwap fields are consistent with the schema changes and correctly typed.

Also applies to: 53-53

ponder.config.ts (1)

33-33: Updated startBlock values for DexAggregator and VapeStaking.

The startBlock values have been updated to 20308160 for DexAggregator and 33291048 for VapeStaking, which align with the PR objectives.

Also applies to: 65-65

ponder.schema.ts (1)

88-89: New boolean fields added to UserHistory table.

The additions of firstWalletInVPNDLM, firstWalletInVAPELM, and firstSwap fields are consistent with the changes in the src/types.ts file and correctly typed.

Also applies to: 96-96

src/helpers.ts (1)

100-102: New boolean fields added to getOrCreateUserData function.

The additions of firstWalletInVPNDLM, firstWalletInVAPELM, and firstSwap fields are consistent with the changes in the src/types.ts and ponder.schema.ts files and correctly typed.

src/index.ts (4)

27-28: Ensure user addresses are processed in lowercase.

The conversion of user addresses to lowercase is correctly implemented and consistent across the event handlers.

Also applies to: 33-34


52-53: Updated logic to handle new boolean fields in LiquidMining:Deposit event handler.

The logic updates to handle the new boolean fields firstWalletInVPNDLM, firstWalletInVAPELM, and firstSwap are correctly implemented and consistent with the schema changes.

Also applies to: 60-64, 74-74, 81-82, 90-93, 104-105, 120-121, 134-134, 144-144, 158-159, 172-172, 183-184, 197-197, 208-209, 222-222


235-236: Updated logic to handle new boolean fields in VapeStaking:Deposit event handler.

The logic updates to handle the new boolean fields firstWalletInVPNDLM, firstWalletInVAPELM, and firstSwap are correctly implemented and consistent with the schema changes.

Also applies to: 242-246, 256-256, 264-265, 272-275, 285-286, 299-299


315-316: Updated logic to handle new boolean fields in DexAggregator:RouterSwap event handler.

The logic updates to handle the new boolean fields firstWalletInVPNDLM, firstWalletInVAPELM, and firstSwap are correctly implemented and consistent with the schema changes.

Also applies to: 328-332, 341-342, 350-354, 356-366, 376-376, 392-393, 406-406, 421-422, 435-435, 450-451, 464-464

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

Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between 59f20ad and 3f21552.
Files selected for processing (4)
  • ponder.schema.ts (2 hunks)
  • src/helpers.ts (3 hunks)
  • src/index.ts (25 hunks)
  • src/types.ts (1 hunks)
Files skipped from review as they are similar to previous changes (4)
  • ponder.schema.ts
  • src/helpers.ts
  • src/index.ts
  • src/types.ts

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

Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between 3f21552 and 22fc28b.
Files selected for processing (5)
  • abis/DexAggregatorV2.ts (1 hunks)
  • ponder.config.ts (3 hunks)
  • src/config/constants.ts (2 hunks)
  • src/helpers.ts (5 hunks)
  • src/index.ts (18 hunks)
Files skipped from review as they are similar to previous changes (2)
  • ponder.config.ts
  • src/index.ts
Additional comments not posted (9)
src/config/constants.ts (2)

87-87: Ensure the DexAggregatorV2 start block is correct.

The start block for DexAggregatorV2 is set to 40178055n. Verify that this is the correct block number for the deployment.


100-102: Ensure the DexAggregatorV2 address is correct.

The address for DexAggregatorV2 on Avalanche is set to 0x55477d8537ede381784b448876AfAa98aa450E63. Verify that this is the correct contract address.

src/helpers.ts (7)

67-86: Verify the correctness of the firstWallet field.

Ensure that the firstWallet field is correctly set and used in the handleChainFirstWallet function.


128-131: Verify the initialization of the new boolean fields.

Ensure that the new boolean fields (firstWalletInVPNDLM, firstSwap, firstWalletInVAPELM, chainFirstWallet) are correctly initialized in the getOrCreateUserData function.


388-556: Verify the correctness of the address conversion and points calculation.

Ensure that the address is correctly converted to lowercase and that the points are correctly calculated and assigned in the handleDexSwap function.


403-407: Verify the correctness of the findBestPath function call.

Ensure that the findBestPath function is correctly called and handled in the queryQuote function.


327-330: Verify the correctness of the weekly ID calculation.

Ensure that the weekly ID is correctly calculated and used in the getOrUpdateTokenIdData function.


388-556: Verify the correctness of the tokenIdOf function call.

Ensure that the tokenIdOf function is correctly called and handled in the getTokenId function.


388-556: Verify the correctness of the ownerOf function call.

Ensure that the ownerOf function is correctly called and handled in the getTokenIdOwner function.

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

Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between 22fc28b and 9c8ed8b.
Files selected for processing (3)
  • ponder.config.ts (2 hunks)
  • src/helpers.ts (3 hunks)
  • src/index.ts (25 hunks)
Files skipped from review as they are similar to previous changes (3)
  • ponder.config.ts
  • src/helpers.ts
  • src/index.ts

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

Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between 9c8ed8b and 19fb3c6.
Files selected for processing (4)
  • ponder.config.ts (5 hunks)
  • ponder.schema.ts (3 hunks)
  • src/config/constants.ts (1 hunks)
  • src/index.ts (26 hunks)
Files skipped from review as they are similar to previous changes (3)
  • ponder.schema.ts
  • src/config/constants.ts
  • src/index.ts
Additional comments not posted (1)
ponder.config.ts (1)

32-35: Ensure the new address for DexAggregatorV2 is correct and consistent with the project's requirements.

Verification successful

The address for DexAggregatorV2 in the src/config/constants.ts file matches the expected address "0x55477d8537ede381784b448876AfAa98aa450E63". Therefore, the new address is correct and consistent with the project's requirements.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the new address for DexAggregatorV2 in the constants file.

# Test: Search for the address definition. Expect: The address should match "0x55477d8537ede381784b448876AfAa98aa450E63".
rg --type ts 'DexAggregatorV2' | rg '0x55477d8537ede381784b448876AfAa98aa450E63'

Length of output: 78



Script:

#!/bin/bash
# Description: Locate the definition of DexAggregatorV2 and verify its address.

# Step 1: Locate the definition of DexAggregatorV2.
rg --type ts 'DexAggregatorV2' 

# Step 2: Verify the address associated with DexAggregatorV2.
rg --type ts 'DexAggregatorV2' | rg 'address'

Length of output: 255



Script:

#!/bin/bash
# Description: Inspect the src/config/constants.ts file to locate the address for DexAggregatorV2.

# Step 1: Print the definition of DexAggregatorV2 in src/config/constants.ts.
rg --type ts 'DexAggregatorV2' -A 5 src/config/constants.ts

Length of output: 248

ponder.config.ts Outdated
addresses.DexAggregator?.avalanche!,
addresses.DexAggregatorV2?.avalanche!,
],
startBlock: 43508160,
Copy link

Choose a reason for hiding this comment

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

Tip

Codebase Verification

The startBlock value needs updating in one instance

The startBlock value of 43508160 is consistent across all instances in the ponder.config.ts file, except for one line that includes a TODO comment indicating it needs to be updated.

  • ponder.config.ts: startBlock: 43508160, // TODO: Update this

Please ensure this startBlock value is updated as per the required configuration.

Analysis chain

Ensure the updated startBlock value is correct and consistent across all contracts.

Also applies to: 46-46, 57-57, 68-68, 79-79

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the updated startBlock values in the configuration file.

# Test: Search for the startBlock definition. Expect: The startBlock should match 43508160.
rg --type ts 'startBlock' | rg '43508160'

Length of output: 305



Script:

#!/bin/bash
# Description: Verify if there are any other `startBlock` values in the configuration file that might indicate inconsistencies or pending updates.

# Test: Search for all instances of `startBlock` in the configuration file.
rg --type ts 'startBlock'

Length of output: 291

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

Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between 19fb3c6 and 2948b26.
Files selected for processing (2)
  • src/helpers.ts (5 hunks)
  • src/index.ts (26 hunks)
Files skipped from review as they are similar to previous changes (1)
  • src/index.ts

src/helpers.ts Outdated
Comment on lines 60 to 79
export const handleChainFirstWallet = async (
context: Context,
chainId: number,
userAddressLowerCase: string,
userData: any
): Promise<UserHistory> => {
const { AllProtocols, UserHistory } = context.db;
let allProtocols = await AllProtocols.findUnique({ id: "protocols" });
if (!allProtocols) {
allProtocols = await AllProtocols.create({
id: "protocols",
data: { firstWallet: userAddressLowerCase },
});
return await UserHistory.update({
id: `${userAddressLowerCase}-${chainId}`,
data: { chainFirstWallet: true },
});
}
return userData;
};
Copy link

Choose a reason for hiding this comment

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

Ensure proper error handling for database operations.

The function handleChainFirstWallet does not handle potential errors that might occur during database operations. This could lead to unhandled exceptions and potential data inconsistencies.

+ try {
    let allProtocols = await AllProtocols.findUnique({ id: "protocols" });
    if (!allProtocols) {
      allProtocols = await AllProtocols.create({
        id: "protocols",
        data: { firstWallet: userAddressLowerCase },
      });
      return await UserHistory.update({
        id: `${userAddressLowerCase}-${chainId}`,
        data: { chainFirstWallet: true },
      });
    }
  } catch (error) {
    console.error("Error handling chain first wallet:", error);
    throw new Error("Failed to handle chain first wallet");
  }
  return userData;

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
export const handleChainFirstWallet = async (
context: Context,
chainId: number,
userAddressLowerCase: string,
userData: any
): Promise<UserHistory> => {
const { AllProtocols, UserHistory } = context.db;
let allProtocols = await AllProtocols.findUnique({ id: "protocols" });
if (!allProtocols) {
allProtocols = await AllProtocols.create({
id: "protocols",
data: { firstWallet: userAddressLowerCase },
});
return await UserHistory.update({
id: `${userAddressLowerCase}-${chainId}`,
data: { chainFirstWallet: true },
});
}
return userData;
};
export const handleChainFirstWallet = async (
context: Context,
chainId: number,
userAddressLowerCase: string,
userData: any
): Promise<UserHistory> => {
const { AllProtocols, UserHistory } = context.db;
try {
let allProtocols = await AllProtocols.findUnique({ id: "protocols" });
if (!allProtocols) {
allProtocols = await AllProtocols.create({
id: "protocols",
data: { firstWallet: userAddressLowerCase },
});
return await UserHistory.update({
id: `${userAddressLowerCase}-${chainId}`,
data: { chainFirstWallet: true },
});
}
} catch (error) {
console.error("Error handling chain first wallet:", error);
throw new Error("Failed to handle chain first wallet");
}
return userData;
};

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

Out of diff range and nitpick comments (5)
src/helpers.ts (5)

Line range hint 94-162: Add error handling for database operations.

The function getOrCreateUserData does not handle potential errors that might occur during database operations. This could lead to unhandled exceptions and potential data inconsistencies.

+ try {
    let userHistory = await UserHistory.findUnique({
      id: `${address}-${chainId}`,
    });

    let mainWallet = await getTokenIdOwner(tokenId, context);

    if (!userHistory) {
      userHistory = await UserHistory.create({
        id: `${address}-${chainId}`,
        data: {
          LMSeasons: [],
          depositInVS: false,
          LMOneSeasonPointsClaimed: false,
          LMThreeSeasonsPointsClaimed: false,
          LMSixSeasonsPointsClaimed: false,
          LMOneYearPointsClaimed: false,
          usdValueOfSwaps: BIGINT_ZERO,
          swaps: BIGINT_ZERO,
          first1kSwaps: false,
          first10kSwaps: false,
          first100kSwaps: false,
          chainId: chainId,
          firstWalletInVPNDLM: false,
          firstSwap: false,
          firstWalletInVAPELM: false,
          chainFirstWallet: false,
        },
      });

      await UserData.create({
        id: `${address}-${chainId}`,
        data: {
          linkedToTokenId: tokenId,
          isMainWallet: address === mainWallet,
          chainId: chainId,
        },
      });
    }
  } catch (error) {
    console.error("Error creating or retrieving user data:", error);
    throw new Error("Failed to create or retrieve user data");
  }
  return userHistory;

Line range hint 212-222: Add error handling for contract read operation.

The function getTokenIdOwner does not handle potential errors that might occur during the contract read operation. This could lead to unhandled exceptions.

+ try {
    const tokenIdOwner = await client.readContract({
      abi: StratosphereAbi,
      address: addresses.Stratosphere![network.name] as `0x${string}`,
      functionName: "ownerOf",
      args: [tokenId],
    });
  } catch (error) {
    console.error("Error retrieving token ID owner:", error);
    throw new Error("Failed to retrieve token ID owner");
  }
  return tokenIdOwner;

Line range hint 224-234: Add error handling for HTTP request.

The function queryLiquidMiningData does not handle potential errors that might occur during the HTTP request. This could lead to unhandled exceptions.

+ try {
    let response = await axios
      .post("https://api.thegraph.com/subgraphs/name/vaporfi/liquid-mining", {
        query: `query UserQuery {
            users(where: {id_contains: "${user}"}) {
              seasonId
              isMainWallet
              linkedToTokenId
              id
            }
          }`,
      })
      .then((res) => {
        return res.data.data.users;
      });
  } catch (error) {
    console.error("Error querying liquid mining data:", error);
    throw new Error("Failed to query liquid mining data");
  }
  return response;

Line range hint 236-246: Add error handling for HTTP request.

The function queryVapeStakingData does not handle potential errors that might occur during the HTTP request. This could lead to unhandled exceptions.

+ try {
    let response = await axios
      .post("https://api.thegraph.com/subgraphs/name/vaporfi/vape-staking", {
        query: `query UserQuery {
          users(where: {id_contains: "${user}"}) {
            id
          }
        }`,
      })
      .then((res) => {
        return res.data.data.users;
      });
  } catch (error) {
    console.error("Error querying vape staking data:", error);
    throw new Error("Failed to query vape staking data");
  }
  return response;

Line range hint 335-382: Add error handling for database operations.

The function getOrUpdateTokenIdData does not handle potential errors that might occur during database operations. This could lead to unhandled exceptions and potential data inconsistencies.

+ try {
    const weeklyId = `${tokenId}-${chainId}-${getWeeklyID(
      timestamp,
      deployedBlockTimestamp
    )}`;

    let tokenIdData = await TokenIdData.findUnique({
      id: `${tokenId}-${chainId}`,
    });
    let tokenIdDataWeekly = await TokenIdDataWeekly.findUnique({ id: weeklyId });

    if (!tokenIdData) {
      tokenIdData = await TokenIdData.create({
        id: `${tokenId}-${chainId}`,
        data: {
          tokenId,
          chainId,
          pointsEarned: BIGINT_ZERO,
          pointsClaimed: BIGINT_ZERO,
          pointsSpent: BIGINT_ZERO,
          lastUpdated: timestamp,
        },
      });
    }

    if (!tokenIdDataWeekly) {
      tokenIdDataWeekly = await TokenIdDataWeekly.create({
        id: weeklyId,
        data: {
          tokenId,
          chainId,
          pointsEarned: BIGINT_ZERO,
          pointsClaimed: BIGINT_ZERO,
          pointsSpent: BIGINT_ZERO,
          lastUpdated: timestamp,
        },
      });
    }

    tokenIdData = await TokenIdData.update({
      id: `${tokenId}-${chainId}`,
      data: ({ current }) => ({
        pointsEarned: current.pointsEarned + pointsEarned,
        pointsClaimed: current.pointsClaimed + pointsClaimed,
        pointsSpent: current.pointsSpent + pointsSpent,
        lastUpdated: timestamp,
      }),
    });

    tokenIdDataWeekly = await TokenIdDataWeekly.update({
      id: weeklyId,
      data: ({ current }) => ({
        pointsEarned: current.pointsEarned + pointsEarned,
        pointsClaimed: current.pointsClaimed + pointsClaimed,
        pointsSpent: current.pointsSpent + pointsSpent,
        lastUpdated: timestamp,
      }),
    });
  } catch (error) {
    console.error("Error updating token ID data:", error);
    throw new Error("Failed to update token ID data");
  }
  return tokenIdData;
Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between 2948b26 and 4fecab8.
Files selected for processing (3)
  • ponder.schema.ts (3 hunks)
  • src/helpers.ts (6 hunks)
  • src/index.ts (26 hunks)
Files skipped from review as they are similar to previous changes (2)
  • ponder.schema.ts
  • src/index.ts
Additional comments not posted (2)
src/helpers.ts (2)

Line range hint 164-188: LGTM! The function handles errors correctly within the loop.


Line range hint 190-210: LGTM! The function handles errors by catching exceptions and logging reverted addresses.

src/helpers.ts Outdated
Comment on lines 61 to 93
export const handleChainFirstWallet = async (
context: Context,
chainId: number,
userAddressLowerCase: string,
userData: any,
event: any
): Promise<UserHistory> => {
const { AllProtocols, UserHistory, Points } = context.db;
let allProtocols = await AllProtocols.findUnique({ id: "protocols" });
if (!allProtocols) {
allProtocols = await AllProtocols.create({
id: "protocols",
data: { firstWallet: userAddressLowerCase },
});
await Points.create({
id: `${userAddressLowerCase}-chain-first-wallet`,
data: {
userDataId: `${userAddressLowerCase}-${chainId}`,
userHistoryId: `${userAddressLowerCase}-${chainId}`,
pointsSource: "chain_first_wallet",
points: pointsMap.ChainFirstWallet,
chainId: chainId,
timestamp: event?.block?.timestamp,
},
});

return await UserHistory.update({
id: `${userAddressLowerCase}-${chainId}`,
data: { chainFirstWallet: true },
});
}
return userData;
};
Copy link

Choose a reason for hiding this comment

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

Add error handling for database operations.

The function handleChainFirstWallet does not handle potential errors that might occur during database operations. This could lead to unhandled exceptions and potential data inconsistencies.

+ try {
    let allProtocols = await AllProtocols.findUnique({ id: "protocols" });
    if (!allProtocols) {
      allProtocols = await AllProtocols.create({
        id: "protocols",
        data: { firstWallet: userAddressLowerCase },
      });
      await Points.create({
        id: `${userAddressLowerCase}-chain-first-wallet`,
        data: {
          userDataId: `${userAddressLowerCase}-${chainId}`,
          userHistoryId: `${userAddressLowerCase}-${chainId}`,
          pointsSource: "chain_first_wallet",
          points: pointsMap.ChainFirstWallet,
          chainId: chainId,
          timestamp: event?.block?.timestamp,
        },
      });
      return await UserHistory.update({
        id: `${userAddressLowerCase}-${chainId}`,
        data: { chainFirstWallet: true },
      });
    }
  } catch (error) {
    console.error("Error handling chain first wallet:", error);
    throw new Error("Failed to handle chain first wallet");
  }
  return userData;

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
export const handleChainFirstWallet = async (
context: Context,
chainId: number,
userAddressLowerCase: string,
userData: any,
event: any
): Promise<UserHistory> => {
const { AllProtocols, UserHistory, Points } = context.db;
let allProtocols = await AllProtocols.findUnique({ id: "protocols" });
if (!allProtocols) {
allProtocols = await AllProtocols.create({
id: "protocols",
data: { firstWallet: userAddressLowerCase },
});
await Points.create({
id: `${userAddressLowerCase}-chain-first-wallet`,
data: {
userDataId: `${userAddressLowerCase}-${chainId}`,
userHistoryId: `${userAddressLowerCase}-${chainId}`,
pointsSource: "chain_first_wallet",
points: pointsMap.ChainFirstWallet,
chainId: chainId,
timestamp: event?.block?.timestamp,
},
});
return await UserHistory.update({
id: `${userAddressLowerCase}-${chainId}`,
data: { chainFirstWallet: true },
});
}
return userData;
};
export const handleChainFirstWallet = async (
context: Context,
chainId: number,
userAddressLowerCase: string,
userData: any,
event: any
): Promise<UserHistory> => {
const { AllProtocols, UserHistory, Points } = context.db;
try {
let allProtocols = await AllProtocols.findUnique({ id: "protocols" });
if (!allProtocols) {
allProtocols = await AllProtocols.create({
id: "protocols",
data: { firstWallet: userAddressLowerCase },
});
await Points.create({
id: `${userAddressLowerCase}-chain-first-wallet`,
data: {
userDataId: `${userAddressLowerCase}-${chainId}`,
userHistoryId: `${userAddressLowerCase}-${chainId}`,
pointsSource: "chain_first_wallet",
points: pointsMap.ChainFirstWallet,
chainId: chainId,
timestamp: event?.block?.timestamp,
},
});
return await UserHistory.update({
id: `${userAddressLowerCase}-${chainId}`,
data: { chainFirstWallet: true },
});
}
} catch (error) {
console.error("Error handling chain first wallet:", error);
throw new Error("Failed to handle chain first wallet");
}
return userData;
};

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

Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between 4fecab8 and 8b2fd23.
Files selected for processing (2)
  • src/helpers.ts (6 hunks)
  • src/index.ts (24 hunks)
Files skipped from review as they are similar to previous changes (1)
  • src/index.ts

Comment on lines +61 to +93
export const handleChainFirstWallet = async (
context: Context,
chainId: number,
userAddressLowerCase: string,
userData: any,
event: any
): Promise<UserHistory> => {
const { AllProtocols, UserHistory, Points } = context.db;
let allProtocols = await AllProtocols.findUnique({ id: "protocols" });
if (!allProtocols) {
allProtocols = await AllProtocols.create({
id: "protocols",
data: { firstWallet: userAddressLowerCase },
});
await Points.create({
id: `${userAddressLowerCase}-chain-first-wallet`,
data: {
userDataId: `${userAddressLowerCase}-${chainId}`,
userHistoryId: `${userAddressLowerCase}-${chainId}`,
pointsSource: "chain_first_wallet",
points: pointsMap.ChainFirstWallet,
chainId: chainId,
timestamp: event?.block?.timestamp,
},
});

userData = await UserHistory.update({
id: `${userAddressLowerCase}-${chainId}`,
data: { chainFirstWallet: true },
});
}
return userData;
};
Copy link

Choose a reason for hiding this comment

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

Add error handling for database operations.

The function handleChainFirstWallet does not handle potential errors that might occur during database operations. This could lead to unhandled exceptions and potential data inconsistencies.

+ try {
    let allProtocols = await AllProtocols.findUnique({ id: "protocols" });
    if (!allProtocols) {
      allProtocols = await AllProtocols.create({
        id: "protocols",
        data: { firstWallet: userAddressLowerCase },
      });
      await Points.create({
        id: `${userAddressLowerCase}-chain-first-wallet`,
        data: {
          userDataId: `${userAddressLowerCase}-${chainId}`,
          userHistoryId: `${userAddressLowerCase}-${chainId}`,
          pointsSource: "chain_first_wallet",
          points: pointsMap.ChainFirstWallet,
          chainId: chainId,
          timestamp: event?.block?.timestamp,
        },
      });
      userData = await UserHistory.update({
        id: `${userAddressLowerCase}-${chainId}`,
        data: { chainFirstWallet: true },
      });
    }
  } catch (error) {
    console.error("Error handling chain first wallet:", error);
    throw new Error("Failed to handle chain first wallet");
  }

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
export const handleChainFirstWallet = async (
context: Context,
chainId: number,
userAddressLowerCase: string,
userData: any,
event: any
): Promise<UserHistory> => {
const { AllProtocols, UserHistory, Points } = context.db;
let allProtocols = await AllProtocols.findUnique({ id: "protocols" });
if (!allProtocols) {
allProtocols = await AllProtocols.create({
id: "protocols",
data: { firstWallet: userAddressLowerCase },
});
await Points.create({
id: `${userAddressLowerCase}-chain-first-wallet`,
data: {
userDataId: `${userAddressLowerCase}-${chainId}`,
userHistoryId: `${userAddressLowerCase}-${chainId}`,
pointsSource: "chain_first_wallet",
points: pointsMap.ChainFirstWallet,
chainId: chainId,
timestamp: event?.block?.timestamp,
},
});
userData = await UserHistory.update({
id: `${userAddressLowerCase}-${chainId}`,
data: { chainFirstWallet: true },
});
}
return userData;
};
export const handleChainFirstWallet = async (
context: Context,
chainId: number,
userAddressLowerCase: string,
userData: any,
event: any
): Promise<UserHistory> => {
const { AllProtocols, UserHistory, Points } = context.db;
try {
let allProtocols = await AllProtocols.findUnique({ id: "protocols" });
if (!allProtocols) {
allProtocols = await AllProtocols.create({
id: "protocols",
data: { firstWallet: userAddressLowerCase },
});
await Points.create({
id: `${userAddressLowerCase}-chain-first-wallet`,
data: {
userDataId: `${userAddressLowerCase}-${chainId}`,
userHistoryId: `${userAddressLowerCase}-${chainId}`,
pointsSource: "chain_first_wallet",
points: pointsMap.ChainFirstWallet,
chainId: chainId,
timestamp: event?.block?.timestamp,
},
});
userData = await UserHistory.update({
id: `${userAddressLowerCase}-${chainId}`,
data: { chainFirstWallet: true },
});
}
} catch (error) {
console.error("Error handling chain first wallet:", error);
throw new Error("Failed to handle chain first wallet");
}
return userData;
};

Comment on lines +135 to +138
firstWalletInVPNDLM: false,
firstSwap: false,
firstWalletInVAPELM: false,
chainFirstWallet: false,
Copy link

Choose a reason for hiding this comment

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

Add error handling for database operations.

The function getOrCreateUserData does not handle potential errors that might occur during database operations. This could lead to unhandled exceptions and potential data inconsistencies.

+ try {
    let userHistory = await UserHistory.findUnique({
      id: `${address}-${chainId}`,
    });

    let mainWallet = await getTokenIdOwner(tokenId, context);

    if (!userHistory) {
      userHistory = await UserHistory.create({
        id: `${address}-${chainId}`,
        data: {
          LMSeasons: [],
          depositInVS: false,
          LMOneSeasonPointsClaimed: false,
          LMThreeSeasonsPointsClaimed: false,
          LMSixSeasonsPointsClaimed: false,
          LMOneYearPointsClaimed: false,
          usdValueOfSwaps: BIGINT_ZERO,
          swaps: BIGINT_ZERO,
          first1kSwaps: false,
          first10kSwaps: false,
          first100kSwaps: false,
          chainId: chainId,
          firstWalletInVPNDLM: false,
          firstSwap: false,
          firstWalletInVAPELM: false,
          chainFirstWallet: false,
        },
      });

      await UserData.create({
        id: `${address}-${chainId}`,
        data: {
          linkedToTokenId: tokenId,
          isMainWallet: address === mainWallet,
          chainId: chainId,
        },
      });
    }
  } catch (error) {
    console.error("Error creating or retrieving user data:", error);
    throw new Error("Failed to create or retrieve user data");
  }
  return userHistory;

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
firstWalletInVPNDLM: false,
firstSwap: false,
firstWalletInVAPELM: false,
chainFirstWallet: false,
firstWalletInVPNDLM: false,
firstSwap: false,
firstWalletInVAPELM: false,
chainFirstWallet: false,

Comment on lines +164 to +165
blockNumber: bigint,
aggregatorAddress: `0x${string}`
Copy link

Choose a reason for hiding this comment

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

Improve error message for better debugging.

The function queryQuote handles errors within the loop, but the error message could be more descriptive to aid in debugging.

- } catch (e) {
+ } catch (error) {
+   console.error(`Error in findBestPath: ${error.message}`, error);
    quoteParams.maxSteps -= BIGINT_ONE;
    continue;
  }

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
blockNumber: bigint,
aggregatorAddress: `0x${string}`
blockNumber: bigint,
aggregatorAddress: `0x${string}`

Comment on lines +335 to +338
const weeklyId = `${tokenId}-${chainId}-${getWeeklyID(
timestamp,
deployedBlockTimestamp
)}`;
Copy link

Choose a reason for hiding this comment

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

Add error handling for database operations.

The function getOrUpdateTokenIdData does not handle potential errors that might occur during database operations. This could lead to unhandled exceptions and potential data inconsistencies.

+ try {
    const weeklyId = `${tokenId}-${chainId}-${getWeeklyID(
      timestamp,
      deployedBlockTimestamp
    )}`;

    let tokenIdData = await TokenIdData.findUnique({
      id: `${tokenId}-${chainId}`,
    });
    let tokenIdDataWeekly = await TokenIdDataWeekly.findUnique({ id: weeklyId });

    if (!tokenIdData) {
      tokenIdData = await TokenIdData.create({
        id: `${tokenId}-${chainId}`,
        data: {
          tokenId,
          chainId,
          pointsEarned: BIGINT_ZERO,
          pointsClaimed: BIGINT_ZERO,
          pointsSpent: BIGINT_ZERO,
          lastUpdated: timestamp,
        },
      });
    }

    if (!tokenIdDataWeekly) {
      tokenIdDataWeekly = await TokenIdDataWeekly.create({
        id: weeklyId,
        data: {
          tokenId,
          chainId,
          pointsEarned: BIGINT_ZERO,
          pointsClaimed: BIGINT_ZERO,
          pointsSpent: BIGINT_ZERO,
          lastUpdated: timestamp,
        },
      });
    }

    tokenIdData = await TokenIdData.update({
      id: `${tokenId}-${chainId}`,
      data: ({ current }) => ({
        pointsEarned: current.pointsEarned + pointsEarned,
        pointsClaimed: current.pointsClaimed + pointsClaimed,
        pointsSpent: current.pointsSpent + pointsSpent,
        lastUpdated: timestamp,
      }),
    });

    tokenIdDataWeekly = await TokenIdDataWeekly.update({
      id: weeklyId,
      data: ({ current }) => ({
        pointsEarned: current.pointsEarned + pointsEarned,
        pointsClaimed: current.pointsClaimed + pointsClaimed,
        pointsSpent: current.pointsSpent + pointsSpent,
        lastUpdated: timestamp,
      }),
    });
  } catch (error) {
    console.error("Error updating token ID data:", error);
    throw new Error("Failed to update token ID data");
  }

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
const weeklyId = `${tokenId}-${chainId}-${getWeeklyID(
timestamp,
deployedBlockTimestamp
)}`;
try {
const weeklyId = `${tokenId}-${chainId}-${getWeeklyID(
timestamp,
deployedBlockTimestamp
)}`;
let tokenIdData = await TokenIdData.findUnique({
id: `${tokenId}-${chainId}`,
});
let tokenIdDataWeekly = await TokenIdDataWeekly.findUnique({ id: weeklyId });
if (!tokenIdData) {
tokenIdData = await TokenIdData.create({
id: `${tokenId}-${chainId}`,
data: {
tokenId,
chainId,
pointsEarned: BIGINT_ZERO,
pointsClaimed: BIGINT_ZERO,
pointsSpent: BIGINT_ZERO,
lastUpdated: timestamp,
},
});
}
if (!tokenIdDataWeekly) {
tokenIdDataWeekly = await TokenIdDataWeekly.create({
id: weeklyId,
data: {
tokenId,
chainId,
pointsEarned: BIGINT_ZERO,
pointsClaimed: BIGINT_ZERO,
pointsSpent: BIGINT_ZERO,
lastUpdated: timestamp,
},
});
}
tokenIdData = await TokenIdData.update({
id: `${tokenId}-${chainId}`,
data: ({ current }) => ({
pointsEarned: current.pointsEarned + pointsEarned,
pointsClaimed: current.pointsClaimed + pointsClaimed,
pointsSpent: current.pointsSpent + pointsSpent,
lastUpdated: timestamp,
}),
});
tokenIdDataWeekly = await TokenIdDataWeekly.update({
id: weeklyId,
data: ({ current }) => ({
pointsEarned: current.pointsEarned + pointsEarned,
pointsClaimed: current.pointsClaimed + pointsClaimed,
pointsSpent: current.pointsSpent + pointsSpent,
lastUpdated: timestamp,
}),
});
} catch (error) {
console.error("Error updating token ID data:", error);
throw new Error("Failed to update token ID data");
}

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

Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between 8b2fd23 and 3fb13b7.
Files selected for processing (1)
  • ponder.config.ts (3 hunks)
Files skipped from review as they are similar to previous changes (1)
  • ponder.config.ts

@royvardhan royvardhan mentioned this pull request Jun 10, 2024
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: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 3fb13b7 and 606701b.

Files selected for processing (3)
  • ponder.schema.ts (4 hunks)
  • src/helpers.ts (7 hunks)
  • src/index.ts (25 hunks)
Additional comments not posted (11)
ponder.schema.ts (5)

43-45: Added new point sources chain_first_wallet and dex_aggregator_first_swap to track specific user actions. Ensure these sources are integrated correctly in the points calculation logic.


Line range hint 1-155: Overall, the schema updates are well-integrated. Ensure all new fields and tables are covered in unit tests to prevent regressions.


90-99: Added new boolean fields to track first wallet and swap actions. Verify that these fields are being updated correctly in the corresponding event handlers.

#!/bin/bash
# Description: Verify that the new boolean fields are updated correctly in event handlers.

# Test: Search for updates to the new fields in event handlers. Expect: Correct update logic.
rg --type typescript $'update.*firstWalletInVPNDLM|firstWalletInVAPELM|firstSwap'

113-114: Introduced a new table AllProtocols. Ensure that this table is utilized appropriately across the application, especially in wallet management logic.

#!/bin/bash
# Description: Verify the usage of the `AllProtocols` table across the application.

# Test: Search for references to the `AllProtocols` table. Expect: Correct and consistent usage.
rg --type typescript $'AllProtocols'

149-155: Added a new table WalletsPerTier to manage wallets per tier. This is crucial for managing tier-based features. Ensure that the logic for updating this table is robust and handles edge cases.

#!/bin/bash
# Description: Verify the logic for updating the `WalletsPerTier` table.

# Test: Search for updates to the `WalletsPerTier` table. Expect: Robust update logic.
rg --type typescript $'update.*WalletsPerTier'
src/helpers.ts (5)

61-93: The function handleChainFirstWallet has been added to handle first wallet events on the chain. Ensure that error handling is robust as per previous comments.


135-138: New fields firstWalletInVPNDLM, firstSwap, firstWalletInVAPELM, and chainFirstWallet added to UserHistory. Ensure these fields are updated correctly in the corresponding logic.


Line range hint 1-428: Overall, the helper functions are well-integrated and address the new requirements effectively. Ensure comprehensive testing to cover all new logic.


Line range hint 164-175: The function queryQuote now includes an aggregatorAddress parameter to handle different aggregators. Ensure that this parameter is validated and used correctly in all calls to this function.

#!/bin/bash
# Description: Verify the correct usage of `aggregatorAddress` in `queryQuote`.

# Test: Search for calls to `queryQuote`. Expect: Correct and validated usage of `aggregatorAddress`.
rg --type typescript $'queryQuote'

396-428: Introduced the function getOrUpdateWalletsPerTier to manage wallet tiers. This function should handle edge cases such as duplicate entries and concurrency issues.

#!/bin/bash
# Description: Verify the handling of edge cases in `getOrUpdateWalletsPerTier`.

# Test: Search for logic handling duplicates and concurrency in `getOrUpdateWalletsPerTier`. Expect: Robust handling of edge cases.
rg --type typescript $'getOrUpdateWalletsPerTier'
src/index.ts (1)

Line range hint 1-507: The modifications in src/index.ts integrate the new helper functions and address the PR objectives effectively. Ensure that all new logic is covered by unit tests to maintain robustness.

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 606701b and 8f87400.

Files selected for processing (4)
  • .env.example (1 hunks)
  • src/sync/merkle.cjs (1 hunks)
  • src/sync/sync.js (1 hunks)
  • tsconfig.json (1 hunks)
Files not reviewed due to errors (1)
  • src/sync/sync.js (no review received)
Files skipped from review due to trivial changes (2)
  • .env.example
  • src/sync/merkle.cjs
Additional comments not posted (1)
tsconfig.json (1)

24-29: Ensure correct inclusion of new files in TypeScript configuration.

The inclusion of src/sync/merkle.mjs, src/sync/utils.cjs, and src/sync/sync.cjs in the tsconfig.json file ensures that TypeScript will type-check these files. This is particularly important as these files seem to be central to new synchronization logic introduced in the project.

@royvardhan royvardhan merged commit 0c249ec into main Jun 28, 2024
1 check passed
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.

3 participants