github.com/0xPolygon/supernets2-node@v0.0.0-20230711153321-2fe574524eaa/etherman/ethgasstation/ethgasstation.go (about)

     1  package ethgasstation
     2  
     3  import (
     4  	"context"
     5  	"encoding/json"
     6  	"fmt"
     7  	"io"
     8  	"math/big"
     9  	"net/http"
    10  
    11  	"github.com/0xPolygon/supernets2-node/encoding"
    12  )
    13  
    14  type ethGasStationResponse struct {
    15  	BaseFee     uint64                `json:"baseFee"`
    16  	BlockNumber uint64                `json:"blockNumber"`
    17  	GasPrice    gasPriceEthGasStation `json:"gasPrice"`
    18  }
    19  
    20  // gasPriceEthGasStation definition
    21  type gasPriceEthGasStation struct {
    22  	Standard uint64 `json:"standard"`
    23  	Instant  uint64 `json:"instant"`
    24  	Fast     uint64 `json:"fast"`
    25  }
    26  
    27  // Client for ethGasStation
    28  type Client struct {
    29  	Http http.Client
    30  	Url  string
    31  }
    32  
    33  // NewEthGasStationService is the constructor that creates an ethGasStationService
    34  func NewEthGasStationService() *Client {
    35  	const url = "https://api.ethgasstation.info/api/fee-estimate"
    36  	return &Client{
    37  		Http: http.Client{},
    38  		Url:  url,
    39  	}
    40  }
    41  
    42  // SuggestGasPrice retrieves the gas price estimation from ethGasStation
    43  func (e *Client) SuggestGasPrice(ctx context.Context) (*big.Int, error) {
    44  	var resBody ethGasStationResponse
    45  	res, err := e.Http.Get(e.Url)
    46  	if err != nil {
    47  		return big.NewInt(0), err
    48  	}
    49  	defer res.Body.Close()
    50  	body, err := io.ReadAll(res.Body)
    51  	if err != nil {
    52  		return big.NewInt(0), err
    53  	}
    54  	if res.StatusCode != http.StatusOK {
    55  		return big.NewInt(0), fmt.Errorf("http response is %d", res.StatusCode)
    56  	}
    57  	// Unmarshal result
    58  	err = json.Unmarshal(body, &resBody)
    59  	if err != nil {
    60  		return big.NewInt(0), fmt.Errorf("Reading body failed: %w", err)
    61  	}
    62  	fgp := big.NewInt(0).SetUint64(resBody.GasPrice.Instant)
    63  	return new(big.Int).Mul(fgp, big.NewInt(encoding.Gwei)), nil
    64  }