Skip to content

Conversion Functions

Utility functions for converting between different data types commonly used in Starknet development.

Common Conversion Patterns

Understanding when and how to use conversions is key to working efficiently with Starknet data types.

Conversion Flow Diagram

┌─────────────┐     ┌──────────┐     ┌──────────┐
│  Hex String │ ←→  │   Felt   │ ←→  │  BigInt  │
└─────────────┘     └──────────┘     └──────────┘
       ↓                  ↓                ↓
┌─────────────┐     ┌──────────┐     ┌──────────┐
│ Hex Array   │ ←→  │ Felt[]   │ ←→  │BigInt[]  │
└─────────────┘     └──────────┘     └──────────┘

┌─────────────┐
│    Bytes    │ ←→  BigInt
└─────────────┘

Pattern 1: Working with Contract Addresses

// String → Felt (most common for addresses)
addressStr := "0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7"
address, err := utils.HexToFelt(addressStr)
 
// Use in RPC calls
balance, err := client.Call(ctx, rpc.FunctionCall{
    ContractAddress: address,
    // ...
})

Pattern 2: Mathematical Operations on Felt Values

// Felt → BigInt → Math → Felt
contractValue, _ := client.Call(ctx, call) // Returns felt
bigValue := utils.FeltToBigInt(contractValue)
 
// Perform operations
doubled := new(big.Int).Mul(bigValue, big.NewInt(2))
halved := new(big.Int).Div(bigValue, big.NewInt(2))
 
// Convert back to felt for Starknet
resultFelt := utils.BigIntToFelt(doubled)

Pattern 3: Building Transaction Calldata

// Multiple hex values → Felt array (common for calldata)
calldata := []string{
    "0x1",                    // Number of calls
    "0x049d...",              // Contract address
    "0x83afd3f4caedc6eeb...", // Function selector
    "0x0",                    // Data offset
    "0x2",                    // Data length
    "0x1234",                 // First parameter
    "0x5678",                 // Second parameter
}
 
calldataFelts, err := utils.HexArrToFelt(calldata)
if err != nil {
    log.Fatal(err)
}
 
// Use in transaction
tx := rpc.InvokeTxnV3{
    Calldata: calldataFelts,
    // ...
}

Pattern 4: Parsing Contract Output

// Contract returns felt array, need to convert to readable format
output := []*felt.Felt{...} // From contract call
 
// Convert to big integers for processing
bigInts := make([]*big.Int, len(output))
for i, felt := range output {
    bigInts[i] = utils.FeltToBigInt(felt)
}
 
// Or convert to hex strings for display
hexStrings := make([]string, len(output))
for i, felt := range output {
    bigInt := utils.FeltToBigInt(felt)
    hexStrings[i] = utils.BigToHex(bigInt)
}

Pattern 5: Working with Short Strings

// Hex → Short string (for Cairo short strings)
nameHex := "0x537461726b6e6574" // "Starknet" in hex
name := utils.HexToShortStr(nameHex)
fmt.Println(name) // Output: "Starknet"
 
// String → Hex (for encoding short strings)
text := "Hello"
hexText := utils.StrToHex(text)

Choosing the Right Conversion

FromToFunctionWhen to Use
Hex StringFeltHexToFeltContract addresses, transaction hashes, class hashes
Hex ArrayFelt ArrayHexArrToFeltBuilding calldata from string values
FeltBigIntFeltToBigIntMath operations, comparisons, working with other Go libraries
BigIntFeltBigIntToFeltPreparing results for Starknet calls
HexBigIntHexToBNQuick hex parsing without intermediate felt
BigIntHexBigToHexDisplay, logging, debugging
HexShort StringHexToShortStrReading Cairo short strings
StringHexStrToHexEncoding short strings for Cairo
HexBytesHexToBytesLow-level operations, hashing
BytesBigIntBytesToBigProcessing raw byte data
Uint64FeltUint64ToFeltConverting Go integers to Starknet values

Performance Tips

Avoid Unnecessary Conversions:
// ❌ BAD: Multiple conversions
hex := "0x123"
felt, _ := utils.HexToFelt(hex)
bigInt := utils.FeltToBigInt(felt)
result := utils.BigToHex(bigInt)
 
// ✅ GOOD: Direct conversion when possible
bigInt, _ := utils.HexToBN("0x123")
result := utils.BigToHex(bigInt)
Batch Conversions:
// ✅ Convert arrays at once rather than in a loop
hexValues := []string{"0x1", "0x2", "0x3"}
felts, err := utils.HexArrToFelt(hexValues) // Single call
 
// ❌ Avoid converting one at a time if you have many values
for _, hex := range hexValues {
    felt, _ := utils.HexToFelt(hex) // Multiple calls
}

Error Handling Best Practices

// Always check conversion errors
address, err := utils.HexToFelt(addressStr)
if err != nil {
    // Handle invalid hex format
    log.Printf("Invalid address format: %v", err)
    return err
}
 
