-
Notifications
You must be signed in to change notification settings - Fork 282
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
Conversation
""" WalkthroughThis 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
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
Possibly related PRs
Suggested labels
Suggested reviewers
Poem
✨ Finishing Touches
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed 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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
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: 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 contractL2BaseFeeOverheadSlot
andL2BaseFeeScalarSlot
should contain the correct storage slot positionsDo 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:
Event validation: Add validation that the log has sufficient topics before accessing
r.Topics[1]
andr.Topics[2]
to prevent panics.Error handling: Consider adding error handling around
misc.UpdateL2BaseFeeParams()
in case the update fails.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
📒 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
androllup/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:
- The L2SystemConfigAddress is set to the correct deployed contract address for each network
- The address corresponds to a contract that emits the expected L2BaseFeeUpdateTopic events
- 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 goLength of output: 1261
Confirm L2SystemConfigAddress Is Configured
The L2 base‐fee update logic in
core/blockchain.go
will be inactive untilL2SystemConfigAddress
is set. Currently both Sepolia and Mainnet entries inparams/config.go
are still defaulting to an empty address:File: params/config.go
// Sepolia L2SystemConfigAddress: common.Address{}, // TODO // Mainnet L2SystemConfigAddress: common.Address{}, // TODOPlease 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]
andtopics[2]
correspond toscalar
andoverhead
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.
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.
looks good except dynamically updating txpool.PriceLimit
0d93eb2
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: 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 usingcommon.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
📒 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
andcommon.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
andcommon.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.
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: 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
📒 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.
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: 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 returnscommon.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
📒 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
andUpdateL2BaseFeeScalar
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. TheMinBaseFee
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:
State access: The
State.GetState()
method returnscommon.Hash
- verify this doesn't silently fail for non-existent storage slots.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 neverLength of output: 251
🏁 Script executed:
#!/bin/bash # Show context around the initialization call to verify timing rg -C5 "InitializeL2BaseFeeCoefficients" -n --color never eth/backend.goLength 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.
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:
Example update logs:
Fee RPC responses:
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:
3. Deployment tag versioning
Has the version in
params/version.go
been updated?4. Breaking change label
Does this PR have the
breaking-change
label?Summary by CodeRabbit
New Features
Bug Fixes
Chores