-
Notifications
You must be signed in to change notification settings - Fork 0
/
ethscan.go
111 lines (92 loc) · 2.44 KB
/
ethscan.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
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
package main
import (
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"net/http"
"github.com/ethereum/go-ethereum/common"
)
const BASE = "https://api.etherscan.io/api"
type ETHScan struct {
client *http.Client
url string
}
func NewETHScan(apikey string) ETHScan {
return ETHScan{
client: http.DefaultClient,
url: fmt.Sprintf("%s?apikey=%s", BASE, apikey),
}
}
type AugmentedSourceCode struct {
SourceCode string `json:SourceCode"`
ConstructArguments []byte
ContractName string `json:"ContractName"`
ABI []byte
}
func (e *ETHScan) GetSourceCode(addr common.Address) (*AugmentedSourceCode, error) {
type augmentedSourceCode struct {
SourceCode string `json:SourceCode"`
ConstructArguments string `json:"ConstructorArguments"`
ContractName string `json:"ContractName"`
ABI string `json:"ABI"`
}
type resJSON struct {
Status string `json:"status"`
Message string `json:"message"`
Result []augmentedSourceCode `json:"result"`
}
endpoint := fmt.Sprintf("%s&module=contract&action=getsourcecode&address=%s", e.url, addr)
res, err := e.client.Get(endpoint)
if err != nil {
return nil, err
}
defer res.Body.Close()
var j resJSON
err = json.NewDecoder(res.Body).Decode(&j)
if err != nil {
return nil, err
}
if j.Message != "OK" {
return nil, nil
}
if len(j.Result) > 1 {
return nil, errors.New("more than one result?")
}
result := j.Result[0]
if result.ABI == "Contract source code not verified" {
return nil, errors.New("contract source code not verified")
}
constructorArgsBytes, err := hex.DecodeString(result.ConstructArguments)
if err != nil {
return nil, err
}
return &AugmentedSourceCode{
SourceCode: result.SourceCode,
ConstructArguments: constructorArgsBytes,
ContractName: result.ContractName,
ABI: []byte(result.ABI),
}, nil
}
func (e *ETHScan) GetABI(addr common.Address) ([]byte, error) {
type resJSON struct {
Status string `json:"status"`
Message string `json:"message"`
Result string `json:"result"`
}
endpoint := fmt.Sprintf("%s&module=contract&action=getabi&address=%s", e.url, addr)
res, err := e.client.Get(endpoint)
if err != nil {
return nil, err
}
defer res.Body.Close()
var j resJSON
err = json.NewDecoder(res.Body).Decode(&j)
if err != nil {
return nil, err
}
if j.Message != "OK" {
return nil, nil
}
return []byte(j.Result), err
}