2017-11-27 15:39:53 +00:00
|
|
|
package geth
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"io/ioutil"
|
|
|
|
"strings"
|
|
|
|
|
2017-12-07 15:58:06 +00:00
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
"time"
|
|
|
|
|
2017-11-27 15:39:53 +00:00
|
|
|
"github.com/ethereum/go-ethereum/accounts/abi"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
2017-12-07 15:58:06 +00:00
|
|
|
ErrInvalidAbiFile = errors.New("invalid abi")
|
|
|
|
ErrMissingAbiFile = errors.New("missing abi")
|
|
|
|
ErrApiRequestFailed = errors.New("etherscan api request failed")
|
2017-11-27 15:39:53 +00:00
|
|
|
)
|
|
|
|
|
2017-12-07 15:58:06 +00:00
|
|
|
type Response struct {
|
|
|
|
Status string
|
|
|
|
Message string
|
|
|
|
Result string
|
|
|
|
}
|
|
|
|
|
|
|
|
type EtherScanApi struct {
|
|
|
|
client *http.Client
|
|
|
|
url string
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewEtherScanClient(url string) *EtherScanApi {
|
|
|
|
return &EtherScanApi{
|
|
|
|
client: &http.Client{Timeout: 10 * time.Second},
|
|
|
|
url: url,
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
2018-01-08 21:59:47 +00:00
|
|
|
func GenUrl(network string) string {
|
|
|
|
switch network {
|
|
|
|
case "ropsten":
|
|
|
|
return "https://ropsten.etherscan.io"
|
|
|
|
case "kovan":
|
|
|
|
return "https://kovan.etherscan.io"
|
|
|
|
case "rinkeby":
|
|
|
|
return "https://rinkeby.etherscan.io"
|
|
|
|
default:
|
|
|
|
return "https://api.etherscan.io"
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-12-07 15:58:06 +00:00
|
|
|
//https://api.etherscan.io/api?module=contract&action=getabi&address=%s
|
|
|
|
func (e *EtherScanApi) GetAbi(contractHash string) (string, error) {
|
|
|
|
target := new(Response)
|
|
|
|
request := fmt.Sprintf("%s/api?module=contract&action=getabi&address=%s", e.url, contractHash)
|
|
|
|
r, err := e.client.Get(request)
|
|
|
|
if err != nil {
|
|
|
|
return "", ErrApiRequestFailed
|
|
|
|
}
|
|
|
|
defer r.Body.Close()
|
|
|
|
json.NewDecoder(r.Body).Decode(&target)
|
|
|
|
return target.Result, nil
|
|
|
|
}
|
|
|
|
|
2017-11-27 15:39:53 +00:00
|
|
|
func ParseAbiFile(abiFilePath string) (abi.ABI, error) {
|
2017-12-04 21:12:27 +00:00
|
|
|
abiString, err := ReadAbiFile(abiFilePath)
|
2017-11-27 15:39:53 +00:00
|
|
|
if err != nil {
|
|
|
|
return abi.ABI{}, ErrMissingAbiFile
|
|
|
|
}
|
2017-12-04 22:35:41 +00:00
|
|
|
return ParseAbi(abiString)
|
|
|
|
}
|
|
|
|
|
|
|
|
func ParseAbi(abiString string) (abi.ABI, error) {
|
2017-11-27 15:39:53 +00:00
|
|
|
parsedAbi, err := abi.JSON(strings.NewReader(abiString))
|
|
|
|
if err != nil {
|
|
|
|
return abi.ABI{}, ErrInvalidAbiFile
|
|
|
|
}
|
|
|
|
return parsedAbi, nil
|
|
|
|
}
|
2017-12-04 21:12:27 +00:00
|
|
|
|
|
|
|
func ReadAbiFile(abiFilePath string) (string, error) {
|
|
|
|
filesBytes, err := ioutil.ReadFile(abiFilePath)
|
|
|
|
if err != nil {
|
|
|
|
return "", ErrMissingAbiFile
|
|
|
|
}
|
|
|
|
return string(filesBytes), nil
|
|
|
|
}
|