Aller au contenu

Aave V3

Connector for Aave V3 lending protocol.

almanak.framework.connectors.aave_v3

Aave V3 Connector.

This module provides an adapter for interacting with Aave V3 lending protocol, supporting supply, borrow, repay, withdraw, flash loans, E-Mode, isolation mode, and comprehensive event parsing.

Aave V3 is a decentralized lending protocol supporting: - Supply assets to earn yield - Borrow against collateral - Flash loans for atomic arbitrage - Efficiency Mode (E-Mode) for correlated assets - Isolation Mode for new assets with limited debt ceiling - Variable and stable interest rates

Supported chains: - Ethereum - Arbitrum - Optimism - Polygon - Base - Avalanche

Example

from almanak.framework.connectors.aave_v3 import AaveV3Adapter, AaveV3Config

config = AaveV3Config( chain="arbitrum", wallet_address="0x...", ) adapter = AaveV3Adapter(config)

Supply collateral

result = adapter.supply( asset="USDC", amount=Decimal("1000"), )

Borrow against collateral

result = adapter.borrow( asset="WETH", amount=Decimal("0.5"), )

Execute flash loan

result = adapter.flash_loan_simple( receiver_address="0x...", asset="USDC", amount=Decimal("100000"), )

Calculate health factor

hf_calc = adapter.calculate_health_factor( positions=positions, reserve_data=reserve_data, )

AaveV3Adapter

AaveV3Adapter(
    config: AaveV3Config,
    price_oracle: PriceOracle | None = None,
    token_resolver: TokenResolver | None = None,
)

Adapter for Aave V3 lending protocol.

This adapter provides methods for interacting with Aave V3: - Supply/withdraw collateral - Borrow/repay assets - Flash loans - E-Mode configuration - Health factor calculations - Liquidation price calculations

Example

config = AaveV3Config( chain="arbitrum", wallet_address="0x...", ) adapter = AaveV3Adapter(config)

Supply USDC as collateral

result = adapter.supply("USDC", Decimal("1000"))

Borrow ETH

result = adapter.borrow("WETH", Decimal("0.5"))

Check health factor

hf = adapter.calculate_health_factor(positions, prices)

Initialize the adapter.

参数:

名称 类型 描述 默认
config AaveV3Config

Adapter configuration

必需
price_oracle PriceOracle | None

Price oracle callback. REQUIRED for production use. If not provided and allow_placeholder_prices=False, health factor calculations will raise an error. Pass a real price oracle from your MarketSnapshot or PriceAggregator.

None
token_resolver TokenResolver | None

Optional TokenResolver instance. If None, uses singleton.

None

引发:

类型 描述
ValueError

If no price_oracle is provided and allow_placeholder_prices=False

supply

supply(
    asset: str,
    amount: Decimal,
    on_behalf_of: str | None = None,
) -> TransactionResult

Build a supply transaction.

参数:

名称 类型 描述 默认
asset str

Asset symbol or address

必需
amount Decimal

Amount to supply (in token units)

必需
on_behalf_of str | None

Address to credit (defaults to wallet_address)

None

返回:

类型 描述
TransactionResult

TransactionResult with transaction data

withdraw

withdraw(
    asset: str,
    amount: Decimal,
    to: str | None = None,
    withdraw_all: bool = False,
) -> TransactionResult

Build a withdraw transaction.

参数:

名称 类型 描述 默认
asset str

Asset symbol or address

必需
amount Decimal

Amount to withdraw (in token units)

必需
to str | None

Address to receive tokens (defaults to wallet_address)

None
withdraw_all bool

If True, use MAX_UINT256 to withdraw all

False

返回:

类型 描述
TransactionResult

TransactionResult with transaction data

borrow

borrow(
    asset: str,
    amount: Decimal,
    interest_rate_mode: AaveV3InterestRateMode = AaveV3InterestRateMode.VARIABLE,
    on_behalf_of: str | None = None,
) -> TransactionResult

Build a borrow transaction.

参数:

名称 类型 描述 默认
asset str

Asset symbol or address

必需
amount Decimal

Amount to borrow (in token units)

必需
interest_rate_mode AaveV3InterestRateMode

Interest rate mode (STABLE or VARIABLE)

VARIABLE
on_behalf_of str | None

Address to debit (defaults to wallet_address)

None

返回:

类型 描述
TransactionResult

TransactionResult with transaction data

repay

