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

feat(rest-api): /destinationTx returns status of refunded when RFQ transaction has been refunded [SLT-350] #3307

Merged
merged 7 commits into from
Oct 18, 2024

Conversation

abtestingalpha
Copy link
Collaborator

@abtestingalpha abtestingalpha commented Oct 17, 2024

  • Returns refunded status alongside response when RFQ transaction has been refunded
  • Returns 404 when neither fromInfo or toInfo are found
  • General refactoring and cleanup of destinationTx controller into utils and serializers
  • Remove detailed stack errors from 500 response as they exist in logging
  • Refactored graphql queries with query constructor and fetch util

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Introduced new constants for the OmniRPC GraphQL explorer URL and a mapping for Fast Bridge Router addresses based on chain IDs.
    • Added a new utility function for fetching bridge transaction details, streamlining data retrieval processes.
    • Implemented a new function to construct GraphQL queries for bridge transactions, enhancing flexibility in data requests.
  • Bug Fixes

    • Improved error handling by updating response structures in transaction status controllers.
  • Tests

    • Expanded test coverage for transaction-related functionalities, ensuring robust error handling and response validation.

Copy link
Contributor

coderabbitai bot commented Oct 17, 2024

Walkthrough

The changes introduce new constants and utility functions to enhance the handling of bridge transactions within the application. Two constants, EXPLORER_GRAPHQL_URL and FAST_BRIDGE_ROUTER_ADDRESS_MAP, are added for improved configuration. The bridgeTxStatusController and destinationTxController functions have been refactored to utilize a new utility function, fetchBridgeTransaction, for retrieving transaction details. Additionally, a new function, constructBridgeTransactionsQuery, is introduced to streamline GraphQL query construction for bridge transactions.

Changes

File Path Change Summary
packages/rest-api/src/constants/index.ts Added constants EXPLORER_GRAPHQL_URL and FAST_BRIDGE_ROUTER_ADDRESS_MAP.
packages/rest-api/src/controllers/bridgeTxStatusController.ts Refactored to use fetchBridgeTransaction for fetching transaction details, modified error response structure.
packages/rest-api/src/controllers/destinationTxController.ts Refactored to use fetchBridgeTransaction, improved response handling and transaction status logic.
packages/rest-api/src/utils/constructBridgeTransactionsQuery.ts Introduced constructBridgeTransactionsQuery to create GraphQL query strings for bridge transactions.
packages/rest-api/src/utils/fetchBridgeTransaction.ts Introduced fetchBridgeTransaction for asynchronous fetching of bridge transaction details via GraphQL.

Possibly related PRs

Suggested labels

size/m, needs-yarn-install, M-deps

Suggested reviewers

  • trajan0x
  • Defi-Moses

🐰 In the land of bridges, we hop and play,
New constants and functions brighten our day!
With statuses clear and paths that align,
Our transactions now flow, oh how they shine!
So let’s celebrate this code, oh so bright,
With a leap and a bound, we’ll take flight! 🌟


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.

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

codecov bot commented Oct 17, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 35.14833%. Comparing base (6880ddd) to head (3b5a684).
Report is 11 commits behind head on master.

❗ There is a different number of reports uploaded between BASE (6880ddd) and HEAD (3b5a684). Click for more details.

HEAD has 3 uploads less than BASE
Flag BASE (6880ddd) HEAD (3b5a684)
promexporter 1 0
solidity 2 0
Additional details and impacted files
@@                 Coverage Diff                 @@
##              master       #3307         +/-   ##
===================================================
- Coverage   44.38046%   35.14833%   -9.23213%     
===================================================
  Files            137          77         -60     
  Lines           5383        2663       -2720     
  Branches         356          82        -274     
===================================================
- Hits            2389         936       -1453     
+ Misses          2979        1722       -1257     
+ Partials          15           5         -10     
Flag Coverage Δ
packages 90.44834% <ø> (ø)
promexporter ?
solidity ?

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link

cloudflare-workers-and-pages bot commented Oct 17, 2024

Deploying sanguine-fe with  Cloudflare Pages  Cloudflare Pages

Latest commit: 3b5a684
Status: ✅  Deploy successful!
Preview URL: https://d27505d6.sanguine-fe.pages.dev
Branch Preview URL: https://rest-api-refund-status.sanguine-fe.pages.dev

View logs

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

🧹 Outside diff range and nitpick comments (13)
packages/rest-api/src/constants/enums.ts (1)

1-7: LGTM! Consider adding documentation and explicit values.

