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

[TASK-6263] feat: improve requests usability #157

Merged
merged 8 commits into from
Oct 17, 2024

Conversation

jjramirezn
Copy link
Contributor

Code changes

  • prepareXchainRequestFulfillmentTransaction now accepts and uses api key

Test changes

  • Use back api instead of front
  • Actually check that balance changed
  • Refactor to remove duplication of code between tests (all tests were the same but with different pairs)

Copy link

coderabbitai bot commented Oct 15, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes in this pull request introduce a new environment variable for the Peanut API in the .env.example file, enhancing the configuration for API interactions. Additionally, the src/consts/interfaces.consts.ts file has been modified to rename the IPrepareXchainRequestFulfillmentTransactionProps interface to IPrepareXchainRequestFulfillmentTransactionResponse, add a feeEstimation property, and introduce a new enum EGenericErrorCodes. The src/request.ts file has been updated to include optional APIKey properties in relevant interfaces and refactor the transaction preparation function. Test suites have been added and restructured for improved modularity and robustness.

Changes

File Change Summary
.env.example Added new environment variable: export PEANUT_API_URL="https://api.staging.peanut.to"
src/consts/interfaces.consts.ts Renamed interface: IPrepareXchainRequestFulfillmentTransactionPropsIPrepareXchainRequestFulfillmentTransactionResponse. Added property: feeEstimation: string. Added new enum: EGenericErrorCodes.
src/request.ts Updated interfaces to include optional APIKey. Changed IPrepareXchainRequestFulfillmentTransactionProps to a union type. Refactored functions to utilize normalizePath and destructure parameters.
src/util.ts Added new function: normalizePath(url: string): string.
test/basic/RequestLinkXChain.test.ts Introduced retry function for assertion retries. Restructured tests using it.each for parameterized testing.
test/unit/request.test.ts Added new test suite for request module with tests for createRequestLink, getRequestLinkDetails, and submitRequestLinkFulfillment.
test/unit/util.test.ts Added new test suite for normalizePath function with multiple test cases.
package.json Added script: "test:unit": "jest test/unit --silent --coverage". Updated "test:basic" script to run both unit and basic tests.

Possibly related PRs

  • Request Links #147: The changes in this PR introduce a new interface IPrepareXchainRequestFulfillmentTransactionProps and modify existing interfaces in src/consts/interfaces.consts.ts, which are directly related to the modifications made in the main PR regarding the IPrepareXchainRequestFulfillmentTransactionResponse interface and the addition of the feeEstimation property.

  • Changing fee estimation function #150: This PR updates the IPrepareXchainRequestFulfillmentTransactionProps interface to include a feeEstimation property, which aligns with the changes made in the main PR that also introduced this property, enhancing the transaction preparation process.

  • fix: resolve ens when preparing request xchain #154: This PR adds functionality to resolve ENS addresses when preparing cross-chain requests, which is relevant to the changes in the main PR that involve modifications to the request handling and transaction preparation processes.

Suggested reviewers

  • pawell24

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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Outside diff range and nitpick comments (3)
.env.example (1)

20-20: LGTM with suggestions for improvement

The addition of the PEANUT_API_URL variable is appropriate and aligns with the PR objectives. However, consider the following suggestions:

  1. Instead of hardcoding the staging URL, consider using a placeholder value (e.g., export PEANUT_API_URL="") to allow for environment-specific configurations.
  2. Add a comment above this line to explain the purpose of this URL and its usage in the application.

Here's a suggested modification:

+# URL for the Peanut API (e.g., https://api.staging.peanut.to for staging)
-export PEANUT_API_URL="https://api.staging.peanut.to"
+export PEANUT_API_URL=""
src/request.ts (1)

181-183: Consider improving error handling for missing API keys.

While the changes look good, I noticed that the createRequestLink and getRequestLinkDetails functions also use an APIKey parameter. To improve robustness, consider adding explicit error handling for cases where the API key is required but not provided.

Here's a suggestion for getRequestLinkDetails (apply similar logic to other functions):

export async function getRequestLinkDetails({
	link,
	APIKey,
	apiUrl = 'https://api.peanut.to/',
}: IGetRequestLinkDetailsProps): Promise<IGetRequestLinkDetailsResponse> {
	if (!APIKey) {
		throw new Error('API key is required for this operation');
	}

	// ... rest of the function
}

This change would provide clearer feedback when the API key is missing, improving the developer experience.

