Skip to main content

AlchemistV3

Description​

The Alchemist is the vault contract responsible for accepting deposits and issuing debt. It stores and tracks user accounts, earmarking and redemptions, and allows users to deposit, withdraw, and repay against their positions. Every Alchemist is associated with one Transmuter, one debt asset, (alAsset) and one MYT (yield strategy).

Variables​

Initialization Parameters​

Set on contract deployment, configuring basic params for the Alchemist.

Addresses​

admin
debtToken
underlyingToken
yieldToken
tokenAdapter
transmuter
protocolFeeReceiver

Uint256​

depositCap
minimumCollateralization
globalMinimumCollateralization
collateralizationLowerBound
protocolFee
liquidatorFee
repaymentFee

Constants​

Immutable variables used as helpers or for informational purposes.

BPS
FIXED_POINT_SCALAR
version
  • Description - Constant expressing Alchemix version. Not used for anything in the contract.
  • Type - uint256
  • Updated By
    • NONE - immutable variable
  • Read By - version()

Account​

A struct for variables related to per-user accounts and balances.

collateralBalance
debt
earmarked
freeCollateral
lastAccruedEarmarkWeight
  • Description - Last weight of debt from the most recent account sync. This is a stored index used as a checkpoint of the last time a position had earmarking applied. The global earmark weight advances as new debt is added and as time in blocks passes (to model earmark progress). The difference between these weightings determines how much additional debt in the position needs to be earmarked.
  • Type - uint256
  • Used By
  • Updated By - _sync(uint256 tokenId)
lastAccruedRedemptionWeight
  • Description - Last weight of redemption from most recent account sync. This is a stored index used as a checkpoint of the last time a position had redemptions applied. The global redemption weight advances as system-wide redemptions occur and as time in blocks passes (to model redemption progress). The difference between these weightings determines how much of the account’s earmarked debt should actually be redeemed.
  • Type - uint256
  • Used By
  • Updated By - _sync(uint256 tokenId)
lastCollateralWeight
  • Description - Last weight of collateral from most recent account sync. This is a stored index used as a checkpoint of the last time a position had its locked collateral adjusted. The global collateral weight advances as system-wide redemptions are processed. The difference between these weightings determines how much of the account’s locked collateral should be reduced.
  • Type - uint256
  • Used By
  • Updated By - _sync(uint256 tokenId)
lastMintBlock
lastRedemptionSync
rawLocked
mintAllowances
allowancesVersion

RedemptionInfo​

Struct for variables related to redemption events.

earmarkWeight

Public State​

State that is available and can be read from outside of the contract.

Addresses​

pendingAdmin
  • Description - The first step in a two-step process of setting a new administrator. The pendingAdmin is set by the current admin, then the pendingAdmin must accept the responsibility to lock in the change of admin.
  • Type - address
  • Updated By
  • Read By
    • pendingAdmin()
  • Notified By - PendingAdminUpdated(address value)
alchemistFeeVault
alchemistPositionNFT

Uint256​

underlyingConversionFactor
  • Description - Set once on initialization, dependent on initialization params, then never again. Determines what you can multiply the underlying token decimals by in order to denominate similarly to alAsset; For example if USDC is 6 decimals and alUSD is 18, then the conversion factor is 10^12 to be able to denominate USDC the same way as alUSD. Used for mathematical operations
  • Type - uint256
  • Used By
  • Updated By
    • initialize(AlchemixInitializationParams memory params)
  • Read By - underlyingConversionFactor()
cumulativeEarmarked
lastEarmarkBlock
lastRedemptionBlock
  • Description - the block number of the most recent redemption that advanced global redemption state. Used to reference the snapshot of earmark and debt state at that block, so accounts can be updated consistently by applying the redemption against that state.
  • Type - uint256
  • Used By
  • Updated By
  • Read By - lastEarmarkBlock()
lastTransmuterTokenBalance
  • Description - the last recorded balance of yieldTokens in the Transmuter. It is periodically updated by a Transmuter call, and is used to help the Alchemist determine how much it needs to earmark.
  • Type - uint256
  • Used By
  • Updated By
  • Read By - lastTransmuterTokenBalance()
totalDebt
totalSyntheticsIssued

Booleans​

depositsPaused
loansPaused

Mappings​

guardians

Private State​

Internal state of the contract. In most cases cannot be read from outside of the contract. In some cases, such as mappings or structs, certain aspects can be read using specific functions. (See ReadingState for more examples)

Uint256​

_earmarkWeight
_redemptionWeight
_collateralWeight
  • Description - A global cumulative scaling factor that increases whenever collateral is redeemed or fees are taken. Accounts use the difference between this value and their account-specific lastCollateralWeight to determine how much of their locked collateral should be seized in proportion to global redemptions.
  • Type - uint256
  • Used By
  • Updated By - redeem(uint256 amount)
_totalLocked

Mappings​

_accounts
_redemptions

Functions​

User Actions​

Functions that can be called by external accounts which influence the state of the Alchemist.

deposit(uint256 amount, address recipient, uint256 tokenId)
  • Description - Allows a user to deposit yieldTokens into the Alchemist.

    The passed uint256 for tokenId should be 0 for any new position, or the tokenId of the AlchemistV3PositionNFT if depositing into an existing position.
    • @param recipient - used to specify an address that will recieve the NFT position if minting a brand new position, which also requires tokenId == 0. Otherwise it won't be used
    • @param tokenId - 0 for a new position, or a valid id for an existing position
  • Visibility Specifier - external
  • State Mutability Specifier - nonpayable
  • Returns - uint256 amountDepositedDenominatedInDebtTokens
  • Emits
  • Reverts - recipient == zero address - amount == 0 - depositsPaused - deposit would result in a total deposit that exceeeds the deposit cap\
  • UnknownAccountOwnerIdError() - passed tokenId does not correspond to an existing NFT and is not 0
