github.com/InjectiveLabs/sdk-go@v1.53.0/chain/types/chain_id.go (about)

     1  package types
     2  
     3  import (
     4  	"fmt"
     5  	"math/big"
     6  	"regexp"
     7  	"strings"
     8  
     9  	"cosmossdk.io/errors"
    10  	tmrand "github.com/cometbft/cometbft/libs/rand"
    11  )
    12  
    13  var (
    14  	regexChainID     = `[a-z]*`
    15  	regexSeparator   = `-{1}`
    16  	regexEpoch       = `[1-9][0-9]*`
    17  	injectiveChainID = regexp.MustCompile(fmt.Sprintf(`^(%s)%s(%s)$`, regexChainID, regexSeparator, regexEpoch))
    18  )
    19  
    20  // IsValidChainID returns false if the given chain identifier is incorrectly formatted.
    21  func IsValidChainID(chainID string) bool {
    22  	if len(chainID) > 48 {
    23  		return false
    24  	}
    25  
    26  	return injectiveChainID.MatchString(chainID)
    27  }
    28  
    29  // ParseChainID parses a string chain identifier's epoch to an Ethereum-compatible
    30  // chain-id in *big.Int format. The function returns an error if the chain-id has an invalid format
    31  func ParseChainID(chainID string) (*big.Int, error) {
    32  	chainID = strings.TrimSpace(chainID)
    33  	if len(chainID) > 48 {
    34  		return nil, errors.Wrapf(ErrInvalidChainID, "chain-id '%s' cannot exceed 48 chars", chainID)
    35  	}
    36  
    37  	matches := injectiveChainID.FindStringSubmatch(chainID)
    38  	if matches == nil || len(matches) != 3 || matches[1] == "" {
    39  		return nil, errors.Wrap(ErrInvalidChainID, chainID)
    40  	}
    41  
    42  	// verify that the chain-id entered is a base 10 integer
    43  	chainIDInt, ok := new(big.Int).SetString(matches[2], 10)
    44  	if !ok {
    45  		return nil, errors.Wrapf(ErrInvalidChainID, "epoch %s must be base-10 integer format", matches[2])
    46  	}
    47  
    48  	return chainIDInt, nil
    49  }
    50  
    51  // GenerateRandomChainID returns a random chain-id in the valid format.
    52  func GenerateRandomChainID() string {
    53  	return fmt.Sprintf("injective-%d", 10+tmrand.Intn(10000))
    54  }