Skip to content

Commit

Permalink
baseFeeConfig as condition for london fork (#43)
Browse files Browse the repository at this point in the history
* baseFeeConfig as condition for london fork

* lint fix

* comment fix

* Update command/genesis/polybft_params.go

Co-authored-by: Goran Rojovic <[email protected]>

* deleted unnecessary if

* e2e test fix

* Linter fix

* Add base-fee-config to e2e tests where needed

* Add SetBaseFeeConfig to the legacy e2e framework

* Remove leftover

* Provide non-validator account as receiver of native tokens in TestE2E_Consensus_MintableERC20NativeToken

---------

Co-authored-by: Goran Rojovic <[email protected]>
Co-authored-by: Stefan Negovanović <[email protected]>
  • Loading branch information
3 people authored Dec 6, 2023
1 parent 88b480f commit 5c5d529
Show file tree
Hide file tree
Showing 11 changed files with 111 additions and 60 deletions.
4 changes: 2 additions & 2 deletions command/bridge/helper/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -275,15 +275,15 @@ func SendTransaction(txRelayer txrelayer.TxRelayer, addr ethgo.Address, input []

// CreateTransaction is a helper function that creates either dynamic fee or legacy transaction based on provided flag
func CreateTransaction(sender ethgo.Address, receiver *ethgo.Address,
input []byte, value *big.Int, isDynamicFee bool) *ethgo.Transaction {
input []byte, value *big.Int, isDynamicFeeTx bool) *ethgo.Transaction {
txn := &ethgo.Transaction{
From: sender,
To: receiver,
Input: input,
Value: value,
}

if isDynamicFee {
if isDynamicFeeTx {
txn.Type = ethgo.TransactionDynamicFee
} else {
txn.Type = ethgo.TransactionLegacy
Expand Down
2 changes: 1 addition & 1 deletion command/genesis/genesis.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ func setFlags(cmd *cobra.Command) {
cmd.Flags().StringVar(
&params.baseFeeConfig,
genesisBaseFeeConfigFlag,
command.DefaultGenesisBaseFeeConfig,
"",
`initial base fee(in wei), base fee elasticity multiplier, and base fee change denominator
(provided in the following format: [<baseFee>][:<baseFeeEM>][:<baseFeeChangeDenom>]).
BaseFeeChangeDenom represents the value to bound the amount the base fee can change between blocks.
Expand Down
26 changes: 16 additions & 10 deletions command/genesis/params.go
Original file line number Diff line number Diff line change
Expand Up @@ -203,19 +203,19 @@ func (p *genesisParams) generateGenesis() error {
}

func (p *genesisParams) initGenesisConfig() error {
enabledForks := chain.AllForksEnabled
enabledForks := chain.AllForksEnabled.Copy()
if p.parsedBaseFeeConfig == nil {
enabledForks.RemoveFork(chain.London)
}

chainConfig := &chain.Chain{
Name: p.name,
Genesis: &chain.Genesis{
GasLimit: p.blockGasLimit,
Difficulty: 1,
Alloc: map[types.Address]*chain.GenesisAccount{},
ExtraData: p.extraData,
GasUsed: command.DefaultGenesisGasUsed,
BaseFee: p.parsedBaseFeeConfig.baseFee,
BaseFeeEM: p.parsedBaseFeeConfig.baseFeeEM,
BaseFeeChangeDenom: p.parsedBaseFeeConfig.baseFeeChangeDenom,
GasLimit: p.blockGasLimit,
Difficulty: 1,
Alloc: map[types.Address]*chain.GenesisAccount{},
ExtraData: p.extraData,
GasUsed: command.DefaultGenesisGasUsed,
},
Params: &chain.Params{
ChainID: int64(p.chainID),
Expand All @@ -227,6 +227,12 @@ func (p *genesisParams) initGenesisConfig() error {
Bootnodes: p.bootnodes,
}

if p.parsedBaseFeeConfig != nil {
chainConfig.Genesis.BaseFee = p.parsedBaseFeeConfig.baseFee
chainConfig.Genesis.BaseFeeChangeDenom = p.parsedBaseFeeConfig.baseFeeChangeDenom
chainConfig.Genesis.BaseFeeEM = p.parsedBaseFeeConfig.baseFeeEM
}

chainConfig.Params.BurnContract = make(map[uint64]types.Address, 1)
chainConfig.Params.BurnContract[0] = types.ZeroAddress

Expand Down Expand Up @@ -296,7 +302,7 @@ func (p *genesisParams) validateBlockTrackerPollInterval() error {

func (p *genesisParams) validateGenesisBaseFeeConfig() error {
if p.baseFeeConfig == "" {
return errors.New("invalid input(empty string) for genesis base fee config flag")
return nil
}

baseFeeInfo, err := parseBaseFeeConfig(p.baseFeeConfig)
Expand Down
27 changes: 17 additions & 10 deletions command/genesis/polybft_params.go
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,11 @@ func (p *genesisParams) generateChainConfig(o command.OutputFormatter) error {
BladeAdmin: types.StringToAddress(p.bladeAdmin),
}

enabledForks := chain.AllForksEnabled
enabledForks := chain.AllForksEnabled.Copy()

if p.parsedBaseFeeConfig == nil {
enabledForks.RemoveFork(chain.London)
}

chainConfig := &chain.Chain{
Name: p.name,
Expand Down Expand Up @@ -216,15 +220,18 @@ func (p *genesisParams) generateChainConfig(o command.OutputFormatter) error {

// populate genesis parameters
chainConfig.Genesis = &chain.Genesis{
GasLimit: p.blockGasLimit,
Difficulty: 0,
Alloc: allocs,
ExtraData: genesisExtraData,
GasUsed: command.DefaultGenesisGasUsed,
Mixhash: polybft.PolyBFTMixDigest,
BaseFee: p.parsedBaseFeeConfig.baseFee,
BaseFeeEM: p.parsedBaseFeeConfig.baseFeeEM,
BaseFeeChangeDenom: p.parsedBaseFeeConfig.baseFeeChangeDenom,
GasLimit: p.blockGasLimit,
Difficulty: 0,
Alloc: allocs,
ExtraData: genesisExtraData,
GasUsed: command.DefaultGenesisGasUsed,
Mixhash: polybft.PolyBFTMixDigest,
}

if p.parsedBaseFeeConfig != nil {
chainConfig.Genesis.BaseFee = p.parsedBaseFeeConfig.baseFee
chainConfig.Genesis.BaseFeeChangeDenom = p.parsedBaseFeeConfig.baseFeeChangeDenom
chainConfig.Genesis.BaseFeeEM = p.parsedBaseFeeConfig.baseFeeEM
}

if len(p.contractDeployerAllowListAdmin) != 0 {
Expand Down
2 changes: 1 addition & 1 deletion command/genesis/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ func parseBaseFeeConfig(baseFeeConfigRaw string) (*baseFeeInfo, error) {

baseFeeConfig := strings.Split(baseFeeConfigRaw, ":")
if len(baseFeeConfig) > 3 {
return baseFeeInfo, errors.New("invalid number of arguments for base fee configuration")
return baseFeeInfo, errors.New("invalid number of arguments provided for the base fee configuration")
}

if len(baseFeeConfig) >= 1 && baseFeeConfig[0] != "" {
Expand Down
57 changes: 32 additions & 25 deletions e2e-polybft/e2e/consensus_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -382,6 +382,9 @@ func TestE2E_Consensus_MintableERC20NativeToken(t *testing.T) {
minter, err := wallet.GenerateKey()
require.NoError(t, err)

receiver, err := wallet.GenerateKey()
require.NoError(t, err)

// because we are using native token as reward wallet, and it has default premine balance
initialTotalSupply := new(big.Int).Set(command.DefaultPremineBalance)

Expand All @@ -391,6 +394,7 @@ func TestE2E_Consensus_MintableERC20NativeToken(t *testing.T) {
fmt.Sprintf("%s:%s:%d", tokenName, tokenSymbol, decimals)),
framework.WithBladeAdmin(minter.Address().String()),
framework.WithEpochSize(epochSize),
framework.WithBaseFeeConfig(""),
framework.WithSecretsCallback(func(addrs []types.Address, config *framework.TestClusterConfig) {
config.Premine = append(config.Premine, fmt.Sprintf("%s:%d", minter.Address(), initMinterBalance))
initialTotalSupply.Add(initialTotalSupply, initMinterBalance)
Expand Down Expand Up @@ -430,45 +434,47 @@ func TestE2E_Consensus_MintableERC20NativeToken(t *testing.T) {
require.Equal(t, decimals, decimalsCount)

// send mint transactions
mintFn, exists := contractsapi.NativeERC20.Abi.Methods["mint"]
require.True(t, exists)

mintAmount := ethgo.Gwei(1)
mintAmount := ethgo.Ether(1)
nativeTokenAddr := ethgo.Address(contracts.NativeERC20TokenContract)

// make sure minter account can mint tokens
for _, addr := range validatorsAddrs {
balanceBefore, err := targetJSONRPC.Eth().GetBalance(ethgo.Address(addr), ethgo.Latest)
require.NoError(t, err)
t.Logf("Pre-mint balance: %v=%d\n", addr, balanceBefore)
receiverAddr := types.Address(receiver.Address())
balanceBefore, err := targetJSONRPC.Eth().GetBalance(ethgo.Address(receiverAddr), ethgo.Latest)
require.NoError(t, err)
t.Logf("Pre-mint balance: %v=%d\n", receiverAddr, balanceBefore)

mintInput, err := mintFn.Encode([]interface{}{addr, mintAmount})
require.NoError(t, err)
mintFn := &contractsapi.MintRootERC20Fn{
To: receiverAddr,
Amount: mintAmount,
}

receipt, err := relayer.SendTransaction(
&ethgo.Transaction{
To: &nativeTokenAddr,
Input: mintInput,
Type: ethgo.TransactionDynamicFee,
}, minter)
require.NoError(t, err)
require.Equal(t, uint64(types.ReceiptSuccess), receipt.Status)
mintInput, err := mintFn.EncodeAbi()
require.NoError(t, err)

balanceAfter, err := targetJSONRPC.Eth().GetBalance(ethgo.Address(addr), ethgo.Latest)
require.NoError(t, err)
receipt, err := relayer.SendTransaction(
&ethgo.Transaction{
To: &nativeTokenAddr,
Input: mintInput,
Type: ethgo.TransactionDynamicFee,
}, minter)
require.NoError(t, err)
require.Equal(t, uint64(types.ReceiptSuccess), receipt.Status)

t.Logf("Post-mint balance: %v=%d\n", addr, balanceAfter)
require.True(t, balanceAfter.Cmp(new(big.Int).Add(mintAmount, balanceBefore)) >= 0)
}
balanceAfter, err := targetJSONRPC.Eth().GetBalance(ethgo.Address(receiverAddr), ethgo.Latest)
require.NoError(t, err)

t.Logf("Post-mint balance: %v=%d\n", receiverAddr, balanceAfter)
require.True(t, balanceAfter.Cmp(new(big.Int).Add(mintAmount, balanceBefore)) >= 0)

// try sending mint transaction from non minter account and make sure it would fail
nonMinterAcc, err := validatorHelper.GetAccountFromDir(cluster.Servers[1].DataDir())
require.NoError(t, err)

mintInput, err := mintFn.Encode([]interface{}{validatorsAddrs[0], ethgo.Ether(1)})
mintFn = &contractsapi.MintRootERC20Fn{To: validatorsAddrs[0], Amount: mintAmount}
mintInput, err = mintFn.EncodeAbi()
require.NoError(t, err)

receipt, err := relayer.SendTransaction(
receipt, err = relayer.SendTransaction(
&ethgo.Transaction{
To: &nativeTokenAddr,
Input: mintInput,
Expand Down Expand Up @@ -520,6 +526,7 @@ func TestE2E_Consensus_EIP1559Check(t *testing.T) {
// sender must have premined some native tokens
cluster := framework.NewTestCluster(t, 5,
framework.WithPremine(types.Address(sender.Address())),
framework.WithBaseFeeConfig(""),
framework.WithSecretsCallback(func(a []types.Address, config *framework.TestClusterConfig) {
for range a {
config.StakeAmounts = append(config.StakeAmounts, command.DefaultPremineBalance)
Expand Down
16 changes: 9 additions & 7 deletions e2e-polybft/e2e/migration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ func TestE2E_Migration(t *testing.T) {
srvs := framework.NewTestServers(t, 1, func(config *framework.TestServerConfig) {
config.SetConsensus(framework.ConsensusDev)
config.Premine(types.Address(userAddr), initialBalance)
config.SetBaseFeeConfig("")
})

srv := srvs[0]
Expand Down Expand Up @@ -63,13 +64,14 @@ func TestE2E_Migration(t *testing.T) {

//send transaction to user2
sendAmount := ethgo.Gwei(10000)
receipt, err := relayer.SendTransaction(&ethgo.Transaction{
From: userAddr,
To: &userAddr2,
Gas: 1000000,
Value: sendAmount,
GasPrice: ethgo.Gwei(2).Uint64(),
}, userKey)
receipt, err := relayer.SendTransaction(
&ethgo.Transaction{
From: userAddr,
To: &userAddr2,
Gas: 1000000,
Value: sendAmount,
GasPrice: ethgo.Gwei(2).Uint64(),
}, userKey)
require.NoError(t, err)
require.NotNil(t, receipt)

Expand Down
6 changes: 5 additions & 1 deletion e2e-polybft/e2e/txpool_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,9 @@ func TestE2E_TxPool_Transfer(t *testing.T) {
require.NoError(t, err)

cluster := framework.NewTestCluster(t, 5,
framework.WithPremine(types.Address(sender.Address())))
framework.WithPremine(types.Address(sender.Address())),
framework.WithBaseFeeConfig(""),
)
defer cluster.Stop()

cluster.WaitForReady(t)
Expand Down Expand Up @@ -99,6 +101,7 @@ func TestE2E_TxPool_Transfer_Linear(t *testing.T) {
// first account should have some matics premined
cluster := framework.NewTestCluster(t, 5,
framework.WithPremine(types.Address(premine.Address())),
framework.WithBaseFeeConfig(""),
)
defer cluster.Stop()

Expand Down Expand Up @@ -231,6 +234,7 @@ func TestE2E_TxPool_BroadcastTransactions(t *testing.T) {
// First account should have some matics premined
cluster := framework.NewTestCluster(t, 5,
framework.WithPremine(types.Address(sender.Address())),
framework.WithBaseFeeConfig(""),
)
defer cluster.Stop()

Expand Down
16 changes: 15 additions & 1 deletion e2e-polybft/framework/test-cluster.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ type TestClusterConfig struct {
EpochSize int
EpochReward int
NativeTokenConfigRaw string
BaseFeeConfig string
SecretsCallback func([]types.Address, *TestClusterConfig)
BladeAdmin string

Expand Down Expand Up @@ -256,6 +257,16 @@ func WithBridge() ClusterOption {
}
}

func WithBaseFeeConfig(config string) ClusterOption {
return func(h *TestClusterConfig) {
if config == "" {
h.BaseFeeConfig = command.DefaultGenesisBaseFeeConfig
} else {
h.BaseFeeConfig = config
}
}
}

func WithGenesisState(databasePath string, stateRoot types.Hash) ClusterOption {
return func(h *TestClusterConfig) {
h.InitialTrieDB = databasePath
Expand Down Expand Up @@ -525,7 +536,10 @@ func NewTestCluster(t *testing.T, validatorsCount int, opts ...ClusterOption) *T
args = append(args, "--reward-token-code", cluster.Config.TestRewardToken)
}

// add optional genesis flags
if cluster.Config.BaseFeeConfig != "" {
args = append(args, "--base-fee-config", cluster.Config.BaseFeeConfig)
}

if cluster.Config.NativeTokenConfigRaw != "" {
args = append(args, "--native-token-config", cluster.Config.NativeTokenConfigRaw)
}
Expand Down
13 changes: 11 additions & 2 deletions e2e/framework/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package framework
import (
"math/big"

"github.com/0xPolygon/polygon-edge/command"
"github.com/0xPolygon/polygon-edge/crypto"
"github.com/0xPolygon/polygon-edge/types"
)
Expand Down Expand Up @@ -40,13 +41,12 @@ type TestServerConfig struct {
DevInterval int // Dev consensus update interval [s]
BlockGasLimit uint64 // Block gas limit
BlockGasTarget uint64 // Gas target for new blocks
BaseFee uint64 // Initial base fee
BaseFeeConfig string // Base fee configuration
ShowsLog bool // Flag specifying if logs are shown
Name string // Name of the server
SaveLogs bool // Flag specifying if logs are saved
LogsDir string // Directory where logs are saved
Signer crypto.TxSigner // Signer used for transactions

}

// DataDir returns path of data directory server uses
Expand Down Expand Up @@ -122,3 +122,12 @@ func (t *TestServerConfig) SetLogsDir(dir string) {
func (t *TestServerConfig) SetName(name string) {
t.Name = name
}

// SetBaseFeeConfig sets base fee configuration
func (t *TestServerConfig) SetBaseFeeConfig(baseFeeConfig string) {
if baseFeeConfig == "" {
t.BaseFeeConfig = command.DefaultGenesisBaseFeeConfig
} else {
t.BaseFeeConfig = baseFeeConfig
}
}
2 changes: 2 additions & 0 deletions e2e/framework/testserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,8 @@ func (t *TestServer) GenerateGenesis() error {
blockGasLimit := strconv.FormatUint(t.Config.BlockGasLimit, 10)
args = append(args, "--block-gas-limit", blockGasLimit)

args = append(args, "--base-fee-config", t.Config.BaseFeeConfig)

cmd := exec.Command(resolveBinary(), args...) //nolint:gosec
cmd.Dir = t.Config.RootDir

Expand Down

0 comments on commit 5c5d529

Please sign in to comment.