// Validate before conversion
if !strings.HasPrefix(addressStr, "0x") {
    return errors.New("address must start with 0x")
}

Felt Conversions

HexToFelt

Converts a hexadecimal string to a Felt object.

func HexToFelt(hex string) (*felt.Felt, error)
Parameters:
  • hex - The input hexadecimal string to be converted
Returns:
  • *felt.Felt - A pointer to the converted Felt object
  • error - Error if conversion fails
Usage Example:
package main
 
import (
	"fmt"
	"log"
 
	"github.com/NethermindEth/starknet.go/utils"
)
 
func main() {
	// Convert hex string to felt
	address, err := utils.HexToFelt("0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7")
	if err != nil {
		log.Fatal("Conversion failed:", err)
	}
 
	fmt.Printf("Felt: %s\n", address)
}

HexArrToFelt

Converts an array of hexadecimal strings to an array of Felt objects.

func HexArrToFelt(hexArr []string) ([]*felt.Felt, error)
Parameters:
  • hexArr - An array of strings representing hexadecimal values
Returns:
  • []*felt.Felt - An array of Felt objects
  • error - Error if any conversion fails
Usage Example:
hexStrings := []string{
	"0x1",
	"0x2",
	"0x3",
}
 
felts, err := utils.HexArrToFelt(hexStrings)
if err != nil {
	log.Fatal("Conversion failed:", err)
}
 
fmt.Printf("Converted %d felts\n", len(felts))

FeltArrToStringArr

Converts an array of Felt objects to an array of string objects.

func FeltArrToStringArr(f []*felt.Felt) []string
Parameters:
  • f - The array of Felt objects to convert
Returns:
  • []string - The array of string objects
Usage Example:
felts := []*felt.Felt{
	new(felt.Felt).SetUint64(1),
	new(felt.Felt).SetUint64(2),
	new(felt.Felt).SetUint64(3),
}
 
strings := utils.FeltArrToStringArr(felts)
fmt.Printf("Strings: %v\n", strings)

Big.Int Conversions

BigIntToFelt

Converts a big integer to a Felt.

func BigIntToFelt(bigNum *big.Int) *felt.Felt
Parameters:
  • bigNum - The big integer to convert
Returns:
  • *felt.Felt - The converted Felt value
Usage Example:
import "math/big"
 
bigNum := big.NewInt(12345)
feltNum := utils.BigIntToFelt(bigNum)
fmt.Printf("Felt: %s\n", feltNum)

FeltToBigInt

Converts a Felt value to a big.Int.

func FeltToBigInt(f *felt.Felt) *big.Int
Parameters:
  • f - The Felt value to convert
Returns:
  • *big.Int - The converted value
Usage Example:
felt := new(felt.Felt).SetUint64(12345)
bigNum := utils.FeltToBigInt(felt)
fmt.Printf("Big.Int: %s\n", bigNum.String())

BigIntArrToFeltArr

Converts an array of big.Int objects to an array of Felt objects.

func BigIntArrToFeltArr(bigArr []*big.Int) []*felt.Felt
Parameters:
  • bigArr - The array of big.Int objects to convert
Returns:
  • []*felt.Felt - The array of Felt objects
Usage Example:
bigInts := []*big.Int{
	big.NewInt(1),
	big.NewInt(2),
	big.NewInt(3),
}
 
felts := utils.BigIntArrToFeltArr(bigInts)
fmt.Printf("Converted %d felts\n", len(felts))

FeltArrToBigIntArr

Converts an array of Felt objects to an array of big.Int objects.

func FeltArrToBigIntArr(f []*felt.Felt) []*big.Int
Parameters:
  • f - The array of Felt objects to convert
Returns:
  • []*big.Int - The array of big.Int objects
Usage Example:
felts := []*felt.Felt{
	new(felt.Felt).SetUint64(1),
	new(felt.Felt).SetUint64(2),
}
 
bigInts := utils.FeltArrToBigIntArr(felts)
fmt.Printf("Converted %d big.Ints\n", len(bigInts))

Hex and Byte Conversions

HexToBN

Converts a hexadecimal string to a big.Int. Automatically trims the "0x" prefix if it exists.

func HexToBN(hexString string) *big.Int
Parameters:
  • hexString - The hexadecimal string to be converted
Returns:
  • *big.Int - The converted value
Usage Example:
bigNum := utils.HexToBN("0x1234")
fmt.Printf("Big.Int: %s\n", bigNum.String())

BigToHex

Converts a big integer to its hexadecimal representation.

func BigToHex(in *big.Int) string
Parameters:
  • in - The big integer to be converted
Returns:
  • string - The hexadecimal representation
Usage Example:
bigNum := big.NewInt(4660)
hex := utils.BigToHex(bigNum)
fmt.Printf("Hex: %s\n", hex) // Output: 0x1234

HexToBytes

Converts a hexadecimal string to a byte slice. Automatically trims the "0x" prefix if it exists.