repay(
    asset: str,
    amount: Decimal,
    interest_rate_mode: AaveV3InterestRateMode = AaveV3InterestRateMode.VARIABLE,
    on_behalf_of: str | None = None,
    repay_all: bool = False,
) -> TransactionResult

Build a repay transaction.

参数:

名称 类型 描述 默认
asset str

Asset symbol or address

必需
amount Decimal

Amount to repay (in token units)

必需
interest_rate_mode AaveV3InterestRateMode

Interest rate mode of debt to repay

VARIABLE
on_behalf_of str | None

Address with debt (defaults to wallet_address)

None
repay_all bool

If True, use MAX_UINT256 to repay full debt

False

返回:

类型 描述
TransactionResult

TransactionResult with transaction data

set_user_use_reserve_as_collateral

set_user_use_reserve_as_collateral(
    asset: str, use_as_collateral: bool
) -> TransactionResult

Build a transaction to enable/disable asset as collateral.

参数:

名称 类型 描述 默认
asset str

Asset symbol or address

必需
use_as_collateral bool

Whether to use as collateral

必需

返回:

类型 描述
TransactionResult

TransactionResult with transaction data

set_user_emode

set_user_emode(category_id: int) -> TransactionResult

Build a transaction to set user E-Mode category.

E-Mode (Efficiency Mode) allows higher LTV for correlated assets.

Categories: - 0: None (normal mode) - 1: ETH correlated (ETH, wstETH, cbETH, rETH) - 2: Stablecoins (USDC, USDT, DAI)

参数:

名称 类型 描述 默认
category_id int

E-Mode category ID

必需

返回:

类型 描述
TransactionResult

TransactionResult with transaction data

get_emode_category_data

get_emode_category_data(category_id: int) -> dict[str, Any]

Get E-Mode category configuration.

参数:

名称 类型 描述 默认
category_id int

E-Mode category ID

必需

返回:

类型 描述
dict[str, Any]

Dictionary with E-Mode category data

flash_loan

flash_loan(
    receiver_address: str,
    assets: list[str],
    amounts: list[Decimal],
    modes: list[int],
    on_behalf_of: str | None = None,
    params: bytes = b"",
) -> TransactionResult

Build a flash loan transaction.

Flash loans allow borrowing assets without collateral, provided they are returned (plus premium) within the same transaction.

Modes: - 0: No open debt (must repay within same transaction) - 1: Open stable rate debt - 2: Open variable rate debt

参数:

名称 类型 描述 默认
receiver_address str

Contract that will receive the flash loan

必需
assets list[str]

List of asset symbols or addresses

必需
amounts list[Decimal]

List of amounts to borrow

必需
modes list[int]

List of debt modes (0, 1, or 2)

必需
on_behalf_of str | None

Address to receive debt if mode != 0

None
params bytes

Extra data to pass to receiver

b''

返回:

类型 描述
TransactionResult

TransactionResult with transaction data

flash_loan_simple

flash_loan_simple(
    receiver_address: str,
    asset: str,
    amount: Decimal,
    params: bytes = b"",
) -> TransactionResult

Build a simple flash loan transaction (single asset, no debt).

This is a simplified flash loan for a single asset that must be repaid within the same transaction.

参数:

名称 类型 描述 默认
receiver_address str

Contract that will receive the flash loan

必需
asset str

Asset symbol or address

必需
amount Decimal

Amount to borrow

必需
params bytes

Extra data to pass to receiver

b''

返回:

类型 描述
TransactionResult

TransactionResult with transaction data

liquidation_call

liquidation_call(
    collateral_asset: str,
    debt_asset: str,
    user: str,
    debt_to_cover: Decimal,
    receive_atoken: bool = False,
) -> TransactionResult

Build a liquidation transaction.

Liquidation allows repaying another user's debt in exchange for their collateral at a discount (liquidation bonus).

参数:

名称 类型 描述 默认
collateral_asset str

Asset to receive as collateral

必需
debt_asset str

Asset to repay

必需
user str

Address of user to liquidate

必需
debt_to_cover Decimal

Amount of debt to repay

必需
receive_atoken bool

If True, receive aTokens instead of underlying

False

返回:

类型 描述
TransactionResult

TransactionResult with transaction data

calculate_health_factor

calculate_health_factor(
    positions: list[AaveV3Position],
    reserve_data: dict[str, AaveV3ReserveData],
    prices: dict[str, Decimal] | None = None,
    emode_category: int = 0,
) -> AaveV3HealthFactorCalculation

