Skip to content

Account Types

Type definitions and structures used in the account package.

Account

Main structure representing a Starknet account.

Type Definition

type Account struct {
	Provider     rpc.RPCProvider
	ChainID      *felt.Felt
	Address      *felt.Felt
	CairoVersion CairoVersion
	// contains filtered or unexported fields
}

Fields

Provider

Provider rpc.RPCProvider

RPC provider used to interact with the Starknet network. This handles all network communication for the account.

ChainID

ChainID *felt.Felt

Chain ID of the Starknet network. Automatically set during account creation:

  • Mainnet: SN_MAIN
  • Sepolia Testnet: SN_SEPOLIA

Used in transaction hash calculations to prevent replay attacks across different networks.

Address

Address *felt.Felt

On-chain address of the account contract. This is the deployed account contract's address that executes transactions.

CairoVersion

CairoVersion CairoVersion

Cairo version of the account contract (CairoV0 or CairoV2). Determines how calldata is formatted for transactions.

Usage Example

package main
 
import (
	"context"
	"fmt"
	"log"
 
	"github.com/NethermindEth/starknet.go/account"
	"github.com/NethermindEth/starknet.go/rpc"
	"github.com/NethermindEth/starknet.go/utils"
)
 
func main() {
	// Create provider
	provider, err := rpc.NewProvider("https://starknet-sepolia.public.blastapi.io/rpc/v0_8")
	if err != nil {
		log.Fatal(err)
	}
 
	// Generate keys
	ks, pubKey, _ := account.GetRandomKeys()
 
	// Create account
	accountAddress, _ := utils.HexToFelt("0x1234...")
	acc, err := account.NewAccount(provider, accountAddress, pubKey.String(), ks, account.CairoV2)
	if err != nil {
		log.Fatal(err)
	}
 
	// Access account fields
	fmt.Printf("Address: %s\n", acc.Address.String())
	fmt.Printf("Chain ID: %s\n", acc.ChainID.String())
	fmt.Printf("Cairo Version: %d\n", acc.CairoVersion)
 
	// Use account
	nonce, err := acc.Nonce(context.Background())
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Nonce: %s\n", nonce.String())
}

Description

The Account struct encapsulates all information needed to interact with a Starknet account contract. It provides methods for:

  • Transaction building and sending
  • Message signing and verification
  • Nonce management
  • Fee estimation

The struct contains unexported fields (private key reference through keystore) that are not directly accessible.

Related Types


AccountInterface

Interface defining the contract for account implementations.

Interface Definition

type AccountInterface interface {
	BuildAndEstimateDeployAccountTxn(
		ctx context.Context,
		salt *felt.Felt,
		classHash *felt.Felt,
		constructorCalldata []*felt.Felt,
		opts *TxnOptions,
	) (*rpc.BroadcastDeployAccountTxnV3, *felt.Felt, error)
 
	BuildAndSendInvokeTxn(
		ctx context.Context,
		functionCalls []rpc.InvokeFunctionCall,
		opts *TxnOptions,
	) (rpc.AddInvokeTransactionResponse, error)
 
	BuildAndSendDeclareTxn(
		ctx context.Context,
		casmClass *contracts.CasmClass,
		contractClass *contracts.ContractClass,
		opts *TxnOptions,
	) (rpc.AddDeclareTransactionResponse, error)
 
	DeployContractWithUDC(
		ctx context.Context,
		classHash *felt.Felt,
		constructorCalldata []*felt.Felt,
		txnOpts *TxnOptions,
		udcOpts *UDCOptions,
	) (rpc.AddInvokeTransactionResponse, *felt.Felt, error)
 
	Nonce(ctx context.Context) (*felt.Felt, error)
 
	SendTransaction(
		ctx context.Context,
		txn rpc.BroadcastTxn,
	) (rpc.TransactionResponse, error)
 
	Sign(ctx context.Context, msg *felt.Felt) ([]*felt.Felt, error)
 
	SignInvokeTransaction(ctx context.Context, tx rpc.InvokeTxnType) error
 
	SignDeployAccountTransaction(
		ctx context.Context,
		tx rpc.DeployAccountType,
		precomputeAddress *felt.Felt,
	) error
 
	SignDeclareTransaction(ctx context.Context, tx rpc.DeclareTxnType) error
 
	TransactionHashInvoke(invokeTxn rpc.InvokeTxnType) (*felt.Felt, error)
 
	TransactionHashDeployAccount(
		tx rpc.DeployAccountType,
		contractAddress *felt.Felt,
	) (*felt.Felt, error)
 
	TransactionHashDeclare(tx rpc.DeclareTxnType) (*felt.Felt, error)
 
	Verify(msgHash *felt.Felt, signature []*felt.Felt) (bool, error)
 
	WaitForTransactionReceipt(
		ctx context.Context,
		transactionHash *felt.Felt,
		pollInterval time.Duration,
	) (*rpc.TransactionReceiptWithBlockInfo, error)
}