withdraw(uint256 amount, address recipient, uint256 tokenId)
  • Description - Allows the owner of an account to withdraw funds to a specfied recipient address.

    First applies all earmarking, redemptions, and locked collateral adjustments to the account so it is up-to-date; then transfers funds if valid.
    • @param amount - the amount of yieldToken to withdraw
    • @param recipient - the address which will recieve the withdrawn assets
    • @param tokenId - the ID of the owner's account, assigned on creation of the AlchemistV3PositionNFT
  • Visibility Specifier - external
  • State Mutability Specifier - nonpayable
  • Returns - uint256 amountOfYieldTokensWithdrawn
  • Emits
  • Reverts - recipient == zero address - amount == 0 - attempted collateral withdrawn > user's unlocked collateral (collateral that isn't pledged to collateralize existing debt) - UnauthorizedAccountAccessError() - msg.sender is not the owner of the account identified by the passed tokenId - UnknownAccountOwnerIdError() - passed tokenId does not correspond to an existing NFT and is not 0 - Undercollateralized() - if the account is undercollateralized don't allow a withdraw
mint(uint256 tokenId, uint256 amount, address recipient)
  • Description - Allows the owner of the account with the passed tokenId to mint debt.

    First syncs global and account state, increases the account’s debt by amount, then mints amount of the debt token to the recipient address.
    • @param tokenId - the ID of the owner's account, assigned on creation of the AlchemistV3PositionNFT
    • @param amount - the amount of alAssets to mint
    • @param recipient - the address which will recieve the minted assets
  • Visibility Specifier - external
  • State Mutability Specifier - nonpayable
  • Returns - uint256 totalTokenTVLInUnderlying
  • Emits
  • Reverts - recipient == zero address - amount == 0 - loansPaused - UnauthorizedAccountAccessError() - msg.sender is not the owner of the account identified by the passed tokenId - UnknownAccountOwnerIdError() - passed tokenId does not correspond to an existing NFT and is not 0 - Undercollateralized() - if the account would be undercollateralized don't allow minting more debt
mintFrom(uint256 tokenId, uint256 amount, address recipient)
  • Description - Borrow on behalf of tokenId using a mint allowance instead of ownership.

    It first decreases msg.sender’s allowance for that account by amount, then performs the same actions as mint, minting debt tokens to the recipient address.
    • @param tokenId - the ID of the owner's account, assigned on creation of the AlchemistV3PositionNFT
    • @param amount - the amount of alAssets to mint
    • @param recipient - the address which will recieve the minted assets
  • Visibility Specifier - external
  • State Mutability Specifier - nonpayable
  • Returns - uint256 totalTokenTVLInUnderlying
  • Emits
  • Reverts - recipient == zero address - amount == 0 - loansPaused - UnknownAccountOwnerIdError() - passed tokenId does not correspond to an existing NFT and is not 0 - Undercollateralized() - if the account would be undercollateralized don't allow minting more debt
burn(uint256 amount, uint256 recipientId)
  • Description - Burn debt tokens (alAssets) from the caller to repay the unearmarked portion of the position’s debt.

    First syncs global/account state and makes sure it would not be burning debt that is locked for the transmuter, then burns the caller’s tokens. Charges a protocol fee in yield tokens against the account’s collateral.

    Difference between repay() and burn():
    repay() takes an amount of yieldTokens and can reconcile earmarked debt in addition to unearmarked debt. It does not actually reduce debtToken supply, it only reconciles accounts and collects funds that will be alter used to burn debt.
    burn() takes debt tokens and can only reconcile unearmarked debt of accounts. It actually removes debtTokens from circulation.
    • @param recipientId - the tokenId of the account for which debt is being repaid
  • Visibility Specifier - external
  • State Mutability Specifier - nonpayable
  • Returns - uint256 debtUnitsRepaid
  • Emits
  • Reverts - amount == 0 - No unearmarked debt to repay - insufficient balance/allowance - UnknownAccountOwnerIdError() - passed tokenId does not correspond to an existing NFT and is not 0 - CannotRepayOnMintBlock() - same-block mint repay is disallowed - BurnLimitExceeded(uint256 amount, uint256 available) - requested burn exceeds totalSyntheticsIssued - transmuter.totalLocked()
repay(uint256 amount, uint256 recipientTokenId)
  • Description - Repay the position’s debt using yield tokens provided by the caller.

    Syncs global/account state, converts the payment from yield units to debt units, consumes earmarked debt first, then repays accounts unearmarked debt, moves the repayment to the Transmuter, and moves the fee to the protocolFeeReciever. Protocol fee is charged in yield tokens against the account’s collateral.

    Difference between repay() and burn():
    repay() takes an amount of yieldTokens and can reconcile earmarked debt in addition to unearmarked debt. It reduces an accounts debt but does not actually reduce debtToken supply, it only reconciles accounts and collects funds for the Transmuter, which will eventually use them to burn the debt.
    burn() takes debt tokens and can only reconcile unearmarked debt of accounts. It removes debtTokens from circulation.
    • @param amount - the amount of yield tokens the caller provides as repayment
    • @param recipientTokenId - the tokenId of the account for which debt is being repaid
  • Visibility Specifier - public
  • State Mutability Specifier - nonpayable
  • Returns - uint256 yieldTokensUsedToRepay
  • Emits
  • Reverts - amount == 0 - account lacks collateral to cover the protocol fee - No outstanding debt for the account of the passed recipientId - UnknownAccountOwnerIDError() - passed tokenId does not correspond to an existing NFT - CannotRepayOnMintBlock() - same-block mint repay is disallowed. For flash loan protection.