The BridgeStatus enum is well-structured and aligns with the PR objectives. It correctly includes the new REFUNDED status as mentioned in the PR title.

To improve maintainability and clarity, consider the following suggestions:

  1. Add JSDoc comments to describe what each status represents. This will help other developers understand the lifecycle of a bridge transaction.

  2. Consider assigning explicit values to each enum member. While the current auto-incrementing behavior works, explicit values can provide more control and stability, especially if the order or number of statuses might change in the future.

Here's an example of how you could implement these suggestions:

/**
 * Represents the various states of a bridge transaction.
 */
export enum BridgeStatus {
  /** Initial state or unknown status */
  NULL = 0,
  /** Transaction has been requested but not yet processed */
  REQUESTED = 1,
  /** Relayer has proved the transaction */
  RELAYER_PROVED = 2,
  /** Relayer has claimed the transaction */
  RELAYER_CLAIMED = 3,
  /** Transaction has been refunded */
  REFUNDED = 4,
}
packages/rest-api/src/utils/fetchBridgeTransaction.ts (1)

1-4: Consider adding a return type for improved type safety.

The function signature looks good, but adding an explicit return type would enhance type safety and make the function's contract clearer.

Consider updating the function signature as follows:

export const fetchBridgeTransaction = async (
  originChainId: number | string,
  txHash: string
): Promise<any> => {
  // ... function body ...
}

Replace any with a more specific type that matches the expected structure of the GraphQL response for even better type safety.

packages/rest-api/src/tests/destinationTxRoute.test.ts (4)

19-19: LGTM! Consider adding a test description.

The new assertion for checking the 'completed' status enhances the test coverage and aligns with the PR objective. Good job!

Consider adding a description to the test case to clarify its purpose:

-  it('should return destination transaction info for valid input', async () => {
+  it('should return destination transaction info with completed status for valid input', async () => {

33-56: Excellent addition! Consider using constants for consistency.

The new test case for refunded transactions is well-structured and covers the expected behavior. It aligns perfectly with the PR objective.

For consistency and maintainability, consider using constants for the status values:

+ const COMPLETED_STATUS = 'completed';
+ const REFUNDED_STATUS = 'refunded';

  it('should return a refunded response for refunded transaction', async () => {
    // ... (existing code)
    expect(response.status).toBe(200)
    expect(response.body).toHaveProperty('status')
-   expect(response.body.status).toBe('refunded')
+   expect(response.body.status).toBe(REFUNDED_STATUS)
    // ... (rest of the test)
  }, 10000)

This approach would make it easier to update status values across all tests if needed in the future.


58-67: Great addition! Consider increasing the timeout for consistency.

The new test case for non-existent transaction hashes is a valuable addition, ensuring proper error handling for edge cases.

For consistency with other tests in this file, consider increasing the timeout to 10000ms:

-  }, 10000)
+  }, 10000)

This change ensures that all tests have the same timeout, which can help prevent potential issues with slower test environments.


Line range hint 1-67: Overall, excellent additions to the test suite!

The new test cases for refunded transactions and non-existent transaction hashes, along with the enhanced assertion for completed transactions, significantly improve the test coverage. These changes align well with the PR objectives and contribute to a more robust API.

If you'd like assistance in implementing any of the suggested improvements or adding more test cases, please let me know. Great job on enhancing the test suite!

packages/rest-api/src/constants/abis/fastBridgeRouter.json (3)

69-160: Consider adding inline documentation for the bridge function.

The bridge function is complex with multiple parameters and nested structures. To improve readability and maintainability, consider adding inline comments or natspec documentation explaining the purpose of each parameter and the overall function logic.


30-68: Clarify the usage of rawParams in the adapterSwap function.

The adapterSwap function uses a rawParams parameter of type bytes. It would be helpful to add a comment explaining the expected format and content of this parameter for better understanding and proper usage.


347-386: LGTM: Custom error definitions are comprehensive and gas-efficient.

The custom error definitions cover various failure scenarios specific to the contract's functionality. Using custom errors is a gas-efficient way to handle exceptions in Solidity contracts. The error names are descriptive, which is good for understanding the reason for reverts.

Consider adding brief comments for each error to provide more context on when they are thrown, especially for less obvious cases like TokenAddressMismatch or TokensIdentical.

packages/rest-api/src/constants/abis/fastBridge.json (1)

807-850: Custom errors are well-defined and cover various failure scenarios.

The ABI includes a comprehensive set of custom errors, which is a gas-efficient way to provide informative error messages. These errors cover various scenarios including access control issues, parameter validation, and invalid state transitions.

