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
- Description - The initial admin account. Can be used to perform any admin/guardian action.
- Type - Address
- Used By
- Updated By
- Read By -
admin()
debtToken
- Description - the address of the ERC20 token used to represent debt. i.e. the alAsset.
- Type - Address
- Used By
- Updated By
- NONE - immutable variable
- Read By -
debtToken()
underlyingToken
- Description - The address of the ERC20 base token/mirrored asset address; ie. USDC or WETH
- Type - Address
- Used By
- Updated By
- NONE - immutable variable
- Read By -
underlyingToken()
myt
- Description - the address of the yield token (MYT) being deposited into this contract. Actions against the contract (withdraw, deposit, etc.) operate on yield tokens.
- Type - Address
- Used By
setDepositCap(uint256 value)deposit(uint256 amount, address recipient, uint256 recipientId)withdraw(uint256 amount, address recipient, uint256 tokenId)repay(uint256 amount, uint256 recipientTokenId)redeem(uint256 amount)selfLiquidate(uint256 accountId, address recipient)convertYieldTokensToUnderlying(uint256 amount)convertUnderlyingTokensToYield(uint256 amount)_forceRepay(uint256 accountId, uint256 amount, bool skipPoke)_liquidate(uint256 accountId)_doLiquidation(uint256 accountId)_earmark()_isProtocolInBadDebt()_simulateUnrealizedEarmark()_getTotalUnderlyingValue()
- Updated By
- NONE - immutable variable
- Read By -
myt()
tokenAdapter
- Description - token adapter used to get price for yield tokens. Currently unused.
- Type - Address
- Used By
- NONE
- Updated By
- Read By
tokenAdapter()
- Notified By -
TokenAdapterUpdated(address value)
transmuter
- Description - address of the transmuter linked to this alchemist. Transmuter seizes collateral (denominated in yieldTokens) from the Alchemist to cover term obligations
- Type - Address
- Used By
burn(uint256 amount, uint256 recipientId)repay(uint256 amount, uint256 recipientTokenId)- Transmuter Actions
redeem(uint256 amount)selfLiquidate(uint256 accountId, address recipient)_forceRepay(uint256 accountId, uint256 amount, bool skipPoke)_doLiquidation(uint256 accountId)_earmark()_isProtocolInBadDebt()_simulateUnrealizedEarmark()
- Updated By
- NONE - set on initialization
- Read By
transmuter()
- Notified By -
TransmuterUpdated(address value)
protocolFeeReceiver
- Description - the address that receives protocol fees.
- Type - Address
- Used By
- Updated By
- Read By
protocolFeeReceiver()
- Notified By -
ProtocolFeeReceiverUpdated(address reciever)
Uint256
depositCap
- Description - the global maximum amount of deposited collateral. AKA the max amount of deposited tokens that can be held by the contract, denomimated in yieldToken
- Type - uint256
- Used By
- Updated By
- Read By
depositCap()
- Notified By -
DepositCapUpdated(uint256 value)
minimumCollateralization
- Description - the minimum collateralization ratio for a specific account, or how much collateral over debt is allowed before liquidation. Inverse of LTV. Value > 1.
- Type - uint256
- Used By
setCollateralizationLowerBound(uint256 value)setGlobalMinimumCollateralization(uint256 value)setLiquidationTargetCollateralization(uint256 value)getMaxBorrowable(uint256 tokenId)getMaxWithdrawable(uint256 tokenId)withdraw(uint256 amount, address recipient, uint256 tokenId)_addDebt(uint256 tokenId, uint256 amount)_isUnderCollateralized(uint256 tokenId)_requiredLockedShares()
- Updated By
- Read By
minimumCollateralization()
- Notified By -
MinimumCollateralizationUpdated(uint256 value)
globalMinimumCollateralization
- Description - represents the minimum allowed global collateralization ratio for the Alchemist. A threshold that if crossed will result in fully liquidating accounts to cover. Only accounts that are already eligible for standard (partial) liquidation can be fully liquidated as a result of the globalMinimumCollateralization.
- Type - uint256
- Used By
- Updated By
- Read By
globalMinimumCollateralization()
- Notified By -
GlobalMinimumCollateralizationUpdated(uint256 value)
collateralizationLowerBound
- Description - The minimum collateralization for liquidation eligibility. between 1 and minimumCollateralization inclusive.
Ifcollateral / debtfalls below this value, the account becomes eligible for liquidation. In LTV terms:liquidation LTV = 1 / collateralizationLowerBound. - Type - uint256
- Used By
- Updated By
- Read By
collateralizationLowerBound()
- Notified By -
CollateralizationLowerBoundUpdated(uint256 value)
liquidationTargetCollateralization
- Description - The target collateralization ratio to restore accounts to after liquidation. Must be
>= minimumCollateralization. - Type - uint256
- Used By
- Updated By
- Read By
liquidationTargetCollateralization()
- Notified By -
LiquidationTargetCollateralizationUpdated(uint256 value)
protocolFee
- Description - the fee percentage (expressed in BPS) on users paid to the protocol. The fee is taken from collateral during redepmtions, or from collateral when users pay down their non-earmarked debt
- Type - uint256
- Used By
- Updated By
- Read By
protocolFee()
- Notified By -
ProtocolFeeUpdated(uint256 fee)
liquidatorFee
- Description - fee percentage (expressed in BPS) paid to liquidators on liquidation. The fee amount (what this percentage is applied to) is denominated in debt token, which is then converted to yieldToken and taken from yieldToken. Also can be taken from underlying if feeBonus > 0.
- Type - uint256
- Used By
- Updated By
- Read By
liquidatorFee()
- Notified By -
LiquidatorFeeUpdated(uint256 fee)
repaymentFee
- Description - fee percentage (expressed in BPS) paid to liquidators on repayment. The fee amount (which this percentage is applied to) is denominated in yieldToken.
- Type - uint256
- Used By
- Updated By
- Read By
repaymentFee()
- Notified By -
RepaymentFeeUpdated(uint256 fee)
Constants
Immutable variables used as helpers or for informational purposes.
BPS
- Description - Constant equaling 10_000. Used for any explicit decimal representation. Treats 100% as 10,000; meaning 10% would be expressed as 1000 BPS.
- Type - uint256
- Used By
- Updated By - NONE - immutable variable
FIXED_POINT_SCALAR
- Description - A multiplier that is used to be able to do fixed point math, since solidity does not natively handle decimals. Like ERC20 tokens which typically use 18 decimals, it expresses 1 as 1e18. Anything less is a fraction of 1.
- Type - uint256
- Used By
setMinimumCollateralization(uint256 value)setCollateralizationLowerBound(uint256 value)setLiquidationTargetCollateralization(uint256 value)getMaxBorrowable(uint256 tokenId)getMaxWithdrawable(uint256 tokenId)withdraw(uint256 amount, address recipient, uint256 tokenId)calculateLiquidation(uint256 collateral, uint256 debt, uint256 targetCollateralization, uint256 alchemistCurrentCollateralization, uint256 alchemistMinimumCollateralization, uint256 feeBps)_addDebt(uint256 tokenId, uint256 amount)_isUnderCollateralized(uint256 tokenId)_isAccountHealthy(uint256 accountId, bool refresh)_doLiquidation(uint256 accountId)_maxRepaymentFeeInYield(uint256 accountId)_requiredLockedShares()
- Updated By - NONE - immutable variable
ONE_Q128
- Description - Constant equaling
uint256(1) << 128. Represents 1.0 in Q128.128 fixed-point format. Multiplying a weight or ratio by this value leaves it unchanged. Used in earmarking and redemption weight calculations. - Type - uint256
- Updated By - NONE - immutable variable
version
- Description - Constant expressing Alchemix version. Not used for anything in the contract.
- Type - string
- Updated By
- NONE - immutable variable
- Read By -
version()
Account
A struct for variables related to per-user accounts and balances.
collateralBalance
- Description - user deposits denominated in yieldTokens.
- Type - uint256
- Used By
withdraw(uint256 amount, address recipient, uint256 tokenId)selfLiquidate(uint256 accountId, address recipient)_subCollateralBalance(uint256 amountInYieldTokens, uint256 accountId)_calculateUnrealizedDebt(uint256 tokenId)_liquidate(uint256 accountId)_doLiquidation(uint256 accountId)_maxRepaymentFeeInYield(uint256 accountId)_totalCollateralValue(uint256 tokenId, bool includeUnrealizedDebt)_sync(uint256 tokenId)
- Updated By
debt
- Description - denominated in alAsset
- Type - uint256
- Used By
burn(uint256 amount, uint256 recipientId)repay(uint256 amount, uint256 recipientTokenId)_forceRepay(uint256 accountId, uint256 amount, bool skipPoke)_liquidate(uint256 accountId)calculateLiquidation(uint256 collateral, uint256 debt, uint256 targetCollateralization, uint256 alchemistCurrentCollateralization, uint256 alchemistMinimumCollateralization, uint256 feeBps)_sync(uint256 tokenId)_calculateUnrealizedDebt(uint256 tokenId)_isUnderCollateralized(uint256 tokenId)
- Updated By
earmarked
- Description - denominated in alAsset. Earmarked funds refer to debt that is reserved to later be redeemed for collateral. Earmarked debt can only be repaid using yieldToken.
- Type - uint256
- Used By
- Updated By
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
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
lastMintBlock
- Description - Block of the most recent mint.
- Type - uint256
- Used By
- Updated By
lastRepayBlock
- Description - Block of the most recent repay.
- Type - uint256
- Used By
- Updated By
lastSurvivalAccumulator
- Description - Last stored survival accumulator from most recent account sync. Used as a checkpoint for computing how much earmarked debt survived redemptions within the current earmark epoch.
- Type - uint256
- Used By
- Updated By
lastTotalRedeemedDebt
- Description - Total debt redeemed at last sync. Used as a checkpoint so the account can compute its share of collateral to remove based on global redemptions since last sync.
- Type - uint256
- Used By
- Updated By
lastTotalRedeemedSharesOut
- Description - Total debt paid out from redemptions at last sync. Used alongside
lastTotalRedeemedDebtto compute how many yield token shares to debit from the account's collateral during sync. - Type - uint256
- Used By
- Updated By
mintAllowances
- Description - allowances for minting alAssets, per version. Indexing by allowances version allows for easy efficient clearing of the entire map if needed.
- Type -
mapping(uint256 => mapping(address => uint256)) - Updated By
- Read By
- Notified By -
MintAllowancesReset(uint256 tokenId)
allowancesVersion
- Description - id used in the mintAllowances map which is incremented on reset.
- Type - uint256
- Used By
- Updated By -
resetMintAllowances(uint256 tokenId)
RedemptionInfo
Struct for variables related to redemption events.
earmarked
- Description - the snapshot of the total earmarked debt at the time of the redemption.
- Type - uint256
- Used By
- Updated By -
redeem(uint256 amount)
debt
- Description - the snapshot of the total debt at the time of the redemption.
- Type - uint256
- Used By
- Updated By -
redeem(uint256 amount)
earmarkWeight
- Description - the snapshot of the global earmark index at the last redemption block. It’s used to rewind an account’s earmarked debt back to what it was when that redemption occurred, so the system can correctly apply the redemption against the right state.
- Type - uint256
- Used By
- Updated By -
redeem(uint256 amount)
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
- Description - An external vault used to hold funds that can be used to pay liquidators in the event that Alchemist funds cannot cover the costs of liquidation. This would occur if (1) the account does not have enough funds to cover the liquidation, or (2) the entire Alchemist is undercollateralized.
- Type - address
- Used By
- Updated By
- Read By
alchemistFeeVault()
- Notified By -
AlchemistFeeVaultUpdated(address value)
alchemistPositionNFT
- Description - the address of the NFT contract for this alchemist. Each position in the alchemist is tied to an NFT.
- Type - address
- Used By
deposit(uint256 amount, address recipient, uint256 tokenId)withdraw(uint256 amount, address recipient, uint256 tokenId)mint(uint256 tokenId, uint256 amount, address recipient)batchLiquidate(uint256[] memory accountIds)approveMint(uint256 tokenId, address spender, uint256 amount)resetMintAllowances(uint256 tokenId)_checkForValidAccountId(uint256 tokenId)
- Updated By
- Read By -
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
- Description - Global running total of system debt currently earmarked for redemption. Can be any amount 0 up to the amount of total system debt. Unearmarked debt = totalDebt - cumulativeEarmarked.
- Type - uint256
- Used By
- Updated By
- Read By
cumulativeEarmarked()
lastEarmarkBlock
- Description - the block number when _earmark() last updated global earmarking. Used to compute how much to earmark from the last time earmarking occured.
- Type - uint256
- Used By
- Updated By
- Read By -
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
lastRedemptionBlock()
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
- Description - The total system-wide debt.
- Type - uint256
- Used By
- Updated By
- Read By -
totalDebt()
totalSyntheticsIssued
- Description - The total system-wide debt tokens issued and circulating.
- Type - uint256
- Used By
- Updated By
- Read By -
totalSyntheticsIssued()
Booleans
depositsPaused
- Description - A flag that prevents depositing by users when set to true. Can be toggled by an Admin or Guardian.
- Type - boolean
- Used By
- Updated By
- Read By
depositsPaused()
- Notified By -
DepositsPaused(bool isPaused)
loansPaused
- Description - A flag that prevents taking loans by users when set to true. Can be toggled by an Admin or Guardian.
- Type - boolean
- Used By
- Updated By
- Read By
loansPaused()
- Notified By -
LoansPaused(bool isPaused)
Mappings
guardians
- Description - A mapping of addresses to true or false values, where true indicates that the address is enabled as having the guardian role (able to execute functions guarded by the
OnlyAdminOrGuardianmodifier), and false marks the address as not having the guardian role. - Type -
mapping(address => bool) - Used By
- Updated By
- Read By
guardians(address guardian)
- Notified By -
GuardianSet(address guardian, bool state)
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
- Description - A global cumulative scaling factor that increases whenever new debt is earmarked. Accounts use the difference between this value and their account-specific lastAccruedEarmarkWeight to determine how much of their outstanding debt should now be considered earmarked.
- Type - uint256
- Used By
- Updated By -
_earmark()
_redemptionWeight
- Description - A global cumulative scaling factor that increases whenever earmarked debt is redeemed. Accounts use the difference between this value and their account-specific lastAccruedRedemptionWeight to determine how much of their earmarked debt has been reconciled by redemptions.
- Type - uint256
- Used By
- Updated By
_survivalAccumulator
- Description - A global accumulator tracking the fraction of earmarked debt that survived redemptions. Used during account sync to compute how much of an account's earmarked debt persists after redemptions within each earmark epoch.
- Type - uint256
- Used By
- Updated By
_totalRedeemedDebt
- Description - Global running total of debt redeemed via Transmuter redemptions. Used alongside
_totalRedeemedSharesOutduring account sync to compute each account's proportional collateral debit. - Type - uint256
- Used By
- Updated By
_totalRedeemedSharesOut
- Description - Global running total of MYT shares paid out for redemptions (collateral redeemed + fee collateral). Used alongside
_totalRedeemedDebtduring account sync to compute each account's proportional collateral debit. - Type - uint256
- Used By
- Updated By
_mytSharesDeposited
- Description - Total yield tokens deposited across all accounts. Used to differentiate between tokens deposited into a CDP and balance of the contract. Also used for deposit cap enforcement and global free collateral calculations.
- Type - uint256
- Used By
- Updated By
- Read By
getTotalDeposited()
_pendingCoverShares
- Description - MYT shares of transmuter balance increase not yet applied as cover in
_earmark(). When the transmuter's balance increases (from repayments or other sources), those shares are held here until consumed by earmarking. - Type - uint256
- Used By
- Updated By
Mappings
_accounts
- Description - tracks user accounts and balances.
- Type -
mapping(uint256 => Account) - Used By
mintAllowance(uint256 ownerTokenId, address spender)deposit(uint256 amount, uint256 recipient, uint256 tokenId)burn(uint256 amount, uint256 recipient)repay(uint256 amount, uint256 recipientTokenId)_forceRepay(uint256 accountId, uint256 amount, bool skipPoke)_liquidate(uint256 accountId)_doLiquidation(uint256 accountId)_addDebt(uint256 tokenId, uint256 amount)_subDebt(uint256 tokenId, uint256 amount)_approveMint(uint256 ownerTokenId, address spender, uint256 amount)_decreaseMintAllowance(uint256 ownerTokenId, address spender, uint256 amount)_sync(uint256 tokenId)_calculateUnrealizedDebt(uint256 tokenId)_isUnderCollateralized(uint256 tokenId)
- Updated By
deposit(uint256 amount, uint256 recipient, uint256 tokenId)withdraw(uint256 amount, uint256 recipient, uint256 tokenId)burn(uint256 amount, uint256 recipient)resetMintAllowances(uint256 tokenId)mint(uint256 tokenId, uint256 amount, uint256 recipient)_doLiquidation(uint256 accountId)_addDebt(uint256 tokenId, uint256 amount)_subDebt(uint256 tokenId, uint256 amount)_approveMint(uint256 ownerTokenId, address spender, uint256 amount)_decreaseMintAllowance(uint256 ownerTokenId, address spender, uint256 amount)_sync(uint256 tokenId)
- Read By -
getCDP(uint256 tokenId)
_earmarkEpochStartRedemptionWeight
- Description - Redemption weight snapshot at the start of each earmark epoch. Used during account sync to determine survival ratios across epoch boundaries.
- Type -
mapping(uint256 => uint256) - Used By
- Updated By
_earmarkEpochStartSurvivalAccumulator
- Description - Survival accumulator snapshot at the start of each earmark epoch. Used during account sync to determine how much earmarked debt persisted across epoch boundaries.
- Type -
mapping(uint256 => uint256) - Used By
- Updated By
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 tokenId, uint256 debtValue)
- 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 - none
- 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 0Undercollateralized()- if the account would be undercollateralized don't allow minting more debtCannotMintOnRepayBlock()- same-block repay mint is disallowed
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 - none
- 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 debtCannotMintOnRepayBlock()- same-block repay mint is disallowed
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.
Difference betweenrepay()andburn():
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 exceedstotalSyntheticsIssued - 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 betweenrepay()andburn():
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 - external
- 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'salchemistFeeVault.@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 yieldfeeInYield— liquidator/repayment fee paid in yield tokensfeeInUnderlying— additional liquidator fee paid in underlying from this Alchemist'salchemistFeeVault(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.
selfLiquidate(uint256 accountId, address recipient)
- Description - Allows the owner of a healthy (overcollateralized) position to close it entirely.
Syncs state, repays any earmarked debt from collateral, clears all remaining debt by consuming collateral, and sends leftover collateral to the recipient. Can only be used when the account is healthy; unhealthy accounts must use the regular liquidation path.@param accountId- the tokenId of the account to self liquidate@param recipient- the address that receives remaining collateral
- Visibility Specifier - external
- State Mutability Specifier - nonpayable
- Returns - uint256 amountLiquidated
- Emits
- Reverts
- recipient == zero address -
UnknownAccountOwnerIDError()— passed accountId does not correspond to an existing NFT UnauthorizedAccountAccessError()— caller is not the owner of the positionAccountNotHealthy()— account is unhealthy, must use regular liquidation path
- recipient == zero address -
batchLiquidate(uint256[] accountIds)
- Description - Attempts liquidation across multiple accounts.
Calls the internal_liquidatefor 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-accountyieldAmountreturned by_liquidate(i.e., total yield moved)totalFeesInYield— sum of yield-denominated liquidator/repayment feestotalFeesInUnderlying— sum of underlying-denominated liquidator fees paid from this Alchemist'salchemistFeeVault(see_liquidate()for when this would occur)
- Emits - none
- Reverts -
MissingInputData()—accountIdsis empty -LiquidationError()— no liquidation/repayment occurred for any account. Seeliquidate()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 bytokenId, for up toamountof debtTokens.
Verifies the caller owns the position, then delegates to_approveMintto 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 bytokenId@param amount- the maximum debt tokens thespendermay mint
- Visibility Specifier - external
- State Mutability Specifier - nonpayable
- Returns - none
- Emits
ApproveMint(uint256 indexed ownerTokenId, address indexed spender, uint256 amount)(emitted by_approveMint)
- Reverts -
UnauthorizedAccountAccessError()— caller is not the owner of the position identified bytokenId
resetMintAllowances(uint256 tokenId)
- Description - Clears all existing mint allowances for the position by bumping its
allowancesVersion. FutureapproveMintentries 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()
- Description - Can only be called by the current pendingAdmin. Used to accept the admin role.
- Visibility Specifier - external
- State Mutability Specifier - nonpayable
- Returns - none
- Emits
- Reverts - Unauthorized()
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
AlchemistV3NFTZeroAddressError- if the NFT is set to the zero addressAlchemistV3NFTAlreadySetError- if the NFT has already been set
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 -
AlchemistVaultTokenMismatchError- if the token of the fee vault doesn't match the underlying
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
value < currentmyt balance of the contract
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
- value == zero address
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
- fee > BPS (10_000 or 100%)
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
- fee > BPS (10_000 or 100%)
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
- fee > BPS (10_000 or 100%)
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
- value == zero address
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
- guardian == zero address
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
value < 1e18(Would allow debt to exceed collateral if allowed. 1e18 is 100% collateralization, or 100% LTV)
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
value < minimumCollateralization(The system cannot be in worse shape than individual borrowers)
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
value >= minimumCollateralization(Liquidation eligibility must be below the minimum collateralization threshold)value < 1e18(Would allow debt to exceed collateral if allowed. 1e18 is 100% collateralization, or 100% LTV)
setLiquidationTargetCollateralization(uint256 value)
- Description - Sets the liquidationTargetCollateralization variable.
@param value- the uint256 to use as the new value. Must be> 1e18,>= minimumCollateralization,> collateralizationLowerBound, and<= 2e18.
- Visibility Specifier - external
- State Mutability Specifier - nonpayable
- Returns - none
- Emits
- Reverts
value <= 1e18(must be above 100% collateralization / below 100% LTV)value < minimumCollateralizationvalue <= collateralizationLowerBoundvalue > 2e18(must be at or below 200% collateralization / at or above 50% LTV)
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 reducescumulativeEarmarkedandtotalDebt. 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 - uint256 sharesSent
- Emits
- Reverts - none
reduceSyntheticsIssued(uint256 amount)
- Description - reduced
totalSyntheticsIssuedby 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
lastTransmuterTokenBalancevariable, 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.
_checkArgument(bool expression)
- Description - Guard for function arguments. Reverts if
expressionevaluates false.@param expression- boolean to assert
- Visibility Specifier - internal
- State Mutability Specifier - pure
- Returns - none
- Emits - none
- Reverts
IllegalArgument()— assertion failed
_sync(uint256 tokenId)
- Description - Bring the account to the latest global state re. earmarking, redemptions, and collateral.
Computes the account's unrealized debt/earmark/redemption state via_computeUnrealizedAccount, applies collateral debits based on global redemption deltas, then updates all account 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, applies pending cover from the Transmuter's newly accrued yield, then increases_earmarkWeightandcumulativeEarmarked. Finally stampslastEarmarkBlock. - 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'salchemistFeeVault.@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 0feeInYield- liquidator/repayment fee paid in yield tokensfeeInUnderlying- additional liquidator fee paid in underlying from this Alchemist'salchemistFeeVault(if needed)
- Emits - none
- Reverts - none
_doLiquidation(uint256 accountId)
- 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’salchemistFeeVault.@param accountId- the tokenId of the account being liquidated
- Visibility Specifier - internal
- State Mutability Specifier - nonpayable
- Returns
amountLiquidated— the amount of yield tokens seized during liquidationfeeInYield— base fee paid to the liquidator in yield tokens, coming from user collateralfeeInUnderlying— additional fee paid to the liquidator in underlying tokens, coming from the fee vault
- Emits - none
- Reverts - none
_subEarmarkedDebt(uint256 amountInDebtTokens, uint256 accountId)
- Description - Subtracts the earmarked debt by
amountInDebtTokensfor the account owned byaccountId. Also reducescumulativeEarmarkedglobally.@param amountInDebtTokens- the amount of debt tokens to subtract from the earmarked debt@param accountId- the tokenId of the account to subtract the earmarked debt from
- Visibility Specifier - internal
- State Mutability Specifier - nonpayable
- Returns -
uint256- the amount of debt tokens subtracted from the earmarked debt - Emits - none
- Reverts - none
_subCollateralBalance(uint256 amountInYieldTokens, uint256 accountId)
- Description - Subtracts the collateral balance by
amountInYieldTokensfor the account owned byaccountId. Also reduces_mytSharesDepositedglobally. Clamps to available balance.@param amountInYieldTokens- the amount of yield tokens to subtract from the collateral balance@param accountId- the tokenId of the account to subtract the collateral balance from
- Visibility Specifier - internal
- State Mutability Specifier - nonpayable
- Returns -
uint256- the amount of yield tokens subtracted from the collateral balance - Emits - none
- Reverts - none
_approveMint(uint256 ownerTokenId, address spender, uint256 amount)
- Description - Isolated logic to overwrite the mint allowance for
spenderunder the account’s currentallowancesVersion, enablingspenderto mint debt on behalf ofownerTokenId. 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 byownerTokenId@param amount- the maximum debt thespendermay mint (for the currentallowancesVersion)
- 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 torecipient. Updates global issuance and recordslastMintBlockto 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 collateralizationCannotMintOnRepayBlock()— if minting on the same block as a repay
_forceRepay(uint256 accountId, uint256 amount, bool skipPoke)
- 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@param skipPoke- whether to skip the poke (earmark + sync) step
- Visibility Specifier - internal
- State Mutability Specifier - nonpayable
- Returns -
uint256 creditToYield- amount of yield tokens that were repaid and sent to the Transmuter - Emits
- Reverts
- No outstanding debt in the account to repay
UnknownAccountOwnerIDError()— invalidaccountId
_addDebt(uint256 tokenId, uint256 amount)
- Description - Increase an account’s debt and verify the account has sufficient collateral as required by
minimumCollateralization.@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 collateral to support the additional debt
_subDebt(uint256 tokenId, uint256 amount)
- Description - Decrease an account’s debt. Also decreases
totalDebtand clampscumulativeEarmarkedif it exceedstotalDebt.@param tokenId- the id of the account to modify@param amount- the amount to decrease debt by
- Visibility Specifier - internal
- State Mutability Specifier - nonpayable
- Returns - none
- Emits - none
- Reverts - none
_checkAccountOwnership(address owner, address user)
- Description - Confirms
useris the same asowner. 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
tokenIdcorresponds 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
expressionevaluates 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
tokenIdmeets 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
_calculateRepaymentFee(uint256 repaidAmountInYield)
- Description - Calculates a repayment fee in yield tokens based on the
repaymentFeeBPS rate.@param repaidAmountInYield- the repaid amount in yield tokens
- Visibility Specifier - internal
- State Mutability Specifier - view
- Returns -
uint256 feeInYield- repayment fee denominated in yield tokens - Emits - none
- Reverts - none
_maxRepaymentFeeInYield(uint256 accountId)
- Description - Returns the maximum yield-denominated fee that can be removed from an account's collateral while keeping the account strictly healthy (above the collateralization lower bound).
@param accountId- the tokenId of the account to compute the max repayment fee for
- Visibility Specifier - internal
- State Mutability Specifier - view
- Returns -
uint256- max repayment fee in yield tokens - Emits - none
- Reverts - none
_payWithFeeVault(uint256 amountInUnderlying)
- Description - Pays the liquidator fee in underlying tokens using the fee vault. Falls back gracefully if the fee vault has insufficient balance or is not set.
@param amountInUnderlying- the amount of underlying tokens to pay
- Visibility Specifier - internal
- State Mutability Specifier - nonpayable
- Returns -
uint256- actual amount paid based on the vault balance - Emits
- Reverts - none
_isAccountHealthy(uint256 accountId, bool refresh)
- Description - Checks if the account is healthy. An account is healthy if its collateralization ratio is greater than the collateralization lower bound, or if it has no debt.
@param accountId- the tokenId of the account to check@param refresh- whether to refresh the account's collateral value by including unrealized debt
- Visibility Specifier - internal
- State Mutability Specifier - view
- Returns -
bool- true if the account is healthy, false otherwise - Emits - none
- Reverts - none
_totalCollateralValue(uint256 tokenId, bool includeUnrealizedDebt)
- Description - Calculate the total collateral value of the account in debt tokens. When
includeUnrealizedDebtis true, simulates unrealized debt to get an up-to-date collateral figure.@param tokenId- the id of the account owner@param includeUnrealizedDebt- whether to include unrealized debt adjustments in the calculation
- Visibility Specifier - internal
- State Mutability Specifier - view
- Returns -
uint256- the total collateral value of the account in debt tokens - Emits - none
- Reverts - none
_computeUnrealizedAccount(Account account, uint256 earmarkWeightCurrent, uint256 redemptionWeightCurrent, uint256 survivalAccumulatorCurrent)
- Description - Computes the account debt/earmark state at a given global weight snapshot. Determines how much debt has been earmarked and redeemed since the account's last sync by comparing its stored checkpoints against the provided current weights.
@param account- the account storage reference@param earmarkWeightCurrent- the current global earmark weight to compute against@param redemptionWeightCurrent- the current global redemption weight to compute against@param survivalAccumulatorCurrent- the current global survival accumulator to compute against
- Visibility Specifier - internal
- State Mutability Specifier - view
- Returns - a tuple (uint256, uint256, uint256) containing the following:
- newDebt - the debt after applying earmark and redemption
- newEarmarked - the earmarked portion after applying survival and new earmarks
- redeemedDebt - realized redeemed debt for this step
- Emits - none
- Reverts - none
_poke(uint256 tokenId)
- Description - Internal helper that applies global earmarking and syncs the specified account's state.
@param tokenId- the tokenId of the account to poke
- Visibility Specifier - internal
- State Mutability Specifier - nonpayable
- Returns - none
- Emits - none
- Reverts - none
_capDebtCredit(uint256 requested, uint256 accountDebt)
- Description - Caps a debt-denominated credit against account debt and global debt.
@param requested- the requested credit amount@param accountDebt- the account's current debt
- Visibility Specifier - internal
- State Mutability Specifier - view
- Returns -
uint256- the capped credit amount - Emits - none
- Reverts - none
_clearableDebt(uint256 accountDebt)
- Description - Returns debt that can be safely cleared against global debt accounting.
@param accountDebt- the account's current debt
- Visibility Specifier - internal
- State Mutability Specifier - view
- Returns -
uint256- the clearable debt amount - Emits - none
- Reverts - none
_simulateUnrealizedEarmark()
- Description - Simulates one uncommitted earmark window using current on-chain state without modifying storage. Used by
_calculateUnrealizedDebtandgetUnrealizedCumulativeEarmarkedto provide view-only projections. - Visibility Specifier - internal
- State Mutability Specifier - view
- Returns - a tuple (uint256, uint256) containing the following:
- earmarkWeightCopy - simulated earmark packed weight after the window
- effectiveEarmarked - the additional earmarked debt from this simulated window
- Emits - none
- Reverts - none
_isProtocolInBadDebt()
- Description - Returns true if issued synthetics exceed global backing. Backing mirrors Transmuter claim math: locked collateral in Alchemist plus MYT shares currently held by Transmuter.
- Visibility Specifier - internal
- State Mutability Specifier - view
- Returns -
bool- true if protocol is in bad debt - Emits - none
- Reverts - none
_getTotalLockedUnderlyingValue()
- Description - Calculates the total value locked in the system from collateralization requirements, denominated in underlying tokens. Caps the result by actual shares held in the Alchemist.
- Visibility Specifier - internal
- State Mutability Specifier - view
- Returns -
uint256- total locked underlying value - 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
getMaxWithdrawable(uint256 tokenId)
- Description - Gets the maximum MYT shares that could be withdrawn from a position, taking into account both per-position locked collateral and global deposit constraints.
@param tokenId- the id used to identify the account.
- Visibility Specifier - external
- State Mutability Specifier - view
- Returns - uint256 maxWithdrawable
- 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
getTotalLockedUnderlyingValue()
- Description - Calculates the total value locked in the system from collateralization requirements, denominated in underlying tokens.
- Visibility Specifier - external
- State Mutability Specifier - view
- Returns - uint256 totalLockedUnderlyingValue
- 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
getUnrealizedCumulativeEarmarked()
- Description - Returns cumulative earmarked debt including one simulated pending earmark window. Useful for off-chain queries to see what earmarking state would look like if
_earmark()were called now. - Visibility Specifier - external
- State Mutability Specifier - view
- Returns - uint256 unrealizedCumulativeEarmarked
- Emits - none
- Reverts - none
convertYieldTokensToUnderlying(uint256 amount)
- Description - Convert yield tokens to underlying tokens using the MYT vault's share-to-asset conversion. 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 via the MYT vault's share-to-asset conversion, then normalizes underlying to debt units withunderlyingConversionFactor.@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 MYT vault's asset-to-share conversion.
@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 withunderlyingConversionFactor, then converts underlying to yield via the MYT vault's asset-to-share conversion.@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-unitsdebtToBurn— amount of debt to burnfee— the fee taken from surplusoutsourcedFee— 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. -
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 -
CannotMintOnRepayBlock()- An error which is used to indicate that a user is trying to mint on the same block they are repaying -
GlobalCollateralizationTooLow(uint256, uint256)- An error which is used to indicate that the global collateralization ratio is too low -
AccountNotHealthy()- An error which is used to indicate that an account is not healthy -
IllegalArgument()- An error which is used to indicate that a function argument is not valid. -
IllegalState()- An error which is used to indicate that the contract is in an illegal state for the requested operation. -
MissingInputData()- An error which is used to indicate that required input data is missing.
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. -
LiquidationTargetCollateralizationUpdated(uint256 liquidationTargetCollateralization)- Emitted when the liquidation target collateralization ratio 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 whenownergrantsspenderthe ability to mint debt tokens on its behalf. -
Deposit(uint256 amount, uint256 indexed recipientId)- Emitted when a user depositsamountof yieldToken torecipient. -
Withdraw(uint256 amount, uint256 indexed tokenId, address recipient)- Emitted when yieldToken is withdrawn from the account owned byownertorecipient. -
Mint(uint256 indexed tokenId, uint256 amount, address recipient)- Emitted whenamountdebt tokens are minted torecipientusing the account owned byowner. -
Burn(address indexed sender, uint256 amount, uint256 indexed recipientId)- Emitted whensenderburnsamountdebt tokens to grant credit to account ownerrecipientId. -
Repay(address indexed sender, uint256 amount, uint256 indexed recipientId, uint256 credit)- Emitted whenamountofunderlyingTokenare repaid to grant credit to account owned byrecipientId. -
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 byaccountIdhas been liquidated. -
SelfLiquidated(uint256 indexed accountId, uint256 amountLiquidated)- Emitted when account owned byaccountIdhas been self 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 bytokenIdare reset. -
ForceRepay(uint256 indexed accountId, uint256 amount, uint256 creditToYield, uint256 protocolFeeTotal)- Emitted whenamountof debt is force repaid fromaccountId. -
RepaymentFee(uint256 indexed accountId, address feeReciever, uint256 feeInYield, uint256 feeInUnderlying)- Emitted when a repayment fee is charged during liquidation. -
FeeShortfall(address indexed liquidator, uint256 requested, uint256 paid)- Emitted when a fee-vault payout is short of the requested amount. -
AlchemistV3PositionNFTMinted(address indexed to, uint256 indexed tokenId)- Emitted when a new Position NFT is minted.