liquidate(uint256 accountId)
  • Description - Attempts to _liquidate() an undercollateralized position of the account identified by the passed accountId.

    First syncs state and applys earmarking so the account is up to date, then repays earmarked debt if present. If that restores the position above the collateralization lower bound, a repayment fee denominated in yield is paid to the caller and no liquidation is performed. If the position remains below the lower bound, proceeds to liquidate, seizing yieldToken-denominated collateral and paying the liquidator fees. If the account does not have enough to cover liquidation fees, or the entire Alchemist is undercollateralized, then the liquidator will be paid using the funds from this Alchemist's alchemistFeeVault.
    • @param accountId - the tokenId of the account to liquidate
  • Visibility Specifier - external
  • State Mutability Specifier - nonpayable
  • Returns
    • yieldAmount — if liquidation happened: collateral in yield seized; if only repayment happened: the repaid amount in yield
    • feeInYield — liquidator/repayment fee paid in yield tokens
    • feeInUnderlying — additional liquidator fee paid in underlying from this Alchemist's alchemistFeeVault (if needed)
  • Emits
  • Reverts
    • UnknownAccountOwnerIDError() — passed accountId does not correspond to an existing NFT
    • LiquidationError() — no liquidation/repayment occurred, either because the account is healthy, the tokenAdapter has trouble pricing the yieldToken (price == 0), etc.
batchLiquidate(uint256[] accountIds)
  • Description - Attempts liquidation across multiple accounts.

    Calls the internal _liquidate for each valid account, aggregates the total amount of yieldToken seized from collateral (earmarked repayment + liquidation seizure) along with the liquidator fees, and returns the totals.
    • @param accountIds - array of tokenIds to attempt liquidation on. Invalid IDs are skipped.
  • Visibility Specifier - external
  • State Mutability Specifier - nonpayable
  • Returns
    • totalAmountLiquidated — sum of per-account yieldAmount returned by _liquidate (i.e., total yield moved)
    • totalFeesInYield — sum of yield-denominated liquidator/repayment fees
    • totalFeesInUnderlying — sum of underlying-denominated liquidator fees paid from this Alchemist's alchemistFeeVault (see _liquidate() for when this would occur)
  • Emits - none
  • Reverts
    • MissingInputData() — accountIds is empty
    • LiquidationError() — no liquidation/repayment occurred for any account. See liquidate() under User Actions for why this might occur.
poke(uint256 tokenId)
  • Description - Brings both global and account state up to date without changing balances.

    Validates the account, applies global earmarking, and syncs the specified account’s debt/collateral state with the latest global weights.
    • @param tokenId - the tokenId of the account to sync
  • Visibility Specifier - external
  • State Mutability Specifier - nonpayable
  • Returns - none
  • Emits - none
  • Reverts - UnknownAccountOwnerIDError() — passed tokenId does not correspond to an existing NFT
approveMint(uint256 tokenId, address spender, uint256 amount)
  • Description - Grant or update a mint allowance so spender can mint debt tokens on behalf of the owner's position (via mintFrom) identified by tokenId, for up to amount of debtTokens.

    Verifies the caller owns the position, then delegates to _approveMint to persist the allowance and emit the approval event.
    • @param tokenId - the id of the position whose minting rights are being delegated
    • @param spender - the address allowed to mint on behalf of the owner of the position identified by tokenId
    • @param amount - the maximum debt tokens the spender may mint
  • Visibility Specifier - external
  • State Mutability Specifier - nonpayable
  • Returns - none
  • Emits
  • Reverts - UnauthorizedAccountAccessError() — caller is not the owner of the position identified by tokenId
resetMintAllowances(uint256 tokenId)
  • Description - Clears all existing mint allowances for the position by bumping its allowancesVersion. Future approveMint entries are written under the new version. Old approvals become ineffective without needing to delete mappings. Callable by the NFT contract or by the current owner.
    • @param tokenId - the id of position for which mint allowances are being reset
  • Visibility Specifier - external
  • State Mutability Specifier - nonpayable
  • Returns - none
  • Emits
  • Reverts - Unauthorized() — caller is neither the NFT contract nor the position’s current owner
acceptAdmin()

Guardian Actions​

Functions that are guarded by the onlyAdminOrGuardian modifier.

pauseDeposits(bool isPaused)
  • Description - Sets the depositsPaused variable, preventing users from calling the deposit function.
    • @param isPaused - true/false value indicating whether or deposits should be accepted.
  • Visibility Specifier - external
  • State Mutability Specifier - nonpayable
  • Returns - none
  • Emits
  • Reverts - none
pauseLoans(bool isPaused)
  • Description - Sets the pauseLoans variable, preventing users from calling the mint and mintFrom functions.
    • @param isPaused - true/false value indicating whether or not to pause the ability to take loans
  • Visibility Specifier - external
  • State Mutability Specifier - nonpayable
  • Returns - none
  • Emits
  • Reverts - none