Positive aspects:

  1. Use of custom errors instead of revert strings for gas efficiency.
  2. Errors cover a wide range of potential issues, aiding in debugging and providing clear feedback.
  3. Some errors include parameters (e.g., AccessControlUnauthorizedAccount), offering more context about the error condition.

Suggestion for improvement:
Consider adding more specific errors for bridge-related operations. For example, you could add errors like InsufficientBridgeLiquidity or BridgeRequestExpired to provide more precise information about why a bridge operation might fail.

Here's an example of how you could add more specific bridge-related errors:

+  {
+    "type": "error",
+    "name": "InsufficientBridgeLiquidity",
+    "inputs": [
+      { "name": "requested", "type": "uint256", "internalType": "uint256" },
+      { "name": "available", "type": "uint256", "internalType": "uint256" }
+    ]
+  },
+  {
+    "type": "error",
+    "name": "BridgeRequestExpired",
+    "inputs": [
+      { "name": "expirationTime", "type": "uint256", "internalType": "uint256" },
+      { "name": "currentTime", "type": "uint256", "internalType": "uint256" }
+    ]
+  },
   { "type": "error", "name": "ZeroAddress", "inputs": [] }
 ]

These additional errors would provide more specific information about why a bridge operation might fail, improving the debugging process and user experience.

packages/rest-api/src/utils/getBridgeStatus.ts (1)

33-33: Validate kappa input format

While you check if kappa starts with '0x', it may be beneficial to validate that kappa is a valid hexadecimal string of the expected length to prevent errors downstream.

packages/rest-api/src/controllers/destinationTxController.ts (2)

28-32: Simplify Payload by Omitting Null Fields

Including fromInfo and toInfo as null in the payload may not be necessary and could clutter the response. Consider omitting these fields when they are null to simplify the payload.

Apply this diff to remove fromInfo and toInfo when they are null:

          payload = {
            status: 'not found',
-           fromInfo,
-           toInfo,
          }

15-15: Limit Scope of payload Variable

Since payload is only used within the try block, declaring it inside the block limits its scope and improves code readability.

Apply this diff to move payload inside the try block:

