-
Notifications
You must be signed in to change notification settings - Fork 0
/
chain_api.go
50 lines (41 loc) · 1019 Bytes
/
chain_api.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
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
)
type ChainAPI interface {
GetABIFromEtherscan(address string) (string, error)
}
type GenericEtherscanAPI struct {
BaseURL string
EnvKey string
}
func (e *GenericEtherscanAPI) GetABIFromEtherscan(address string) (string, error) {
apiKey := os.Getenv(e.EnvKey)
if apiKey == "" {
return "", fmt.Errorf("API key not set for chain: %s", e.EnvKey)
}
url := fmt.Sprintf("%s?module=contract&action=getabi&address=%s&apikey=%s", e.BaseURL, address, apiKey)
return fetchABI(url)
}
func fetchABI(url string) (string, error) {
resp, err := http.Get(url)
if err != nil {
return "", err
}
defer resp.Body.Close()
var result struct {
Status string `json:"status"`
Message string `json:"message"`
Result string `json:"result"`
}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return "", err
}
if result.Status != "1" {
return "", fmt.Errorf("API error: %s", result.Message)
}
return result.Result, nil
}