Skip to content

feat: update base fee via contract #1189

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

Merged
merged 23 commits into from
May 28, 2025
Merged

Conversation

Thegaram
Copy link

@Thegaram Thegaram commented May 23, 2025

1. Purpose or design rationale of this PR

Revert most changes from #1183.

Update L2 base fee coefficients automatically after block import using a new system contract scroll-tech/scroll-contracts#114.

Testing notes

Tested this version on a local devnet.

Example startup logs:

Initialised chain configuration          config="{ChainID: 333333 [...] L2SystemConfigAddress: 0xfF8F50bDb55f2dA8A38417C49BE9DDDf068EA973}, genesisStateRoot: <nil>}}"
Initialized L2 base fee coefficients     overhead=15,680,000 scalar=34,000,000,000,000
Transaction pool price threshold updated price=15,680,000

Example update logs:

Updated L2 base fee overhead             blockNumber=3 blockHash=0x54a232b7dcd01e8fd8e5176d36925db92b67d959f8a9ef40027cb39e688a3b73 old=0 new=1
Updated L2 base fee scalar               blockNumber=3 blockHash=0x54a232b7dcd01e8fd8e5176d36925db92b67d959f8a9ef40027cb39e688a3b73 old=0 new=2
Updating min base fee in txpool          old=15,680,000 new=1
Transaction pool price threshold updated price=1

...

Updated L2 base fee overhead             blockNumber=38 blockHash=0x234e9036c575a6eb904444190d62ddd7cb39a6bce3dff7bea46aab6cb548e46c old=1          new=2
Updating min base fee in txpool          old=1          new=2
Transaction pool price threshold updated price=2

...

Updated L2 base fee scalar               blockNumber=40 blockHash=0xb32329c765d4cecfd7dc62ae10faf2087ba9ef2e2b13c0bbd44b37b5e7c23c71 old=2          new=1,000,000,000,000,000,000

Fee RPC responses:

# initial values (overhead=15,680,000 scalar=34,000,000,000,000)
eth_gasPrice:                  15680100
eth_maxPriorityFeePerGas:      100
eth_feeHistory(pending):       15680000
eth_getBlockByNumber(pending): 15680000

# after 1st update (overhead=1 scalar=2)
eth_gasPrice:                  101
eth_maxPriorityFeePerGas:      100
eth_feeHistory(pending):       1
eth_getBlockByNumber(pending): 1

# after 2nd update (overhead=2 scalar=2)
eth_gasPrice:                  102
eth_maxPriorityFeePerGas:      100
eth_feeHistory(pending):       2
eth_getBlockByNumber(pending): 2

# after 3rd update (overhead=2 scalar=1,000,000,000,000,000,000, l1BaseFee=7wei)
eth_gasPrice:                  109
eth_maxPriorityFeePerGas:      100
eth_feeHistory(pending):       9
eth_getBlockByNumber(pending): 9

2. PR title

Your PR title must follow conventional commits (as we are doing squash merge for each PR), so it must start with one of the following types:

  • feat: A new feature

3. Deployment tag versioning

Has the version in params/version.go been updated?

  • This PR doesn't involve a new deployment, git tag, docker image tag, and it doesn't affect traces
  • Yes

4. Breaking change label

Does this PR have the breaking-change label?

  • This PR is not a breaking change
  • Yes

Summary by CodeRabbit

  • New Features

    • L2 base fee parameters now update dynamically via on-chain events for improved accuracy.
    • Initialization of L2 base fee coefficients directly from blockchain state added.
    • Transaction pool gas price automatically adjusts to the current minimum base fee on chain head changes.
    • Mining worker panic logs enhanced with full stack traces for better debugging.
    • New package introduced for decoding and verifying L2 system config events.
    • Added a new web3 extension property exposing L2 base fee configuration.
  • Bug Fixes

    • Removed deprecated CLI flags and config fields related to L2 base fee to simplify configuration.
  • Chores

    • Internal version updated to 0.0.51.

Copy link

coderabbitai bot commented May 23, 2025