- let payload = {}

  try {
+   let payload = {}
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 6415acd and 0bbf24c.

📒 Files selected for processing (9)
  • packages/rest-api/src/constants/abis/fastBridge.json (1 hunks)
  • packages/rest-api/src/constants/abis/fastBridgeRouter.json (1 hunks)
  • packages/rest-api/src/constants/enums.ts (1 hunks)
  • packages/rest-api/src/constants/index.ts (1 hunks)
  • packages/rest-api/src/controllers/destinationTxController.ts (1 hunks)
  • packages/rest-api/src/serializers/serializeBridgeInfo.ts (1 hunks)
  • packages/rest-api/src/tests/destinationTxRoute.test.ts (2 hunks)
  • packages/rest-api/src/utils/fetchBridgeTransaction.ts (1 hunks)
  • packages/rest-api/src/utils/getBridgeStatus.ts (1 hunks)
🧰 Additional context used
🔇 Additional comments (10)
packages/rest-api/src/serializers/serializeBridgeInfo.ts (2)

1-4: LGTM: Imports are relevant and concise.

The imported libraries and utility functions are appropriate for the task at hand. Good job keeping the imports minimal and focused.


1-19: Overall assessment: Good implementation with room for improvement.

The serializeBridgeInfo function effectively processes and formats bridge transaction information. However, consider implementing the suggested improvements to enhance type safety, error handling, and code clarity. These changes will make the code more robust and maintainable in the long run.

packages/rest-api/src/constants/index.ts (1)

31-41: Verify the correctness of FAST_BRIDGE_ROUTER_ADDRESS_MAP

The new constant FAST_BRIDGE_ROUTER_ADDRESS_MAP has been added, but there are a couple of points that need attention:

  1. All addresses in the map are identical ('0x00cD000000003f7F682BE4813200893d4e690000'). Please verify if this is intentional or if unique addresses should be assigned for each chain.

  2. Some chain IDs present in SUPPORTED_SWAP_CHAIN_IDS are missing from this new map (e.g., AURORA, AVALANCHE, FANTOM). Consider if these should be included or if there's a reason for their exclusion.

To help verify the correctness of the addresses, you can run the following script:

packages/rest-api/src/constants/abis/fastBridgeRouter.json (2)

1-12: LGTM: Constructor definition is appropriate.

The constructor is well-defined with a single owner_ parameter of type address. This is a good practice for setting up the initial owner of the contract.


302-346: LGTM: Event definitions are well-structured.

The event definitions for FastBridgeSet, OwnershipTransferred, and SwapQuoterSet are appropriate for logging important state changes. The use of indexed parameters in OwnershipTransferred is a good practice for efficient event filtering.

packages/rest-api/src/constants/abis/fastBridge.json (4)

1-8: Constructor looks good.

The constructor is correctly defined with an _owner parameter, which is a common pattern for setting up initial ownership of the contract. The nonpayable state mutability is appropriate for a constructor.


9-15: View functions are well-defined and comprehensive.

The ABI includes a wide range of view functions that provide read-only access to important contract state and configuration. These functions cover roles (e.g., DEFAULT_ADMIN_ROLE, GOVERNOR_ROLE), constants (e.g., DISPUTE_PERIOD, FEE_BPS), and state readers (e.g., bridgeProofs, bridgeStatuses). The use of view state mutability is correct, ensuring these functions don't modify the contract state.

Particularly noteworthy is the getBridgeTransaction function, which provides a comprehensive view of a bridge transaction's details. This function will be crucial for off-chain services to retrieve and verify transaction information.

Also applies to: 16-22, 23-29, 30-36, 37-43, 44-50, 51-57, 58-64, 65-71, 72-78, 124-132, 133-139, 140-152, 153-166, 167-173, 184-190, 204-272, 273-281, 282-291, 292-300, 311-320, 321-327, 328-334, 335-341, 416-424


1-851: Overall, the FastBridge ABI is well-designed and comprehensive.

This ABI provides a complete interface for interacting with the FastBridge contract, covering all necessary aspects including the constructor, view and state-changing functions, events, and custom errors.

Key strengths:

  1. Comprehensive set of functions for both core bridge operations and administrative tasks.
  2. Well-structured events that provide a detailed audit trail of contract activities.
  3. Use of custom errors for gas-efficient and informative error handling.
  4. Proper use of state mutability specifiers (view, payable, nonpayable).

Recommendations:

  1. Ensure that access control is properly implemented in the contract code, especially for administrative functions.
  2. Consider adding more specific bridge-related errors as suggested earlier.
  3. Thoroughly test all functions, especially those involving cross-chain operations, to ensure they behave as expected in various scenarios.

This ABI forms a solid foundation for a cross-chain bridge contract. When implementing the contract, pay close attention to security best practices, especially around access control and handling of user funds.


435-471: Events are well-defined and provide a comprehensive audit trail.

The ABI includes a robust set of events that cover all major operations and state changes in the contract. These events are crucial for off-chain services to track and react to on-chain activities.

Key points:

  1. Events cover bridge operations (e.g., BridgeRequested, BridgeRelayed, BridgeDepositClaimed) and administrative actions (e.g., RoleGranted, FeeRateUpdated).
  2. Proper use of indexing for key parameters (e.g., transactionId, sender, relayer) allows for efficient event filtering.
  3. Events include all relevant information about each action, providing a detailed audit trail.

These events will be invaluable for monitoring the bridge's activities, reconciling cross-chain transactions, and maintaining an off-chain record of administrative changes. Ensure that these events are emitted at the appropriate points in the contract's functions.

To verify the correct emission of events, you can run the following script:

#!/bin/bash
# Check for event emissions in the contract implementation
ast-grep --lang solidity --pattern 'function $FUNC_NAME($_) $_ {
  $$$
  emit $EVENT_NAME($$$);
  $$$
}'

This script will help identify functions that emit events, ensuring that all important actions are properly logged.

Also applies to: 472-502, 503-521, 522-546, 547-607, 608-668, 669-687, 688-706, 707-731, 732-756, 757-781, 782-806

packages/rest-api/src/controllers/destinationTxController.ts (1)

68-71: Verify That Logged Payload Does Not Contain Sensitive Information

When logging payload, ensure it does not include any sensitive user information that should not be recorded.

Run the following script to check for sensitive data in the payload:

packages/rest-api/src/serializers/serializeBridgeInfo.ts Outdated Show resolved Hide resolved
packages/rest-api/src/utils/fetchBridgeTransaction.ts Outdated Show resolved Hide resolved
packages/rest-api/src/utils/fetchBridgeTransaction.ts Outdated Show resolved Hide resolved
packages/rest-api/src/utils/fetchBridgeTransaction.ts Outdated Show resolved Hide resolved
packages/rest-api/src/utils/getBridgeStatus.ts Outdated Show resolved Hide resolved
packages/rest-api/src/utils/getBridgeStatus.ts Outdated Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 4

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 0bbf24c and a92b71e.