Description

AccountInterface defines the standard interface for Starknet account implementations. The Account type implements this interface.

This interface can be used to:

  • Write functions that accept any account implementation
  • Create mock accounts for testing
  • Implement custom account types with different behavior

Usage Example

package main
 
import (
	"context"
	"fmt"
 
	"github.com/NethermindEth/starknet.go/account"
	"github.com/NethermindEth/starknet.go/rpc"
)
 
// Function accepting any account implementation
func GetAccountInfo(acc account.AccountInterface) error {
	nonce, err := acc.Nonce(context.Background())
	if err != nil {
		return err
	}
 
	fmt.Printf("Account nonce: %s\n", nonce.String())
	return nil
}
 
func main() {
	// Can pass any AccountInterface implementation
	var acc *account.Account // Standard account
	GetAccountInfo(acc)
 
	// Or a custom implementation
	// var customAcc account.AccountInterface = &CustomAccount{}
	// GetAccountInfo(customAcc)
}

Implementing Custom Accounts

package main
 
import (
	"context"
	"time"
 
	"github.com/NethermindEth/juno/core/felt"
	"github.com/NethermindEth/starknet.go/account"
	"github.com/NethermindEth/starknet.go/contracts"
	"github.com/NethermindEth/starknet.go/rpc"
)
 
// CustomAccount implements AccountInterface with custom behavior
type CustomAccount struct {
	*account.Account
	// Additional fields...
}
 
// Override methods as needed
func (ca *CustomAccount) BuildAndSendInvokeTxn(
	ctx context.Context,
	functionCalls []rpc.InvokeFunctionCall,
	opts *account.TxnOptions,
) (rpc.AddInvokeTransactionResponse, error) {
	// Custom logic before sending
	fmt.Println("Custom account sending transaction...")
 
	// Call base implementation or implement from scratch
	return ca.Account.BuildAndSendInvokeTxn(ctx, functionCalls, opts)
}
 
// Ensure CustomAccount implements AccountInterface
var _ account.AccountInterface = (*CustomAccount)(nil)

Methods

See the Methods documentation for detailed information about each interface method.

Related Types


CairoVersion

Enum representing Cairo contract versions.

Type Definition

type CairoVersion int
 
const (
	CairoV0 CairoVersion = 0
	CairoV2 CairoVersion = 2
)

Constants

CairoV0

const CairoV0 CairoVersion = 0

Represents Cairo 0 contracts. Uses the older calldata format with offsets.

CairoV2

const CairoV2 CairoVersion = 2

Represents Cairo 2 contracts (also known as Cairo 1). Uses the simplified calldata format without offsets.

Usage Example

package main
 
import (
	"fmt"
 
	"github.com/NethermindEth/starknet.go/account"
)
 
func main() {
	// Create account with Cairo 2
	acc, err := account.NewAccount(provider, address, pubKey, ks, account.CairoV2)
	if err != nil {
		log.Fatal(err)
	}
 
	// Check Cairo version
	if acc.CairoVersion == account.CairoV0 {
		fmt.Println("Using Cairo 0 account")
	} else if acc.CairoVersion == account.CairoV2 {
		fmt.Println("Using Cairo 2 account")
	}
 
	// The account automatically formats calldata based on its version
	response, err := acc.BuildAndSendInvokeTxn(ctx, functionCalls, nil)
}

Description

CairoVersion determines how the account formats calldata for transactions:

Cairo 0 Format:
  • More complex structure with offsets
  • Required for older account contracts
  • Format: [call_array_len, call_array..., calldata_len, calldata...]
Cairo 2 Format:
  • Simplified structure without offsets
  • Used by modern account contracts
  • Format: [calls_len, (contract, selector, data_len, data)...]

The Account methods automatically handle the correct format based on the CairoVersion field.

Determining Your Account's Version

To determine which version your account uses:

  1. Check your account contract's Cairo version
  2. OpenZeppelin accounts from 0.7.0+ use Cairo 2
  3. ArgentX accounts use Cairo 2
  4. Older contracts may use Cairo 0

When in doubt, check your account contract's documentation or source code.

Related Functions


TxnOptions

Configuration options for building and sending transactions.

Type Definition