Admin Actions​

Functions guarded by the onlyAdmin modifier.

setAlchemistPositionNFT(address NFT)
  • Description - Sets the NFT contract that will be used to represent NFT positions. Can only be set once.
    • @param NFT - the addressof the alchemistPositionNft contract.
  • Visibility Specifier - external
  • State Mutability Specifier - nonpayable
  • Returns - none
  • Emits - none
  • Reverts
setAlchemistFeeVault(address value)
  • Description - Sets the fee vault used for liquidations in the event of (1) an account not being able to cover, (2) the Alchemist itself being globally undercollateralized.
    • @param value - the address of the AlchemistFeeVault contract to use.
  • Visibility Specifier - external
  • State Mutability Specifier - nonpayable
  • Returns - none
  • Emits
  • Reverts
setPendingAdmin(address value)
  • Description - Sets the pending admin. First part of a two-step process to change the admin. The second step is the pendingAdmin accepting the role by calling acceptAdmin.
    • @param value - the address of the EOA to set as the new pending admin
  • Visibility Specifier - external
  • State Mutability Specifier - nonpayable
  • Returns - none
  • Emits
  • Reverts - none
setDepositCap(uint256 value)
  • Description - Sets the maximum number of yieldTokens that can be held by this contract. Must exceed the current balance of yield tokens.
    • @param quantity of yield tokens to set as the new cap
  • Visibility Specifier - external
  • State Mutability Specifier - nonpayable
  • Returns - none
  • Emits
  • Reverts - none
setProtocolFeeReceiver(address value)
  • Description - Sets the address which receives protocol fees.
    • @param value - the address to recieve fees.
  • Visibility Specifier - external
  • State Mutability Specifier - nonpayable
  • Returns - none
  • Emits
  • Reverts - none
setProtocolFee(uint256 fee)
  • Description - Sets the fee percentage paid to the protocol denominated in BPS.
    • @param fee - a uint number from 0 to 10_000
  • Visibility Specifier - external
  • State Mutability Specifier - nonpayable
  • Returns - none
  • Emits
  • Reverts - none
setLiquidatorFee(uint256 fee)
  • Description - Sets the fee percentage paid to liquidators for liquidating an account denominated in BPS.
    • @param fee - a uint number from 0 to 10_000
  • Visibility Specifier - external
  • State Mutability Specifier - nonpayable
  • Returns - none
  • Emits
  • Reverts - none
setRepaymentFee(uint256 fee)
  • Description - Sets the fee percentage paid to liquidators for repaying an account denominated in BPS.
    • @param fee - a uint number from 0 to 10_000
  • Visibility Specifier - external
  • State Mutability Specifier - nonpayable
  • Returns - none
  • Emits
  • Reverts - none
setTokenAdapter(address value)
  • Description - Sets the tokenAdapter which is used to price yieldTokens.
    • @param value - the address of the contract to price yieldTokens.
  • Visibility Specifier - external
  • State Mutability Specifier - nonpayable
  • Returns - none
  • Emits
  • Reverts - none
setGuardian(address guardian, bool isActive)
  • Description - Sets an address as an active guardian in the guardians mapping.
    • @param guardian - the address to activate or de-actviate as a guardian
    • @param isActive - a true/false value indicating if the address should be an active guardian or not.
  • Visibility Specifier - external
  • State Mutability Specifier - nonpayable
  • Returns - none
  • Emits
  • Reverts - none
setMinimumCollateralization(uint256 value)
  • Description - Sets the minimumCollateralization variable.
    • @param value - the value to use for the new minimumCollateralization variable. Must be >= 1e18. (1)
  • Visibility Specifier - external
  • State Mutability Specifier - nonpayable
  • Returns - none
  • Emits
  • Reverts - none
setGlobalMinimumCollateralization(uint256 value)
  • Description - Sets the globalMinimumCollateralization variable.
    • @param value - the uint256 to set as globalMinCollateralization. Must be above minimumCollateralization
  • Visibility Specifier - external
  • State Mutability Specifier - nonpayable
  • Returns - none
  • Emits
  • Reverts - none
setCollateralizationLowerBound(uint256 value)
  • Description - Sets the collateralizationLowerBound variable.
    • @param value - the uint256 to use as the new value.
  • Visibility Specifier - external
  • State Mutability Specifier - nonpayable
  • Returns - none
  • Emits
  • Reverts - none

Transmuter Actions​

Functions guarded by the onlyTransmuter modifier.

redeem(uint256 amount)
  • Description - Fulfills a Transmuter-initiated redemption.

    Updates global earmark, redemption, and collateral weights. Converts the requested debt amount to yield tokens, subtracts a protocol fee in yield tokens, and reduces cumulativeEarmarked and totalDebt. Records a redemption snapshot. Sends seized yieldTokens to the Transmuter, and the fee to the protocol.
    • @param amount - amount to redeem denominated in debt token
  • Visibility Specifier - external
  • State Mutability Specifier - nonpayable
  • Returns - none
  • Emits
  • Reverts - none
reduceSyntheticsIssued(uint256 amount)
  • Description - reduced totalSyntheticsIssued by amount
    • @param amount - amount denominated in debtToken
  • Visibility Specifier - external
  • State Mutability Specifier - nonpayable
  • Returns - none
  • Emits - none
  • Reverts - none
