validator.go 1.42 KB
Newer Older
1
package service
2 3 4

import (
	"errors"
5
	"strconv"
6 7

	"github.com/ethereum/go-ethereum/common"
8 9 10
)

// Validator ... Validates API user request parameters
11
type Validator struct{}
12

13 14
// ParseValidateAddress ... Validates and parses the address query parameter
func (v *Validator) ParseValidateAddress(addr string) (common.Address, error) {
15
	if !common.IsHexAddress(addr) {
16 17 18 19 20 21 22 23 24 25
		return common.Address{}, errors.New("address must be represented as a valid hexadecimal string")
	}

	parsedAddr := common.HexToAddress(addr)
	if parsedAddr == common.HexToAddress("0x0") {
		return common.Address{}, errors.New("address cannot be the zero address")
	}

	return parsedAddr, nil
}
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42

// ValidateCursor ... Validates and parses the cursor query parameter
func (v *Validator) ValidateCursor(cursor string) error {
	if cursor == "" {
		return nil
	}

	if len(cursor) != 66 { // 0x + 64 chars
		return errors.New("cursor must be a 32 byte hex string")
	}

	if cursor[:2] != "0x" {
		return errors.New("cursor must begin with 0x")
	}

	return nil
}
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61

// ParseValidateLimit ... Validates and parses the limit query parameters
func (v *Validator) ParseValidateLimit(limit string) (int, error) {
	if limit == "" {
		return 100, nil
	}

	val, err := strconv.Atoi(limit)
	if err != nil {
		return 0, errors.New("limit must be an integer value")
	}

	if val <= 0 {
		return 0, errors.New("limit must be greater than 0")
	}

	// TODO - Add a check against a max limit value
	return val, nil
}