Skip to content

Utils Package

The Utils package provides essential utility functions and helpers for Starknet development. This comprehensive toolkit simplifies common operations including data type conversions, transaction building, cryptographic operations, and unit conversions.

Overview

The Utils package is designed to streamline Starknet development by providing battle-tested utilities for everyday tasks. Whether you're converting hex strings to Felt values, building complex transactions, or performing cryptographic operations, the utils package offers a consistent and intuitive API.

Key capabilities include:

  • Type Conversions: Seamlessly convert between hex strings, Felt values, big.Int, and other data types
  • Transaction Building: Construct invoke, declare, and deploy account transactions with proper formatting
  • Cryptographic Operations: Generate function selectors, compute Keccak256 hashes, and perform hash operations
  • Unit Conversions: Convert between ETH/Wei and STRK/FRI with precision
  • Universal Deployer Contract: Deploy contracts using Starknet's UDC with flexible configuration

Key Components

Conversion Functions

Essential functions for converting between different data representations:

Transaction Builders

Helper functions for constructing Starknet transactions:

Cryptographic Utilities

Functions for hashing, selector generation, and cryptographic operations:

Unit Conversions

Currency and unit conversion utilities for Starknet tokens:

Type Definitions

Core types used throughout the utils package:

  • TxnOptions - Optional settings for transaction building
  • UDCOptions - Options for Universal Deployer Contract
  • UDCVersion - Enum for UDC version selection
  • KeccakState - Interface for Keccak hashing operations

Getting Started

To use the Utils package, import it in your Go code:

import "github.com/NethermindEth/starknet.go/utils"

Quick Example

package main
 
import (
	"fmt"
	"log"
	"math/big"
 
	"github.com/NethermindEth/juno/core/felt"
	"github.com/NethermindEth/starknet.go/rpc"
	"github.com/NethermindEth/starknet.go/utils"
)
 
func main() {
	// Convert hex string to felt
	contractAddress, err := utils.HexToFelt("0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7")
	if err != nil {
		log.Fatal("Failed to convert hex to felt:", err)
	}
	fmt.Printf("Contract Address: %s\n", contractAddress)
 
	// Get selector from function name
	transferSelector := utils.GetSelectorFromNameFelt("transfer")
	fmt.Printf("Transfer Selector: %s\n", transferSelector)
 
	// Convert ETH to Wei
	weiAmount := utils.ETHToWei(1.5)
	fmt.Printf("1.5 ETH = %s Wei\n", weiAmount)
 
	// Convert Wei back to ETH
	ethAmount := utils.WeiToETH(weiAmount)
	fmt.Printf("%s Wei = %.2f ETH\n", weiAmount, ethAmount)
 
	// Build a simple invoke transaction
	senderAddress, _ := utils.HexToFelt("0x123...")
	nonce := new(felt.Felt).SetUint64(1)
	calldata := []*felt.Felt{contractAddress, transferSelector}
 
	resourceBounds := &rpc.ResourceBoundsMapping{
		L1Gas: rpc.ResourceBounds{
			MaxAmount:       rpc.U64("0x2710"), // 10000
			MaxPricePerUnit: rpc.U128("0x64"),  // 100
		},
		L2Gas: rpc.ResourceBounds{
			MaxAmount:       rpc.U64("0x0"),
			MaxPricePerUnit: rpc.U128("0x0"),
		},
	}
 
	tx := utils.BuildInvokeTxn(senderAddress, nonce, calldata, resourceBounds, nil)
	fmt.Printf("Transaction Type: %s\n", tx.Type)
	fmt.Printf("Transaction Version: %s\n", tx.Version)
}

How Utils Work in Starknet

Data Type Conversions

Starknet uses the Felt (Field Element) type as its fundamental data unit. Felts are integers modulo a large prime number (p = 2^251 + 17 * 2^192 + 1). The utils package provides seamless conversion between:

  • Hexadecimal strings → Used in API responses and user input
  • Felt values → Native Starknet data type for on-chain operations
  • big.Int → Go's arbitrary-precision integer type for calculations
  • uint64 → For small numbers and counters

Understanding these conversions is crucial for working with contract addresses, function selectors, calldata, and return values.

Transaction Building

Starknet transactions (v3) require careful construction with multiple fields:

  1. Sender Address: The account contract initiating the transaction
  2. Calldata: The function calls and their parameters
  3. Nonce: Sequential counter to prevent replay attacks
  4. Resource Bounds: Gas limits for L1, L2, and data availability
  5. Signature: Cryptographic signature from the account
  6. Fee Configuration: Tip amount and data availability mode

The transaction builder functions handle the complexity of proper field formatting, version selection, and default value initialization, allowing you to focus on the transaction logic.

Resource Bounds

Starknet v3 transactions use a three-dimensional gas system:

  • L1 Gas: Cost of settling the transaction on Ethereum L1
  • L1 Data Gas: Cost of publishing calldata to L1 for data availability
  • L2 Gas: Cost of executing the transaction on Starknet L2

The FeeEstToResBoundsMap function converts fee estimations into properly formatted resource bounds with safety multipliers to account for price fluctuations.

Universal Deployer Contract (UDC)

The UDC is a special contract on Starknet that deploys other contracts. It offers two deployment modes:

  • Origin-Dependent: Contract address includes the deployer's address (prevents address squatting)
  • Origin-Independent: Contract address is deterministic without deployer info (enables CREATE2-like behavior)

The utils package provides helpers for building UDC calldata and precomputing deployment addresses.

Common Use Cases

The utils package is essential for:

  • Contract Integration: Generate function selectors and format calldata for contract calls
  • Transaction Building: Construct properly formatted invoke, declare, and deploy transactions
  • Fee Management: Estimate fees and convert to resource bounds with safety multipliers
  • Token Operations: Convert between Wei/ETH and FRI/STRK for user-friendly displays
  • Contract Deployment: Deploy contracts via UDC with address precomputation
  • Data Formatting: Convert between hex strings, Felt values, and big integers

For comprehensive examples covering all these scenarios, see the Examples page.

Choosing the Right Conversion Function

Hex String Conversions

  • Use HexToFelt when: Converting contract addresses, transaction hashes, or any hex value from APIs
  • Use FeltToHex when: Preparing Felt values for display or API submission

Numeric Conversions

  • Use Uint64ToFelt when: Converting small integers like counters, indices, or enum values
  • Use BigIntToFelt when: Converting large numbers like token amounts or computed values
  • Use FeltToBigInt when: Need to perform mathematical operations on Felt values

Array Conversions

  • Use HexArrToFelt when: Converting multiple hex values from JSON responses
  • Use FeltArrToBigIntArr when: Need to process multiple Felt values mathematically

Best Practices