setTransmuterTokenBalance(uint256 amount)
  • Description - sets the lastTransmuterTokenBalance variable, which tells the Alchemist how many yieldTokens are in the Transmuter.
    • @param amount - amount denominated in yieldToken
  • Visibility Specifier - external
  • State Mutability Specifier - nonpayable
  • Returns - none
  • Emits - none
  • Reverts - none

Internal Operations​

Functions that are cannot be called by other contracts or EOAs. Used only as helpers for performing internal logic.

_sync(uint256 tokenId)
  • Description - Bring the account to the latest global state re. earmarking, redemptions, and collateral.

    Advances earmark to the current global earmark weight, applies any past redemption not yet reflected on the account by rewinding its earmark to the redemption block and then applying the redemption, applies collateral decay via the collateral weight, and recomputs locked collateral for the remaining debt. Updates all account weights/checkpoints.
    • @param tokenId - the account to sync
  • Visibility Specifier - internal
  • State Mutability Specifier - nonpayable
  • Returns - none
  • Emits - none
  • Reverts - none
_earmark()
  • Description - Advance global earmarking for this block.

    Computes the new earmark amount since the last run, subtracts Transmuter’s newly accrued yield, then increases _earmarkWeight and cumulativeEarmarked. Finally stamps lastEarmarkBlock.
  • Visibility Specifier - internal
  • State Mutability Specifier - nonpayable
  • Returns - none
  • Emits - none
  • Reverts - none
_calculateUnrealizedDebt(uint256 tokenId)
  • Description - Gets a snapshot of what account debt values will be after a sync occurs
    • @param tokenId - the id of the account owner used to access their account.
  • Visibility Specifier - internal
  • State Mutability Specifier - view
  • Returns - a tuple (uint256, uint256, uint256) containing the following:
    • debt - the amount of debt the account will have after an update
    • earmarked - the amount of debt which is currently earmarked for redemption
    • collateral - the amount of collateral that has yet to be redeemed
  • Emits - none
  • Reverts - none
_liquidate(uint256 accountId)
  • Description - Internal helper that performs the liquidation logic for an undercollateralized account.

    First syncs state and applies earmarking so the account is up to date, then repays earmarked debt if present. If that restores the position above the collateralization lower bound, a repayment fee denominated in yield is paid to the caller and no liquidation is performed. If the position remains below the lower bound, proceeds to liquidate, seizing yieldToken-denominated collateral and paying the liquidator fees. If the account does not have enough to cover liquidation fees, or the entire Alchemist is undercollateralized, then the liquidator will be paid using the funds from this Alchemist's alchemistFeeVault.
    • @param accountId - the tokenId of the account to liquidate
  • Visibility Specifier - internal
  • State Mutability Specifier - nonpayable
  • Returns
    • amountLiquidated - if liquidation happened: collateral in yield seized; if only repayment happened: the repaid amount in yield; If the tokenAdapter prices the yieldToken at 0, returns 0
    • feeInYield - liquidator/repayment fee paid in yield tokens
    • feeInUnderlying - additional liquidator fee paid in underlying from this Alchemist's alchemistFeeVault (if needed)
  • Emits - none
  • Reverts - none
_doLiquidation(uint256 accountId, uint256 collateralInUnderlying, uint256 repaidAmountInYield)
  • Description - Performs isolated liquidation logic. Occurring after _liquidate() handles syncing/earmarking, and once an account is already determined to be below the collateralization lower bound.

    Calculates liquidation terms using account and global ratios, converts debt-denominated amounts to tokens, reduces account debt, and seizes collateral in yield tokens. It then transfers amount seized minus fees to the Transmuter, and pays the liquidator fees using user collateral, or from this Alchemist’s alchemistFeeVault.
    • @param accountId - the tokenId of the account being liquidated
    • @param collateralInUnderlying - the account’s collateral value expressed in underlying units (used for liquidation math)
    • @param repaidAmountInYield - the amount of debt paid off in yield token during earmarking settlement prior to this liquidation
  • Visibility Specifier - internal
  • State Mutability Specifier - nonpayable
  • Returns
    • amountLiquidated — the amount of yield tokens seized in _doLiquidation, plus the amount seized prior to this function call for earmarking repayment (forwarded to this function as repaidAmountInYield)
    • feeInYield — base fee paid to the liquidator in yield tokens, coming from user collateral
    • feeInUnderlying — additional fee paid to the liquidator in underlying tokens, coming from the fee vault
  • Emits - none
  • Reverts - none
_approveMint(uint256 ownerTokenId, address spender, uint256 amount)
  • Description - Isolated logic to overwrite the mint allowance for spender under the account’s current allowancesVersion, enabling spender to mint debt on behalf of ownerTokenId. Check and requires done outside of the scope of this call.
    • @param ownerTokenId - the Id of the account for which a new minting limit is being approved
    • @param spender - the address allowed to mint on behalf of owner of the position identified by ownerTokenId
    • @param amount - the maximum debt the spender may mint (for the current allowancesVersion)
  • Visibility Specifier - internal
  • State Mutability Specifier - nonpayable
  • Returns - none
  • Emits
  • Reverts - none
_mint(uint256 tokenId, uint256 amount, address recipient)
  • Description - Internal function for performing mint logic.

    Adds debt to the account, validates collateralization, then mints debt tokens to recipient. Updates global issuance and records lastMintBlock to prevent same-block repay/burn exploits.
    • @param tokenId - the id of the position to mint debt for
    • @param amount - the amount of debt tokens to mint
    • @param recipient - address receiving the minted debt tokens
  • Visibility Specifier - internal
  • State Mutability Specifier - nonpayable
  • Returns - none
  • Emits
  • Reverts - Undercollateralized() — if minting would violate the minimum collateralization
