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(evm): erc20 born funtoken: properly burn bank coins after convert… #2139

Merged
merged 4 commits into from
Jan 8, 2025

Conversation

onikonychev
Copy link
Contributor

@onikonychev onikonychev commented Jan 3, 2025

Summary by CodeRabbit

  • Bug Fixes

    • Fixed an issue with ERC20 born funtoken to ensure bank coins are properly burned after converting back to ERC20.
  • New Features

    • Added a new test ERC20 contract with a transfer fee mechanism.
    • Introduced additional test coverage for ERC20 token conversion.
  • Documentation

    • Updated changelog with details of the bug fix and changes.

@onikonychev onikonychev requested a review from a team as a code owner January 3, 2025 17:12
Copy link
Contributor

coderabbitai bot commented Jan 3, 2025

Warning

Rate limit exceeded

@Unique-Divine has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 22 minutes and 25 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between f9c3d3f and 31a462f.

📒 Files selected for processing (1)
  • CHANGELOG.md (1 hunks)

Walkthrough

The pull request introduces updates to the Nibiru EVM project, focusing on a bug fix for ERC20 token burning and the addition of a new test contract. It includes a changelog entry documenting a fix related to the ERC20 born funtoken, ensuring proper burning of bank coins. A new Solidity contract, TestERC20TransferWithFee, implements a fee mechanism for transfers. Additionally, the codebase is updated to streamline the initialization of module addresses and enhance test coverage for the new contract's functionality.

Changes

File Change Summary
CHANGELOG.md Added bug fix entry for ERC20 born funtoken coin burning
x/evm/const.go Introduced EVM_MODULE_ADDRESS_NIBI variable and updated EVM_MODULE_ADDRESS initialization
x/evm/embeds/artifacts/... Added JSON artifact for TestERC20TransferWithFee contract
x/evm/embeds/contracts/... New Solidity contract with 10% transfer fee mechanism
x/evm/embeds/embeds.go Added new contract to embedded resources
x/evm/embeds/embeds_test.go Included MustLoad() for SmartContract_TestERC20TransferWithFee in tests
x/evm/keeper/funtoken_from_erc20_test.go Added TestSendERC20WithFee test method
x/evm/keeper/msg_server.go Simplified coin conversion logic

Sequence Diagram

sequenceDiagram
    participant User
    participant ERC20Contract
    participant Bank
    participant EVMKeeper

    User->>ERC20Contract: Transfer tokens
    ERC20Contract->>ERC20Contract: Calculate and deduct fee
    ERC20Contract->>Bank: Send remaining tokens
    Bank->>EVMKeeper: Convert tokens
    EVMKeeper->>Bank: Burn converted coins
    EVMKeeper-->>User: Confirm conversion
Loading

Possibly related PRs

  • fix(bank): fix gas invariant wrapper to actually charge gas #2140: The changes in this PR relate to the bank operations and gas charging, which are indirectly connected to the bug fix documented in the main PR regarding the ERC20 token conversion and burning of bank coins. Both involve financial transactions within the Nibiru EVM ecosystem.

Poem

🐰 A Rabbit's Ode to Token Fees 🪙

With transfers swift and fees so neat,
Our ERC20 dance is now complete.
Ten percent skimmed with rabbit's glee,
Burning coins, setting balances free.
Nibiru's magic, code so bright! 🌟


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
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (6)
x/evm/embeds/contracts/TestERC20TransferWithFee.sol (1)

14-25: Fee Deduction Logic

This logic successfully deducts 10% and transfers it to the contract. Check for potential corner cases (e.g., dust amounts, large integer overflows, or fee distribution beyond the contract).

If needed, consider parameterizing the fee or distributing it to a designated feeCollector address.

- uint256 constant FEE_PERCENTAGE = 10;
+ uint256 public feePercentage = 10;

...
- _transfer(owner, address(this), fee);
+ _transfer(owner, feeCollector, fee);
x/evm/keeper/funtoken_from_erc20_test.go (4)

455-457: Add descriptive comments for newly introduced test method.
It might be beneficial to add a concise description or docstring above the test method, clarifying that this test verifies handling of transfer fees, ERC20-Bank conversions, and burned coins.