📒 Files selected for processing (1)
  • packages/rest-api/src/routes/destinationTxRoute.ts (3 hunks)
🧰 Additional context used
🔇 Additional comments (1)
packages/rest-api/src/routes/destinationTxRoute.ts (1)

37-39: Update All References to status Type Change

The status property's type has been changed from boolean to string. Ensure that all parts of the documentation and codebase that reference status are updated accordingly to reflect this change. This is important so that consumers of the API are aware of the new possible string values for status.

packages/rest-api/src/routes/destinationTxRoute.ts Outdated Show resolved Hide resolved
packages/rest-api/src/routes/destinationTxRoute.ts Outdated Show resolved Hide resolved
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: 9

🧹 Outside diff range and nitpick comments (4)
packages/rest-api/src/types/index.d.ts (2)

37-41: LGTM! Consider adding JSDoc comments.

The BridgeTransaction interface is well-structured and clearly represents a cross-chain transaction. The use of fromInfo and toInfo of type BridgeTransactionInfo provides a clear separation of source and destination information.

Consider adding JSDoc comments to explain the purpose of each property, especially kappa. This would enhance code readability and maintainability. For example:

export interface BridgeTransaction {
  /** Unique identifier for the bridge transaction */
  kappa: string;
  /** Information about the source of the transaction */
  fromInfo: BridgeTransactionInfo;
  /** Information about the destination of the transaction */
  toInfo: BridgeTransactionInfo;
}

43-53: LGTM! Consider adding optional properties and JSDoc comments.

The BridgeTransactionInfo interface provides comprehensive information about a transaction on a specific chain. The properties cover essential details such as chain ID, addresses, transaction hash, values, and timing information.

Consider the following suggestions to enhance the interface:

  1. Add JSDoc comments to explain the purpose of each property, especially for less obvious ones like USDValue.

  2. Consider making some properties optional with the ? operator, as they might not always be available immediately (e.g., blockNumber or formattedTime might not be known until the transaction is confirmed).

Here's an example of how you could implement these suggestions:

export interface BridgeTransactionInfo {
  /** ID of the blockchain where the transaction occurred */
  chainID: number;
  /** Address involved in the transaction (sender or recipient) */
  address: string;
  /** Transaction hash */
  txnHash: string;
  /** Transaction amount in the native token */
  value: string;
  /** Transaction amount converted to USD */
  USDValue: string;
  /** Symbol of the token involved in the transaction */
  tokenSymbol: string;
  /** Contract address of the token */
  tokenAddress: string;
  /** Block number where the transaction was included (optional) */
  blockNumber?: number;
  /** Formatted timestamp of the transaction (optional) */
  formattedTime?: string;
}

These changes would improve code documentation and allow for more flexible use of the interface.

packages/rest-api/src/utils/fetchBridgeTransaction.ts (1)

1-6: Add explicit return type to the function signature.

For improved type safety and code readability, consider adding an explicit return type to the fetchBridgeTransaction function. This will make the function's contract clearer and help prevent potential type-related bugs.