Calculate health factor from positions.

Health Factor = (Sum of Collateral * Liquidation Threshold) / Total Debt

A health factor < 1.0 means the position can be liquidated.

参数:

名称 类型 描述 默认
positions list[AaveV3Position]

List of user positions

必需
reserve_data dict[str, AaveV3ReserveData]

Reserve data for each asset

必需
prices dict[str, Decimal] | None

Asset prices in USD (uses oracle if not provided)

None
emode_category int

User's E-Mode category (affects LT calculations)

0

返回:

类型 描述
AaveV3HealthFactorCalculation

AaveV3HealthFactorCalculation with detailed breakdown

calculate_liquidation_price

calculate_liquidation_price(
    collateral_asset: str,
    collateral_amount: Decimal,
    debt_usd: Decimal,
    liquidation_threshold_bps: int,
) -> Decimal

Calculate the price at which a position becomes liquidatable.

参数:

名称 类型 描述 默认
collateral_asset str

Collateral asset symbol

必需
collateral_amount Decimal

Amount of collateral (in token units)

必需
debt_usd Decimal

Total debt in USD

必需
liquidation_threshold_bps int

Liquidation threshold in basis points

必需

返回:

类型 描述
Decimal

Price at which position becomes liquidatable

calculate_max_borrow

calculate_max_borrow(
    collateral_value_usd: Decimal,
    current_debt_usd: Decimal,
    ltv_bps: int,
) -> Decimal

Calculate maximum additional borrow amount.

参数:

名称 类型 描述 默认
collateral_value_usd Decimal

Total collateral value in USD

必需
current_debt_usd Decimal

Current debt in USD

必需
ltv_bps int

Loan-to-Value ratio in basis points

必需

返回:

类型 描述
Decimal

Maximum additional borrow amount in USD

calculate_health_factor_after_borrow

calculate_health_factor_after_borrow(
    current_hf_calc: AaveV3HealthFactorCalculation,
    borrow_amount_usd: Decimal,
) -> Decimal

Calculate health factor after a hypothetical borrow.

参数:

名称 类型 描述 默认
current_hf_calc AaveV3HealthFactorCalculation

Current health factor calculation

必需
borrow_amount_usd Decimal

Amount to borrow in USD

必需

返回:

类型 描述
Decimal

Projected health factor after borrow

get_isolation_mode_debt_ceiling

get_isolation_mode_debt_ceiling(asset: str) -> Decimal

Get debt ceiling for an isolated asset.

Assets in isolation mode have a debt ceiling limiting total borrows.

参数:

名称 类型 描述 默认
asset str

Asset symbol

必需

返回:

类型 描述
Decimal

Debt ceiling in USD (0 if not isolated)

is_asset_isolated

is_asset_isolated(asset: str) -> bool

Check if asset is in isolation mode.

参数:

名称 类型 描述 默认
asset str

Asset symbol

必需

返回:

类型 描述
bool

True if asset is isolated

build_approve_tx

build_approve_tx(
    asset: str, amount: Decimal | None = None
) -> TransactionResult

Build an ERC20 approve transaction for Aave Pool.

参数:

名称 类型 描述 默认
asset str

Asset symbol or address

必需
amount Decimal | None

Amount to approve (defaults to MAX_UINT256)

None

返回:

类型 描述
TransactionResult

TransactionResult with transaction data

get_reserve_data

get_reserve_data(asset: str) -> AaveV3ReserveData | None

Get reserve data for an asset.

参数:

名称 类型 描述 默认
asset str

Asset symbol

必需

返回:

类型 描述
AaveV3ReserveData | None

Reserve data or None

set_reserve_data

set_reserve_data(
    asset: str, data: AaveV3ReserveData
) -> None

Set reserve data for an asset (for testing/mocking).

参数:

名称 类型 描述 默认
asset str

Asset symbol

必需
data AaveV3ReserveData

Reserve data

必需

AaveV3Config dataclass

AaveV3Config(
    chain: str,
    wallet_address: str,
    default_slippage_bps: int = 50,
    allow_placeholder_prices: bool = False,
)

Configuration for Aave V3 adapter.

属性:

名称 类型 描述
chain str

Blockchain network (ethereum, arbitrum, optimism, polygon, base, avalanche)

wallet_address str