_forceRepay(uint256 accountId, uint256 amount)
  • Description - Repays earmarked debt using the account’s collateral (denominated in yieldToken).

    Earmarks and syncs to update global/account state, then reduces account debt through repayment. First consumes earmarked debt, then deducts the repayment from collateral. (yieldToken)
    Charges a protocol fee if collateral remains to pay it, and only after funding the repayment. Transfers the repaid yield to the Transmuter.

    Difference between _forceRepay and _liquidate:
    Both use collateral to cover the cost, however for different purposes. ForceRepay is using collateral to reconcile earmarked debt. This may or may not bring collateralization ratio to the correct threshold. Liquidation occurs afterwords and uses collateral to reconcile LTV such that it meets the required threshold. ForceRepay occurs before Liquidations do.
    • @param accountId - the id of the position to repay debt for
    • @param amount - desired repayment in debt tokens
  • Visibility Specifier - internal
  • State Mutability Specifier - nonpayable
  • Returns - uint256 creditToYield - amount of yield tokens that were repaid and sent to the Transmuter
  • Emits - none
  • Reverts
_addDebt(uint256 tokenId, uint256 amount)
  • Description - Increase an account’s debt and lock the corresponding amount of collateral required by minimumCollateralization.

    Ensures sufficient free collateral exists, then updates the account’s locked collateral rawLocked, and global _totalLocked collateral.
    • @param tokenId - the id of the account to modify
    • @param amount - the amount to increase debt by
  • Visibility Specifier - internal
  • State Mutability Specifier - nonpayable
  • Returns - none
  • Emits - none
  • Reverts - Undercollateralized() - not enough free collateral to lock for the additional debt
_subDebt(uint256 tokenId, uint256 amount)
  • Description - Decrease an account’s debt and free the corresponding portion of locked collateral.

    Updates rawLocked and global _totalLocked collateral.
    • @param tokenId - the id of the account to modify
    • @param amount - the amount to increase debt by
  • Visibility Specifier - internal
  • State Mutability Specifier - nonpayable
  • Returns - none
  • Emits - none
  • Reverts - none
_checkAccountOwnership(address owner, address user)
  • Description - Confirms user is the same as owner. Reverts if not.
    • @param owner - the address of the owner of the account
    • @param user - the address attempting access
  • Visibility Specifier - internal
  • State Mutability Specifier - pure
  • Returns - none
  • Emits - none
  • Reverts - UnauthorizedAccountAccessError() - owner and user are not the same
_checkForValidAccountId(uint256 tokenId)
  • Description - Confirms the tokenId corresponds to an existing account NFT, or reverts.
    • @param tokenId - the account ID to check
  • Visibility Specifier - internal
  • State Mutability Specifier - view
  • Returns - none
  • Emits - none
  • Reverts - UnknownAccountOwnerIDError() — tokenId not linked to a valid NFT
_tokenExists(address nft, uint256 tokenId)
  • Description - Utility to check if an alchemist NFT position exists for a given tokenId.
    • @param nft - the address of the AlchemistV3NFTPosition contract
    • @param tokenId - the tokenId to check for
  • Visibility Specifier - internal
  • State Mutability Specifier - view
  • Returns - bool exists
  • Emits - none
  • Reverts - none
_checkState(bool expression)
  • Description - Guard for internal invariants. Reverts if expression evaluates false.
    • @param expression - boolean to assert
  • Visibility Specifier - internal
  • State Mutability Specifier - pure
  • Returns - none
  • Emits - none
  • Reverts - IllegalState() — assertion failed
_validate(uint256 tokenId)
  • Description - Verifies the account identified by tokenId meets minimum collateralization. Reverts if undercollateralized.
    • @param tokenId - the id of the account to validate
  • Visibility Specifier - internal
  • State Mutability Specifier - view
  • Returns - none
  • Emits - none
  • Reverts - Undercollateralized() — account not sufficiently collateralized
_isUnderCollateralized(uint256 tokenId)
  • Description - Returns true if the specified account is below the minimum collateralization ratio, otherwise returns false.
    • @param tokenId - the id of the account being checked
  • Visibility Specifier - internal
  • State Mutability Specifier - view
  • Returns - bool undercollateralized
  • Emits - none
  • Reverts - none
_getTotalUnderlyingValue()
  • Description - Calculates the total value of this Alchemist in underlying tokens by converting the yield tokens deposited into their equivalent underlying-denominated amount.
  • Visibility Specifier - internal
  • State Mutability Specifier - view
  • Returns - uint256 totalUnderlyingValue
  • Emits - none
  • Reverts - none
_decreaseMintAllowance(uint256 ownerTokenId, address spender, uint256 amount)
  • Description - Reduce a spender’s allowance to mint on behalf of an account. The reduction applies within the account’s current allowancesVersion. No checks or events are emitted; calling functions are responsible for validating sufficient allowance exists before this decrease.
    • @param ownerTokenId - the tokenId of the account for which allowance is granted
    • @param spender - the address whose allowance is being decreased
    • @param amount - the amount by which to decrease the allowance
  • Visibility Specifier - internal
  • State Mutability Specifier - nonpayable
  • Returns - none
  • Emits - none
  • Reverts - none