Here's the suggested change:

 export const fetchBridgeTransaction = async (
   originChainId: number | string,
   txHash: string
-) => {
+): Promise<BridgeTransaction | null> => {

This change clearly indicates that the function returns a Promise that resolves to either a BridgeTransaction object or null.

packages/rest-api/src/routes/destinationTxRoute.ts (1)

137-151: LGTM with suggestion: 404 response added

The addition of the 404 response schema aligns with the PR objectives and correctly uses nullable: true for fromInfo and toInfo. This addresses the previous comment about the correct way to indicate nullable properties.

To improve consistency and reduce duplication, consider referencing the existing schemas for fromInfo and toInfo:

 *               properties:
 *                 status:
 *                   type: string
 *                 fromInfo:
-*                   type: object
+*                   $ref: '#/components/schemas/FromInfo'
 *                   nullable: true
 *                 toInfo:
-*                   type: object
+*                   $ref: '#/components/schemas/ToInfo'
 *                   nullable: true

This assumes that FromInfo and ToInfo are defined in your components schemas. If not, you should define them there.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between a92b71e and 2a794cb.

📒 Files selected for processing (25)
  • packages/rest-api/src/controllers/bridgeController.ts (0 hunks)
  • packages/rest-api/src/controllers/bridgeLimitsController.ts (0 hunks)
  • packages/rest-api/src/controllers/bridgeTxInfoController.ts (0 hunks)
  • packages/rest-api/src/controllers/bridgeTxStatusController.ts (0 hunks)
  • packages/rest-api/src/controllers/destinationTokensController.ts (0 hunks)
  • packages/rest-api/src/controllers/destinationTxController.ts (1 hunks)
  • packages/rest-api/src/controllers/indexController.ts (0 hunks)
  • packages/rest-api/src/controllers/swapController.ts (0 hunks)
  • packages/rest-api/src/controllers/swapTxInfoController.ts (0 hunks)
  • packages/rest-api/src/controllers/synapseTxIdController.ts (0 hunks)
  • packages/rest-api/src/routes/bridgeLimitsRoute.ts (0 hunks)
  • packages/rest-api/src/routes/bridgeRoute.ts (0 hunks)
  • packages/rest-api/src/routes/bridgeTxInfoRoute.ts (0 hunks)
  • packages/rest-api/src/routes/bridgeTxStatusRoute.ts (0 hunks)
  • packages/rest-api/src/routes/destinationTokensRoute.ts (0 hunks)
  • packages/rest-api/src/routes/destinationTxRoute.ts (3 hunks)
  • packages/rest-api/src/routes/indexRoute.ts (0 hunks)
  • packages/rest-api/src/routes/swapRoute.ts (0 hunks)
  • packages/rest-api/src/routes/swapTxInfoRoute.ts (0 hunks)
  • packages/rest-api/src/routes/synapseTxIdRoute.ts (0 hunks)
  • packages/rest-api/src/routes/tokenListRoute.ts (0 hunks)
  • packages/rest-api/src/serializers/serializeBridgeInfo.ts (1 hunks)
  • packages/rest-api/src/types/index.d.ts (1 hunks)
  • packages/rest-api/src/utils/fetchBridgeTransaction.ts (1 hunks)
  • packages/rest-api/src/utils/getBridgeStatus.ts (1 hunks)
💤 Files with no reviewable changes (19)
  • packages/rest-api/src/controllers/bridgeController.ts
  • packages/rest-api/src/controllers/bridgeLimitsController.ts
  • packages/rest-api/src/controllers/bridgeTxInfoController.ts
  • packages/rest-api/src/controllers/bridgeTxStatusController.ts
  • packages/rest-api/src/controllers/destinationTokensController.ts
  • packages/rest-api/src/controllers/indexController.ts
  • packages/rest-api/src/controllers/swapController.ts
  • packages/rest-api/src/controllers/swapTxInfoController.ts
  • packages/rest-api/src/controllers/synapseTxIdController.ts
  • packages/rest-api/src/routes/bridgeLimitsRoute.ts
  • packages/rest-api/src/routes/bridgeRoute.ts
  • packages/rest-api/src/routes/bridgeTxInfoRoute.ts
  • packages/rest-api/src/routes/bridgeTxStatusRoute.ts
  • packages/rest-api/src/routes/destinationTokensRoute.ts
  • packages/rest-api/src/routes/indexRoute.ts
  • packages/rest-api/src/routes/swapRoute.ts
  • packages/rest-api/src/routes/swapTxInfoRoute.ts
  • packages/rest-api/src/routes/synapseTxIdRoute.ts
  • packages/rest-api/src/routes/tokenListRoute.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/rest-api/src/serializers/serializeBridgeInfo.ts
🧰 Additional context used
🪛 Biome
packages/rest-api/src/utils/fetchBridgeTransaction.ts

[error] 53-54: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (14)
packages/rest-api/src/types/index.d.ts (1)

Line range hint 1-53: Verify the impact of removed BridgeableToken constants.

The AI summary mentioned the removal of several BridgeableToken constants (e.g., AGEUR, AVAX, BTCB, etc.). While these removals are not visible in the provided code snippet, it's important to verify that this change doesn't negatively impact other parts of the codebase.

Please run the following script to check for any remaining references to the removed constants:

If any references are found, please ensure they are updated or removed as necessary.

packages/rest-api/src/utils/getBridgeStatus.ts (3)

1-8: LGTM: Imports and cache initialization look good.

The necessary dependencies are imported, and the provider cache is initialized using a Map. This is a good optimization to avoid creating new providers for each call.


17-22: LGTM: Effective provider caching implementation.

The caching logic for the JsonRpcProvider is well-implemented. This addresses the performance concern by reusing provider instances, which is especially beneficial if the getBridgeStatus function is called frequently.


34-38: LGTM: Fast bridge contract initialization is correct.

The initialization of the fast bridge contract looks good, using the retrieved fastBridgeAddress and the appropriate ABI.

packages/rest-api/src/controllers/destinationTxController.ts (6)

4-7: LGTM: New imports enhance modularity

The addition of these imports indicates a good separation of concerns. Utility functions and constants are now imported from separate modules, which should improve the overall structure and maintainability of the codebase.


15-16: LGTM: Clear payload initialization

Initializing the payload variable as an empty object at the beginning of the function is a good practice. It provides a clear starting point for the response and ensures that the variable is always defined, even if an error occurs early in the function execution.


24-36: LGTM: Proper handling of 'not found' scenario

The addition of this block improves the API's responsiveness by explicitly handling cases where no bridge transaction is found. Returning a 404 status with a clear "not found" payload is appropriate. The logging before the response is also a good practice for debugging and monitoring purposes.


38-54: LGTM: Clear handling of pending and refunded states

This block effectively differentiates between 'refunded' and 'pending' states based on the bridge status. The use of the serializeBridgeInfo function ensures that the fromInfo is consistently formatted in the response. The logic is clear and easy to follow.


56-63: LGTM: Proper handling of completed state

This block correctly identifies and handles the 'completed' state when both fromInfo and toInfo are present. The use of serializeBridgeInfo for both pieces of information ensures a consistent format in the response payload.


76-80: LGTM: Improved error handling

This change addresses the security concern raised in a previous review comment about exposing internal error messages to clients. The generic error message is now appropriate for client-facing responses, improving the security of the API.

packages/rest-api/src/routes/destinationTxRoute.ts (4)

37-37: LGTM: Status type change enhances response flexibility

Changing the status type from boolean to string allows for more detailed status information, which aligns with the PR objective of returning a refunded status when applicable.


39-65: LGTM: Comprehensive fromInfo object added

The new fromInfo object provides detailed information about the transaction's origin, enhancing the API's usefulness. All properties are well-defined with appropriate types and descriptions.

This addition also resolves the previous comment about the missing blockNumber property.


84-86: LGTM: blockNumber added to toInfo

The addition of the blockNumber property to the toInfo object enhances consistency with the fromInfo object and provides valuable information about the transaction on the destination chain.


94-112: LGTM: Example response updated to match schema changes

The example response has been correctly updated to reflect all the schema changes, including the string status and the new properties in both fromInfo and toInfo objects. This provides a clear illustration of the API response structure.

This update also resolves the previous comment about consistency between the schema and example for the blockNumber property.

packages/rest-api/src/utils/getBridgeStatus.ts Outdated Show resolved Hide resolved
packages/rest-api/src/utils/getBridgeStatus.ts Outdated Show resolved Hide resolved
packages/rest-api/src/utils/getBridgeStatus.ts Outdated Show resolved Hide resolved
packages/rest-api/src/utils/fetchBridgeTransaction.ts Outdated Show resolved Hide resolved
packages/rest-api/src/utils/fetchBridgeTransaction.ts Outdated Show resolved Hide resolved
packages/rest-api/src/utils/fetchBridgeTransaction.ts Outdated Show resolved Hide resolved
@synapsecns synapsecns deleted a comment from coderabbitai bot Oct 18, 2024
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: 6

🧹 Outside diff range and nitpick comments (4)
packages/rest-api/src/utils/constructBridgeTransactionsQuery.ts (1)

1-46: Enhance documentation and add input validation.

The overall structure of the file is clean and focused. Consider the following improvements:

  1. Add JSDoc comments to document the function's purpose, parameters, and return value.
  2. Implement input validation for required parameters, especially useMv.

Here's an example of how you could implement these suggestions:

/**
 * Constructs a GraphQL query string for retrieving bridge transaction data.
 *
 * @param {Object} params - The parameters for the query.
 * @param {boolean} params.useMv - Indicates whether to use a specific mode.
 * @param {(string|number|null)} [params.originChainId] - The identifier for the originating blockchain.
 * @param {string|null} [params.txnHash] - The transaction hash.
 * @param {string|null} [params.kappa] - The kappa value.
 * @returns {string} The constructed GraphQL query string.
 * @throws {Error} If required parameters are missing or invalid.
 */
export const constructBridgeTransactionsQuery = ({
  useMv,
  originChainId,
  txnHash,
  kappa,
}: {
  useMv: boolean
  originChainId?: string | number | null
  txnHash?: string | null
  kappa?: string | null
}) => {
  if (typeof useMv !== 'boolean') {
    throw new Error('useMv must be a boolean');
  }

  // ... rest of the function implementation
};

These additions will improve the function's documentation and robustness.

packages/rest-api/src/utils/fetchBridgeTransaction.ts (1)

1-13: LGTM! Consider adding input validation.

The function signature and imports look good. The use of optional parameters provides flexibility. However, consider adding input validation to ensure at least one of the parameters is provided and they are of the correct type.

Here's a suggestion for input validation:

if (!originChainId && !txnHash && !kappa) {
  throw new Error('At least one of originChainId, txnHash, or kappa must be provided');
}
packages/rest-api/src/controllers/destinationTxController.ts (2)

25-39: LGTM: Improved transaction data handling with a minor suggestion.

The destructuring with default values and the explicit check for non-existent transactions are excellent improvements. Returning a 404 status for non-existent transactions is appropriate.

Consider adding error logging for the 404 case:

      logger.info(`Successful destinationTxController response`, {
        query: req.query,
        payload,
      })
+     logger.warn(`Transaction not found`, {
+       query: req.query,
+     })
      return res.status(404).json(payload)

This will help in monitoring and debugging potential issues with missing transactions.


41-66: LGTM: Improved status determination logic with a suggestion.

The status determination logic is clear and covers important scenarios, including the new 'refunded' status. The use of getBridgeStatus function enhances the accuracy of status reporting.

Consider handling the case where only toInfo is present:

    } else {
      payload = {
        status: 'pending',
        fromInfo: serializeBridgeInfo(fromInfo),
        toInfo,
      }
    }
