Skip to content

Flash Loan

Connector for flash loan utilities.

almanak.framework.connectors.flash_loan

Flash Loan Module.

This module provides flash loan adapters and the FlashLoanSelector for automatic provider selection based on liquidity, fees, and token availability.

Supported providers: - Aave V3: Most widely supported, 0.09% fee - Balancer: Zero fees, limited token availability

Example

from almanak.framework.connectors.flash_loan import FlashLoanSelector

selector = FlashLoanSelector(chain="arbitrum")

Select best provider for USDC flash loan

result = selector.select_provider( token="USDC", amount=Decimal("1000000"), )

print(f"Selected: {result.provider}, fee: {result.fee_amount}")

FlashLoanProviderInfo dataclass

FlashLoanProviderInfo(
    provider: str,
    is_available: bool = False,
    fee_bps: int = 0,
    fee_amount: Decimal = Decimal("0"),
    estimated_liquidity_usd: int = 0,
    gas_estimate: int = 0,
    pool_address: str = "",
    reliability_score: float = 0.5,
    score: float = 1.0,
    unavailable_reason: str | None = None,
)

Information about a flash loan provider for a specific token.

Attributes:

Name Type Description
provider str

Provider name ("aave" or "balancer")

is_available bool

Whether provider supports this token on this chain

fee_bps int

Flash loan fee in basis points

fee_amount Decimal

Calculated fee amount for the requested loan

estimated_liquidity_usd int

Estimated available liquidity in USD

gas_estimate int

Estimated gas for flash loan (base, without callbacks)

pool_address str

Contract address for flash loan

reliability_score float

Historical reliability (0-1)

score float

Calculated overall score (lower is better)

unavailable_reason str | None

Reason if provider is unavailable

to_dict

to_dict() -> dict[str, Any]

Convert to dictionary.

FlashLoanSelectionResult dataclass

FlashLoanSelectionResult(
    provider: str | None = None,
    pool_address: str = "",
    fee_bps: int = 0,
    fee_amount: Decimal = Decimal("0"),
    total_repay: Decimal = Decimal("0"),
    gas_estimate: int = 0,
    providers_evaluated: list[
        FlashLoanProviderInfo
    ] = list(),
    selection_reasoning: str = "",
)

Result of flash loan provider selection.

Attributes:

Name Type Description
provider str | None

Selected provider name (or None if no provider available)

pool_address str

Contract address to call for flash loan

fee_bps int

Fee in basis points for the selected provider

fee_amount Decimal

Calculated fee amount for the requested loan

total_repay Decimal

Total amount to repay (loan + fee)

gas_estimate int

Estimated gas for the flash loan

providers_evaluated list[FlashLoanProviderInfo]

Information about all evaluated providers

selection_reasoning str

Human-readable explanation of selection

is_success property

is_success: bool

Check if a provider was successfully selected.

to_dict

to_dict() -> dict[str, Any]

Convert to dictionary.

FlashLoanSelector

FlashLoanSelector(
    chain: str,
    reliability_scores: dict[str, float] | None = None,
    default_priority: SelectionPriority = SelectionPriority.FEE,
)

Selects optimal flash loan provider based on configurable criteria.

The selector evaluates Aave V3 and Balancer for the requested token and amount, selecting the best provider based on: - Fee: Balancer has zero fees, Aave charges 0.09% - Liquidity: Check if provider has sufficient liquidity - Reliability: Aave is more battle-tested - Gas: Balancer is slightly cheaper on gas

Example

selector = FlashLoanSelector(chain="arbitrum")

Select provider for 1M USDC flash loan

result = selector.select_provider( token="USDC", amount=Decimal("1000000"), priority="fee", # Will prefer Balancer (zero fee) )

if result.is_success: print(f"Use {result.provider} at {result.pool_address}") print(f"Fee: {result.fee_amount} ({result.fee_bps} bps)")

Initialize the flash loan selector.

Parameters:

Name Type Description Default
chain str

Target blockchain (ethereum, arbitrum, optimism, polygon, base)

required
reliability_scores dict[str, float] | None

Optional custom reliability scores per provider

None
default_priority SelectionPriority

Default selection priority

FEE

select_provider

select_provider(
    token: str,
    amount: Decimal,
    priority: str | None = None,
    min_liquidity_usd: int = 0,
) -> FlashLoanSelectionResult

Select the optimal flash loan provider.

Evaluates Aave and Balancer for the requested token and amount, returning the best provider based on the priority criteria.

Parameters:

Name Type Description Default
token str

Token symbol (e.g., "USDC", "WETH")

required
amount Decimal

Flash loan amount in token units

required
priority str | None

Selection priority ("fee", "liquidity", "reliability", "gas")

None
min_liquidity_usd int

Minimum required liquidity in USD

0

Returns:

Type Description
FlashLoanSelectionResult

FlashLoanSelectionResult with selected provider details

Raises:

Type Description
NoProviderAvailableError

If no provider supports the token/amount

get_provider_info

get_provider_info(
    provider: str, token: str, amount: Decimal
) -> FlashLoanProviderInfo

Get information about a specific provider for a token.

Parameters:

Name Type Description Default
provider str

Provider name ("aave" or "balancer")

required
token str

Token symbol

required
amount Decimal

Flash loan amount

required

Returns:

Type Description
FlashLoanProviderInfo

FlashLoanProviderInfo for the provider

is_token_supported

is_token_supported(
    token: str, provider: str | None = None
) -> bool

Check if a token is supported for flash loans.

Parameters:

Name Type Description Default
token str

Token symbol

required
provider str | None

Optional specific provider to check

None

Returns:

Type Description
bool

True if token is supported

get_supported_tokens

get_supported_tokens(
    provider: str | None = None,
) -> set[str]

Get set of tokens supported for flash loans.

Parameters:

Name Type Description Default
provider str | None

Optional specific provider to check

None

Returns:

Type Description
set[str]

Set of supported token symbols

estimate_liquidity

estimate_liquidity(
    token: str, provider: str | None = None
) -> dict[str, int]

Estimate available liquidity for a token.

Parameters:

Name Type Description Default
token str

Token symbol

required
provider str | None

Optional specific provider

None

Returns:

Type Description
dict[str, int]

Dict mapping provider name to estimated liquidity in USD

FlashLoanSelectorError

Bases: Exception

Base exception for flash loan selector errors.

NoProviderAvailableError

Bases: FlashLoanSelectorError

Raised when no provider can fulfill the flash loan request.

SelectionPriority

Bases: Enum

Priority for flash loan provider selection.

Attributes:

Name Type Description
FEE

Minimize flash loan fees (Balancer preferred - zero fee)

LIQUIDITY

Prefer providers with deeper liquidity

RELIABILITY

Prefer more battle-tested providers (Aave preferred)

GAS

Minimize gas costs