_resolveRepaymentFee(uint256 accountId, uint256 repaidAmountInYield) → (uint256 fee)
  • Description - Calculates a repayment fee in yield tokens when debt is repaid.

    Deducts the fee from the account’s collateral balance and returns the fee for transfer to the liquidator.
    • @param accountId - the tokenId of the account incurring the repayment fee
    • @param repaidAmountInYield - the repaid amount in yield tokens
  • Visibility Specifier - internal
  • State Mutability Specifier - nonpayable
  • Returns - uint256 fee - repayment fee denominated in yield tokens
  • Emits - none
  • Reverts - none

Reading State​

Reads derived, calculated, or internal state. For getters of public variables see the Variable section.

getCDP(uint256 tokenId)
  • Description - Gets an Account's simulated up-to-date collateral, debt, and earmarked amounts. (as if it were synced to be current with global state)
    • @param tokenId - the id used to identify the account.
  • Visibility Specifier - external
  • State Mutability Specifier - view
  • Returns - a tuple (uint256, uint256, uint256) containing the following:
    • debt - the amount of debt the account will have after an update
    • earmarked - the amount of debt which is currently earmarked for redemption
    • collateral - the amount of collateral that has yet to be redeemed
  • Emits - none
  • Reverts - none
getTotalDeposited()
  • Description - Gets the Alchemist's balance of yieldTokens.
  • Visibility Specifier - external
  • State Mutability Specifier - view
  • Returns - uint256 balance
  • Emits - none
  • Reverts - none
getMaxBorrowable(uint256 tokenId)
  • Description - Gets an Account's max amount of debtTokens that they can borrow (mint) given their outstanding LTV and deposited collateral.
    • @param tokenId - the id used to identify the account.
  • Visibility Specifier - external
  • State Mutability Specifier - view
  • Returns - uint256 maxBorrowable
  • Emits - none
  • Reverts - none
mintAllowance(uint256 ownerTokenId, address spender)
  • Description - Gets the max amount of debt an approved spender is allowed to mint on behalf of an owner's account.
    • @param ownerTokenId - the id used to identify the account of the owner.
    • @param spender - the address of the person being granted allowance to mint on behalf of the owner.
  • Visibility Specifier - external
  • State Mutability Specifier - view
  • Returns - uint256 mintAllowance
  • Emits - none
  • Reverts - none
getTotalUnderlyingValue()
  • Description - Calculates the total value of the alchemist in the underlying token
  • Visibility Specifier - external
  • State Mutability Specifier - view
  • Returns - uint256 totalTokenTVLInUnderlying
  • Emits - none
  • Reverts - none
totalValue(uint256 tokenId)
  • Description - Calculates the total value of a specific accounts up-to-date collateral value by first converting to underlying, and then denominating in debt tokens. Used internally during liquidations.
    • @param tokenId - the id used to identify the account.
  • Visibility Specifier - public
  • State Mutability Specifier - view
  • Returns - uint256 totalTokenTVLInUnderlying
  • Emits - none
  • Reverts - none
convertYieldTokensToUnderlying(uint256 amount)
  • Description - Convert yield tokens to underlying tokens using the adapter price and the yield token’s decimals. Returns the underlying-denominated amount
    • @param amount - yieldToken amount
  • Visibility Specifier - public
  • State Mutability Specifier - view
  • Returns - uint256 underlyingAmount
  • Emits - none
  • Reverts - none
normalizeUnderlyingTokensToDebt(uint256 amount)
  • Description - Scale an underlyingToken-denominated amount into debt units via underlyingConversionFactor.
    • @param amount - underlying token amount
  • Visibility Specifier - public
  • State Mutability Specifier - view
  • Returns - uint256 debtAmount
  • Emits - none
  • Reverts - none
convertYieldTokensToDebt(uint256 amount)
  • Description - A multi-step conversion starting with an amount in yieldToken, converting to underlyingToken, and then finally from underlyingToken to debtToken.

    First converts yield to underlying with the adapter price/decimals, then normalizes underlying to debt units with underlyingConversionFactor.
    • @param amount - yieldToken amount
  • Visibility Specifier - public
  • State Mutability Specifier - view
  • Returns - uint256 debtAmount
  • Emits - none
  • Reverts - none
normalizeDebtTokensToUnderlying(uint256 amount)
  • Description - Scale a debtToken-denominated amount into underlyingToken units via underlyingConversionFactor.
    • @param amount - debtToken amount
  • Visibility Specifier - public
  • State Mutability Specifier - view
  • Returns - uint256 underlyingAmount
  • Emits - none
  • Reverts - none
convertUnderlyingTokensToYield(uint256 amount)
  • Description - Convert underlying tokens to yield tokens using the adapter price and the yield token’s decimals. Returns 0 if adapter price is unavailable.
    • @param amount - underlyingToken amount
  • Visibility Specifier - public
  • State Mutability Specifier - view
  • Returns - uint256 yieldAmount
  • Emits - none
  • Reverts - none
convertDebtTokensToYield(uint256 amount)
  • Description - A multi-step conversion starting with an amount in debtToken, converting to underlyingToken, and then finally from underlyingToken to yieldToken.

    First normalizes debt to underlying with underlyingConversionFactor, then converts underlying to yield using the adapter price/decimals.
    • @param amount - debtToken amount
  • Visibility Specifier - public
  • State Mutability Specifier - view
  • Returns - uint256 yieldAmount
  • Emits - none
  • Reverts - none