+   } else if (!fromInfo && toInfo) {
+     payload = {
+       status: 'received',
+       fromInfo,
+       toInfo: serializeBridgeInfo(toInfo),
+     }
    }

    if (fromInfo && toInfo) {

This addition would provide a more complete handling of all possible scenarios.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 9298344 and 3b5a684.

📒 Files selected for processing (5)
  • packages/rest-api/src/constants/index.ts (2 hunks)
  • packages/rest-api/src/controllers/bridgeTxStatusController.ts (2 hunks)
  • packages/rest-api/src/controllers/destinationTxController.ts (1 hunks)
  • packages/rest-api/src/utils/constructBridgeTransactionsQuery.ts (1 hunks)
  • packages/rest-api/src/utils/fetchBridgeTransaction.ts (1 hunks)
🧰 Additional context used
🪛 Biome
packages/rest-api/src/utils/fetchBridgeTransaction.ts

[error] 29-30: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (9)
packages/rest-api/src/utils/constructBridgeTransactionsQuery.ts (1)

1-11: Well-structured function declaration with clear parameter typing.

The function declaration uses modern JavaScript practices with TypeScript typing. The use of object destructuring for parameters and clear type definitions enhances code readability and maintainability.

packages/rest-api/src/controllers/destinationTxController.ts (5)

4-6: LGTM: New imports are well-organized and necessary.

The new imports (getBridgeStatus, BridgeStatus, and fetchBridgeTransaction) are correctly added and align with the refactored functionality of the controller.


15-16: LGTM: Clear payload initialization.

Initializing the payload variable as an empty object outside the try-catch block is a good practice. It provides a clear starting point for payload construction and ensures the variable is accessible throughout the function scope.


20-24: LGTM: Improved abstraction for fetching bridge transaction.

The use of fetchBridgeTransaction function improves code readability and maintainability by abstracting the GraphQL query logic. The object destructuring in the function call enhances clarity.


67-72: LGTM: Proper logging and response handling.

The logging of successful responses with query and payload information is valuable for monitoring and debugging. The JSON response is correctly sent.


79-83: LGTM: Improved error handling for better security.

Removing err.message from the client response is an excellent security improvement. It prevents potential leakage of sensitive information while still maintaining detailed error logging internally.

packages/rest-api/src/controllers/bridgeTxStatusController.ts (3)

7-7: Import statement added correctly

The addition of fetchBridgeTransaction import enhances code modularity by leveraging utility functions.


29-31: Refactored fetch logic improves maintainability

Constructing the params object and utilizing fetchBridgeTransaction(params) centralizes the transaction fetching logic. This refactoring promotes code reuse and simplifies future maintenance.


33-33: Destructuring 'toInfo' with default value ensures robustness

By destructuring toInfo from bridgeTxn with a default of null, the code safely handles cases where bridgeTxn might be undefined or lacking toInfo, preventing potential runtime errors.

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

Successfully merging this pull request may close these issues.

2 participants