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