StarkFiStarkFi

Error Handling

25 typed error codes, retry logic, and error recovery patterns

StarkfiError

All errors in StarkFi use the custom StarkfiError class. Every error carries a typed ErrorCode, a human-readable message, and optional structured details:

class StarkfiError extends Error {
	constructor(
		public readonly code: ErrorCode,
		message: string,
		public readonly details?: unknown,
		options?: { cause?: unknown }
	) {
		super(message, options);
		this.name = "StarkfiError";
	}

	toJSON() {
		return {
			error: true,
			code: this.code,
			message: this.message,
			...(this.details ? { details: this.details } : {}),
		};
	}
}

The toJSON() method ensures errors are consistently serialized in MCP responses and --json CLI output.

Error Codes

StarkFi defines 25 typed error codes organized by domain:

Authentication & Session

CodeWhenResolution
AUTH_REQUIREDNo active sessionRun starkfi auth login
AUTH_FAILEDLogin or verify failedCheck email/OTP and retry
SESSION_EXPIREDJWT token expiredRe-authenticate with auth login

Wallet

CodeWhenResolution
WALLET_NOT_DEPLOYEDAccount contract not deployedRun starkfi deploy
WALLET_NOT_FOUNDNo wallet associated with sessionRe-authenticate
INSUFFICIENT_BALANCENot enough tokens for operationCheck balance and reduce amount

Transactions

CodeWhenResolution
TX_FAILEDTransaction execution revertedCheck parameters and try again
TX_NOT_FOUNDInvalid or unknown transaction hashVerify the hash is correct
SIMULATION_FAILEDDry-run preflight check failedReview transaction parameters

Trading

CodeWhenResolution
SWAP_FAILEDSwap execution errorCheck token pair and liquidity
NO_ROUTE_FOUNDNo swap route available via FibrousTry a different pair or smaller amount
SLIPPAGE_EXCEEDEDPrice moved beyond toleranceIncrease --slippage or retry

Staking

CodeWhenResolution
STAKING_FAILEDStaking operation errorCheck amount and pool availability
VALIDATOR_NOT_FOUNDUnknown validator nameRun starkfi validators to see available options
EXIT_NOT_READYUnstake cooldown not passedWait for cooldown, check with stake-status

Lending

CodeWhenResolution
LENDING_FAILEDLending operation errorCheck balance, allowance, and health factor
POOL_NOT_FOUNDInvalid pool name or addressRun starkfi lend-pools to see available pools

Infrastructure

CodeWhenResolution
PAYMASTER_ERRORGas abstraction failedCheck Paymaster credits or gas token balance
NETWORK_ERRORRPC or API connectivity issueCheck connection, retry automatically
RATE_LIMITEDToo many requests to RPC/APIWait and retry, or configure a custom RPC
BATCH_LIMIT_EXCEEDEDMore than 3 operations in multi-swapSplit into multiple transactions

Validation

CodeWhenResolution
INVALID_CONFIGBad configuration valueCheck starkfi config list
INVALID_ADDRESSMalformed Starknet addressEnsure address starts with 0x and is valid
INVALID_AMOUNTNon-positive or non-numeric amountUse a positive number (e.g., 0.1, 100)

General

CodeWhenResolution
UNKNOWNUnexpected error (catch-all)Check the error message for details

Starknet Error Parsing

Raw Starknet JSON-RPC errors often contain hex-encoded Cairo short strings (e.g., 0x753235365f737562204f766572666c6f77u256_sub Overflow) that are unreadable. The parseStarknetError() utility automatically:

  1. Decodes hex-encoded short strings from execution_error payloads
  2. Matches known Cairo error patterns against a map of 15 common errors
  3. Returns a user-friendly message, or passes through the original if no match is found
  4. Strips ENTRYPOINT_FAILED noise from error chains

Error Map (15 patterns)

Cairo ErrorUser-Friendly Message
u256_sub OverflowInsufficient balance — you don't have enough tokens (including gas fees)
u256_add OverflowAmount overflow — the value is too large
ERC20: transfer amount exceeds balanceInsufficient token balance for this transfer
ERC20: burn amount exceeds balanceInsufficient token balance to burn
ERC20: insufficient allowanceToken approval required — not enough allowance for this operation
argent/multicall-failedOne or more calls in the transaction failed
argent/invalid-signatureInvalid signature — try re-authenticating with: starkfi auth login
argent/invalid-timestampTransaction expired — please retry
is_valid_signatureSignature validation failed — try re-authenticating
assert_not_zeroOperation failed — a required value was zero
Contract not foundContract not found — the target contract does not exist on this network
UNAUTHORIZEDUnauthorized — session may have expired, try: starkfi auth login
nonceTransaction nonce error — please retry
dusty-collateral-balanceCollateral amount is below the pool's minimum (dust limit). Please increase the amount.
dusty-debt-balanceBorrow amount is below the pool's minimum (dust limit). Please increase the amount.

Integration

  • CLI: formatError() in lib/format.ts calls parseStarknetError() before displaying
  • MCP: withErrorHandling() in mcp/tools/error-handling.ts calls parseStarknetError() before returning JSON

This ensures both human users and AI agents receive the same readable error messages.

Retry Logic

Network requests use automatic retry with exponential backoff via withRetry():

SettingValue
Max retries2 (3 total attempts)
Base delay500ms
Backoff formulabaseDelay × 2^attempt
Retry sequence500ms → 1000ms

Only retryable error codes (specified per call via retryOnCodes) trigger retries. Domain errors like INSUFFICIENT_BALANCE or NO_ROUTE_FOUND fail immediately — there's no point retrying when the input is invalid.

Fetch Timeout

All HTTP requests use fetchWithTimeout() which wraps the native fetch() with an AbortController that auto-cancels after 15 seconds by default. This prevents hanging requests from blocking the CLI or MCP server.

Error Handling Patterns

CLI Commands

CLI commands catch errors at the top level, stop the spinner, and print a formatted error message:

try {
	// ... operation
	spinner.succeed("Done");
} catch (error) {
	spinner.fail("Operation failed");
	console.error(formatError(error));
	process.exit(1);
}

MCP Handlers

MCP handlers return errors as structured JSON, allowing AI clients to parse and understand the failure:

{
	"error": true,
	"code": "INSUFFICIENT_BALANCE",
	"message": "Not enough ETH — have 0.01, need 0.1"
}

Simulation Before Execution

Transaction commands support --simulate (CLI) or simulation parameters (MCP) to catch errors before they cost gas. Always simulate first when the outcome is uncertain.

Edit on GitHub

Last updated on

On this page