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: audit gas refund logic #24

Draft
wants to merge 36 commits into
base: main
Choose a base branch
from
Draft

fix: audit gas refund logic #24

wants to merge 36 commits into from

Conversation

fadeev
Copy link
Member

@fadeev fadeev commented Dec 18, 2024

  • emitting an event instead of reverting when refunding

Summary by CodeRabbit

  • New Features

    • Introduced a RefundFailed event to log instances of failed gas token transfers in both UniversalNFT and UniversalToken contracts.
  • Bug Fixes

    • Removed the GasTokenTransferFailed error, improving error handling for gas token transfers by shifting to event-based notifications.

@fadeev fadeev changed the title audit gas refund logic fix: audit gas refund logic Dec 18, 2024
@fadeev fadeev changed the base branch from main to upgradeable December 18, 2024 08:10
@fadeev fadeev linked an issue Dec 18, 2024 that may be closed by this pull request
@fadeev fadeev requested review from 0xM3R and removed request for 0xM3R December 18, 2024 08:14
@fadeev
Copy link
Member Author

fadeev commented Dec 19, 2024

@coderabbitai review

Copy link

coderabbitai bot commented Dec 19, 2024

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link

coderabbitai bot commented Dec 19, 2024

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

📝 Walkthrough

Walkthrough

The pull request introduces a refined error handling mechanism across multiple contracts, specifically in UniversalNFT and UniversalToken. The primary modification involves replacing the GasTokenTransferFailed error with a new RefundFailed event. This change shifts the error management strategy from a transaction-reverting approach to an event-based notification system, allowing for more flexible handling of gas token transfer failures while maintaining the core functionality of cross-chain token and NFT transfers.

Changes

File Change Summary
contracts/nft/contracts/evm/UniversalNFT.sol - Removed GasTokenTransferFailed error
- Added RefundFailed event for logging gas transfer failures
contracts/nft/contracts/shared/Events.sol - Added RefundFailed(address, uint256) event
contracts/token/contracts/evm/UniversalToken.sol - Removed GasTokenTransferFailed error
- Added RefundFailed event for logging gas transfer failures
contracts/token/contracts/shared/Events.sol - Added RefundFailed(address, uint256) event

Sequence Diagram

sequenceDiagram
    participant Sender
    participant Contract
    participant Gateway
    
    Sender->>Contract: Initiate Cross-Chain Transfer
    Contract->>Gateway: Attempt Gas Token Transfer
    alt Gas Transfer Fails
        Contract->>Contract: Emit RefundFailed Event
        Contract->>Sender: Log Failure Details
    else Gas Transfer Succeeds
        Gateway->>Contract: Process Transfer
    end
Loading

The sequence diagram illustrates the new error handling flow, where instead of reverting on a failed gas token transfer, the contract now emits a RefundFailed event, providing transparency and flexibility in managing transfer failures.


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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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: 0

🧹 Nitpick comments (2)
contracts/nft/contracts/shared/Events.sol (1)

31-31: Consider enhancing event parameter naming and indexing

The RefundFailed event parameters should be named and indexed for better readability and efficient event filtering.

-event RefundFailed(address, uint256);
+event RefundFailed(address indexed recipient, uint256 amount);
contracts/nft/contracts/evm/UniversalNFT.sol (1)

142-142: Ensure NFT state consistency with non-blocking refunds

While the change aligns with UniversalToken.sol, NFTs require special consideration:

  1. The NFT is minted and ownership transferred before the refund attempt
  2. Failed refunds could leave users with valid NFTs but lost gas funds

Consider:

  1. Documenting the new behavior in contract comments
  2. Adding a recovery mechanism specific to NFT transfers
 if (gasAmount > 0) {
     if (sender == address(0)) revert InvalidAddress();
     (bool success, ) = payable(sender).call{value: gasAmount}("");
-    if (!success) emit RefundFailed(sender, gasAmount);
+    if (!success) {
+        // Document: NFT transfer successful but gas refund failed
+        emit RefundFailed(sender, gasAmount);
+        // Consider: Add to a recovery mapping for later claiming
+    }
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between fd3d640 and 9ed7830.

📒 Files selected for processing (4)
  • contracts/nft/contracts/evm/UniversalNFT.sol (1 hunks)
  • contracts/nft/contracts/shared/Events.sol (1 hunks)
  • contracts/token/contracts/evm/UniversalToken.sol (1 hunks)
  • contracts/token/contracts/shared/Events.sol (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • contracts/token/contracts/shared/Events.sol
🔇 Additional comments (1)
contracts/token/contracts/evm/UniversalToken.sol (1)

115-115: Consider implications of non-blocking gas refunds

The change from reverting to event emission on refund failure introduces potential silent failures. While this prevents transaction reversion, it may lead to:

  1. Lost gas refunds without user notification
  2. Inconsistent state between successful token transfer but failed refund

Consider:

  1. Adding logging with detailed failure reason
  2. Implementing a recovery mechanism for failed refunds

@@ -140,7 +139,7 @@ contract UniversalNFT is
if (gasAmount > 0) {
if (sender == address(0)) revert InvalidAddress();
(bool success, ) = payable(sender).call{value: gasAmount}("");
if (!success) revert GasTokenTransferFailed();
if (!success) emit RefundFailed(sender, gasAmount);
Copy link

Choose a reason for hiding this comment

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

i am not sure i understand this, so for example if we refund to smart contract, and it fails, lets say smart contract doesn't have receiver function by mistake - we let tx succeed even though funds are not transfered, do we then transfer funds manually?

it doesn't look like a security issue to me, would be nice to add exploit scenario to issue for better understanding

Copy link
Member Author

Choose a reason for hiding this comment

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

Right now tokens just remain in the contract. I suppose we can implement a recover function so that the owner can recover these tokens.

  function recover(address tokenAddress, uint256 tokenAmount) public onlyOwner {
    if (tokenAddress == address(0)) {
      payable(owner()).transfer(tokenAmount);
    } else {
      IERC20(tokenAddress).transfer(owner(), tokenAmount);
    }

@0xM3R

@fadeev fadeev marked this pull request as draft December 23, 2024 08:51
Base automatically changed from upgradeable to main December 23, 2024 09:11
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.

Gas refund logic may lead to DDoS condition in the smart contracts
2 participants