2023-01-05 12:45:09 +01:00
|
|
|
package fetch
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
2023-01-11 09:13:59 +01:00
|
|
|
"context"
|
2023-03-11 10:29:51 +01:00
|
|
|
"encoding/json"
|
2023-01-05 12:45:09 +01:00
|
|
|
"fmt"
|
2023-03-14 08:19:07 +01:00
|
|
|
"io"
|
2023-01-05 12:45:09 +01:00
|
|
|
"net/http"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
graphqlQuery = `{"query":"{block(number:%d){transactions{block{number,timestamp},hash,index,from{address},to{address},value,inputData,status,gasUsed}}}"}`
|
|
|
|
)
|
|
|
|
|
|
|
|
type GraphqlOpts struct {
|
|
|
|
GraphqlEndpoint string
|
|
|
|
}
|
|
|
|
|
|
|
|
type Graphql struct {
|
|
|
|
graphqlEndpoint string
|
|
|
|
httpClient *http.Client
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewGraphqlFetcher(o GraphqlOpts) Fetch {
|
|
|
|
return &Graphql{
|
|
|
|
httpClient: &http.Client{
|
2023-03-11 10:29:51 +01:00
|
|
|
Transport: &http.Transport{
|
|
|
|
MaxIdleConns: 100,
|
|
|
|
MaxIdleConnsPerHost: 100,
|
|
|
|
IdleConnTimeout: 60 * time.Second,
|
|
|
|
},
|
2023-01-18 20:40:14 +01:00
|
|
|
Timeout: time.Second * 5,
|
2023-01-05 12:45:09 +01:00
|
|
|
},
|
|
|
|
graphqlEndpoint: o.GraphqlEndpoint,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-01-11 09:13:59 +01:00
|
|
|
func (f *Graphql) Block(ctx context.Context, blockNumber uint64) (FetchResponse, error) {
|
2023-03-11 10:29:51 +01:00
|
|
|
fetchResponse := FetchResponse{}
|
2023-01-05 12:45:09 +01:00
|
|
|
|
2023-01-11 09:13:59 +01:00
|
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, f.graphqlEndpoint, bytes.NewBufferString(fmt.Sprintf(graphqlQuery, blockNumber)))
|
2023-01-05 12:45:09 +01:00
|
|
|
if err != nil {
|
2023-03-11 10:29:51 +01:00
|
|
|
return fetchResponse, err
|
2023-01-05 12:45:09 +01:00
|
|
|
}
|
2023-01-11 09:13:59 +01:00
|
|
|
req.Header.Set("Content-Type", "application/json")
|
|
|
|
|
|
|
|
resp, err := f.httpClient.Do(req)
|
|
|
|
if err != nil {
|
2023-03-11 10:29:51 +01:00
|
|
|
return fetchResponse, err
|
2023-01-11 09:13:59 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
if resp.StatusCode >= http.StatusBadRequest {
|
2023-03-11 10:29:51 +01:00
|
|
|
return fetchResponse, fmt.Errorf("error fetching block %s", resp.Status)
|
2023-01-05 12:45:09 +01:00
|
|
|
}
|
|
|
|
|
2023-03-14 08:19:07 +01:00
|
|
|
out, err := io.ReadAll(resp.Body)
|
|
|
|
_ = resp.Body.Close()
|
|
|
|
if err != nil {
|
|
|
|
return fetchResponse, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := json.Unmarshal(out, &fetchResponse); err != nil {
|
2023-03-11 10:29:51 +01:00
|
|
|
return fetchResponse, err
|
2023-01-05 12:45:09 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
return fetchResponse, nil
|
|
|
|
}
|