User wallet address

default_slippage_bps int

Default slippage tolerance in basis points

allow_placeholder_prices bool

If True, allows fallback to hardcoded placeholder prices. WARNING: NEVER set to True in production! Placeholder prices cause incorrect health factor calculations which can lead to unexpected liquidations. Only use for local testing/development without real price data.

__post_init__

__post_init__() -> None

Validate configuration.

AaveV3EModeCategory

Bases: IntEnum

Aave V3 E-Mode categories.

AaveV3FlashLoanParams dataclass

AaveV3FlashLoanParams(
    assets: list[str],
    amounts: list[Decimal],
    modes: list[int],
    on_behalf_of: str,
    params: bytes = bytes(),
    referral_code: int = 0,
)

Parameters for an Aave V3 flash loan.

属性:

名称 类型 描述
assets list[str]

List of asset addresses to borrow

amounts list[Decimal]

List of amounts to borrow (in token units)

modes list[int]

Interest rate modes (0 = no debt, 1 = stable, 2 = variable)

on_behalf_of str

Address to receive debt (if modes != 0)

params bytes

Extra params to pass to receiver contract

referral_code int

Referral code (usually 0)

__post_init__

__post_init__() -> None

Validate flash loan parameters.

AaveV3HealthFactorCalculation dataclass

AaveV3HealthFactorCalculation(
    total_collateral_usd: Decimal,
    total_debt_usd: Decimal,
    weighted_liquidation_threshold: Decimal,
    health_factor: Decimal,
    liquidation_price: Decimal | None = None,
    assets_breakdown: dict[str, dict[str, Any]] = dict(),
)

Health factor calculation details.

属性:

名称 类型 描述
total_collateral_usd Decimal

Total collateral value in USD

total_debt_usd Decimal

Total debt value in USD

weighted_liquidation_threshold Decimal

Weighted average liquidation threshold

health_factor Decimal

Calculated health factor

liquidation_price Decimal | None

Price at which position becomes liquidatable

assets_breakdown dict[str, dict[str, Any]]

Per-asset breakdown

is_healthy property

is_healthy: bool

Check if position is healthy (HF >= 1).

buffer_to_liquidation property

buffer_to_liquidation: Decimal

Get buffer to liquidation as percentage.

to_dict

to_dict() -> dict[str, Any]

Convert to dictionary.

AaveV3InterestRateMode

Bases: IntEnum

Aave V3 interest rate modes.

AaveV3Position dataclass

AaveV3Position(
    asset: str,
    asset_address: str,
    current_atoken_balance: Decimal = Decimal("0"),
    current_stable_debt: Decimal = Decimal("0"),
    current_variable_debt: Decimal = Decimal("0"),
    principal_stable_debt: Decimal = Decimal("0"),
    scaled_variable_debt: Decimal = Decimal("0"),
    stable_borrow_rate: Decimal = Decimal("0"),
    liquidity_rate: Decimal = Decimal("0"),
    usage_as_collateral_enabled: bool = False,
)

User position in a specific Aave V3 reserve.

属性:

名称 类型 描述
asset str

Asset symbol

asset_address str

Asset contract address

current_atoken_balance Decimal

Current aToken balance (supplied amount + interest)

current_stable_debt Decimal

Current stable debt

current_variable_debt Decimal

Current variable debt

principal_stable_debt Decimal

Principal stable debt

scaled_variable_debt Decimal

Scaled variable debt

stable_borrow_rate Decimal

Current stable borrow rate

liquidity_rate Decimal

Current supply/liquidity rate

usage_as_collateral_enabled bool

Whether using as collateral

is_collateral bool

Alias for usage_as_collateral_enabled

is_collateral property

is_collateral: bool

Check if position is being used as collateral.

total_debt property

total_debt: Decimal

Get total debt (stable + variable).

has_supply property

has_supply: bool

Check if user has supply in this reserve.

has_debt property

has_debt: bool

Check if user has debt in this reserve.

to_dict

to_dict() -> dict[str, Any]

Convert to dictionary.

AaveV3ReserveData dataclass