type TxnOptions struct {
	// The multiplier to be used when estimating the tip when no custom tip is set.
	// If <= 0, it'll be set to 1.0 (no multiplier, just the estimated tip).
	TipMultiplier float64
 
	// A custom tip amount in FRI for the transaction in hexadecimal format.
	// If not set, the tip will be automatically estimated for the transaction.
	CustomTip rpc.U64
 
	// A boolean flag indicating whether the transaction version should have
	// the query bit when estimating fees. If true, the transaction version
	// will be `rpc.TransactionV3WithQueryBit` (0x100000000000000000000000000000003).
	// If false, the transaction version will be `rpc.TransactionV3` (0x3).
	// In case of doubt, set to `false`. Default: `false`.
	UseQueryBit bool
 
	// A safety factor for fee estimation that helps prevent transaction
	// failures due to fee fluctuations. It multiplies both the max amount
	// and max price per unit by this value.
	// A value of 1.5 (estimated fee + 50%) is recommended to balance between
	// transaction success rate and avoiding excessive fees. Higher values
	// provide more safety margin but may result in overpayment.
	// If FeeMultiplier <= 0, it'll be set to 1.5.
	FeeMultiplier float64
 
	// A boolean flag indicating whether to use the latest block tag
	// when estimating fees instead of the pre_confirmed block. Default: `false`.
	UseLatest bool
 
	// The simulation flag to be used when estimating fees. Default: none.
	SimulationFlag rpc.SimulationFlag
}

Fields

TipMultiplier

TipMultiplier float64

The multiplier to be used when estimating the tip when no custom tip is set.

Default: 1.0 if <= 0 (no multiplier, just the estimated tip)

Examples:
  • 1.0: Use estimated tip as-is
  • 1.5: Add 50% to estimated tip
  • 2.0: Double the estimated tip

Note: Only used when CustomTip is not set.

CustomTip

CustomTip rpc.U64

A custom tip amount in FRI (smallest unit of STRK) for transaction prioritization in hexadecimal format.

Default: Not set (tip will be automatically estimated)

Example: "0x1000" (4096 FRI)

Note: If set, this overrides the automatic tip estimation and TipMultiplier is ignored. Transaction tips are only active after Starknet v0.14.0 upgrade.

UseQueryBit

UseQueryBit bool

Whether to use the query bit in transaction version during fee estimation.

Values:
  • true: Uses version 0x100000000000000000000000000000003 (TransactionV3WithQueryBit)
  • false: Uses version 0x3 (TransactionV3)

Default: false

Usage: Set to false unless you have specific needs for query bit transactions. In case of doubt, set to false.

FeeMultiplier

FeeMultiplier float64

A safety factor for fee estimation that helps prevent transaction failures due to fee fluctuations. It multiplies both the max amount and max price per unit by this value.

Recommended: 1.5 (50% safety margin)

Default: 1.5 if <= 0

Examples:
  • 1.0: No safety margin (risky, may fail if fees increase)
  • 1.5: 50% safety margin (recommended, balances safety and cost)
  • 2.0: 100% safety margin (very safe, may overpay)
  • 3.0: 200% safety margin (maximum safety for critical transactions)

Higher values provide more safety against fee fluctuations but may result in overpayment.

UseLatest

UseLatest bool

Whether to use the latest block tag for fee estimation instead of pre_confirmed.

Values:
  • true: Use latest block
  • false: Use pre_confirmed block

Default: false

Usage: Set to true if you need the most recent block state for estimation.

SimulationFlag

SimulationFlag rpc.SimulationFlag

The simulation flag to be used when estimating fees.

Options:
  • rpc.SkipValidate: Skip validation during simulation
  • "": No simulation flags (default)

Default: No flags (empty)

Usage Example

package main
 
import (
	"context"
	"log"
 
	"github.com/NethermindEth/starknet.go/account"
	"github.com/NethermindEth/starknet.go/rpc"
)
 