calculateLiquidation(uint256 collateral, uint256 debt, uint256 targetCollateralization, uint256 alchemistCurrentCollateralization, uint256 alchemistMinimumCollateralization, uint256 feeBps)
  • Description - Calculate how much debt to burn and collateral to seize to restore a position to targetCollateralization, including a fee on surplus collateral. (collateral - debt) Fully liquidates if position’s debt ≥ collateral, or the protocol’s global collateralization is below its minimum. Otherwise, charges a fee from surplus, checks if the target is already met, and if not, computes the minimal partial liquidation needed to reach the target.
    • @param collateral - position collateral denominated in underlying units
    • @param debt - position debt denonimated in debt units
    • @param targetCollateralization - per-position target collateral ratio
    • @param alchemistCurrentCollateralization - global current ratio
    • @param alchemistMinimumCollateralization - global minimum ratio
    • @param feeBps - fee in basis points taken from surplus
  • Visibility Specifier - public
  • State Mutability Specifier - pure
  • Returns
    • grossCollateralToSeize — total collateral to seize including the fee, denominated in debt-units
    • debtToBurn — amount of debt to burn
    • fee — the fee taken from surplus
    • outsourcedFee — the fee charged in the event of a full-liquidation
  • Emits - none
  • Reverts - none

Errors​

  • Undercollateralized() - An error which is used to indicate that an operation failed because an account became undercollateralized.
  • LiquidationError() - An error which is used to indicate that a liquidate operation failed because an account is sufficiently collateralized.
  • UnauthorizedAccountAccessError() - An error which is used to indicate that a user is performing an action on an account that requires account ownership
  • BurnLimitExceeded(uint256 amount, uint256 available) - An error which is used to indicate that a burn operation failed because the transmuter requires more debt in the system.
  • UnknownAccountOwnerIDError() - An error which is used to indicate that the account id used is not linked to any owner
  • AlchemistV3NFTZeroAddressError(); - An error which is used to indicate that the NFT address being set is the zero address
  • AlchemistV3NFTAlreadySetError() - An error which is used to indicate that the NFT address for the Alchemist has already been set
  • AlchemistVaultTokenMismatchError(); - An error which is used to indicate that the token address for the AlchemistTokenVault does not match the underlyingToken
  • CannotRepayOnMintBlock() - An error which is used to indicate that a user is trying to repay on the same block they are minting

Events​

  • PendingAdminUpdated(address pendingAdmin) - Emitted when the pending admin is updated.
  • AlchemistFeeVaultUpdated(address alchemistFeeVault) - Emitted when the alchemist Fee vault is updated.
  • AdminUpdated(address admin) - Emitted when the administrator is updated.
  • DepositCapUpdated(uint256 value) - Emitted when the deposit cap is updated.
  • GuardianSet(address guardian, bool state) - Emitted when a guardian is added or removed from the alchemist.
  • TokenAdapterUpdated(address adapter) - Emitted when a new token adapter is set in the alchemist.
  • TransmuterUpdated(address transmuter) - Emitted when the transmuter is updated.
  • MinimumCollateralizationUpdated(uint256 minimumCollateralization) - Emitted when the minimum collateralization is updated.
  • GlobalMinimumCollateralizationUpdated(uint256 globalMinimumCollateralization) - Emitted when the global minimum collateralization is updated.
  • CollateralizationLowerBoundUpdated(uint256 collateralizationLowerBound) - Emitted when the collateralization lower bound (for a liquidation) is updated.
  • DepositsPaused(bool isPaused) - Emitted when deposits are paused or unpaused in the alchemist.
  • LoansPaused(bool isPaused) - Emitted when loans are paused or unpaused in the alchemist.
  • ApproveMint(uint256 indexed ownerTokenId, address indexed spender, uint256 amount) - Emitted when owner grants spender the ability to mint debt tokens on its behalf.
  • Deposit(uint256 amount, uint256 indexed recipientId) - Emitted when a user deposits amount of yieldToken to recipient.
  • Withdraw(uint256 amount, uint256 indexed tokenId, address recipient) - Emitted when yieldToken is withdrawn from the account owned by owner to recipient.
  • Mint(uint256 indexed tokenId, uint256 amount, address recipient) - Emitted when amount debt tokens are minted to recipient using the account owned by owner.
  • Burn(address indexed sender, uint256 amount, uint256 indexed recipientId) - Emitted when sender burns amount debt tokens to grant credit to account owner recipientId.
  • Repay(address indexed sender, uint256 amount, uint256 indexed recipientId, uint256 credit) - Emitted when amount of underlyingToken are repaid to grant credit to account owned by recipientId.
  • Redemption(uint256 amount) - Emitted when the transmuter triggers a redemption.
  • ProtocolFeeUpdated(uint256 fee) - Emitted when the protocol debt fee is updated.
  • LiquidatorFeeUpdated(uint256 fee) - Emitted when the liquidator fee is updated.
  • RepaymentFeeUpdated(uint256 fee) - Emitted when the repayment fee is updated.
  • ProtocolFeeReceiverUpdated(address receiver) - Emitted when the fee receiver is updated.
  • Liquidated(uint256 indexed accountId, address liquidator, uint256 amount, uint256 feeInYield, uint256 feeInUnderlying) - Emitted when account owned by accountId has been liquidated.
  • BatchLiquidated(uint256[] indexed accounts, address liquidator, uint256 amount, uint256 feeInYield, uint256 feeInETH) - Emitted when accounts have been batch liquidated.
  • MintAllowancesReset(uint256 indexed tokenId) - Emitted when all mint allowances for account managed by tokenId are reset.