"""

Walkthrough

This change removes CLI flags, configuration fields, and related logic for L2 base fee scalar and overhead, centralizing their management via package-level variables updated by chain events. It also introduces new configuration fields for the L2 system config address and event topics, adds dynamic initialization from chain state, enhances panic logging, and bumps the patch version.

Changes

Files / Areas Changed Summary
cmd/geth/main.go, cmd/geth/usage.go Removed L2BaseFeeScalarFlag and L2BaseFeeOverheadFlag from CLI flags and help groups.
cmd/utils/flags.go Deleted flag declarations, flag handling, and the setBaseFee function. Removed imports and flag setup.
consensus/misc/eip1559.go Centralized L2 base fee parameters as package-level variables with mutex; added UpdateL2BaseFeeScalar and UpdateL2BaseFeeOverhead.
consensus/misc/eip1559_test.go Updated tests to use UpdateL2BaseFeeScalar and UpdateL2BaseFeeOverhead instead of direct config assignment.
core/blockchain.go Added logic to update L2 base fee parameters from chain events during block processing; added metrics timer; improved logging.
eth/backend.go Removed assignment of base fee scalar/overhead to chain config during initialization; added dynamic state-based initialization of coefficients.
eth/ethconfig/config.go Removed BaseFeeScalar and BaseFeeOverhead fields from Config struct.
params/config.go Added L2SystemConfigAddress to L1Config. Removed base fee fields from ScrollConfig. Updated String() and added accessor method.
params/version.go Bumped VersionPatch from 50 to 51.
rollup/rcfg/config.go Added variables for L2 base fee update event topics and storage slots with detailed comments.
core/tx_pool.go Added logic to update transaction pool gas price dynamically based on the current minimum base fee.
core/state_processor_test.go Updated expected error strings for transaction failure test cases to new transaction hashes.
miner/scroll_worker.go Enhanced panic recovery in worker mainLoop to print stack traces on panic.
rollup/l2_system_config/abi.go Added new package for L2 system config ABI with event definitions and unpacking functions for base fee updates.
rollup/l2_system_config/abi_test.go Added tests verifying event signature hashes and unpacking of base fee update logs.
eth/api.go Added comment clarifying gas price override behavior in SetGasPrice method of PrivateMinerAPI.
internal/web3ext/web3ext.go Added new l2BaseFeeConfig property with getter scroll_getL2BaseFeeConfig to the scroll web3 extension.

Sequence Diagram(s)

sequenceDiagram
    participant BlockChain
    participant Log
    participant misc as EIP1559 Package

    BlockChain->>Log: Process block logs
    alt If log is BaseFeeOverheadUpdated event
        Log->>misc: UpdateL2BaseFeeOverhead(new value)
        misc-->>Log: Update internal base fee overhead
    else If log is BaseFeeScalarUpdated event
        Log->>misc: UpdateL2BaseFeeScalar(new value)
        misc-->>Log: Update internal base fee scalar
    end
    BlockChain->>misc: CalcBaseFee(...)
    misc-->>BlockChain: Return calculated base fee
Loading

Possibly related PRs

  • feat: update base fee via cli #1183: The main PR removes the CLI flags and related code for L2 base fee scalar and overhead that were introduced in the retrieved PR feat: update base fee via cli #1183, effectively undoing the addition of these flags and their configuration handling; thus, the changes are directly related but inverse in purpose.
  • feat: update L2 base fee formula #1169: Updates the L2 base fee formula constants inside the calculation function; related to base fee handling but focuses on formula changes rather than configuration and update mechanisms.

Suggested labels

bump-version

Suggested reviewers

  • georgehao
  • colinlyguo

Poem

The flags are gone, the scalars too,
Now base fees dance when events come through.
No more config fields to clutter the scene,
Updates are locked, atomic, and clean.
With a hop and a skip, the patch ticks anew—
A rabbit’s delight in code review! 🐇✨
"""

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (2)
rollup/rcfg/config.go (1)

52-56: Address TODO comments before deployment.

The L2 base fee configuration variables are initialized with placeholder values and contain TODO comments indicating they need proper assignment. These must be set to correct values before this code can be used in production.

Please ensure these values are properly configured:

  • L2BaseFeeUpdateTopic should contain the actual event topic hash from the L2 system config contract
  • L2BaseFeeOverheadSlot and L2BaseFeeScalarSlot should contain the correct storage slot positions

Do you need help determining the correct values for these variables, or should we create an issue to track setting these properly?

core/blockchain.go (1)

275-293: Review the L2 base fee update implementation for robustness.