func main() {
	// Assume acc and functionCalls are already created
	var acc *account.Account
	var functionCalls []rpc.InvokeFunctionCall
 
	// Example 1: Use default options (nil)
	response, err := acc.BuildAndSendInvokeTxn(context.Background(), functionCalls, nil)
	if err != nil {
		log.Fatal(err)
	}
 
	// Example 2: Configure specific options with auto-estimated tip
	opts := &account.TxnOptions{
		TipMultiplier:  1.5,              // Add 50% to estimated tip
		UseQueryBit:    false,            // Standard version
		FeeMultiplier:  1.5,              // 50% safety margin
		UseLatest:      false,            // Use pre_confirmed block
		SimulationFlag: rpc.SkipValidate, // Skip validation
	}
 
	response, err = acc.BuildAndSendInvokeTxn(context.Background(), functionCalls, opts)
	if err != nil {
		log.Fatal(err)
	}
 
	// Example 3: Custom tip amount
	customTipOpts := &account.TxnOptions{
		CustomTip:     "0x1000",  // Custom tip of 4096 FRI
		FeeMultiplier: 1.5,       // 50% safety margin
	}
 
	response, err = acc.BuildAndSendInvokeTxn(context.Background(), functionCalls, customTipOpts)
	if err != nil {
		log.Fatal(err)
	}
 
	// Example 4: Conservative fee estimation
	conservativeOpts := &account.TxnOptions{
		FeeMultiplier: 2.0,  // 100% safety margin
		UseLatest:     true, // Use latest block
	}
 
	response, err = acc.BuildAndSendInvokeTxn(context.Background(), functionCalls, conservativeOpts)
}

Methods

BlockID

func (opts *TxnOptions) BlockID() rpc.BlockID

Returns the block ID for fee estimation based on the UseLatest flag.

Returns:
  • rpc.WithBlockTag("latest") if UseLatest is true
  • rpc.WithBlockTag("pre_confirmed") if UseLatest is false
Usage:
opts := &account.TxnOptions{UseLatest: true}
blockID := opts.BlockID() // Returns WithBlockTag("latest")

FmtFeeMultiplier

func (opts *TxnOptions) FmtFeeMultiplier() float64

Returns the fee multiplier specified in the options. If not set or negative, returns the default fee multiplier (1.5).

Returns:
  • opts.FeeMultiplier if > 0
  • 1.5 (default) if <= 0
Usage:
opts := &account.TxnOptions{FeeMultiplier: 2.0}
multiplier := opts.FmtFeeMultiplier() // Returns 2.0
 
nilOpts := &account.TxnOptions{}
multiplier = nilOpts.FmtFeeMultiplier() // Returns 1.5 (default)

FmtTipMultiplier

func (opts *TxnOptions) FmtTipMultiplier() float64

Returns the tip multiplier specified in the options. If not set or negative, returns the default tip multiplier (1.0).

Returns:
  • opts.TipMultiplier if > 0
  • 1.0 (default) if <= 0
Usage:
opts := &account.TxnOptions{TipMultiplier: 1.5}
multiplier := opts.FmtTipMultiplier() // Returns 1.5
 
nilOpts := &account.TxnOptions{}
multiplier = nilOpts.FmtTipMultiplier() // Returns 1.0 (default)

SimulationFlags

func (opts *TxnOptions) SimulationFlags() []rpc.SimulationFlag

Returns simulation flags as a slice. Returns empty slice if no flags set.

Returns:
  • []rpc.SimulationFlag{opts.SimulationFlag} if flag is set
  • []rpc.SimulationFlag{} (empty slice) if flag is not set
Usage:
opts := &account.TxnOptions{SimulationFlag: rpc.SkipValidate}
flags := opts.SimulationFlags() // Returns []rpc.SimulationFlag{rpc.SkipValidate}
 
nilOpts := &account.TxnOptions{}
flags = nilOpts.SimulationFlags() // Returns []rpc.SimulationFlag{}

Default Behavior

When opts is nil or fields are not set:

// These are equivalent:
acc.BuildAndSendInvokeTxn(ctx, calls, nil)
 
acc.BuildAndSendInvokeTxn(ctx, calls, &account.TxnOptions{
	TipMultiplier:  1.0,   // No tip multiplier (use estimated tip)
	CustomTip:      "",    // No custom tip (auto-estimate)
	UseQueryBit:    false, // Use standard transaction version
	FeeMultiplier:  1.5,   // 50% safety margin for fees
	UseLatest:      false, // Use pre_confirmed block
	SimulationFlag: "",    // No simulation flags
})

Fee Estimation Strategy

Choosing the Right Fee Multiplier

The FeeMultiplier provides safety against fee fluctuations:

// Low risk, predictable fees (testnet, low value)
opts := &account.TxnOptions{FeeMultiplier: 1.2} // 20% safety
 
// Recommended for most cases
opts := &account.TxnOptions{FeeMultiplier: 1.5} // 50% safety (default)
 
// High risk or volatile fees (mainnet, high value)
opts := &account.TxnOptions{FeeMultiplier: 2.0} // 100% safety
 
// Maximum safety (critical transactions)
opts := &account.TxnOptions{FeeMultiplier: 3.0} // 200% safety

Choosing the Right Tip Strategy

The TipMultiplier and CustomTip control transaction prioritization:

