/
address.go
73 lines (60 loc) · 2.12 KB
/
address.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
package cli
import (
"context"
"fmt"
"strings"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/ethereum/go-ethereum/common"
"github.com/elysium-station/black/x/evmutil/types"
)
// ParseAddrFromHexOrBech32 parses a string address that can be either a hex or
//Bech32 string.
func ParseAddrFromHexOrBech32(addrString string) (common.Address, error) {
if common.IsHexAddress(addrString) {
return common.HexToAddress(addrString), nil
}
cfg := sdk.GetConfig()
if !strings.HasPrefix(addrString, cfg.GetBech32AccountAddrPrefix()) {
return common.Address{}, fmt.Errorf("receiver '%s' is not a hex or bech32 address (prefix does not match)", addrString)
}
accAddr, err := sdk.AccAddressFromBech32(addrString)
if err != nil {
return common.Address{}, fmt.Errorf("receiver '%s' is not a hex or bech32 address (could not parse as bech32 string)", addrString)
}
return common.BytesToAddress(accAddr), nil
}
// ParseOrQueryConversionPairAddress returns an EVM address of the provided
// ERC20 contract address string or denom. If an address string, just returns
// the parsed address. If a denom, fetches params, searches the enabled
// conversion pairs, and returns corresponding ERC20 contract address.
func ParseOrQueryConversionPairAddress(
queryClient types.QueryClient,
addrOrDenom string,
) (common.Address, error) {
if common.IsHexAddress(addrOrDenom) {
return common.HexToAddress(addrOrDenom), nil
}
if err := sdk.ValidateDenom(addrOrDenom); err != nil {
return common.Address{}, fmt.Errorf(
"Black ERC20 '%s' is not a valid hex address or denom",
addrOrDenom,
)
}
// Valid denom, try looking up as denom to get corresponding Black ERC20 address
paramsRes, err := queryClient.Params(
context.Background(),
&types.QueryParamsRequest{},
)
if err != nil {
return common.Address{}, err
}
for _, pair := range paramsRes.Params.EnabledConversionPairs {
if pair.Denom == addrOrDenom {
return pair.GetAddress().Address, nil
}
}
return common.Address{}, fmt.Errorf(
"Black ERC20 '%s' is not a valid hex address or denom (did not match any denoms in queried enabled conversion pairs)",
addrOrDenom,
)
}