460-470: Consider renaming the log message or grouping logs.
To ensure clarity when scanning test logs, rename or group repeated logs (e.g. “Deploy ERC20”) if necessary, or provide more details about the contract features (fee structure) being deployed.


479-488: Ensure test coverage for all error paths of CreateFunToken.
For example, consider adding negative tests where the contract is not fee-enabled or the user lacks enough funds.


491-495: Refine logging or verify random account usage.
Ensure that the random account is both funded (if needed) and consistently used across the test. If it’s only used to receive tokens, clarifying comments could help maintain the test.

x/evm/keeper/msg_server.go (1)

606-607: Clarify the explanatory comment.
The statement is helpful, but adding an explicit mention that this pre-escrow design ensures re-conversions remain consistent may further clarify the rationale.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1ae53e4 and 087b77d.

📒 Files selected for processing (8)
  • CHANGELOG.md (1 hunks)
  • x/evm/const.go (2 hunks)
  • x/evm/embeds/artifacts/contracts/TestERC20TransferWithFee.sol/TestERC20TransferWithFee.json (1 hunks)
  • x/evm/embeds/contracts/TestERC20TransferWithFee.sol (1 hunks)
  • x/evm/embeds/embeds.go (3 hunks)
  • x/evm/embeds/embeds_test.go (1 hunks)
  • x/evm/keeper/funtoken_from_erc20_test.go (1 hunks)
  • x/evm/keeper/msg_server.go (3 hunks)
🔇 Additional comments (21)
x/evm/embeds/embeds_test.go (1)

23-23: Ensure Additional Coverage for Fee Mechanisms

Adding the SmartContract_TestERC20TransferWithFee.MustLoad() call is good, but please confirm the associated fee logic is covered through relevant test cases. If not, add or expand test coverage to ensure the contract’s fee behavior is verified.

x/evm/embeds/contracts/TestERC20TransferWithFee.sol (3)

1-2: License and Compatibility Advisory

Great to see the SPDX license identifier. Confirm that the chosen license is compatible with other project dependencies and that all relevant requirements are satisfied.


4-5: OpenZeppelin Import Check

Importing @openzeppelin/contracts/token/ERC20/ERC20.sol is standard. Verify that the project is using the correct version of OpenZeppelin for your Solidity compiler version.


6-13: Constructor Initialization

The constructor properly sets up the token name, symbol, and mints 1000 tokens to the deployer. However, ensure that 1000 tokens is sufficient for tests or real usage, or parameterize if needed.

x/evm/const.go (3)

9-9: Import Usage Validation

You’ve introduced the Cosmos SDK types package (aliased as sdk), but confirm that it’s needed for the new code or used consistently elsewhere.


88-88: Separate Module Address Variables

Defining both EVM_MODULE_ADDRESS and EVM_MODULE_ADDRESS_NIBI can help maintain clarity. Verify all references to EVM_MODULE_ADDRESS fully account for this new variable, especially if existing logic depends on the original address.


91-92: Initialization Order

The initialization sets EVM_MODULE_ADDRESS_NIBI first, then EVM_MODULE_ADDRESS. This is correct. Just ensure no downstream usage occurs before these are fully set.

x/evm/embeds/embeds.go (3)

42-43: Embedded JSON Declaration

The embedded JSON for TestERC20TransferWithFee is introduced. Ensure the artifact is correctly generated and up to date with the Solidity contract’s bytecode and ABIs.


131-136: New SmartContract Instance

Defining SmartContract_TestERC20TransferWithFee is a good approach. Confirm the contract name, file path, and JSON data reference match exactly to avoid initialization errors.


152-152: Initialization Sequence

Loading the new contract in init() ensures it’s available at runtime. Verify that the order of .MustLoad() calls meets the dependencies for any existing or future tests, especially if fee-collecting logic depends on other contracts being loaded first.

x/evm/keeper/funtoken_from_erc20_test.go (6)

458-459: No concerns found.
Initialization and environment setup via evmtest.NewTestDeps() is standard practice and appears correct.


