github.com/0xsequence/ethkit@v1.25.0/ethcoder/hex.go (about)

     1  package ethcoder
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"math/big"
     7  	"strings"
     8  
     9  	"github.com/0xsequence/ethkit/go-ethereum/common/hexutil"
    10  )
    11  
    12  func HexEncode(h []byte) string {
    13  	return hexutil.Encode(h)
    14  }
    15  
    16  func HexDecode(h string) ([]byte, error) {
    17  	return hexutil.Decode(h)
    18  }
    19  
    20  func MustHexDecode(h string) []byte {
    21  	b, err := HexDecode(h)
    22  	if err != nil {
    23  		panic(fmt.Errorf("ethcoder: must hex decode but failed due to, %v", err))
    24  	}
    25  	return b
    26  }
    27  
    28  func HexDecodeBytes32(h string) ([32]byte, error) {
    29  	slice, err := hexutil.Decode(h)
    30  	if err != nil {
    31  		return [32]byte{}, err
    32  	}
    33  	if len(slice) != 32 {
    34  		return [32]byte{}, errors.New("hex input is not 32 bytes")
    35  	}
    36  
    37  	return BytesToBytes32(slice), nil
    38  }
    39  
    40  func HexDecodeBigIntArray(bigNumsHex []string) ([]*big.Int, error) {
    41  	var err error
    42  	nums := make([]*big.Int, len(bigNumsHex))
    43  	for i := 0; i < len(bigNumsHex); i++ {
    44  		nums[i], err = hexutil.DecodeBig(bigNumsHex[i])
    45  		if err != nil {
    46  			return nil, err
    47  		}
    48  	}
    49  	return nums, nil
    50  }
    51  
    52  func HexEncodeBigIntArray(bigNums []*big.Int) ([]string, error) {
    53  	nums := make([]string, len(bigNums))
    54  	for i := 0; i < len(bigNums); i++ {
    55  		nums[i] = hexutil.EncodeBig(bigNums[i])
    56  	}
    57  	return nums, nil
    58  }
    59  
    60  func HexTrimLeadingZeros(hex string) (string, error) {
    61  	if hex[0:2] != "0x" {
    62  		return "", errors.New("ethcoder: expecting hex value")
    63  	}
    64  	hex = fmt.Sprintf("0x%s", strings.TrimLeft(hex[2:], "0"))
    65  	if hex == "0x" {
    66  		return "0x0", nil
    67  	} else {
    68  		return hex, nil
    69  	}
    70  }