The implementation correctly processes L2 system config events to update base fee parameters, but consider these potential improvements:

  1. Event validation: Add validation that the log has sufficient topics before accessing r.Topics[1] and r.Topics[2] to prevent panics.

  2. Error handling: Consider adding error handling around misc.UpdateL2BaseFeeParams() in case the update fails.

  3. Performance consideration: The code iterates through all logs for every block. For blocks with many logs, this could be expensive, but it's likely acceptable given the importance of fee updates.

Example improvement for safety:

 for _, r := range logs {
-	if r.Address == l2SystemConfigAddress && r.Topics[0] == rcfg.L2BaseFeeUpdateTopic {
+	if r.Address == l2SystemConfigAddress && len(r.Topics) >= 3 && r.Topics[0] == rcfg.L2BaseFeeUpdateTopic {
 		scalar := r.Topics[1].Big()
 		overhead := r.Topics[2].Big()
-		misc.UpdateL2BaseFeeParams(scalar, overhead)
+		if err := misc.UpdateL2BaseFeeParams(scalar, overhead); err != nil {
+			log.Warn("Failed to update L2 base fee params", "err", err, "blockNumber", block.NumberU64())
+		} else {
 			log.Info("Updated L2 base fee coefficients", "blockNumber", block.NumberU64(), "blockHash", block.Hash().Hex(), "scalar", scalar, "overhead", overhead)
+		}
 	}
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 141a8df and cf9d97d.

📒 Files selected for processing (11)
  • cmd/geth/main.go (0 hunks)
  • cmd/geth/usage.go (0 hunks)
  • cmd/utils/flags.go (0 hunks)
  • consensus/misc/eip1559.go (3 hunks)
  • consensus/misc/eip1559_test.go (3 hunks)
  • core/blockchain.go (4 hunks)
  • eth/backend.go (0 hunks)
  • eth/ethconfig/config.go (0 hunks)
  • params/config.go (4 hunks)
  • params/version.go (1 hunks)
  • rollup/rcfg/config.go (1 hunks)
💤 Files with no reviewable changes (5)
  • cmd/geth/main.go
  • eth/ethconfig/config.go
  • eth/backend.go
  • cmd/geth/usage.go
  • cmd/utils/flags.go
🧰 Additional context used
🧬 Code Graph Analysis (2)
rollup/rcfg/config.go (1)
common/types.go (2)
  • HexToHash (66-66)
  • BigToHash (62-62)
consensus/misc/eip1559_test.go (1)
consensus/misc/eip1559.go (2)
  • UpdateL2BaseFeeParams (46-52)
  • MinBaseFee (87-89)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: test
  • GitHub Check: Analyze (go)
🔇 Additional comments (13)
params/version.go (1)

27-27: LGTM! Version bump is appropriate.

The patch version increment from 49 to 50 correctly reflects the deployment of the new L2 base fee management features introduced in this PR.

consensus/misc/eip1559.go (3)

22-22: LGTM! Proper import for synchronization.

The addition of the sync package is necessary for the mutex-based thread safety implementation.


36-44: LGTM! Well-designed package-level variable structure.

The use of package-level variables with default values and mutex protection is a good architectural choice for centralizing L2 base fee parameter management. The default values match the previous configuration defaults, ensuring backward compatibility.


81-84: LGTM! Proper mutex usage for thread safety.

The read lock acquisition before accessing the package-level variables ensures thread-safe access to the base fee parameters. The defer statement ensures proper lock release.

consensus/misc/eip1559_test.go (3)

125-125: LGTM! Test properly updated for new parameter management.

The test correctly uses UpdateL2BaseFeeParams to set the base fee parameters before testing the calculation logic. The values (10000000, 1) are appropriate for this test scenario.


144-144: LGTM! Test uses correct default values.

The test properly uses the default base fee parameters (34000000000000, 15680000) that match the package-level defaults, ensuring consistency with the refactored implementation.


153-153: LGTM! Test updated to use explicit values.

The test correctly uses explicit big integer values instead of the removed constants, maintaining the same test logic while adapting to the new parameter management approach.

core/blockchain.go (3)

37-37: LGTM! Necessary imports for L2 base fee functionality.

The imports for consensus/misc and rollup/rcfg packages are required for the new L2 base fee update mechanism implemented in this file.

Also applies to: 49-49


60-61: LGTM! Proper metrics for L2 base fee monitoring.

The new metrics follow the existing naming conventions and provide valuable observability for L2 base fee values and update performance.


280-280:

❓ Verification inconclusive

Verify L2SystemConfigAddress configuration is properly set.

The L2 base fee update functionality depends on L2SystemConfigAddress being correctly configured. Currently, this address is set to empty in the chain configurations with TODO comments.

Please ensure that:

  1. The L2SystemConfigAddress is set to the correct deployed contract address for each network
  2. The address corresponds to a contract that emits the expected L2BaseFeeUpdateTopic events
  3. The event structure matches the expected format with scalar and overhead in topics[1] and topics[2]

🏁 Script executed:

#!/bin/bash
# Verify L2SystemConfigAddress configuration across different networks
echo "Checking L2SystemConfigAddress configuration in chain configs:"
rg -A 2 -B 2 "L2SystemConfigAddress.*common\.Address" --type go

Length of output: 1261


Confirm L2SystemConfigAddress Is Configured

The L2 base‐fee update logic in core/blockchain.go will be inactive until L2SystemConfigAddress is set. Currently both Sepolia and Mainnet entries in params/config.go are still defaulting to an empty address:

File: params/config.go

// Sepolia
L2SystemConfigAddress:           common.Address{}, // TODO

// Mainnet
L2SystemConfigAddress:           common.Address{}, // TODO

Please ensure you:

  • Populate L2SystemConfigAddress with the correct deployed L2SystemConfig contract address for each network.
  • Confirm the contract emits the expected L2BaseFeeUpdateTopic events.
  • Verify that topics[1] and topics[2] correspond to scalar and overhead in your event decoding.
params/config.go (3)

719-719: LGTM! Proper field addition to L1Config struct.

The L2SystemConfigAddress field is correctly added with appropriate type and JSON serialization tag.


727-728: LGTM! String method properly updated for new field.

The L1Config String method correctly includes the new L2SystemConfigAddress field with proper hex formatting, maintaining consistency with other address fields.


759-760: LGTM! ScrollConfig String method updated correctly.

The String method properly excludes the removed BaseFeeScalar and BaseFeeOverhead fields, maintaining consistency with the transition to dynamic L2 base fee updates.

colinlyguo
colinlyguo previously approved these changes May 23, 2025
Copy link

@jonastheis jonastheis left a comment

Choose a reason for hiding this comment

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

looks good except dynamically updating txpool.PriceLimit

colinlyguo
colinlyguo previously approved these changes May 26, 2025
zimpha
zimpha previously approved these changes May 26, 2025
jonastheis
jonastheis previously approved these changes May 26, 2025
@Thegaram Thegaram dismissed stale reviews from jonastheis, zimpha, and colinlyguo via 0d93eb2 May 26, 2025 16:23
colinlyguo
colinlyguo previously approved these changes May 26, 2025
colinlyguo
colinlyguo previously approved these changes May 27, 2025
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: 1

🧹 Nitpick comments (2)
rollup/l2_system_config/abi_test.go (1)

19-21: Consider using a more descriptive function name.

The helper function bigToBytesPadded correctly converts a big.Int to 32-byte padded format using common.BigToHash. However, the name could be more descriptive to clarify its purpose.

-func bigToBytesPadded(num *big.Int) []byte {
+func bigIntTo32BytesPadded(num *big.Int) []byte {
	return common.BigToHash(num).Bytes()
}
rollup/l2_system_config/abi.go (1)

30-32: Consider validating the embedded ABI JSON.

The hardcoded ABI JSON string is quite long and could be error-prone to maintain. Consider adding validation or extracting it to a separate file.

You could add validation in the init function:

func init() {
	var err error
	l2SystemConfigABI, err = l2SystemConfigMetaData.GetAbi()
	if err != nil {
		panic(fmt.Sprintf("failed to parse L2 system config ABI: %v", err))
	}

+	// Validate expected events exist
+	if _, exists := l2SystemConfigABI.Events[baseFeeOverheadUpdatedEventName]; !exists {
+		panic(fmt.Sprintf("missing event %s in ABI", baseFeeOverheadUpdatedEventName))
+	}
+	if _, exists := l2SystemConfigABI.Events[baseFeeScalarUpdatedEventName]; !exists {
+		panic(fmt.Sprintf("missing event %s in ABI", baseFeeScalarUpdatedEventName))
+	}

	BaseFeeOverheadUpdatedTopic = l2SystemConfigABI.Events[baseFeeOverheadUpdatedEventName].ID
	BaseFeeScalarUpdatedTopic = l2SystemConfigABI.Events[baseFeeScalarUpdatedEventName].ID
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f05c634 and 28d1daa.

📒 Files selected for processing (6)
  • core/blockchain.go (6 hunks)
  • eth/backend.go (5 hunks)
  • miner/scroll_worker.go (2 hunks)
  • rollup/l2_system_config/abi.go (1 hunks)
  • rollup/l2_system_config/abi_test.go (1 hunks)
  • rollup/rcfg/config.go (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • rollup/rcfg/config.go
  • miner/scroll_worker.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • eth/backend.go
  • core/blockchain.go
🧰 Additional context used
🧬 Code Graph Analysis (1)
rollup/l2_system_config/abi.go (3)
accounts/abi/abi.go (1)
  • ABI (33-44)
accounts/abi/bind/base.go (1)
  • MetaData (82-88)
rollup/l1/abi.go (1)
  • UnpackLog (272-288)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (go)
🔇 Additional comments (5)
rollup/l2_system_config/abi_test.go (3)

14-17: LGTM! Well-structured event signature validation.

The test correctly verifies that the computed Keccak256 hashes of the event signatures match the topic constants defined in the companion ABI file. This ensures consistency between the hardcoded ABI and the expected event signatures.


23-36: Excellent test coverage for BaseFeeOverheadUpdated event unpacking.

The test properly constructs a mock log with the correct topic and data format, then verifies that the unpacking function correctly extracts the old and new base fee overhead values. The use of common.Big1 and common.Big2 provides clear, distinguishable test values.


38-51: Comprehensive test for BaseFeeScalarUpdated event unpacking.

Similar to the overhead test, this properly validates the scalar event unpacking with different test values (common.Big32 and common.Big256). The test structure is consistent and thorough.

rollup/l2_system_config/abi.go (2)

34-42: Well-designed event structs with appropriate field types.

The event structs correctly use *big.Int for uint256 fields, which is the standard approach for handling large integers in Ethereum applications. The field names clearly correspond to the ABI event parameters.


44-54: Good delegation to shared unpacking utility.

The unpacking functions properly delegate to l1.UnpackLog, which promotes code reuse and consistency across the codebase. Error handling is appropriately propagated to the caller.

colinlyguo
colinlyguo previously approved these changes May 27, 2025
jonastheis
jonastheis previously approved these changes May 28, 2025
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
consensus/misc/eip1559.go (1)

137-163: Consider returning errors for better error handling.

The function always returns nil even when the L2SystemConfig address is not configured. Consider returning an error in this case to allow callers to handle it appropriately.

 	if l2SystemConfig := chainConfig.Scroll.L2SystemConfigAddress(); l2SystemConfig != (common.Address{}) {
 		overhead = state.GetState(l2SystemConfig, rcfg.L2BaseFeeOverheadSlot).Big()
 		scalar = state.GetState(l2SystemConfig, rcfg.L2BaseFeeScalarSlot).Big()
 	} else {
 		log.Warn("L2SystemConfig address is not configured")
+		// Optionally return an error to let caller decide how to handle
+		// return fmt.Errorf("L2SystemConfig address is not configured")
 	}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0a2ca25 and a7d324d.

📒 Files selected for processing (3)
  • consensus/misc/eip1559.go (3 hunks)
  • eth/backend.go (5 hunks)
  • internal/web3ext/web3ext.go (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • internal/web3ext/web3ext.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • eth/backend.go
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: test
  • GitHub Check: Analyze (go)
🔇 Additional comments (8)
consensus/misc/eip1559.go (8)

19-30: Imports look good!

All new imports are appropriately used for thread safety, logging, state access, and RPC API functionality.


32-41: Well-documented constants with reasonable defaults.

The constants provide good fallback values and the maximum base fee acts as a safety mechanism. The comment clearly explains when the maximum would be exceeded.


63-71: Good defensive programming with nil check.

The function properly validates input and uses Set() to copy the value, avoiding shared references. The error logging provides visibility into failures.


73-81: Consistent implementation with overhead update function.

Good to see the same defensive programming pattern applied here.


105-112: Thread-safe access to coefficients.

Good use of the new read function to ensure thread-safe access to the shared state.


114-118: Useful addition for minimum base fee calculation.

Clean implementation that reuses the existing calculation logic with zero L1 base fee.


133-136: Clean interface design for state access.

Minimal interface that provides just what's needed and enables easy testing.


165-188: Well-structured RPC API for monitoring.

The API provides a clean way to monitor the current L2 base fee configuration. Good choice to put it in the scroll namespace and keep it private.

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

♻️ Duplicate comments (1)
consensus/misc/eip1559.go (1)

51-52: Initialize with default values to prevent zero fee calculations.

The variables are still initialized to zero, which could cause zero fee calculations if InitializeL2BaseFeeCoefficients fails or is not called before these values are used.

This issue was previously flagged but remains unaddressed. Apply this fix:

-	baseFeeScalar   = big.NewInt(0)
-	baseFeeOverhead = big.NewInt(0)
+	baseFeeScalar   = big.NewInt(DefaultBaseFeeScalar)
+	baseFeeOverhead = big.NewInt(DefaultBaseFeeOverhead)
🧹 Nitpick comments (1)
consensus/misc/eip1559.go (1)

133-135: Consider extending the State interface for better error handling.

The current State interface only returns common.Hash without error information. Consider if state access failures need explicit handling.

If state access errors need handling, consider:

 type State interface {
-	GetState(addr common.Address, hash common.Hash) common.Hash
+	GetState(addr common.Address, hash common.Hash) (common.Hash, error)
 }

However, this change would require updates throughout the codebase, so it may be better as a separate refactor if needed.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a7d324d and aec13ff.

📒 Files selected for processing (1)
  • consensus/misc/eip1559.go (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: test
  • GitHub Check: Analyze (go)
🔇 Additional comments (5)
consensus/misc/eip1559.go (5)

57-61: LGTM: Properly returns copies to prevent external modification.

The function correctly returns copies of the internal *big.Int variables, preventing external modification and maintaining encapsulation.


63-81: LGTM: Well-implemented update functions with proper validation.

Both UpdateL2BaseFeeOverhead and UpdateL2BaseFeeScalar include:

  • Proper nil validation with descriptive error logging
  • Thread-safe access using write locks
  • Safe assignment using .Set() method

110-118: LGTM: Clean integration with the new coefficient management.

The functions properly use ReadL2BaseFeeCoefficients() to get current values with appropriate thread safety. The MinBaseFee signature simplification makes the API cleaner.


165-188: LGTM: Well-designed RPC API for coefficient inspection.

The API provides read-only access to current L2 base fee coefficients through a clean JSON structure. The namespace separation and proper RPC registration follow Go-Ethereum conventions.


137-163:

✅ Verification successful

Verify state access error handling and initialization timing.

The initialization function looks mostly correct, but consider these potential issues:

  1. State access: The State.GetState() method returns common.Hash - verify this doesn't silently fail for non-existent storage slots.

  2. Initialization timing: Ensure this function is called during chain startup before any fee calculations occur.

Run this script to verify the initialization is properly called during startup:


🏁 Script executed:

#!/bin/bash
# Check where InitializeL2BaseFeeCoefficients is called
ast-grep --pattern 'InitializeL2BaseFeeCoefficients($_)'

Length of output: 58


🏁 Script executed:

#!/bin/bash
# Search for any invocation of InitializeL2BaseFeeCoefficients across the repository
rg "InitializeL2BaseFeeCoefficients" -n --color never

Length of output: 251


🏁 Script executed:

#!/bin/bash
# Show context around the initialization call to verify timing
rg -C5 "InitializeL2BaseFeeCoefficients" -n --color never eth/backend.go

Length of output: 491


L2 base fee initialization timing and state access verified

Both concerns have been checked and require no changes:

  • State.GetState returns a zero hash for missing or uninitialized storage slots, and the existing fallback logic correctly applies the default overhead and scalar.
  • InitializeL2BaseFeeCoefficients is called in eth/backend.go (line 221) immediately after loading the chain state during startup—well before any fee calculations occur.

@Thegaram Thegaram merged commit cdd77c1 into develop May 28, 2025
14 checks passed
@Thegaram Thegaram deleted the feat-update-base-fee-via-contract branch May 28, 2025 12:51
@coderabbitai coderabbitai bot mentioned this pull request Jun 9, 2025
13 tasks
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