AaveV3ReserveData(
    asset: str,
    asset_address: str,
    atoken_address: str = "",
    stable_debt_token_address: str = "",
    variable_debt_token_address: str = "",
    ltv: int = 0,
    liquidation_threshold: int = 0,
    liquidation_bonus: int = 0,
    reserve_factor: int = 0,
    usage_as_collateral_enabled: bool = True,
    borrowing_enabled: bool = True,
    stable_borrow_rate_enabled: bool = False,
    is_active: bool = True,
    is_frozen: bool = False,
    is_paused: bool = False,
    supply_cap: Decimal = Decimal("0"),
    borrow_cap: Decimal = Decimal("0"),
    debt_ceiling: Decimal = Decimal("0"),
    emode_ltv: int = 0,
    emode_liquidation_threshold: int = 0,
    emode_liquidation_bonus: int = 0,
    emode_category: int = 0,
)

Reserve data for an Aave V3 asset.

属性:

名称 类型 描述
asset str

Asset symbol

asset_address str

Asset contract address

atoken_address str

aToken contract address

stable_debt_token_address str

Stable debt token address

variable_debt_token_address str

Variable debt token address

ltv int

Loan-to-Value ratio (in basis points, e.g., 8000 = 80%)

liquidation_threshold int

Liquidation threshold (in basis points)

liquidation_bonus int

Liquidation bonus (in basis points, e.g., 10500 = 5% bonus)

reserve_factor int

Reserve factor (in basis points)

usage_as_collateral_enabled bool

Whether asset can be used as collateral

borrowing_enabled bool

Whether asset can be borrowed

stable_borrow_rate_enabled bool

Whether stable borrow rate is enabled

is_active bool

Whether reserve is active

is_frozen bool

Whether reserve is frozen

is_paused bool

Whether reserve is paused

supply_cap Decimal

Maximum supply (0 = unlimited)

borrow_cap Decimal

Maximum borrow (0 = unlimited)

debt_ceiling Decimal

Debt ceiling for isolation mode (0 = not isolated)

emode_ltv int

LTV when in E-Mode

emode_liquidation_threshold int

Liquidation threshold in E-Mode

emode_liquidation_bonus int

Liquidation bonus in E-Mode

emode_category int

E-Mode category ID

is_isolated property

is_isolated: bool

Check if asset is in isolation mode.

to_dict

to_dict() -> dict[str, Any]

Convert to dictionary.

AaveV3UserAccountData dataclass

AaveV3UserAccountData(
    total_collateral_base: Decimal,
    total_debt_base: Decimal,
    available_borrows_base: Decimal,
    current_liquidation_threshold: int,
    ltv: int,
    health_factor: Decimal,
    emode_category: int = 0,
)

User account data from Aave V3.

属性:

名称 类型 描述
total_collateral_base Decimal

Total collateral in base currency (USD)

total_debt_base Decimal

Total debt in base currency (USD)

available_borrows_base Decimal

Available borrows in base currency

current_liquidation_threshold int

Current weighted liquidation threshold

ltv int

Current weighted LTV

health_factor Decimal

Health factor (1e18 = 1.0, < 1.0 = liquidatable)

emode_category int

Current E-Mode category

health_factor_normalized property

health_factor_normalized: Decimal

Get health factor as a normalized value (1.0 = healthy threshold).

is_liquidatable property

is_liquidatable: bool

Check if position is liquidatable.

distance_to_liquidation property

distance_to_liquidation: Decimal

Get distance to liquidation (0 = liquidatable, 1 = 2x health factor).

to_dict

to_dict() -> dict[str, Any]

Convert to dictionary.

TransactionResult dataclass

TransactionResult(
    success: bool,
    tx_data: dict[str, Any] | None = None,
    gas_estimate: int = 0,
    description: str = "",
    error: str | None = None,
)

Result of a transaction build operation.

属性:

名称 类型 描述
success bool

Whether operation succeeded

tx_data dict[str, Any] | None

Transaction data (to, value, data)

gas_estimate int

Estimated gas

description str

Human-readable description

error str | None

Error message if failed

to_dict

to_dict() -> dict[str, Any]

Convert to dictionary.

AaveV3Event dataclass

AaveV3Event(
    event_type: AaveV3EventType,
    event_name: str,
    log_index: int,
    transaction_hash: str,
    block_number: int,
    contract_address: str,
    data: dict[str, Any],
    raw_topics: list[str] = list(),
    raw_data: str = "",
    timestamp: datetime = (lambda: datetime.now(tz=None))(),
)

Parsed Aave V3 event.

属性:

名称 类型 描述
event_type AaveV3EventType

Type of event

event_name str

Name of event (e.g., "Supply")

log_index int