471-478: Check for consistent error handling after funding the account.
The code funds the user’s account and then calls CreateFunToken. If any additional steps require user funds, ensure that exceptions or failures are consistently handled/logged.


489-490: No concerns found.
The bankDemon assignment looks straightforward, and naming is consistent with the rest of the test.


496-508: Good coverage of ERC20 → Bank flow.
The flow checks final ERC20 and bank balances thoroughly. This is comprehensive and ensures the 10% transfer fee logic is validated. No issues detected.


510-515: Thorough final checks.
Verifying module address, user address, and random account address balances after the ERC20→Bank conversion is robust. Looks good.


516-536: Comprehensive coverage of the Bank → ERC20 flow.
This section verifies that coins are burned after conversion, ensuring that supply consistency is maintained. The tests look correct.

x/evm/keeper/msg_server.go (3)

613-613: Ensure inline references remain up to date.
Check that the reference to the preceding ERC20→BC conversion step is accurate if the relevant code shifts or is refactored.


628-628: Appropriate coin burning logic.
The burn step is crucial for supply consistency. It is well-placed to ensure bank coin supply remains sync’d to the ERC20 supply.


638-638: No concerns for event emission.
This event usage for conversion is consistent with the existing pattern. Looks correct and transparent for auditing.

x/evm/embeds/artifacts/contracts/TestERC20TransferWithFee.sol/TestERC20TransferWithFee.json (1)

1-297: ABI definitions look standard.
No security or correctness issues found in the ABI. Consider documenting any special constructor arguments or fee logic in a separate doc to help integrators.

CHANGELOG.md (1)

57-57: Good practice adding the PR reference.
This clarifies the fix related to ERC20 FunToken burn logic. No concerns.

Copy link

codecov bot commented Jan 3, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 65.13%. Comparing base (e5274c0) to head (31a462f).
Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #2139   +/-   ##
=======================================
  Coverage   65.13%   65.13%           
=======================================
  Files         277      277           
  Lines       22167    22168    +1     
=======================================
+ Hits        14439    14440    +1     
  Misses       6738     6738           
  Partials      990      990           
Files with missing lines Coverage Δ
x/evm/const.go 84.00% <100.00%> (+0.66%) ⬆️
x/evm/embeds/embeds.go 74.19% <100.00%> (+0.86%) ⬆️
x/evm/keeper/msg_server.go 77.05% <100.00%> (-0.05%) ⬇️

Copy link
Member

Choose a reason for hiding this comment

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

This looks like the re-introduction of a bug fixed in the first audit. Please explain further why the sent amount is being ignored now

Copy link
Contributor Author

Choose a reason for hiding this comment

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

All this is related to some weird or malicious contracts which do not transfer 1:1 of the tokens they are intended to transfer.
The most realistic case which I can imagine is that part of the tokens is transferred as a fee to another (non-recipient) account. So, the total amount of ERC20 tokens remains the same but the actualSentAmount in this case is lower. If we do not burn the full amount in this case - we have an imbalance with extra coins accumulated on a module account.

Copy link
Member

Choose a reason for hiding this comment

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

Copy link
Contributor

Choose a reason for hiding this comment

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

@Unique-Divine I think we should burn them (approve this PR). For reference, this types of transfer function are usually either:

  • Burned (sent to a dead address).
  • Reflected (distributed to existing holders).
  • Routed to a Marketing/Dev Wallet (for project funding).
  • Used for Liquidity (auto-liquidity functions).
  • Any combination of the above (split fees).

In any of these cases, all of the tokens are expected to be used by the function and derived to wallets, so we can burn all the amount.

As for the previous fix, it was related to this code but not exactly the same. We use to check that input in = input sent to the transferee wallet, which is not correct considering these weird fee-on-transfer tokens, and that's why we made it more lax and don't check this anymore.

@Unique-Divine Unique-Divine merged commit 20531e7 into main Jan 8, 2025
13 checks passed
@Unique-Divine Unique-Divine deleted the fix/burn-erc20-funtoken branch January 8, 2025 04:26
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.

4 participants