Skip to content

Commit

Permalink
Nicolas/1559 persist (#6812)
Browse files Browse the repository at this point in the history
* persisting to disk

* better prints after testing
  • Loading branch information
nicolaslara authored Nov 2, 2023
1 parent 235f440 commit 0c18e31
Showing 1 changed file with 47 additions and 2 deletions.
49 changes: 47 additions & 2 deletions x/txfees/keeper/mempool-1559/code.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package mempool1559

import (
"encoding/json"
"fmt"
"os"

sdk "github.com/cosmos/cosmos-sdk/types"
)
Expand Down Expand Up @@ -31,26 +33,33 @@ var MinBaseFee = sdk.MustNewDecFromStr("0.0025")
var TargetGas = int64(70_000_000)
var MaxBlockChangeRate = sdk.NewDec(1).Quo(sdk.NewDec(16))
var ResetInterval = int64(1000)
var BackupFile = "eip1559state.json"

type EipState struct {
// Signal when we are starting a new block
// TODO: Or just use begin block
lastBlockHeight int64
totalGasWantedThisBlock int64

CurBaseFee sdk.Dec
CurBaseFee sdk.Dec `json:"cur_base_fee"`
}

var CurEipState = EipState{
lastBlockHeight: 0,
totalGasWantedThisBlock: 0,
CurBaseFee: DefaultBaseFee.Clone(),
CurBaseFee: sdk.NewDec(0),
}

func (e *EipState) startBlock(height int64) {
e.lastBlockHeight = height
e.totalGasWantedThisBlock = 0

if e.CurBaseFee.Equal(sdk.NewDec(0)) {
// CurBaseFee has not been initialized yet. This only happens when the node has just started.
// Try to read the previous value from the backup file and if not available, set it to the default.
e.CurBaseFee = e.tryLoad()
}

if height%ResetInterval == 0 {
e.CurBaseFee = DefaultBaseFee.Clone()
}
Expand Down Expand Up @@ -84,8 +93,44 @@ func (e *EipState) updateBaseFee(height int64) {
if e.CurBaseFee.LT(MinBaseFee) {
e.CurBaseFee = MinBaseFee.Clone()
}

go e.tryPersist()
}

func (e *EipState) GetCurBaseFee() sdk.Dec {
return e.CurBaseFee.Clone()
}

func (e *EipState) tryPersist() {
bz, err := json.Marshal(e)
if err != nil {
fmt.Println("Error marshalling eip1559 state", err)
return
}

err = os.WriteFile(BackupFile, bz, 0644)
if err != nil {
fmt.Println("Error writing eip1559 state", err)
return
}
}

func (e *EipState) tryLoad() sdk.Dec {
bz, err := os.ReadFile(BackupFile)
if err != nil {
fmt.Println("Error reading eip1559 state", err)
fmt.Println("Setting eip1559 state to default value", MinBaseFee)
return MinBaseFee
}

var loaded EipState
err = json.Unmarshal(bz, &loaded)
if err != nil {
fmt.Println("Error unmarshalling eip1559 state", err)
fmt.Println("Setting eip1559 state to default value", MinBaseFee)
return MinBaseFee
}

fmt.Println("Loaded eip1559 state. CurBaseFee=", loaded.CurBaseFee)
return loaded.CurBaseFee
}

0 comments on commit 0c18e31

Please sign in to comment.