Index of log in transaction

transaction_hash str

Transaction hash

block_number int

Block number

contract_address str

Contract that emitted event

data dict[str, Any]

Parsed event data

raw_topics list[str]

Raw event topics

raw_data str

Raw event data

timestamp datetime

Event timestamp

to_dict

to_dict() -> dict[str, Any]

Convert to dictionary.

from_dict classmethod

from_dict(data: dict[str, Any]) -> AaveV3Event

Create from dictionary.

AaveV3EventType

Bases: Enum

Aave V3 event types.

AaveV3ReceiptParser

AaveV3ReceiptParser(**kwargs: Any)

Parser for Aave V3 transaction receipts.

This parser extracts and decodes Aave V3 events from transaction receipts, providing structured data for supplies, borrows, repays, flash loans, liquidations, and other protocol events.

Example

parser = AaveV3ReceiptParser()

Parse a receipt dict (from web3.py)

result = parser.parse_receipt(receipt)

if result.success: for event in result.events: print(f"Event: {event.event_name}")

for supply in result.supplies:
    print(f"Supply: {supply.amount} to {supply.reserve}")

Initialize the parser.

参数:

名称 类型 描述 默认
**kwargs Any

Additional arguments (ignored for compatibility)

{}

parse_receipt

parse_receipt(receipt: dict[str, Any]) -> ParseResult

Parse a transaction receipt.

参数:

名称 类型 描述 默认
receipt dict[str, Any]

Transaction receipt dict containing 'logs', 'transactionHash', 'blockNumber', etc.

必需

返回:

类型 描述
ParseResult

ParseResult with extracted events and data

parse_logs

parse_logs(logs: list[dict[str, Any]]) -> list[AaveV3Event]

Parse a list of logs.

参数:

名称 类型 描述 默认
logs list[dict[str, Any]]

List of log dicts

必需

返回:

类型 描述
list[AaveV3Event]

List of parsed events

extract_supply_amount

extract_supply_amount(
    receipt: dict[str, Any],
) -> int | None

Extract supply amount from a transaction receipt.

参数:

名称 类型 描述 默认
receipt dict[str, Any]

Transaction receipt dict with 'logs' field

必需

返回:

类型 描述
int | None

Supply amount if found, None otherwise

extract_withdraw_amount

extract_withdraw_amount(
    receipt: dict[str, Any],
) -> int | None

Extract withdraw amount from a transaction receipt.

参数:

名称 类型 描述 默认
receipt dict[str, Any]

Transaction receipt dict with 'logs' field

必需

返回:

类型 描述
int | None

Withdraw amount if found, None otherwise

extract_borrow_amount

extract_borrow_amount(
    receipt: dict[str, Any],
) -> int | None

Extract borrow amount from a transaction receipt.

参数:

名称 类型 描述 默认
receipt dict[str, Any]

Transaction receipt dict with 'logs' field

必需

返回:

类型 描述
int | None

Borrow amount if found, None otherwise

extract_repay_amount

extract_repay_amount(receipt: dict[str, Any]) -> int | None

Extract repay amount from a transaction receipt.

参数:

名称 类型 描述 默认
receipt dict[str, Any]

Transaction receipt dict with 'logs' field

必需

返回:

类型 描述
int | None

Repay amount if found, None otherwise

extract_a_token_received

extract_a_token_received(
    receipt: dict[str, Any],
) -> int | None

Extract aToken amount received from a transaction receipt.

Looks for Transfer events from the zero address (minting).

参数:

名称 类型 描述 默认
receipt dict[str, Any]

Transaction receipt dict with 'logs' field

必需

返回:

类型 描述
int | None

aToken amount if found, None otherwise

extract_borrow_rate

extract_borrow_rate(
    receipt: dict[str, Any],
) -> Decimal | None

Extract borrow rate from a transaction receipt.

参数:

名称 类型 描述 默认
receipt dict[str, Any]

Transaction receipt dict with 'logs' field

必需

返回:

类型 描述
Decimal | None

Borrow rate (as decimal, e.g., 0.05 for 5%) if found, None otherwise

extract_debt_token

extract_debt_token(receipt: dict[str, Any]) -> str | None

Extract debt token address from a Borrow transaction receipt.

Finds the variable debt token by looking for Transfer events from 0x0 (minting) where the amount matches the borrow amount. The emitting contract address is the debt token.

参数:

名称 类型 描述 默认
receipt dict[str, Any]

Transaction receipt dict with 'logs' field

必需

返回:

类型 描述
str | None

Debt token contract address if found, None otherwise

extract_supply_rate

extract_supply_rate(
    receipt: dict[str, Any],
) -> Decimal | None

Extract supply rate (APY) from a transaction receipt.

Reads the currentLiquidityRate from the ReserveDataUpdated event, which is emitted by the Aave V3 pool on every supply/borrow/repay/withdraw.

参数:

名称 类型 描述 默认
receipt dict[str, Any]

Transaction receipt dict with 'logs' field

必需

返回:

类型 描述
Decimal | None

Supply rate as decimal (e.g., 0.035 for 3.5% APY) if found, None otherwise

extract_remaining_debt

extract_remaining_debt(
    receipt: dict[str, Any],
) -> int | None

Extract remaining debt after a Repay transaction.

Aave V3 does not emit authoritative post-repay debt balance in receipt events. Debt token Transfer amounts use scaled units (not raw amounts), and accrued interest can cause Mint events during burns. Determining remaining debt reliably requires an on-chain state query (balanceOf on the debt token).

参数:

名称 类型 描述 默认
receipt dict[str, Any]

Transaction receipt dict with 'logs' field

必需

返回:

类型 描述
int | None

Always None - remaining debt cannot be reliably inferred from receipts

is_aave_event

is_aave_event(topic: str | bytes) -> bool

Check if a topic is a known Aave V3 event.

参数:

名称 类型 描述 默认
topic str | bytes

Event topic (supports bytes, hex string with/without 0x, any case)

必需

返回:

类型 描述
bool

True if topic is a known Aave V3 event

get_event_type

get_event_type(topic: str | bytes) -> AaveV3EventType

Get the event type for a topic.

参数:

名称 类型 描述 默认
topic str | bytes

Event topic (supports bytes, hex string with/without 0x, any case)

必需

返回:

类型 描述
AaveV3EventType

Event type or UNKNOWN

BorrowEventData dataclass

BorrowEventData(
    reserve: str,
    user: str,
    on_behalf_of: str,
    amount: Decimal,
    interest_rate_mode: int,
    borrow_rate: Decimal = Decimal("0"),
    referral_code: int = 0,
)

Parsed data from Borrow event.

属性:

名称 类型 描述
reserve str

Asset address that was borrowed

user str

User who initiated the borrow

on_behalf_of str

Address that received the debt

amount Decimal

Amount borrowed (in token units)

interest_rate_mode int

1 = stable, 2 = variable

borrow_rate Decimal

Current borrow rate (ray, 1e27)

referral_code int

Referral code used

is_variable_rate property

is_variable_rate: bool

Check if borrow is variable rate.

to_dict

to_dict() -> dict[str, Any]

Convert to dictionary.

FlashLoanEventData dataclass

FlashLoanEventData(
    target: str,
    initiator: str,
    asset: str,
    amount: Decimal,
    interest_rate_mode: int,
    premium: Decimal = Decimal("0"),
    referral_code: int = 0,
)

Parsed data from FlashLoan event.

属性:

名称 类型 描述
target str

Contract that received the flash loan

initiator str

Address that initiated the flash loan

asset str

Asset address that was borrowed

amount Decimal

Amount borrowed (in token units)

interest_rate_mode int

Debt mode (0 = no debt, 1 = stable, 2 = variable)

premium Decimal

Premium paid (in token units)

referral_code int

Referral code used

opened_debt property

opened_debt: bool

Check if flash loan opened debt.

to_dict

to_dict() -> dict[str, Any]

Convert to dictionary.

IsolationModeDebtUpdatedEventData dataclass

IsolationModeDebtUpdatedEventData(
    asset: str, total_debt: Decimal
)

Parsed data from IsolationModeTotalDebtUpdated event.

属性:

名称 类型 描述
asset str

Asset address

total_debt Decimal

New total debt (in USD with 2 decimals)

to_dict

to_dict() -> dict[str, Any]

Convert to dictionary.

LiquidationCallEventData dataclass

LiquidationCallEventData(
    collateral_asset: str,
    debt_asset: str,
    user: str,
    debt_to_cover: Decimal,
    liquidated_collateral_amount: Decimal,
    liquidator: str,
    receive_atoken: bool = False,
)

Parsed data from LiquidationCall event.

属性:

名称 类型 描述
collateral_asset str

Collateral asset that was seized

debt_asset str

Debt asset that was repaid

user str

User who was liquidated

debt_to_cover Decimal

Amount of debt repaid (in debt token units)

liquidated_collateral_amount Decimal

Amount of collateral seized (in collateral token units)

liquidator str

Address that performed the liquidation

receive_atoken bool

Whether liquidator received aTokens

to_dict

to_dict() -> dict[str, Any]

Convert to dictionary.

ParseResult dataclass

ParseResult(
    success: bool,
    events: list[AaveV3Event] = list(),
    supplies: list[SupplyEventData] = list(),
    withdraws: list[WithdrawEventData] = list(),
    borrows: list[BorrowEventData] = list(),
    repays: list[RepayEventData] = list(),
    flash_loans: list[FlashLoanEventData] = list(),
    liquidations: list[LiquidationCallEventData] = list(),
    error: str | None = None,
    transaction_hash: str = "",
    block_number: int = 0,
)

Result of parsing a receipt.

属性:

名称 类型 描述
success bool

Whether parsing succeeded

events list[AaveV3Event]

List of parsed events

supplies list[SupplyEventData]

Supply events

withdraws list[WithdrawEventData]

Withdraw events

borrows list[BorrowEventData]

Borrow events

repays list[RepayEventData]

Repay events

flash_loans list[FlashLoanEventData]

Flash loan events

liquidations list[LiquidationCallEventData]

Liquidation events

error str | None

Error message if parsing failed

transaction_hash str

Transaction hash

block_number int

Block number

to_dict

to_dict() -> dict[str, Any]

Convert to dictionary.

RepayEventData dataclass

RepayEventData(
    reserve: str,
    user: str,
    repayer: str,
    amount: Decimal,
    use_atokens: bool = False,
)

Parsed data from Repay event.

属性:

名称 类型 描述
reserve str

Asset address that was repaid

user str

User whose debt was repaid

repayer str

Address that made the repayment

amount Decimal

Amount repaid (in token units)

use_atokens bool

Whether aTokens were used for repayment

to_dict

to_dict() -> dict[str, Any]

Convert to dictionary.

ReserveDataUpdatedEventData dataclass

ReserveDataUpdatedEventData(
    reserve: str,
    liquidity_rate: Decimal,
    stable_borrow_rate: Decimal,
    variable_borrow_rate: Decimal,
    liquidity_index: Decimal = Decimal("0"),
    variable_borrow_index: Decimal = Decimal("0"),
)

Parsed data from ReserveDataUpdated event.

属性:

名称 类型 描述
reserve str

Asset address

liquidity_rate Decimal

Current supply/liquidity rate (ray, 1e27)

stable_borrow_rate Decimal

Current stable borrow rate (ray, 1e27)

variable_borrow_rate Decimal

Current variable borrow rate (ray, 1e27)

liquidity_index Decimal

Current liquidity index

variable_borrow_index Decimal

Current variable borrow index

to_dict

to_dict() -> dict[str, Any]

Convert to dictionary.

SupplyEventData dataclass

SupplyEventData(
    reserve: str,
    user: str,
    on_behalf_of: str,
    amount: Decimal,
    referral_code: int = 0,
)

Parsed data from Supply event.

属性:

名称 类型 描述
reserve str

Asset address that was supplied

user str

User who initiated the supply

on_behalf_of str

Address that received the aTokens

amount Decimal

Amount supplied (in token units)

referral_code int

Referral code used

to_dict

to_dict() -> dict[str, Any]

Convert to dictionary.

UserEModeSetEventData dataclass

UserEModeSetEventData(user: str, category_id: int)

Parsed data from UserEModeSet event.

属性:

名称 类型 描述
user str

User address

category_id int

E-Mode category ID (0 = none, 1 = ETH correlated, 2 = stablecoins)

category_name property

category_name: str

Get category name.

to_dict

to_dict() -> dict[str, Any]

Convert to dictionary.

WithdrawEventData dataclass

WithdrawEventData(
    reserve: str, user: str, to: str, amount: Decimal
)

Parsed data from Withdraw event.

属性:

名称 类型 描述
reserve str

Asset address that was withdrawn

user str

User who initiated the withdrawal

to str

Address that received the tokens

amount Decimal

Amount withdrawn (in token units)

to_dict

to_dict() -> dict[str, Any]

Convert to dictionary.