func HexToBytes(hexString string) ([]byte, error)
Parameters:
  • hexString - The hexadecimal string to be converted
Returns:
  • []byte - The converted byte slice
  • error - An error if conversion fails
Usage Example:
bytes, err := utils.HexToBytes("0x48656c6c6f")
if err != nil {
	log.Fatal("Conversion failed:", err)
}
fmt.Printf("Bytes: %v\n", bytes)

BytesToBig

Converts a byte slice to a big.Int.

func BytesToBig(bytes []byte) *big.Int
Parameters:
  • bytes - The byte slice to be converted
Returns:
  • *big.Int - The converted value
Usage Example:
bytes := []byte{0x12, 0x34}
bigNum := utils.BytesToBig(bytes)
fmt.Printf("Big.Int: %s\n", bigNum.String())

String Conversions

StringToByteArrFelt

Converts a string to an array of Felt objects following the Cairo ByteArray format.

The returned array follows the Cairo ByteArray serialization format: [number of 31-byte felts, 31-byte felts..., pending word (max 30 bytes), pending word byte size]

For more details, see the Starknet documentation on ByteArray serialization.

func StringToByteArrFelt(s string) ([]*felt.Felt, error)
Parameters:
  • s - String/bytearray to convert
Returns:
  • []*felt.Felt - The array of Felt objects
  • error - An error if any
Usage Example:
str := "Hello, Starknet!"
felts, err := utils.StringToByteArrFelt(str)
if err != nil {
	log.Fatal("Conversion failed:", err)
}
fmt.Printf("Converted to %d felts\n", len(felts))

ByteArrFeltToString

Converts an array of Felts to a string following the Cairo ByteArray format.

The input array should follow the Cairo ByteArray serialization format: [number of 31-byte felts, 31-byte felts..., pending word (max 30 bytes), pending word byte size]

For more details, see the Starknet documentation on ByteArray serialization.

func ByteArrFeltToString(arr []*felt.Felt) (string, error)
Parameters:
  • arr - The array of Felt objects
Returns:
  • string - The converted string
  • error - An error if any
Usage Example:
// Assuming 'felts' is a ByteArray format felt array
str, err := utils.ByteArrFeltToString(felts)
if err != nil {
	log.Fatal("Conversion failed:", err)
}
fmt.Printf("String: %s\n", str)

HexToShortStr

Converts a hexadecimal string to a short string (Cairo short string representation).

func HexToShortStr(hexStr string) string
Parameters:
  • hexStr - The hexadecimal string to convert
Returns:
  • string - A short string
Usage Example:
// 0x455448 represents "ETH" in hex
shortStr := utils.HexToShortStr("0x455448")
fmt.Printf("Short string: %s\n", shortStr) // Output: ETH

Numeric Conversions

Uint64ToFelt

Generates a new Felt from a given uint64 number.

func Uint64ToFelt(num uint64) *felt.Felt
Parameters:
  • num - The uint64 number to convert to a Felt
Returns:
  • *felt.Felt - A Felt representation of the number
Usage Example:
felt := utils.Uint64ToFelt(12345)
fmt.Printf("Felt: %s\n", felt)

U256 Conversions

HexToU256Felt

Converts a hexadecimal string to a Cairo u256 representation.

The Cairo u256 is represented as two Felt values:

  • The first Felt contains the 128 least significant bits (low part)
  • The second Felt contains the 128 most significant bits (high part)
func HexToU256Felt(hexStr string) ([]*felt.Felt, error)
Parameters:
  • hexStr - The hexadecimal string to convert to a Cairo u256
Returns:
  • []*felt.Felt - A slice containing two Felt values [low, high]
  • error - Error if conversion fails
Usage Example:
// Convert a large hex value to u256
u256, err := utils.HexToU256Felt("0x123456789abcdef0123456789abcdef0")
if err != nil {
	log.Fatal("Conversion failed:", err)
}
fmt.Printf("U256 low: %s, high: %s\n", u256[0], u256[1])

U256FeltToHex

Converts a Cairo u256 representation (two Felt values) back to a hexadecimal string.

The Cairo u256 is represented as two Felt values:

  • The first Felt contains the 128 least significant bits (low part)
  • The second Felt contains the 128 most significant bits (high part)
func U256FeltToHex(u256 []*felt.Felt) (string, error)
Parameters:
  • u256 - A slice containing two Felt values [low, high]
Returns:
  • string - The hexadecimal representation of the combined value
  • error - Error if conversion fails
Usage Example:
// Convert u256 back to hex
low := new(felt.Felt).SetUint64(0x123456789abcdef0)
high := new(felt.Felt).SetUint64(0x123456789abcdef0)
u256 := []*felt.Felt{low, high}
 
hex, err := utils.U256FeltToHex(u256)
if err != nil {
	log.Fatal("Conversion failed:", err)
}
fmt.Printf("Hex: %s\n", hex)

Related