-
Notifications
You must be signed in to change notification settings - Fork 201
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(evm): gas usage in precompiles: limits, local gas meters #2093
base: main
Are you sure you want to change the base?
Conversation
WalkthroughThe changes in this pull request include updates to the Changes
Possibly related issues
Possibly related PRs
Suggested labels
Suggested reviewers
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
Codecov ReportAttention: Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #2093 +/- ##
==========================================
+ Coverage 64.45% 64.48% +0.02%
==========================================
Files 270 271 +1
Lines 21190 21231 +41
==========================================
+ Hits 13659 13690 +31
- Misses 6579 6587 +8
- Partials 952 954 +2
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 23
🧹 Outside diff range and nitpick comments (20)
x/evm/embeds/contracts/TestFunTokenPrecompileLocalGas.sol (2)
7-7
: Consider adding explicit visibility modifier.The
erc20
state variable should have an explicit visibility modifier for better code clarity.- address erc20; + address private immutable erc20;
6-47
: Consider architectural improvements.Suggestions for better architecture:
- Define an interface for the FunToken precompile
- Add events for successful transfers
- Consider implementing a more robust error handling mechanism
Example interface:
interface IFunTokenPrecompile { function bankSend( address token, uint256 amount, string memory recipient ) external returns (bool); }Example event:
event BankSendExecuted( address indexed token, uint256 amount, string recipient, uint256 gasUsed );x/evm/evmtest/test_deps.go (1)
64-67
: Add documentation for the ResetGasMeter method.The implementation looks good, but consider adding a doc comment to explain the method's purpose and when it should be used in tests.
+// ResetGasMeter resets both the transient gas state and the gas meter in the EVM context. +// This is useful in tests where you need to clear gas usage between operations. func (deps TestDeps) ResetGasMeter() {🧰 Tools
🪛 GitHub Check: codecov/patch
[warning] 64-66: x/evm/evmtest/test_deps.go#L64-L66
Added lines #L64 - L66 were not covered by testsx/evm/precompile/oracle_test.go (1)
15-15
: Document the rationale for the gas limit value.Consider adding a comment explaining why 100,000 was chosen as the gas limit for oracle queries. This helps maintainers understand if this value needs adjustment in the future.
x/evm/precompile/oracle.go (1)
Line range hint
41-63
: Well-structured gas management implementation.The implementation of local gas meters in the oracle precompile follows good practices:
- Clear separation of gas meter initialization and cleanup
- Proper error propagation
- Safe gas consumption checks
Consider documenting these gas management patterns in a shared location as they might be useful for other precompiles.
x/evm/embeds/embeds.go (1)
81-86
: Consider enhancing the documentation with more specific details.While the implementation is correct and follows the package patterns, the documentation could be more specific about:
- The purpose of the local gas limit feature
- How it differs from regular precompile calls
- Expected usage scenarios
Example enhancement:
// SmartContract_TestFunTokenPrecompileLocalGas is a test contract -// which allows precompile execution with custom local gas set (calling precompile within contract) +// which demonstrates and tests the execution of precompiles with custom gas limits +// from within another contract. This enables controlled gas consumption for +// precompile calls, ensuring they operate within a subset of the parent +// contract's gas allowance.x/evm/keeper/erc20.go (1)
16-26
: LGTM! Consider enhancing constant documentation.The gas limits are well-structured and appropriate for their respective operations. The deployment limit provides adequate headroom, query limit is suitable for read operations, and execute limit aligns with typical ERC20 operation costs.
Consider adding references to standard ERC20 operation gas costs in the comments to justify these limits. For example:
// Erc20GasLimitExecute used for transfer, mint and burn. -// All must not exceed 200_000 +// Standard ERC20 operations typically consume: +// - transfer: ~65,000 gas +// - mint: ~90,000 gas +// - burn: ~80,000 gas +// 200,000 limit provides sufficient headroom Erc20GasLimitExecute uint64 = 200_000x/evm/precompile/funtoken_test.go (2)
Line range hint
93-153
: Consider adding more assertions for gas consumption.The test structure looks good and properly validates the basic functionality. However, since this PR focuses on gas management, consider adding assertions to verify:
- Gas consumption after each operation
- Remaining gas in the gas meter
- Gas refunds if applicable
Example assertion:
// Assert gas consumption is within expected range gasUsed := deps.Ctx.GasMeter().GasConsumed() s.Assert().Greater(gasUsed, uint64(0)) s.Assert().Less(gasUsed, keeper.Erc20GasLimitQuery)
155-218
: Enhance gas limit test coverage.While the test effectively validates the happy path for local gas usage, consider adding:
Negative test cases:
- Insufficient gas limit
- Zero gas limit
- Gas limit exceeding parent contract's limit
Specific gas consumption assertions:
- Verify exact gas used by precompile
- Check remaining gas after operation
- Validate gas refunds
Example test cases:
s.T().Log("Fail: insufficient local gas") _, err = deps.EvmKeeper.CallContract( deps.Ctx, embeds.SmartContract_TestFunTokenPrecompileLocalGas.ABI, deps.Sender.EthAddr, &contractAddr, true, precompile.FunTokenGasLimitBankSend, "callBankSendLocalGas", big.NewInt(1), randomAcc.String(), big.NewInt(100), // insufficient gas ) s.Require().ErrorContains(err, "out of gas")x/evm/precompile/wasm_test.go (1)
21-25
: LGTM! Consider enhancing the constant documentation.The gas limit constants are well-defined and follow good practices. The values are reasonable for test scenarios and the formatting improves readability.
Consider adding a brief comment explaining the rationale behind these specific gas values to help other developers understand the test constraints:
// rough gas limits for wasm execution - used in tests only +// WasmGasLimitQuery: 200k gas sufficient for read-only operations +// WasmGasLimitExecute: 1M gas sufficient for state-modifying operations const ( WasmGasLimitQuery uint64 = 200_000 WasmGasLimitExecute uint64 = 1_000_000 )x/evm/precompile/test/export.go (1)
24-28
: LGTM! Consider enhancing the documentation.The gas limit constants are well-defined and appropriately scoped for test usage.
Consider adding a brief comment explaining the rationale behind these specific gas values to help other developers understand the chosen limits.
x/evm/embeds/artifacts/contracts/TestFunTokenPrecompileLocalGas.sol/TestFunTokenPrecompileLocalGas.json (2)
1-63
: Consider adding natspec documentation.While the contract implementation looks solid, consider adding natspec documentation in the source contract to:
- Document the gas management behavior
- Explain the relationship with the bankSend precompile
- Provide usage examples with gas limits
1-63
: Security considerations for gas management.The implementation allows for custom gas limits but should be used carefully:
- Ensure the parent contract has sufficient gas
- Consider implementing minimum gas requirements
- Add gas estimation helpers
Would you like me to provide implementation examples for these security enhancements?
x/evm/keeper/funtoken_from_erc20_test.go (1)
Line range hint
332-337
: Consider enhancing gas consumption verificationWhile the error handling for gas-related issues is comprehensive, consider enhancing the test coverage by:
- Capturing and verifying the exact gas consumption before the error occurs
- Adding assertions to verify that the gas consumption is within expected ranges
- Testing edge cases around the gas limits
This would provide more precise validation of the gas management implementation.
Example enhancement for the malicious transfer test:
s.T().Log("send erc20 tokens to cosmos") + initialGas := deps.Ctx.GasMeter().GasConsumed() _, err = deps.EvmKeeper.CallContract( deps.Ctx, embeds.SmartContract_FunToken.ABI, deps.Sender.EthAddr, &precompile.PrecompileAddr_FunToken, true, precompile.FunTokenGasLimitBankSend, "bankSend", deployResp.ContractAddr, big.NewInt(1), randomAcc.String(), ) + gasUsed := deps.Ctx.GasMeter().GasConsumed() - initialGas + s.Require().Greater(gasUsed, precompile.FunTokenGasLimitBankSend, "gas consumption should exceed limit") s.Require().ErrorContains(err, "gas required exceeds allowance")Also applies to: 384-386
x/evm/keeper/grpc_query.go (1)
803-803
: LGTM: Consider adding documentation.The
false
parameter is correctly added for transaction message tracing. Consider adding a comment explaining the purpose of this parameter for better maintainability.- res, _, err := k.ApplyEvmMsg(ctx, msg, tracer, commitMessage, cfg, txConfig, false) + // Pass false to prevent committing state changes during tracing + res, _, err := k.ApplyEvmMsg(ctx, msg, tracer, commitMessage, cfg, txConfig, false)CHANGELOG.md (1)
72-72
: Consider expanding the changelog entry to better reflect the changes.The current entry for PR #2093 could be expanded to better document the significant changes introduced, such as:
- Addition of local gas meters for precompile execution
- Support for custom gas limits in precompile calls
- Relocation of CallContractWithInput method
- Addition of gasLimit parameter
- Reorganization of funtoken methods
-- [#2093](https://github.com/NibiruChain/nibiru/pull/2093) - feat(evm): gas usage in precompiles: limits, local gas meters +- [#2093](https://github.com/NibiruChain/nibiru/pull/2093) - feat(evm): gas usage in precompiles: limits, local gas meters. Introduces local gas meters for precompile execution, allowing custom gas limits for precompile calls. Relocates CallContractWithInput method from ERC20 module to msg_server.go, adds gasLimit parameter, and reorganizes funtoken methods.x/evm/keeper/funtoken_from_coin.go (1)
128-133
: Ensure Atomicity in Coin Transfer and Error HandlingWhen transferring coins from the sender to the module account, ensure that the operation is atomic to prevent partial transfers in case of failures. The current implementation seems appropriate, but consider reviewing transaction atomicity for robustness.
x/evm/precompile/funtoken.go (1)
31-41
: Clarify Gas Limit Calculation in CommentsThe comments provide gas estimates for each step, totaling approximately 325,000 gas:
- Step 1: Up to 200,000 gas
- Step 2: ~60,000 gas
- Step 3: ~65,000 gas
- Total: ~325,000 gas
However,
FunTokenGasLimitBankSend
is set to 400,000 gas. Consider updating the comments to explain the additional 75,000 gas (perhaps accounting for overhead or gas discrepancies) or adjust the constant to better reflect the estimated total.x/evm/keeper/funtoken_from_erc20.go (1)
211-216
: Add detailed function parameter documentationTo enhance readability and maintainability, consider adding GoDoc comments for each parameter of the
convertCoinNativeERC20
function. This will help other developers understand the purpose and expected values of each parameter.x/evm/keeper/msg_server.go (1)
252-255
: Clarify Documentation for New ParameterfullRefundLeftoverGas
The
ApplyEvmMsg
function now includes the boolean parameterfullRefundLeftoverGas
, which affects gas refund logic. Ensure that the function's documentation clearly explains the purpose and impact of this parameter. Providing detailed comments or examples can help other developers understand its intended use and avoid misuse.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (23)
- CHANGELOG.md (1 hunks)
- x/evm/embeds/artifacts/contracts/TestFunTokenPrecompileLocalGas.sol/TestFunTokenPrecompileLocalGas.json (1 hunks)
- x/evm/embeds/contracts/TestFunTokenPrecompileLocalGas.sol (1 hunks)
- x/evm/embeds/embeds.go (3 hunks)
- x/evm/embeds/embeds_test.go (1 hunks)
- x/evm/evmtest/test_deps.go (1 hunks)
- x/evm/keeper/erc20.go (7 hunks)
- x/evm/keeper/funtoken_from_coin.go (2 hunks)
- x/evm/keeper/funtoken_from_coin_test.go (2 hunks)
- x/evm/keeper/funtoken_from_erc20.go (2 hunks)
- x/evm/keeper/funtoken_from_erc20_test.go (5 hunks)
- x/evm/keeper/grpc_query.go (4 hunks)
- x/evm/keeper/keeper.go (2 hunks)
- x/evm/keeper/msg_server.go (5 hunks)
- x/evm/precompile/funtoken.go (3 hunks)
- x/evm/precompile/funtoken_test.go (5 hunks)
- x/evm/precompile/oracle.go (2 hunks)
- x/evm/precompile/oracle_test.go (2 hunks)
- x/evm/precompile/precompile.go (4 hunks)
- x/evm/precompile/test/export.go (4 hunks)
- x/evm/precompile/wasm.go (2 hunks)
- x/evm/precompile/wasm_test.go (5 hunks)
- x/evm/statedb/journal_test.go (2 hunks)
🧰 Additional context used
🪛 GitHub Check: codecov/patch
x/evm/evmtest/test_deps.go
[warning] 64-66: x/evm/evmtest/test_deps.go#L64-L66
Added lines #L64 - L66 were not covered by testsx/evm/keeper/funtoken_from_coin.go
[warning] 104-105: x/evm/keeper/funtoken_from_coin.go#L104-L105
Added lines #L104 - L105 were not covered by tests
[warning] 107-108: x/evm/keeper/funtoken_from_coin.go#L107-L108
Added lines #L107 - L108 were not covered by tests
[warning] 149-150: x/evm/keeper/funtoken_from_coin.go#L149-L150
Added lines #L149 - L150 were not covered by tests
[warning] 152-154: x/evm/keeper/funtoken_from_coin.go#L152-L154
Added lines #L152 - L154 were not covered by testsx/evm/keeper/funtoken_from_erc20.go
[warning] 221-222: x/evm/keeper/funtoken_from_erc20.go#L221-L222
Added lines #L221 - L222 were not covered by tests
[warning] 224-225: x/evm/keeper/funtoken_from_erc20.go#L224-L225
Added lines #L224 - L225 were not covered by tests
[warning] 245-246: x/evm/keeper/funtoken_from_erc20.go#L245-L246
Added lines #L245 - L246 were not covered by tests
[warning] 248-249: x/evm/keeper/funtoken_from_erc20.go#L248-L249
Added lines #L248 - L249 were not covered by tests
[warning] 251-252: x/evm/keeper/funtoken_from_erc20.go#L251-L252
Added lines #L251 - L252 were not covered by tests
[warning] 263-264: x/evm/keeper/funtoken_from_erc20.go#L263-L264
Added lines #L263 - L264 were not covered by tests
[warning] 266-267: x/evm/keeper/funtoken_from_erc20.go#L266-L267
Added lines #L266 - L267 were not covered by tests
[warning] 272-273: x/evm/keeper/funtoken_from_erc20.go#L272-L273
Added lines #L272 - L273 were not covered by tests
[warning] 275-276: x/evm/keeper/funtoken_from_erc20.go#L275-L276
Added lines #L275 - L276 were not covered by tests
[warning] 280-281: x/evm/keeper/funtoken_from_erc20.go#L280-L281
Added lines #L280 - L281 were not covered by tests
[warning] 286-287: x/evm/keeper/funtoken_from_erc20.go#L286-L287
Added lines #L286 - L287 were not covered by testsx/evm/keeper/msg_server.go
[warning] 348-349: x/evm/keeper/msg_server.go#L348-L349
Added lines #L348 - L349 were not covered by tests
[warning] 591-592: x/evm/keeper/msg_server.go#L591-L592
Added lines #L591 - L592 were not covered by tests
[warning] 650-652: x/evm/keeper/msg_server.go#L650-L652
Added lines #L650 - L652 were not covered by tests
[warning] 665-669: x/evm/keeper/msg_server.go#L665-L669
Added lines #L665 - L669 were not covered by tests
[warning] 688-690: x/evm/keeper/msg_server.go#L688-L690
Added lines #L688 - L690 were not covered by tests
[warning] 695-696: x/evm/keeper/msg_server.go#L695-L696
Added lines #L695 - L696 were not covered by testsx/evm/precompile/funtoken.go
[warning] 94-95: x/evm/precompile/funtoken.go#L94-L95
Added lines #L94 - L95 were not covered by testsx/evm/precompile/oracle.go
[warning] 61-62: x/evm/precompile/oracle.go#L61-L62
Added lines #L61 - L62 were not covered by testsx/evm/precompile/precompile.go
[warning] 238-239: x/evm/precompile/precompile.go#L238-L239
Added lines #L238 - L239 were not covered by testsx/evm/precompile/wasm.go
[warning] 72-73: x/evm/precompile/wasm.go#L72-L73
Added lines #L72 - L73 were not covered by tests
🔇 Additional comments (51)
x/evm/embeds/embeds_test.go (1)
19-19
: LGTM! The test addition aligns with PR objectives.The new test case follows the established pattern and verifies the loading of the
TestFunTokenPrecompileLocalGas
contract, which is essential for testing the new local gas meter functionality.Let's verify the contract's existence:
✅ Verification successful
Contract verification successful - both source and artifact files exist
The verification confirms that both required files are present in the expected locations:
- Source:
x/evm/embeds/contracts/TestFunTokenPrecompileLocalGas.sol
- Artifact:
x/evm/embeds/artifacts/contracts/TestFunTokenPrecompileLocalGas.sol/TestFunTokenPrecompileLocalGas.json
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify that the TestFunTokenPrecompileLocalGas contract exists # Expected: Find the contract file and its corresponding JSON artifact # Test 1: Find the contract file fd "TestFunTokenPrecompileLocalGas.sol" --type f # Test 2: Find the contract's JSON artifact fd "TestFunTokenPrecompileLocalGas.json" --type fLength of output: 260
x/evm/embeds/contracts/TestFunTokenPrecompileLocalGas.sol (1)
4-4
: Verify the imported constant usage.The contract uses
FUNTOKEN_PRECOMPILE_ADDRESS
but it's not clear where this constant is defined.✅ Verification successful
Let me gather more information about the constant definition.
Import is correctly used and constant is properly defined
The constant
FUNTOKEN_PRECOMPILE_ADDRESS
is defined inFunToken.sol
as0x0000000000000000000000000000000000000800
and is properly used inTestFunTokenPrecompileLocalGas.sol
for making precompile calls. The import statement is necessary and valid.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for FUNTOKEN_PRECOMPILE_ADDRESS definition rg -l "FUNTOKEN_PRECOMPILE_ADDRESS" # Search for the constant's value in FunToken.sol ast-grep --pattern 'constant FUNTOKEN_PRECOMPILE_ADDRESS = $_'Length of output: 194
Script:
#!/bin/bash # Show the content around FUNTOKEN_PRECOMPILE_ADDRESS in both files rg -B2 -A2 "FUNTOKEN_PRECOMPILE_ADDRESS" x/evm/embeds/contracts/FunToken.sol x/evm/embeds/contracts/TestFunTokenPrecompileLocalGas.solLength of output: 1484
x/evm/evmtest/test_deps.go (1)
64-67
: Ensure test coverage for the new ResetGasMeter method.While this method is part of test utilities and might be indirectly tested through its usage in funtoken tests, consider adding direct unit tests to verify its behavior.
Would you like me to help create unit tests for this method?
🧰 Tools
🪛 GitHub Check: codecov/patch
[warning] 64-66: x/evm/evmtest/test_deps.go#L64-L66
Added lines #L64 - L66 were not covered by testsx/evm/precompile/oracle_test.go (1)
64-69
: Verify the purpose of thefalse
parameter.The boolean parameter (line 67) seems to be related to gas limit usage. Please verify its purpose and consider adding a comment explaining what this boolean controls, as it's not immediately clear from the context.
✅ Verification successful
From the search results, I found the documentation of
CallContractWithInput
inx/evm/keeper/msg_server.go
which shows that the boolean parameter is namedcommit
and is used to determine whether the contract call should be committed or simulated. Looking at the usage patterns across the codebase:
- For query operations (like in oracle_test.go),
commit
is set tofalse
- For state-changing operations (like in other tests),
commit
is set totrue
The
false
value in the oracle test is correct because it's performing a query operation (queryExchangeRate
) which doesn't modify state.The
false
parameter is correctly used for this query operation.The boolean parameter controls whether the contract call should commit changes (true) or just simulate/query (false). In this case, since it's a query to get exchange rate data, using
false
is the appropriate choice.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for the CallContractWithInput definition to understand the boolean parameter ast-grep --pattern 'func $_ CallContractWithInput($_, $_, $_, $useGasLimit bool, $_, $_)'Length of output: 91
Script:
#!/bin/bash # Let's try a broader search for CallContractWithInput function definition rg -A 5 "CallContractWithInput" # Also search for any comments or documentation about this function rg -B 2 -A 5 "CallContractWithInput"Length of output: 13478
x/evm/precompile/oracle.go (3)
41-45
: LGTM! Clear variable naming improvement.The rename from 'res' to 'start' better reflects the initialization nature of the
OnRunStart
function.
47-48
: Excellent gas meter cleanup implementation!The deferred reset of the gas meter is a crucial safety feature that ensures:
- Proper cleanup of gas meter state
- Graceful handling of "out of gas" scenarios
- Consistent gas tracking across precompile executions
58-62
: Add tests and documentation for gas consumption check.This critical gas consumption check needs:
- Test coverage to verify proper handling of out-of-gas scenarios
- A comment explaining the purpose and importance of this check
Would you like me to help:
- Generate test cases for the gas consumption check?
- Draft documentation for this security-critical feature?
🧰 Tools
🪛 GitHub Check: codecov/patch
[warning] 61-62: x/evm/precompile/oracle.go#L61-L62
Added lines #L61 - L62 were not covered by testsx/evm/embeds/embeds.go (3)
32-33
: LGTM! Embedded JSON declaration follows established patterns.The new embedded JSON variable follows the package's conventions for naming and file structure.
97-97
: LGTM! Contract loading follows established patterns.The initialization is correctly implemented using
MustLoad()
, maintaining consistency with other contract loading.
32-33
: Verify the contract's integration and test coverage.Let's ensure the contract is properly integrated and tested:
Also applies to: 81-86
✅ Verification successful
Let me gather more information about the test files to better understand the integration.
Let me check the actual Solidity contract implementation to complete the verification.
Based on the comprehensive verification results, I can now provide the final response:
Contract is properly integrated and well-tested ✅
The verification confirms:
- The Solidity contract exists and implements gas-specific test scenarios for the FunToken precompile
- The contract is properly used in test files:
x/evm/precompile/funtoken_test.go
: Tests both default and custom gas scenariosx/evm/embeds/embeds_test.go
: Verifies contract loading- The implementation aligns with its intended purpose of testing gas limits in precompiles
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify contract integration and test coverage # Test 1: Check if the JSON file exists echo "Checking for contract JSON file..." fd -t f "TestFunTokenPrecompileLocalGas.json" artifacts/ # Test 2: Look for test files using this contract echo "Checking for test files using this contract..." rg -l "TestFunTokenPrecompileLocalGas" -g "**/*_test.go" # Test 3: Check for actual contract usage echo "Checking for contract usage in codebase..." rg "SmartContract_TestFunTokenPrecompileLocalGas" -g "!**/embeds.go"Length of output: 994
Script:
#!/bin/bash # Check the test implementations to understand how the contract is used echo "Checking funtoken_test.go implementation..." rg -A 5 -B 5 "TestFunTokenPrecompileLocalGas" x/evm/precompile/funtoken_test.go echo -e "\nChecking embeds_test.go implementation..." rg -A 5 -B 5 "TestFunTokenPrecompileLocalGas" x/evm/embeds/embeds_test.go # Check if there's a corresponding Solidity contract echo -e "\nLooking for the Solidity contract..." fd -t f "TestFunTokenPrecompileLocalGas.sol"Length of output: 1826
Script:
#!/bin/bash # Check the Solidity contract implementation echo "Checking Solidity contract implementation..." cat x/evm/embeds/contracts/TestFunTokenPrecompileLocalGas.sol # Verify if the contract is properly loaded in embeds.go echo -e "\nChecking contract loading in embeds.go..." rg -A 5 "var SmartContract_TestFunTokenPrecompileLocalGas" x/evm/embeds/embeds.goLength of output: 1748
x/evm/keeper/keeper.go (2)
7-7
: LGTM: Import change looks correct.The import of
cosmossdk.io/math
is appropriate as it's used by theGetMinGasUsedMultiplier
method.
112-116
: LGTM: Method rename and documentation improvements.The rename to
GetMinGasUsedMultiplier
better reflects the method's purpose, and the documentation clearly explains how the gas limit and multiplier interact.x/evm/statedb/journal_test.go (2)
12-13
: LGTM: Import added for accessing gas limit constants.The keeper package import is correctly added to support the gas limit parameter changes.
70-75
: Verify gas limit appropriateness for test scenarios.The addition of
keeper.Erc20GasLimitExecute
as the gas limit parameter aligns with the PR objectives. However, we should ensure this limit is appropriate for the test scenario and consistent across similar test cases.Let's verify the consistency of gas limit usage across test files:
✅ Verification successful
Let me analyze the results and generate a final response based on the findings.
Gas limit parameter is consistently used across the codebase
The verification shows that
CallContractWithInput
is properly used with appropriate gas limits across the codebase:
- ERC20 operations use
Erc20GasLimitExecute
in keeper operations- Test files correctly use the gas limit parameter:
journal_test.go
usesErc20GasLimitExecute
for ERC20 operationsfuntoken_test.go
usesErc20GasLimitQuery
for queries- Precompile tests (
oracle_test.go
,wasm_test.go
) have their own gas limit configurationsThe gas limit parameter addition is appropriate for the test scenario and maintains consistency with the production code patterns.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Check for other test files that might need similar gas limit updates # and verify the consistency of CallContractWithInput usage. # Search for other test files using CallContractWithInput echo "Files containing CallContractWithInput calls that might need gas limit updates:" rg -l "CallContractWithInput" --type go --type-add 'go:*.go' | grep "_test.go" # Check the actual usage patterns echo -e "\nUsage patterns of CallContractWithInput:" rg -A 5 "CallContractWithInput\(" --type goLength of output: 6043
x/evm/keeper/erc20.go (6)
66-66
: LGTM! Gas limit properly applied to mint operation.The addition of
Erc20GasLimitExecute
ensures controlled gas consumption for minting operations.
88-88
: LGTM! Gas limit properly applied to transfer operation.The addition of
Erc20GasLimitExecute
ensures controlled gas consumption for transfer operations.
128-128
: LGTM! Gas limit properly applied to burn operation.The addition of
Erc20GasLimitExecute
ensures controlled gas consumption for burn operations.
157-163
: LGTM! Query gas limit properly applied to string loading operations.The addition of
Erc20GasLimitQuery
is appropriate for these read-only operations.
189-191
: LGTM! Query gas limit properly applied to uint8 loading operations.The addition of
Erc20GasLimitQuery
is appropriate for these read-only operations.
220-220
: LGTM! Query gas limit properly applied to BigInt loading operations.The addition of
Erc20GasLimitQuery
is appropriate for these read-only operations.x/evm/precompile/funtoken_test.go (2)
11-12
: LGTM! Well-structured test suite modifications.The addition of
deps
andfuntoken
fields toFuntokenSuite
improves test organization and follows good practices for dependency injection.Also applies to: 30-32
34-40
: LGTM! Clean and well-documented test setup.The
SetupSuite
implementation properly initializes test dependencies and includes helpful logging.x/evm/precompile/wasm_test.go (3)
62-67
: LGTM! Gas limit properly applied to denom creation call.The gas limit is appropriately set for the contract execution, and error handling is in place.
333-338
: LGTM! Consistent gas limit usage in error test cases.The execution gas limit is consistently applied even in error test cases, which is a good practice for thorough testing.
155-163
: LGTM! Verify gas meter reset effectiveness.The gas meter reset and query gas limit are properly implemented. The lower gas limit for queries is appropriate for read-only operations.
Let's verify that the gas meter reset is working as expected:
✅ Verification successful
Gas meter reset is consistently used before gas-sensitive operations
The verification shows that
ResetGasMeter()
is consistently used before EVM contract calls and other gas-sensitive operations across test files. The implementation inevmtest/test_deps.go
properly resets both transient and regular gas meters, ensuring accurate gas measurements in tests.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Check if ResetGasMeter is consistently used before gas-sensitive operations # across the codebase to ensure accurate gas measurements in tests. rg -B 2 -A 2 'ResetGasMeter\(\)' --type goLength of output: 2997
x/evm/keeper/funtoken_from_coin_test.go (2)
260-261
: LGTM: Proper gas meter reset before conversion.The addition of
ResetGasMeter()
ensures accurate gas measurement for the ERC-20 to bank coin conversion operation by starting with a clean gas state.
269-269
: LGTM: Gas limit enforcement for bankSend operation.The addition of
precompile.FunTokenGasLimitBankSend
implements proper gas management for the bankSend operation, aligning with the PR's objective of introducing local gas meters in precompiles.Let's verify the gas limit value is appropriate:
Also applies to: 297-297
✅ Verification successful
Let me gather more context about the gas limit usage in the code.
Gas limit value for bankSend is appropriately set
The
FunTokenGasLimitBankSend
value of 400,000 gas is well-justified based on the code comments and comparison with other gas limits in the codebase:
- It accounts for ~65,000 gas for bank send operation
- Includes buffer for additional operations (mint/burn ~60,000 gas each)
- Aligns proportionally with other precompile gas limits (e.g., Erc20GasLimitExecute: 200,000, WasmGasLimitQuery: 200,000)
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify the FunTokenGasLimitBankSend constant value and its usage # Check the constant definition rg -A 1 "FunTokenGasLimitBankSend.*=.*" # Check all usages of this constant rg "FunTokenGasLimitBankSend"Length of output: 1014
Script:
#!/bin/bash # Get the implementation details around FunTokenGasLimitBankSend ast-grep --pattern 'const FunTokenGasLimitBankSend = $_' # Get more context around the constant definition and its comments rg -B 3 -A 3 "FunTokenGasLimitBankSend.*=.*" # Check if there are any other gas limits defined for comparison rg "GasLimit.*=.*\d+"Length of output: 2217
x/evm/precompile/test/export.go (2)
80-85
: LGTM! Gas limit properly applied to contract instantiation.The WasmGasLimitInstantiate constant is correctly used in the CallContractWithInput method.
326-334
: Consider scaling gas limit with message count.While the gas management is generally good with the reset and appropriate limit, the gas limit doesn't scale with the number of messages being executed.
Consider adjusting the gas limit based on the number of messages:
- WasmGasLimitExecute, + WasmGasLimitExecute * uint64(times),Let's verify if there are any existing tests that might fail with multiple messages:
x/evm/precompile/wasm.go (2)
69-73
:⚠️ Potential issueAdd test coverage for gas consumption checks.
The gas consumption check logic is correct, but lacks test coverage according to static analysis. This is critical functionality that should be thoroughly tested.
Test cases should cover:
- Normal case: Contract has sufficient gas
- Edge case: Contract runs out of gas
- Integration with parent gas meter
Let's verify existing gas-related test coverage:
#!/bin/bash # Search for gas-related test cases in precompile tests rg -g "**/*_test.go" -B 5 -A 5 "UseGas|GasConsumed|ErrOutOfGas" x/evm/precompile/Would you like me to help generate comprehensive test cases for this functionality?
🧰 Tools
🪛 GitHub Check: codecov/patch
[warning] 72-73: x/evm/precompile/wasm.go#L72-L73
Added lines #L72 - L73 were not covered by tests
45-46
: LGTM: Gas meter reset implementation looks correct.The deferred gas meter reset ensures proper cleanup after precompile execution and handles "out of gas" errors gracefully.
Let's verify the
ReturnToParentGasMeter
implementation:✅ Verification successful
Gas meter reset implementation is correctly implemented and used
The verification confirms that
ReturnToParentGasMeter
is properly implemented inx/evm/precompile/precompile.go
and correctly used across multiple precompiles. The implementation:
- Resets the context gas meter back to parent after precompile execution
- Properly handles out of gas panics by catching
storetypes.ErrorOutOfGas
- Correctly updates the contract's gas usage
- Is consistently used in all precompile implementations (wasm.go, funtoken.go, oracle.go)
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for ReturnToParentGasMeter implementation and usages rg -A 5 "ReturnToParentGasMeter"Length of output: 83
Script:
#!/bin/bash # Let's try a broader search for gas meter related functions and their implementations rg -A 10 "func.*GasMeter|ReturnToParentGasMeter" # Also search for the specific file content cat x/evm/precompile/wasm.goLength of output: 21827
x/evm/embeds/artifacts/contracts/TestFunTokenPrecompileLocalGas.sol/TestFunTokenPrecompileLocalGas.json (2)
5-57
: LGTM: Contract interface properly implements gas management requirements.The ABI definition correctly implements:
- Constructor with ERC20 address parameter
- Base function
callBankSend
for standard calls- Extended function
callBankSendLocalGas
with custom gas parameter
59-60
: Verify the bytecode's gas management implementation.The bytecode includes proper error handling for failed calls and uses the correct precompile interaction pattern. However, let's verify the gas forwarding implementation in the source contract.
✅ Verification successful
Based on the source code verification, I can now generate the final response:
Gas management implementation is correctly implemented
The bytecode correctly reflects the source contract's gas management implementation where:
callBankSend()
forwards all available gas (default behavior)callBankSendLocalGas()
allows custom gas limit via thegas
parameter- Both functions include proper error handling with require statements
- No other hardcoded gas values were found in the codebase
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for the source contract to verify gas forwarding implementation fd -t f "TestFunTokenPrecompileLocalGas.sol" | xargs cat # Verify no hardcoded gas values in other precompile calls rg -g "*.sol" "gas:" -A 5Length of output: 2077
x/evm/keeper/funtoken_from_erc20_test.go (2)
205-205
: LGTM: Consistent gas limit implementationThe gas limits are appropriately set for different operations:
Erc20GasLimitExecute
for ERC20 mint operationsFunTokenGasLimitBankSend
for bank send operationsThis aligns well with the PR's objective of enhancing gas management in precompiles.
Also applies to: 223-223, 247-247, 379-379
214-215
: LGTM: Strategic gas meter resetsGas meters are appropriately reset before major operations to ensure accurate gas measurement in each test case. The placement is consistent and helps isolate gas consumption for individual operations.
Also applies to: 238-239, 256-257, 370-371
x/evm/keeper/grpc_query.go (3)
287-287
: LGTM: Consistent with non-committing behavior.The addition of
false
parameter aligns with the comment above about not committing StateDB.
425-425
: LGTM: Appropriate for gas estimation.The
false
parameter is correctly added to maintain the non-committing nature of gas estimation.
521-521
: LGTM: Suitable for transaction tracing.The
false
parameter is correctly added to maintain the non-committing nature of transaction tracing.CHANGELOG.md (1)
Line range hint
1-1338
: LGTM! Well-structured changelog following best practices.The changelog is well-organized and follows the Keep a Changelog format consistently. It effectively documents changes with:
- Clear sections for different types of changes
- Consistent PR link formatting
- Chronological ordering
- Good use of markdown for readability
x/evm/keeper/funtoken_from_coin.go (5)
4-4
: Approved: Proper Import of"context"
PackageThe import of the
"context"
package is necessary for usingcontext.Context
in the new methodConvertCoinToEvm
.
96-117
: Review Error Handling inConvertCoinToEvm
MethodThe method
ConvertCoinToEvm
properly handles various error cases such as missing or multiple FunToken mappings. Ensure that all possible error paths are adequately tested.Would you like help in identifying any untested error paths within this method?
🧰 Tools
🪛 GitHub Check: codecov/patch
[warning] 104-105: x/evm/keeper/funtoken_from_coin.go#L104-L105
Added lines #L104 - L105 were not covered by tests
[warning] 107-108: x/evm/keeper/funtoken_from_coin.go#L107-L108
Added lines #L107 - L108 were not covered by tests
156-160
: Approved: Event Emission After Successful ConversionEmitting the
EventConvertCoinToEvm
event after a successful conversion is good practice for transparency and auditing.
83-83
: Verify the Use ofErc20GasLimitDeploy
in Contract DeploymentEnsure that the
Erc20GasLimitDeploy
parameter is correctly defined and passed to thedeployERC20ForBankCoin
function. This parameter controls the gas limit for contract deployment and should be consistently used across the codebase.Run the following script to confirm that
Erc20GasLimitDeploy
is appropriately defined and used:#!/bin/bash # Description: Verify usage of Erc20GasLimitDeploy in the codebase. # Test: Search for the definition and usage of Erc20GasLimitDeploy. # Expect: Erc20GasLimitDeploy is defined and used where necessary. rg 'Erc20GasLimitDeploy'
143-143
: Confirm Definition ofErc20GasLimitExecute
The variable
Erc20GasLimitExecute
used in theCallContract
function should be defined and set appropriately. Verify that it holds the correct gas limit value for executing contracts.Run the following script to check the definition and usage of
Erc20GasLimitExecute
:✅ Verification successful
Based on the search results, I can generate the final response as we have found clear evidence of the definition and usage of
Erc20GasLimitExecute
.
Erc20GasLimitExecute
is properly defined with appropriate gas limitThe constant is well-defined in
x/evm/keeper/erc20.go
with a value of 200,000 gas units and is documented as being used for transfer, mint, and burn operations. This is a reasonable gas limit for ERC20 operations.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify definition and usage of Erc20GasLimitExecute. # Test: Search for the definition and ensure it's correctly assigned. # Expect: Erc20GasLimitExecute is defined with an appropriate gas limit. rg 'Erc20GasLimitExecute'Length of output: 725
x/evm/precompile/precompile.go (2)
151-152
: Looks good: Addition ofparentGasMeter
fieldThe inclusion of
parentGasMeter
in theOnRunStartResult
struct is appropriate for managing gas meters during precompile execution.
199-205
: Verify thatReturnToParentGasMeter
is properly invokedAfter switching to a local gas meter within
OnRunStart
, please ensure thatReturnToParentGasMeter
is called appropriately to restore the parent gas meter after execution or in case of errors. This is crucial for maintaining accurate gas accounting.x/evm/precompile/funtoken.go (1)
74-76
: Proper Handling of Gas Meter ResetThe deferred call to
ReturnToParentGasMeter
correctly ensures that the gas meter is reset to the parent gas meter after precompile execution and gracefully handles "out of gas" errors. This implementation enhances the reliability of gas management within the precompile.x/evm/keeper/funtoken_from_erc20.go (3)
296-296
: Ensure consistent return values on errorsVerify that all error paths return
nil
for the response to maintain consistency and prevent potential nil pointer dereferences.Please confirm that in all error scenarios, the function returns
nil
for the*evm.MsgConvertCoinToEvmResponse
to ensure consistency.
245-249
: 🛠️ Refactor suggestionSimplify EVM module balance error handling
Similar to the previous comment, consider simplifying the error handling for
evmModuleBalance
to improve code clarity.Suggested change:
evmModuleBalance, err := k.ERC20().BalanceOf( erc20Addr, evm.EVM_MODULE_ADDRESS, ctx, ) if err != nil { return nil, errors.Wrap(err, "failed to retrieve EVM module balance") } - if evmModuleBalance == nil { - return nil, fmt.Errorf("failed to retrieve balance, balance is nil") - }Likely invalid or redundant comment.
🧰 Tools
🪛 GitHub Check: codecov/patch
[warning] 245-246: x/evm/keeper/funtoken_from_erc20.go#L245-L246
Added lines #L245 - L246 were not covered by tests
[warning] 248-249: x/evm/keeper/funtoken_from_erc20.go#L248-L249
Added lines #L248 - L249 were not covered by tests
270-276
: 🛠️ Refactor suggestionSimplify recipient balance after transfer error handling
Consistent with prior suggestions, streamline the error checks for
recipientBalanceAfter
.Suggested change:
recipientBalanceAfter, err := k.ERC20().BalanceOf(erc20Addr, recipient, ctx) if err != nil { return nil, errors.Wrap(err, "failed to retrieve recipient balance after transfer") } - if recipientBalanceAfter == nil { - return nil, fmt.Errorf("failed to retrieve balance, balance is nil") - }Likely invalid or redundant comment.
🧰 Tools
🪛 GitHub Check: codecov/patch
[warning] 272-273: x/evm/keeper/funtoken_from_erc20.go#L272-L273
Added lines #L272 - L273 were not covered by tests
[warning] 275-276: x/evm/keeper/funtoken_from_erc20.go#L275-L276
Added lines #L275 - L276 were not covered by testsx/evm/keeper/msg_server.go (1)
66-66
: Ensure Consistent Usage of New Parameter inApplyEvmMsg
At line 66, the
ApplyEvmMsg
function is called with the new parameterfalse
. Please verify that all other invocations ofApplyEvmMsg
throughout the codebase have been updated to include the newfullRefundLeftoverGas
parameter to maintain consistency and prevent potential issues.You can run the following script to identify all usages of
ApplyEvmMsg
and check for correct parameter usage:✅ Verification successful
Based on the
rg
search results, I can generate the final response as all instances ofApplyEvmMsg
calls are visible with their parameters.All
ApplyEvmMsg
Calls Are Consistent with New ParameterAll invocations of
ApplyEvmMsg
throughout the codebase have been properly updated to include the newfullRefundLeftoverGas
parameter:
x/evm/keeper/msg_server.go:66
:false
for regular EVM transactionsx/evm/keeper/msg_server.go:144
:true
for internal callsx/evm/keeper/grpc_query.go:52
:false
for query operationsx/evm/keeper/grpc_query.go:108
:false
for estimationx/evm/keeper/grpc_query.go:143
:false
for trace operationsx/evm/keeper/grpc_query.go:171
:false
for raw call operations🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Search for all calls to ApplyEvmMsg and display the surrounding lines. # Expectation: All calls should include the new parameter. rg 'ApplyEvmMsg\(' -A 3 -B 3Length of output: 3408
func (k Keeper) GetMinGasUsedMultiplier(ctx sdk.Context) math.LegacyDec { | ||
return math.LegacyNewDecWithPrec(50, 2) // 50% | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Consider making the gas multiplier configurable.
The 50% multiplier is currently hardcoded. Consider making this value configurable through module parameters to allow for future adjustments based on network needs without requiring a code change.
Example implementation:
+// Params keys
+const (
+ KeyMinGasUsedMultiplier = "MinGasUsedMultiplier"
+)
func (k Keeper) GetMinGasUsedMultiplier(ctx sdk.Context) math.LegacyDec {
- return math.LegacyNewDecWithPrec(50, 2) // 50%
+ return k.GetParams(ctx).MinGasUsedMultiplier
}
Committable suggestion was skipped due to low confidence.
deps.Ctx, | ||
deps.Sender.EthAddr, | ||
&precompile.PrecompileAddr_Wasm, | ||
true, | ||
input, | ||
WasmGasLimitInstantiate, |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Consider using a separate gas limit constant for queries.
Currently using WasmGasLimitInstantiate
for a query operation, which is excessive as queries typically consume less gas than contract instantiation.
Consider introducing a new constant like WasmGasLimitQuery
with a lower value appropriate for query operations:
const (
WasmGasLimitInstantiate uint64 = 1_000_000
WasmGasLimitExecute uint64 = 10_000_000
+ WasmGasLimitQuery uint64 = 100_000
)
Then update the query operation:
- WasmGasLimitInstantiate,
+ WasmGasLimitQuery,
Committable suggestion was skipped due to low confidence.
x/evm/keeper/msg_server.go
Outdated
return nil, fmt.Errorf("failed to pack ABI args: %w", err) | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Add Test Coverage for ABI Packing Failure
Lines 591-592 handle errors that may occur during ABI argument packing. Consider adding test cases that simulate a packing failure to verify that the error is correctly caught and handled, ensuring robustness in contract interactions.
🧰 Tools
🪛 GitHub Check: codecov/patch
[warning] 591-592: x/evm/keeper/msg_server.go#L591-L592
Added lines #L591 - L592 were not covered by tests
x/evm/keeper/msg_server.go
Outdated
err = errors.Wrapf(err, "failed to load EVM config") | ||
return | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Add Test Coverage for EVM Config Loading Failure
The error handling at lines 650-652 addresses failures in loading the EVM configuration. Adding unit tests that simulate this failure scenario can help ensure that the system responds appropriately when such an error occurs.
🧰 Tools
🪛 GitHub Check: codecov/patch
[warning] 650-652: x/evm/keeper/msg_server.go#L650-L652
Added lines #L650 - L652 were not covered by tests
x/evm/keeper/msg_server.go
Outdated
// We don't know the actual gas used, so consuming the gas limit | ||
k.ResetGasMeterAndConsumeGas(ctx, gasLimit) | ||
err = errors.Wrap(err, "failed to apply ethereum core message") | ||
return | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Add Test Coverage for EVM Message Application Failure
Lines 665-669 deal with failures when applying the EVM message. Implementing tests to cover this failure path will help validate that the system handles such errors gracefully and that the correct amount of gas is consumed.
🧰 Tools
🪛 GitHub Check: codecov/patch
[warning] 665-669: x/evm/keeper/msg_server.go#L665-L669
Added lines #L665 - L669 were not covered by tests
x/evm/keeper/msg_server.go
Outdated
k.ResetGasMeterAndConsumeGas(ctx, ctx.GasMeter().Limit()) | ||
return nil, nil, errors.Wrap(err, "error adding transient gas used to block") | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Add Test Coverage for Block Gas Usage Update Failure
At lines 688-690, there's error handling for failures in updating the block's gas usage. It's important to include tests that cover this scenario to ensure that any issues in gas accounting are detected and managed correctly.
🧰 Tools
🪛 GitHub Check: codecov/patch
[warning] 688-690: x/evm/keeper/msg_server.go#L688-L690
Added lines #L688 - L690 were not covered by tests
x/evm/keeper/msg_server.go
Outdated
return nil, nil, errors.Wrap(err, "error emitting ethereum tx events") | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Add Test Coverage for Event Emission Failure
Lines 695-696 address potential errors when emitting Ethereum transaction events. Considering the importance of accurate event logs, adding tests for this failure scenario will help ensure reliable system behavior and easier troubleshooting.
🧰 Tools
🪛 GitHub Check: codecov/patch
[warning] 695-696: x/evm/keeper/msg_server.go#L695-L696
Added lines #L695 - L696 were not covered by tests
There was a problem hiding this 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)
x/evm/keeper/funtoken_from_coin.go (1)
82-82
: Document the gas limit parameter.
Consider adding a comment explaining the expected gas limit range and any constraints for ERC20 deployment.
Add a comment above the CallContractWithInput call:
+ // Erc20GasLimitDeploy should be sufficient for standard ERC20 deployment
+ // Typical deployment costs: [ADD TYPICAL GAS COST HERE]
_, _, err = k.CallContractWithInput(
x/evm/keeper/call_contract.go (2)
62-63
: Update function comment to reflect custom gas limit
The comment states: "It uses a default gas limit." However, the function now accepts a gasLimit
parameter, allowing callers to specify a custom gas limit. Please update the comment to reflect this change.
81-81
: Rename unusedBigInt
to zeroBigInt
for clarity
The variable unusedBigInt
is actively used as a zero value for amount
, gasFeeCap
, gasTipCap
, and gasPrice
in the evmMsg
. Since it is not unused, consider renaming it to zeroBigInt
or bigIntZero
to enhance code readability and accurately represent its purpose.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (3)
- x/evm/keeper/call_contract.go (1 hunks)
- x/evm/keeper/funtoken_from_coin.go (1 hunks)
- x/evm/keeper/msg_server.go (5 hunks)
🔇 Additional comments (2)
x/evm/keeper/funtoken_from_coin.go (1)
82-82
: Verify gas limit sufficiency for ERC20 deployment.
The addition of Erc20GasLimitDeploy
improves gas management control. However, we should ensure the gas limit is sufficient for all ERC20 deployment scenarios.
Let's analyze the gas usage patterns in existing deployments:
✅ Verification successful
Based on the search results, I found clear evidence about the gas limit in x/evm/keeper/erc20.go
:
// Erc20GasLimitDeploy only used internally when deploying ERC20Minter.
// Deployment requires ~1_600_000 gas
Erc20GasLimitDeploy uint64 = 2_000_000
Let's verify if this gas limit has been sufficient in practice by checking the test cases:
Let me try a different search pattern to find any test cases or issues related to ERC20 deployment:
Based on the evidence gathered, I can now provide a final response:
Gas limit of 2M for ERC20 deployment is well-calibrated
The Erc20GasLimitDeploy
value of 2,000,000 gas is appropriate because:
- Internal documentation confirms deployment requires ~1.6M gas
- The 2M limit provides a 25% safety margin above the required amount
- No gas-related failures were found in the test suite
- The gas limit is used consistently across contract deployments via
CallContractWithInput
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Search for existing ERC20 deployment gas usage patterns
rg -A 5 "deploy.*ERC20"
Length of output: 6995
Script:
#!/bin/bash
# Search for any gas-related failures or issues in ERC20 tests
rg -i "gas.*fail.*erc20|erc20.*gas.*fail"
# Check test files for any gas-related configurations
rg "gas.*erc20|erc20.*gas" "**/*test*"
Length of output: 134
Script:
#!/bin/bash
# Search for ERC20 deployment tests and any gas-related configurations
rg -A 5 "TestERC20.*deploy|test.*deploy.*ERC20"
# Search for any gas-related constants or configurations in ERC20 files
rg "gas.*=|gasLimit" x/evm/keeper/
Length of output: 2608
x/evm/keeper/msg_server.go (1)
66-66
: Verify consistent usage of fullRefundLeftoverGas
parameter across codebase.
In this call to ApplyEvmMsg
, the fullRefundLeftoverGas
parameter is set to false
. Please ensure that all calls to ApplyEvmMsg
pass the appropriate value for fullRefundLeftoverGas
based on the context, to maintain consistent gas refund behavior.
Run the following script to find all calls to ApplyEvmMsg
and display the values passed for fullRefundLeftoverGas
:
✅ Verification successful
Let me get more context by checking the actual calls to ApplyEvmMsg with surrounding code.
fullRefundLeftoverGas
parameter is used consistently across the codebase
The parameter is used consistently based on the context:
- Set to
false
for all regular EVM transactions and queries - Set to
true
only incall_contract.go
for internal contract calls, where the comment explicitly states "For internal calls like funtokens, user does not specify gas limit explicitly. In this case we don't apply any caps for refund and refund 100%"
The current change setting it to false
in msg_server.go
aligns with this pattern since it handles regular EVM transactions.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Find all calls to ApplyEvmMsg and extract the `fullRefundLeftoverGas` argument.
# Test: Search for ApplyEvmMsg function calls and list the values of `fullRefundLeftoverGas`.
rg --no-filename --no-line-number 'ApplyEvmMsg\([^)]*\)' -t go \
| grep -o 'ApplyEvmMsg([^)]*)' \
| sed -E 's/.*ApplyEvmMsg\(([^)]*)\).*/\1/' \
| awk -F',' '{print $NF}' \
| sed 's/^[ \t]*//;s/[ \t]*$//' \
| sort | uniq -c
Length of output: 253
Script:
#!/bin/bash
# Search for ApplyEvmMsg calls with context
rg "ApplyEvmMsg\(" -B 2 -A 2 -t go
Length of output: 2480
// | ||
// # fullRefundLeftoverGas parameter | ||
// For internal calls like funtokens, user does not specify gas limit explicitly. | ||
// In this case we don't apply any caps for refund and refund 100% |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Include fullRefundLeftoverGas
in the function's documentation.
The parameter fullRefundLeftoverGas
is introduced in the ApplyEvmMsg
function but is not described in the function's doc comment. To improve clarity and maintain comprehensive documentation, please include a description of the fullRefundLeftoverGas
parameter within the function's documentation. This will help other developers understand its purpose and usage.
refundQuotient := params.RefundQuotientEIP3529 // EIP-3529: refunds are capped to gasUsed / 5 | ||
minGasUsedPct := k.GetMinGasUsedMultiplier(ctx) // Evmos invention: https://github.com/evmos/ethermint/issues/1085 | ||
if fullRefundLeftoverGas { | ||
refundQuotient = 1 // 100% refund | ||
minGasUsedPct = math.LegacyZeroDec() // no minimum, get the actual gasUsed value |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Add unit tests for fullRefundLeftoverGas
logic.
The conditional logic based on fullRefundLeftoverGas
affects the refund calculation by altering refundQuotient
and minGasUsedPct
. To ensure correctness and prevent regressions, please add unit tests that cover both scenarios where fullRefundLeftoverGas
is true
and false
. This will verify that the refund calculations behave as expected in both cases.
Notes
Example:
gasLimit
toCallContractWithInput
to limit gas for internal calls related to funtoken.Summary by CodeRabbit
New Features
Bug Fixes
Performance Improvements
Documentation
Tests