client.go 5.64 KB
Newer Older
Wyatt Barnes's avatar
Wyatt Barnes committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
package etherscan

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"time"

	"github.com/ethereum-optimism/optimism/op-service/retry"
)

type client struct {
Matthew Slipper's avatar
Matthew Slipper committed
17
	baseUrl    string
Wyatt Barnes's avatar
Wyatt Barnes committed
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
	httpClient *http.Client
}

type apiResponse struct {
	Status  string          `json:"status"`
	Message string          `json:"message"`
	Result  json.RawMessage `json:"result"`
}

type rpcResponse struct {
	JsonRpc string          `json:"jsonrpc"`
	Id      int             `json:"id"`
	Result  json.RawMessage `json:"result"`
}

33 34 35 36
type Transaction struct {
	Hash  string `json:"hash"`
	Input string `json:"input"`
	To    string `json:"to"`
Wyatt Barnes's avatar
Wyatt Barnes committed
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 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
}

const apiMaxRetries = 3
const apiRetryDelay = time.Duration(2) * time.Second
const errRateLimited = "Max rate limit reached"

func NewClient(baseUrl, apiKey string) *client {
	return &client{
		baseUrl: baseUrl + "/api?apikey=" + apiKey + "&",
		httpClient: &http.Client{
			Timeout: time.Second * 10,
		},
	}
}

func NewEthereumClient(apiKey string) *client {
	return NewClient("https://api.etherscan.io", apiKey)
}

func NewOptimismClient(apiKey string) *client {
	return NewClient("https://api-optimistic.etherscan.io", apiKey)
}

func (c *client) fetch(ctx context.Context, url string) ([]byte, error) {
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
	if err != nil {
		return nil, err
	}
	resp, err := c.httpClient.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	return body, nil
}

func (c *client) fetchEtherscanApi(ctx context.Context, url string) (apiResponse, error) {
	return retry.Do[apiResponse](ctx, apiMaxRetries, retry.Fixed(apiRetryDelay), func() (apiResponse, error) {
		body, err := c.fetch(ctx, url)
		if err != nil {
			return apiResponse{}, err
		}

		var response apiResponse
		err = json.Unmarshal(body, &response)
		if err != nil {
			return apiResponse{}, fmt.Errorf("failed to unmarshal as apiResponse: %w", err)
		}

		if response.Message != "OK" {
			var resultString string
			err = json.Unmarshal(response.Result, &resultString)
			if err != nil {
				return apiResponse{}, fmt.Errorf("response for %s not OK, returned message: %s", url, response.Message)
			}

			if resultString == errRateLimited {
				return apiResponse{}, errors.New(errRateLimited)
			}

			return apiResponse{}, fmt.Errorf("there was an issue with the Etherscan request to %s, received response: %v", url, response)
		}

		return response, nil
	})
}

func (c *client) fetchEtherscanRpc(ctx context.Context, url string) (rpcResponse, error) {
	return retry.Do[rpcResponse](ctx, apiMaxRetries, retry.Fixed(apiRetryDelay), func() (rpcResponse, error) {
		body, err := c.fetch(ctx, url)
		if err != nil {
			return rpcResponse{}, err
		}

		var response rpcResponse
		err = json.Unmarshal(body, &response)
		if err != nil {
			return rpcResponse{}, fmt.Errorf("failed to unmarshal as rpcResponse: %w", err)
		}

		var resultString string
123
		_ = json.Unmarshal(response.Result, &resultString)
Wyatt Barnes's avatar
Wyatt Barnes committed
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
		if resultString == errRateLimited {
			return rpcResponse{}, errors.New(errRateLimited)
		}

		return response, nil
	})
}

func (c *client) FetchAbi(ctx context.Context, address string) (string, error) {
	params := url.Values{}
	params.Set("address", address)
	url := constructUrl(c.baseUrl, "getabi", "contract", params)
	response, err := c.fetchEtherscanApi(ctx, url)
	if err != nil {
		return "", err
	}

	var abi string
	err = json.Unmarshal(response.Result, &abi)
	if err != nil {
		return "", fmt.Errorf("API response result is not expected ABI string: %w", err)
	}

	return abi, nil
}

func (c *client) FetchDeployedBytecode(ctx context.Context, address string) (string, error) {
	params := url.Values{}
	params.Set("address", address)
	url := constructUrl(c.baseUrl, "eth_getCode", "proxy", params)
	response, err := c.fetchEtherscanRpc(ctx, url)
	if err != nil {
		return "", fmt.Errorf("error fetching deployed bytecode: %w", err)
	}

	var bytecode string
	err = json.Unmarshal(response.Result, &bytecode)
	if err != nil {
		return "", errors.New("API response result is not expected bytecode string")
	}

	return bytecode, nil
}

func (c *client) FetchDeploymentTxHash(ctx context.Context, address string) (string, error) {
	params := url.Values{}
	params.Set("contractaddresses", address)
	url := constructUrl(c.baseUrl, "getcontractcreation", "contract", params)
	response, err := c.fetchEtherscanApi(ctx, url)
	if err != nil {
		return "", err
	}

177 178 179
	var results []struct {
		Hash string `json:"txHash"`
	}
Wyatt Barnes's avatar
Wyatt Barnes committed
180 181 182 183 184 185 186 187 188
	err = json.Unmarshal(response.Result, &results)
	if err != nil {
		return "", fmt.Errorf("failed to unmarshal API response as []txInfo: %w", err)
	}

	if len(results) == 0 {
		return "", fmt.Errorf("API response result is an empty array")
	}

189
	return results[0].Hash, nil
Wyatt Barnes's avatar
Wyatt Barnes committed
190 191
}

192
func (c *client) FetchDeploymentTx(ctx context.Context, txHash string) (Transaction, error) {
Wyatt Barnes's avatar
Wyatt Barnes committed
193 194 195 196 197 198
	params := url.Values{}
	params.Set("txHash", txHash)
	params.Set("tag", "latest")
	url := constructUrl(c.baseUrl, "eth_getTransactionByHash", "proxy", params)
	response, err := c.fetchEtherscanRpc(ctx, url)
	if err != nil {
199
		return Transaction{}, err
Wyatt Barnes's avatar
Wyatt Barnes committed
200 201 202 203
	}

	resultBytes, err := json.Marshal(response.Result)
	if err != nil {
204
		return Transaction{}, fmt.Errorf("failed to marshal Result into JSON: %w", err)
Wyatt Barnes's avatar
Wyatt Barnes committed
205 206
	}

207
	var tx Transaction
Wyatt Barnes's avatar
Wyatt Barnes committed
208 209
	err = json.Unmarshal(resultBytes, &tx)
	if err != nil {
210
		return Transaction{}, fmt.Errorf("API response result is not expected txInfo struct: %w", err)
Wyatt Barnes's avatar
Wyatt Barnes committed
211 212 213 214 215 216 217 218 219 220 221
	}

	return tx, nil
}

func constructUrl(baseUrl, action, module string, params url.Values) string {
	params.Set("action", action)
	params.Set("module", module)
	queryFragment := params.Encode()
	return baseUrl + queryFragment
}