test/basic/RequestLinkXChain.test.ts (1)

9-19: Enhance Error Logging in the retry Function

The retry function is a useful utility for handling intermittent failures. To improve debugging, consider adding more informative error messages or logging within the retry mechanism. This will help identify the cause of failures when all retry attempts have been exhausted.

You might modify the catch block to log the error:

 try {
   await assertion()
   return
 } catch (err) {
   if (i === times - 1) throw err
+  console.warn(`Assertion failed on attempt ${i + 1}:`, err)
   await new Promise((resolve) => setTimeout(resolve, interval))
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 030a1f4 and 2fc4b6c.

📒 Files selected for processing (3)
  • .env.example (1 hunks)
  • src/request.ts (2 hunks)
  • test/basic/RequestLinkXChain.test.ts (1 hunks)
🧰 Additional context used
🔇 Additional comments (5)
src/request.ts (3)

181-183: LGTM: Function updated to use API key.

The prepareXchainRequestFulfillmentTransaction function has been correctly updated to accept and utilize the APIKey. The changes are consistent with the interface update and implement the PR objective.


Line range hint 1-383: Summary: Changes align with PR objectives, minor improvement suggested.

The modifications to src/request.ts successfully implement the PR objective of updating the prepareXchainRequestFulfillmentTransaction function to accept and utilize an API key. The changes are well-implemented and maintain consistency across the file.

A minor suggestion for improvement has been made regarding error handling for missing API keys, which would enhance the robustness of the SDK.

Overall, the changes look good and are ready for merging after addressing the suggested improvement.


49-49: LGTM: Interface update for API key.

The addition of the optional APIKey property to the IPrepareXchainRequestFulfillmentTransactionProps interface is a good change. It aligns with the PR objective and maintains backward compatibility.

To ensure consistency, let's verify if this interface is used elsewhere in the codebase:

✅ Verification successful

Verification Complete: APIKey Addition Approved.

The addition of the optional APIKey property to the IPrepareXchainRequestFulfillmentTransactionProps interface is safe and does not impact existing implementations.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for uses of IPrepareXchainRequestFulfillmentTransactionProps
rg --type typescript "IPrepareXchainRequestFulfillmentTransactionProps"

Length of output: 106


Script:

#!/bin/bash
# Search for uses of IPrepareXchainRequestFulfillmentTransactionProps with correct file type
rg --type ts "IPrepareXchainRequestFulfillmentTransactionProps"

Length of output: 386

test/basic/RequestLinkXChain.test.ts (2)

115-126: Handle Missing API Key and API URL in Function Call

In the call to prepareXchainRequestFulfillmentTransaction, the APIKey and apiUrl are provided. Ensure that the underlying function properly handles cases where these parameters might be undefined or invalid, to prevent unexpected errors.

Verify that the function gracefully handles missing or incorrect API credentials.

If needed, I can help review the prepareXchainRequestFulfillmentTransaction function to ensure robust error handling. Let me know if you'd like me to assist with this.


88-88: Ensure Unique Sender and Recipient Wallets

The sender and recipient wallets are derived from environment variables. To accurately test the transfer functionality, confirm that these wallets are not the same. Using the same wallet for both roles could mask issues in the transfer logic.

Run the following script to verify that the sender and recipient addresses are different:

This script checks that TEST_WALLET_PRIVATE_KEY and TEST_WALLET_PRIVATE_KEY2 correspond to different addresses.

@jjramirezn jjramirezn changed the title test: update request tests feat: improve requests usability Oct 17, 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: 2

🧹 Outside diff range and nitpick comments (16)
test/unit/util.test.ts (1)

5-12: Comprehensive test cases with room for expansion

The test cases cover a good range of scenarios for URL normalization, including trailing slashes, double slashes, and leading slashes. This is a solid foundation for testing the normalizePath function.

Consider adding a few more test cases to further improve coverage:

  1. A URL with query parameters (e.g., 'https://example.com/foo?bar=baz')
  2. A URL with a hash fragment (e.g., 'https://example.com/foo#section1')
  3. A URL with both query parameters and a hash fragment
  4. A URL with unusual characters that might need encoding
test/unit/request.test.ts (4)

14-35: LGTM: Well-structured test for createRequestLink

The test case for createRequestLink is well-implemented and verifies the correct URL construction when the API URL is not provided.

Consider adding additional test cases to cover:

  1. A scenario where the API URL is provided.
  2. Error handling for failed API responses.
  3. Validation of the request payload sent to the API.

37-63: LGTM: Comprehensive test for getRequestLinkDetails

The test case for getRequestLinkDetails is well-implemented, providing a thorough mock response and verifying the correct URL construction using the link UUID.

Consider the following improvements:

  1. Add a test case for when the API URL is provided.
  2. Include error handling tests for failed API responses or invalid UUIDs.
  3. Verify that the function correctly parses and returns the mock response data.

65-86: LGTM: Good test coverage for submitRequestLinkFulfillment

The test case for submitRequestLinkFulfillment correctly verifies the API URL construction and basic functionality.

Consider enhancing the test suite with:

  1. A test case for when the API URL is provided.
  2. Error handling tests for failed API responses or invalid input data.
  3. Verification of the request payload sent to the API, ensuring all required fields are included.
  4. A more comprehensive mock response to test proper handling of additional returned data.

1-87: Good test coverage, with room for improvement

The test file provides good coverage for the main functions of the request module, focusing on URL construction when the API URL is not provided. The use of Jest's mocking capabilities is effective and the tests are well-structured.

To further enhance the test suite, consider:

  1. Adding test cases for scenarios where the API URL is provided.
  2. Implementing error handling tests for each function.
  3. Including edge case tests (e.g., invalid inputs, network errors).
  4. Verifying the request payloads sent to the API in each test.
  5. Expanding mock responses to cover more fields and scenarios.
  6. Adding tests for any untested parameters or options in the functions.

These additions would provide more comprehensive coverage and align well with the PR objective of updating and improving the request tests.

package.json (1)

11-11: Good consolidation of tests, but consider renaming the script.

The modification to the test:basic script to include both unit and basic tests is a smart move for consolidation. It aligns well with the PR objective of reducing code duplication in tests.

However, the script name test:basic might now be misleading since it includes unit tests as well. Consider renaming this script to something more descriptive, such as test:all or test:unit-and-basic.

Here's a suggested change:

-		"test:basic": "npm run pkg-move && jest 'test/(unit|basic)' --silent --coverage",
+		"test:unit-and-basic": "npm run pkg-move && jest 'test/(unit|basic)' --silent --coverage",

This change would make the script name more accurately reflect its functionality.

test/basic/RequestLinkXChain.test.ts (3)

9-19: LGTM! Consider adding type annotations for improved readability.

The retry function is well-implemented and provides a useful mechanism for retrying asynchronous assertions. It correctly handles multiple attempts and throws the last error if all attempts fail.

Consider adding type annotations to improve readability:

const retry = async (
  assertion: () => Promise<void>,
  { times = 3, interval = 100 }: { times?: number; interval?: number } = {}
): Promise<void> => {
  // ... function body ...
}

22-160: Great refactoring! Consider extracting test data for improved maintainability.

The use of it.each for parameterized testing is an excellent improvement. It reduces code duplication and makes it easy to add new test scenarios. The consolidated test logic covers various token types and cross-chain scenarios effectively.

Consider extracting the test data into a separate constant or file. This would further improve maintainability and make it easier to manage test scenarios:

const TEST_SCENARIOS = [
  {
    amount: '0.1',
    sourceToken: { /* ... */ },
    destinationToken: { /* ... */ },
  },
  // ... other scenarios ...
];

it.each(TEST_SCENARIOS)(
  '$sourceToken.name to $destinationToken.name',
  async ({ amount, sourceToken, destinationToken }) => {
    // ... test logic ...
  }
);

Line range hint 162-254: Good addition of a new test case. Consider refactoring to reduce duplication.

The new test case for fetching link details when not provided is a valuable addition to the test suite. It covers an important scenario that wasn't tested before.

To reduce code duplication, consider extracting the common logic (especially the balance check) into a separate function that can be reused across test cases. For example:

async function verifyBalanceChange(
  destinationToken: TokenInfo,
  recipientAddress: string,
  amount: string
) {
  const initialBalance = await peanut.getTokenBalance({ /* ... */ });
  // ... perform transaction ...
  const numDigits = Math.floor(Math.log10(1 / Number(amount))) + 1;
  const expectedBalance = Number(initialBalance) + Number(amount);

  await retry(
    async () => {
      const finalBalance = await peanut.getTokenBalance({ /* ... */ });
      expect(Number(finalBalance)).toBeCloseTo(expectedBalance, numDigits);
    },
    { times: 15, interval: 2000 }
  );
}

// Use in both test cases
await verifyBalanceChange(destinationToken, recipientAddress, amount);

This refactoring would make the tests more maintainable and reduce the risk of inconsistencies between test cases.

src/request.ts (4)

39-59: LGTM: Refactored IPrepareXchainRequestFulfillmentTransactionProps

The transformation of IPrepareXchainRequestFulfillmentTransactionProps into a union type enhances the flexibility of the prepareXchainRequestFulfillmentTransaction function. This change allows for more versatile input handling, aligning well with the PR objectives of updating and refactoring the request tests.

Consider adding JSDoc comments to explain the purpose of each union type option, which would improve code readability and maintainability.


Line range hint 137-143: LGTM with suggestion: Updated createRequestLink function

The changes to createRequestLink function, including the use of normalizePath and the addition of the APIKey header, align well with the PR objectives and previous interface updates.

Consider adding a check for the presence of APIKey before using it in the header to avoid potential runtime errors:

- 'api-key': APIKey!,
+ 'api-key': APIKey || '',

This change would provide better error handling if the APIKey is not provided.


Line range hint 164-169: LGTM with suggestion: Updated getRequestLinkDetails function

The changes to getRequestLinkDetails function, including the use of normalizePath and the addition of the APIKey header, are consistent with the updates to createRequestLink and align well with the PR objectives.

Similar to the suggestion for createRequestLink, consider adding a check for the presence of APIKey before using it in the header:

- 'api-key': APIKey!,
+ 'api-key': APIKey || '',

This change would provide better error handling if the APIKey is not provided.


180-193: LGTM with suggestion: Refactored prepareXchainRequestFulfillmentTransaction function

The refactoring of prepareXchainRequestFulfillmentTransaction function aligns well with the updated IPrepareXchainRequestFulfillmentTransactionProps type. The changes improve the function's flexibility and maintainability, consistent with the PR objectives.

To improve code readability, consider using a type guard function to determine which structure is being used:

function isLinkProps(props: IPrepareXchainRequestFulfillmentTransactionProps): props is { link: string; apiUrl?: string; APIKey?: string } {
  return 'link' in props;
}

// Then in the function:
if (isLinkProps(props)) {
  const { link, apiUrl = 'https://api.peanut.to/', APIKey } = props;
  linkDetails = await getRequestLinkDetails({ link, apiUrl, APIKey });
} else {
  linkDetails = props.linkDetails;
}

This approach would make the code more type-safe and easier to understand.

Also applies to: 199-199

src/consts/interfaces.consts.ts (2)

Line range hint 170-174: LGTM! Consider using more specific types for numerical values.

The renaming and addition of new properties in the IPrepareXchainRequestFulfillmentTransactionResponse interface improve its clarity and provide more detailed information about cross-chain transactions. This is a positive change that enhances the SDK's functionality.

Consider using more specific types for feeEstimation and estimatedFromAmount. While strings offer flexibility, using BigNumber from ethers.js might provide better precision and type safety for financial calculations. For example:

import { BigNumber } from 'ethers'

export interface IPrepareXchainRequestFulfillmentTransactionResponse {
  unsignedTxs: IPeanutUnsignedTransaction[]
  feeEstimation: BigNumber
  estimatedFromAmount: BigNumber
}

This change would ensure type consistency with other parts of the SDK and prevent potential issues with string-to-number conversions.


Line range hint 570-579: LGTM! Consider adding documentation for the new error codes.

The addition of the EGenericErrorCodes enum and its integration into the allErrorEnums type and SDKStatus class is a great improvement to the error handling system. This change will allow for more specific and informative error reporting, which is crucial for debugging and user experience.

To further enhance the usability of these new error codes, consider adding brief documentation comments for each error code in the EGenericErrorCodes enum. This will help developers understand when and why each error might occur. For example:

export enum EGenericErrorCodes {
  /** A general error that doesn't fit into other categories */
  GENERIC_ERROR,
  /** The specified blockchain is not supported by the SDK */
  ERROR_UNSUPPORTED_CHAIN,
  /** The provided name exceeds the maximum allowed length */
  ERROR_NAME_TOO_LONG,
  /** The input contains prohibited symbols */
  ERROR_PROHIBITED_SYMBOL,
  /** Failed to retrieve the token balance */
  ERROR_GETTING_TOKENBALANCE,
  /** The specified token is not supported by the SDK */
  ERROR_UNSUPPORTED_TOKEN,
  // Add more generic error codes here if needed
}

These comments will appear in IDE tooltips, making it easier for developers to understand and use the error codes correctly.

Also applies to: 583-583, 590-638

src/util.ts (1)

757-757: Consider adding a brief documentation comment for the normalizePath function.

To improve code readability and maintainability, it would be helpful to add a brief JSDoc comment explaining the purpose and usage of the normalizePath function. This will make it easier for other developers to understand and use the function correctly.

Here's a suggested comment you could add above the function:

/**
 * Normalizes a URL or path by replacing multiple consecutive slashes with a single slash.
 * @param url - The URL or path to normalize
 * @returns The normalized URL or path as a string
 */
export function normalizePath(url: string): string {
  // ... (existing implementation)
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 2fc4b6c and e7c87e5.

📒 Files selected for processing (7)
  • package.json (1 hunks)
  • src/consts/interfaces.consts.ts (1 hunks)
  • src/request.ts (6 hunks)
  • src/util.ts (1 hunks)
  • test/basic/RequestLinkXChain.test.ts (2 hunks)
  • test/unit/request.test.ts (1 hunks)
  • test/unit/util.test.ts (1 hunks)
🧰 Additional context used
📓 Learnings (1)
test/basic/RequestLinkXChain.test.ts (1)
Learnt from: jjramirezn
PR: peanutprotocol/peanut-sdk#157
File: test/basic/RequestLinkXChain.test.ts:143-145
Timestamp: 2024-10-16T16:53:52.383Z
Learning: In `test/basic/RequestLinkXChain.test.ts`, the calculation of `numDigits` using `Math.floor(Math.log10(1 / Number(amount))) + 1` is intentional and determines how close the numbers must be to pass the test.
🔇 Additional comments (15)
test/unit/util.test.ts (3)

1-4: Well-structured test suite

The import statement and overall structure of the test suite are well-organized and follow best practices for Jest testing.


13-15: Correct test assertion

The test assertion expect(normalizePath(url)).toBe(normalizedUrl) is correctly implemented and follows Jest's best practices for comparing expected and actual values.


1-17: Overall excellent test implementation

This test file for the normalizePath function is well-implemented, with a clear structure, comprehensive test cases, and correct assertions. It provides a solid foundation for ensuring the reliability of the normalizePath function.

The use of it.each for multiple test cases is an efficient approach, making the tests easy to read and maintain. The variety of URL scenarios covered demonstrates thorough consideration of different use cases.

While the current test cases are good, consider adding a few more edge cases as suggested earlier to further enhance the test coverage.

test/unit/request.test.ts (1)

1-12: LGTM: Proper test setup and mocking

The import statement and mock setup are well-implemented. The use of beforeEach and afterEach hooks ensures proper isolation between tests and cleanup of mocks.

package.json (2)

10-10: Excellent addition of a dedicated unit test script!

The new test:unit script is a valuable addition to the project's testing infrastructure. It allows for running unit tests separately, which can speed up the development process and make it easier to focus on specific test types.

The use of the --silent and --coverage flags is also commendable, as it provides a cleaner output and generates useful code coverage information.


10-11: Overall improvement to testing infrastructure

These changes to the testing scripts in package.json represent a significant improvement to the project's testing infrastructure. They align well with the PR objectives of updating request tests and eliminating code duplication.

The addition of a dedicated unit test script and the consolidation of unit and basic tests provide more flexibility and efficiency in the testing process. These improvements will likely lead to better code quality and easier maintenance in the long run.

Great job on enhancing the testing capabilities of the project!

test/basic/RequestLinkXChain.test.ts (2)

141-157: Effective balance check implementation with retry mechanism.

The balance check implementation using the retry function improves the test's reliability by accommodating potential delays in transaction finalization. The calculation of numDigits is intentional and determines the precision for the balance comparison.

As per the previous discussion, the current retry parameters (15 attempts, 2000ms interval) allowing for up to 30 seconds of retries are considered sufficient.


Line range hint 1-254: Overall, excellent improvements to the test suite.

The refactoring and additions to this test file have significantly enhanced its maintainability, reliability, and coverage. The introduction of the retry function, use of parameterized testing with it.each, and the new test case for fetching link details are all valuable improvements.

While there are some opportunities for further refactoring to reduce duplication and improve organization, the current state of the file is a substantial step forward. Great work on improving the test suite!

src/request.ts (4)

5-5: LGTM: Addition of APIKey to ICreateRequestLinkProps

The addition of the optional APIKey property to the ICreateRequestLinkProps interface enhances the flexibility of API authentication. This change aligns well with the PR objectives of updating the request tests to use an API key.

Also applies to: 22-22


Line range hint 24-28: LGTM: Addition of APIKey to IGetRequestLinkDetailsProps

The addition of the optional APIKey property to the IGetRequestLinkDetailsProps interface is consistent with the previous interface update and the PR objectives. This change enhances the flexibility of API authentication for getting request link details.


394-394: LGTM: Updated submitRequestLinkFulfillment function

The update to submitRequestLinkFulfillment function, incorporating the use of normalizePath, ensures consistent URL formatting. This change is in line with the updates made to other functions in the file.


Line range hint 1-426: Overall assessment: Well-structured and consistent changes

The changes in this file are well-aligned with the PR objectives. The refactoring of interfaces and functions improves code flexibility and maintainability. The consistent use of normalizePath and the addition of APIKey handling enhance the robustness of the API interactions.

A few minor suggestions have been made to further improve error handling and code readability. These suggestions are not critical and can be addressed in a follow-up PR if desired.

src/consts/interfaces.consts.ts (1)

Line range hint 1-638: Overall, these changes significantly improve the SDK's functionality and error handling.

The modifications to the IPrepareXchainRequestFulfillmentTransactionResponse interface and the introduction of the EGenericErrorCodes enum represent substantial improvements to the Peanut SDK. These changes enhance cross-chain transaction handling and provide more detailed error reporting, which will benefit both developers using the SDK and end-users of applications built with it.

The renaming of the interface from "Props" to "Response" clarifies its purpose, and the additional properties provide valuable transaction details. The new generic error codes allow for more precise error handling across various scenarios.

These updates demonstrate a commitment to improving the SDK's usability, maintainability, and robustness. Great work on these enhancements!

src/util.ts (2)

757-766: LGTM: New normalizePath function added to handle URL path normalization.

The normalizePath function is a useful addition that normalizes URL paths by replacing multiple consecutive slashes with a single slash. It handles both full URLs and path-only strings, making it versatile for various use cases within the SDK.

Some observations:

  1. The function correctly uses a try-catch block to handle both full URLs and path-only strings.
  2. The regular expression /\/+/g efficiently replaces multiple slashes with a single slash.
  3. The error handling assumes any failure in URL creation means the input is a path-only string, which is a reasonable approach.

757-766: Overall assessment: Approved with minor suggestions for improvement.

The addition of the normalizePath function is a valuable enhancement to the utility file. It provides a standardized way to handle URL and path normalization, which can improve consistency across the SDK. The implementation is sound and doesn't introduce any breaking changes.

To further improve this addition:

  1. Consider adding a brief documentation comment as suggested earlier.
  2. Enhance the error handling to make the function more robust.
  3. Review the broader codebase to identify potential uses for this new function and ensure consistent URL/path handling.

These minor improvements will make the normalizePath function even more valuable and easier to maintain in the long run.

@jjramirezn
Copy link
Contributor Author

Deployment notes

This was tested with peanut-ui and related flows (creating and paying request link) and it works, a PR will be created on ui to use the new linkDetails param for prepare xchain when this is deployed.

The changes are: MINOR

Changes

Fixes

  • On request functions now we normalize the urls we get as api url to be more robust (handle double slashes)
  • When preparing xchain request transaction we now accept the link details as a parameter instead of link, apiurl and apikey. This makes sense because in the usual flows the link details will be fetched before preparing the txs (for showing to an user for example)

Changes in Testing

  • Moved unit test to their own dir in order to be able to run them alone (ideally to start writing unit tests when it make sense and having a 0 cost suite of tests in the sdk)

@Hugo0 Hugo0 changed the title feat: improve requests usability [TASK-6263] feat: improve requests usability Oct 17, 2024
Copy link

Copy link
Contributor

@Hugo0 Hugo0 left a comment

Choose a reason for hiding this comment

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

very nice!

@Hugo0 Hugo0 merged commit caa5c39 into develop Oct 17, 2024
@jjramirezn jjramirezn deleted the test/update-request-tests branch October 17, 2024 16:27
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