Skip to content
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

migrate gas price models from xlayer-node #27

Merged
merged 22 commits into from
Jul 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion cmd/rpcdaemon/commands/eth_api.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (

lru "github.com/hashicorp/golang-lru/v2"
"github.com/holiman/uint256"
"github.com/ledgerwatch/erigon/eth/gasprice"
"github.com/ledgerwatch/log/v3"

"github.com/gateway-fm/cdk-erigon-lib/common"
Expand Down Expand Up @@ -347,6 +348,7 @@ type APIImpl struct {
MaxGasPrice uint64
GasPriceFactor float64
L1GasPrice L1GasPrice
L2GasPircer gasprice.L2GasPricer
EnableInnerTx bool // XLayer
}

Expand All @@ -356,7 +358,7 @@ func NewEthAPI(base *BaseAPI, db kv.RoDB, eth rpchelper.ApiBackend, txPool txpoo
gascap = uint64(math.MaxUint64 / 2)
}

return &APIImpl{
apii := &APIImpl{
BaseAPI: base,
db: db,
ethBackend: eth,
Expand All @@ -374,8 +376,15 @@ func NewEthAPI(base *BaseAPI, db kv.RoDB, eth rpchelper.ApiBackend, txPool txpoo
MaxGasPrice: ethCfg.MaxGasPrice,
GasPriceFactor: ethCfg.GasPriceFactor,
L1GasPrice: L1GasPrice{},
L2GasPircer: gasprice.NewL2GasPriceSuggester(context.Background(), ethconfig.Defaults.GPO),
EnableInnerTx: ethCfg.EnableInnerTx,
}

// set default gas price
apii.gasCache.SetLatest(common.Hash{}, apii.L2GasPircer.GetConfig().Default)
go apii.runL2GasPriceSuggester()
LeoGuo621 marked this conversation as resolved.
Show resolved Hide resolved

return apii
}

// RPCTransaction represents a transaction that will serialize to the RPC representation of a transaction
Expand Down
157 changes: 157 additions & 0 deletions cmd/rpcdaemon/commands/eth_system_xlayer.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
package commands

import (
"context"
"encoding/json"
"errors"
"math/big"
"time"

proto_txpool "github.com/gateway-fm/cdk-erigon-lib/gointerfaces/txpool"
"github.com/ledgerwatch/erigon/common/hexutil"
"github.com/ledgerwatch/erigon/core/rawdb"
"github.com/ledgerwatch/erigon/eth/ethconfig"
"github.com/ledgerwatch/erigon/eth/gasprice"
"github.com/ledgerwatch/erigon/rpc"
"github.com/ledgerwatch/erigon/zkevm/jsonrpc/client"
"github.com/ledgerwatch/log/v3"
)

func (api *APIImpl) gasPriceXL(ctx context.Context) (*hexutil.Big, error) {
tx, err := api.db.BeginRo(ctx)
if err != nil {
return nil, err
}
defer tx.Rollback()
cc, err := api.chainConfig(tx)
if err != nil {
return nil, err
}
chainId := cc.ChainID
if !api.isZkNonSequencer(chainId) {
return api.gasPriceNonRedirectedXL(ctx)
}

price, err := api.getGPFromTrustedNode()
if err != nil {
log.Error("eth_gasPrice error: ", err)
return (*hexutil.Big)(api.L2GasPircer.GetConfig().Default), nil
}

return (*hexutil.Big)(price), nil
}

func (api *APIImpl) gasPriceNonRedirectedXL(ctx context.Context) (*hexutil.Big, error) {
tx, err := api.db.BeginRo(ctx)
if err != nil {
return nil, err
}
defer tx.Rollback()
cc, err := api.chainConfig(tx)
if err != nil {
return nil, err
}
oracle := gasprice.NewOracle(NewGasPriceOracleBackend(tx, cc, api.BaseAPI), ethconfig.Defaults.GPO, api.gasCache)
tipcap, err := oracle.SuggestTipCap(ctx)
gasResult := big.NewInt(0)
gasResult.Set(tipcap)
if err != nil {
return nil, err
}
if head := rawdb.ReadCurrentHeader(tx); head != nil && head.BaseFee != nil {
gasResult.Add(tipcap, head.BaseFee)
}

rgp := api.L2GasPircer.GetLastRawGP()
if gasResult.Cmp(rgp) < 0 {
gasResult = new(big.Int).Set(rgp)
}

if !api.isCongested(ctx) {
gasResult = getAvgPrice(rgp, gasResult)
}

return (*hexutil.Big)(gasResult), err
}

func (api *APIImpl) isCongested(ctx context.Context) bool {

latestBlockTxNum, err := api.getLatestBlockTxNum(ctx)
if err != nil {
return false
}
isLatestBlockEmpty := latestBlockTxNum == 0

poolStatus, err := api.txPool.Status(ctx, &proto_txpool.StatusRequest{})
if err != nil {
return false
}

isPendingTxCongested := int(poolStatus.PendingCount) >= api.L2GasPircer.GetConfig().CongestionThreshold

return !isLatestBlockEmpty && isPendingTxCongested
}

func (api *APIImpl) getLatestBlockTxNum(ctx context.Context) (int, error) {
tx, err := api.db.BeginRo(ctx)
if err != nil {
return 0, err
}
defer tx.Rollback()

b, err := api.blockByNumber(ctx, rpc.LatestBlockNumber, tx)
if err != nil {
return 0, err
}
return len(b.Transactions()), nil
}

func (api *APIImpl) getGPFromTrustedNode() (*big.Int, error) {
res, err := client.JSONRPCCall(api.l2RpcUrl, "eth_gasPrice")
if err != nil {
return nil, errors.New("failed to get gas price from trusted node")
}

if res.Error != nil {
return nil, errors.New(res.Error.Message)
}

var gasPrice uint64
err = json.Unmarshal(res.Result, &gasPrice)
if err != nil {
return nil, errors.New("failed to read gas price from trusted node")
}
return new(big.Int).SetUint64(gasPrice), nil
}

func (api *APIImpl) runL2GasPriceSuggester() {
cfg := api.L2GasPircer.GetConfig()
ctx := api.L2GasPircer.GetCtx()

//todo: apollo
l1gp, err := gasprice.GetL1GasPrice(api.L1RpcUrl)
// if err != nil, do nothing
if err == nil {
api.L2GasPircer.UpdateGasPriceAvg(l1gp)
}
updateTimer := time.NewTimer(cfg.UpdatePeriod)
for {
select {
case <-ctx.Done():
log.Info("Finishing l2 gas price suggester...")
return
case <-updateTimer.C:
l1gp, err := gasprice.GetL1GasPrice(api.L1RpcUrl)
if err == nil {
api.L2GasPircer.UpdateGasPriceAvg(l1gp)
}
updateTimer.Reset(cfg.UpdatePeriod)
}
}
}

func getAvgPrice(low *big.Int, high *big.Int) *big.Int {
avg := new(big.Int).Add(low, high)
avg = avg.Quo(avg, big.NewInt(2)) //nolint:gomnd
return avg
}
5 changes: 5 additions & 0 deletions cmd/rpcdaemon/commands/eth_system_zk.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ type L1GasPrice struct {
}

func (api *APIImpl) GasPrice(ctx context.Context) (*hexutil.Big, error) {
// xlayer handler
if api.L2GasPircer.GetConfig().Type != "" {
return api.gasPriceXL(ctx)
}

tx, err := api.db.BeginRo(ctx)
if err != nil {
return nil, err
Expand Down
Loading
Loading