// Use estimated tip as-is (default)
opts := &account.TxnOptions{TipMultiplier: 1.0}
 
// Add safety margin to estimated tip
opts := &account.TxnOptions{TipMultiplier: 1.5} // 50% higher tip
 
// Set custom tip for guaranteed prioritization
opts := &account.TxnOptions{CustomTip: "0x2710"} // 10000 FRI custom tip
 
// No tip (may be slower)
opts := &account.TxnOptions{CustomTip: "0x0"} // Explicitly set to 0

Related Methods


UDCOptions

Configuration options for Universal Deployer Contract (UDC) deployments.

Type Definition

type UDCOptions = utils.UDCOptions

This is an alias for utils.UDCOptions. See the utils package documentation for complete details.

Fields

Based on the utils package, UDCOptions typically includes:

type UDCOptions struct {
	Salt   *felt.Felt // Salt for address computation
	Unique bool       // Whether to make address unique to deployer
}

Salt

Random value used in contract address computation. If not provided, a random salt is generated.

Unique

If true, includes the deployer address in address calculation, making the deployed address unique to the deployer. If false, anyone can deploy to the same address with the same parameters.

Usage Example

package main
 
import (
	"context"
	"fmt"
	"log"
 
	"github.com/NethermindEth/juno/core/felt"
	"github.com/NethermindEth/starknet.go/account"
	"github.com/NethermindEth/starknet.go/utils"
)
 
func main() {
	// Assume acc is already created
	var acc *account.Account
	var classHash *felt.Felt
	var constructorCalldata []*felt.Felt
 
	// Example 1: Use default options (random salt, unique=true)
	response, salt, err := acc.DeployContractWithUDC(
		context.Background(),
		classHash,
		constructorCalldata,
		nil, // Transaction options
		nil, // UDC options - will use defaults
	)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Deployed with random salt: %s\n", salt.String())
 
	// Example 2: Specify custom salt
	udcOpts := &utils.UDCOptions{
		Salt:   new(felt.Felt).SetUint64(42),
		Unique: true,
	}
 
	response, salt, err = acc.DeployContractWithUDC(
		context.Background(),
		classHash,
		constructorCalldata,
		nil,
		udcOpts,
	)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Deployed with custom salt: %s\n", salt.String())
 
	// Example 3: Non-unique deployment (counterfactual address)
	nonUniqueOpts := &utils.UDCOptions{
		Salt:   new(felt.Felt).SetUint64(123),
		Unique: false, // Anyone can deploy to this address
	}
 
	response, salt, err = acc.DeployContractWithUDC(
		context.Background(),
		classHash,
		constructorCalldata,
		nil,
		nonUniqueOpts,
	)
}

Description

UDCOptions configures how contracts are deployed through the Universal Deployer Contract:

Random Salt (nil options):
  • Generates random salt
  • Unique to deployer
  • Address cannot be predicted beforehand
Custom Salt + Unique:
  • Predictable address
  • Unique to deployer
  • Prevents others from deploying to same address
Custom Salt + Non-Unique:
  • Counterfactual address
  • Same for all deployers with same parameters
  • Allows CREATE2-style deployments

Calculating Deployed Address

// After deployment, calculate the address
deployedAddress := utils.CalculateUDCAddress(
	classHash,
	salt,
	constructorCalldata,
	acc.Address, // Include if Unique: true
)
fmt.Printf("Contract deployed at: %s\n", deployedAddress.String())

Related Methods


Error Types

Common errors returned by account methods.

ErrTxnTypeUnSupported

var ErrTxnTypeUnSupported = errors.New("unsupported transaction type")

Returned when an unsupported transaction type is passed to a method.

Example:
hash, err := acc.TransactionHashInvoke(invalidTxType)
if err != nil {
	if errors.Is(err, account.ErrTxnTypeUnSupported) {
		fmt.Println("Transaction type not supported")
	}
}

ErrTxnVersionUnSupported

var ErrTxnVersionUnSupported = errors.New("unsupported transaction version")

Returned when an unsupported transaction version is used.

Example:
hash, err := acc.TransactionHashDeclare(declareTxnV0)
if err != nil {
	if errors.Is(err, account.ErrTxnVersionUnSupported) {
		fmt.Println("Declare V0 hash calculation not supported")
	}
}

ErrSenderNoExist

var ErrSenderNoExist = errors.New("sender does not exist")

Returned by MemKeystore.Get when a key is not found.

Example:
key, err := ks.Get(publicKey)
if err != nil {
	if errors.Is(err, account.ErrSenderNoExist) {
		fmt.Println("Key not found in keystore")
	}
}

Related Resources