> For the complete documentation index, see [llms.txt](https://docs.mavenfinance.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.mavenfinance.io/smart-contracts/smart-contracts-overview/lending-controller-contract.md).

# Lending Controller Contract

Controlling the Pulse of Maven Finance's Lending

The Lending Controller Contract is a critical piece of the Maven Finance ecosystem.&#x20;

It lies at the heart of Maven's lending operations, managing the complex dynamics of multiple lending pools and facilitating seamless interaction between borrowers, lenders, and various digital assets.

Within the Maven Finance landscape, the Lending Controller Contract has the essential role of setting parameters for lending, calculating interest rates, and enforcing the lending policies.&#x20;

Whether you're a lender looking to earn yield on your assets or a borrower seeking liquidity, this contract underpins your experience within Maven's lending framework.&#x20;

### Token Pool Entrypoints

#### addLiquidity

`function addLiquidity(string loanTokenName, nat amount)`

Adds liquidity to the provided loan token pool. An equal amount of corresponding mTokens will be minted and sent to users, representing their liquidity provided.&#x20;

| Param Name    | Type   | Description                                             |
| ------------- | ------ | ------------------------------------------------------- |
| loanTokenName | string | Loan token for which liquidity will be added            |
| amount        | nat    | Total amount of the loan token to be added as liquidity |

#### removeLiquidity

`function removeLiquidity(string loanTokenName, nat amount)`

Removes liquidity to the provided loan token pool. An equal amount of corresponding mTokens will be burned from users, representing their liquidity removed.&#x20;

| Param Name    | Type   | Description                                             |
| ------------- | ------ | ------------------------------------------------------- |
| loanTokenName | string | Loan token for which liquidity will be added            |
| amount        | nat    | Total amount of the loan token to be added as liquidity |

### Vault Entrypoints

#### closeVault

`function closeVault(nat vaultId)`

Closes the provided vault.&#x20;

A vault can only be closed if it has zero outstanding loans. All collateral tokens remaining in the vault will be transferred back to the vault owner.

{% hint style="info" %}
Can be called only by the vault owner
{% endhint %}

| Param Name | Type | Description                      |
| ---------- | ---- | -------------------------------- |
| vaultId    | nat  | The id of the vault to be closed |

#### registerDeposit

`function registerDeposit(vaultHandleType vaultHandle, nat amount, string tokenName)`

Registers a collateral deposit from a vault

{% hint style="info" %}
Can be called only by a Vault Contract or by the vault Factory
{% endhint %}

| Param Name  | Type                                                            | Description                                                                                                 |
| ----------- | --------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
| vaultHandle | <p>vaultHandleType: <br>nat vaultId, <br>address vaultOwner</p> | The identifier key of the vault in lending controller consisting of the vault id and vault owner as the key |
| vaultId     | nat                                                             | The id of the vault                                                                                         |
| vaultOwner  | address                                                         | The address of the vault owner                                                                              |
| amount      | nat                                                             | The total amount that is deposited                                                                          |
| tokenName   | string                                                          | The name of the collateral token deposited                                                                  |

#### registerWithdrawal

`function registerWithdrawal(vaultHandleType vaultHandle, nat amount, string tokenName)`

Registers a collateral withdrawal from a vault. Vaults may not withdraw if they are under-collaterized.&#x20;

{% hint style="info" %}
Can be called only by a Vault Contract&#x20;
{% endhint %}

| Param Name  | Type                                                            | Description                                                                                                 |
| ----------- | --------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
| vaultHandle | <p>vaultHandleType: <br>nat vaultId, <br>address vaultOwner</p> | The identifier key of the vault in lending controller consisting of the vault id and vault owner as the key |
| vaultId     | nat                                                             | The id of the vault                                                                                         |
| vaultOwner  | address                                                         | The address of the vault owner                                                                              |
| amount      | nat                                                             | The total amount that is withdrawn                                                                          |
| tokenName   | string                                                          | The name of the collateral token withdrawn                                                                  |

#### markForLiquidation

`function markForLiquidation(nat vaultId, address vaultOwner)`

Marks a vault for liquidation which starts a grace period for the vault owner to deposit additional collateral into the vault to raise its liquidation ratio.&#x20;

After the grace period, the vault can be liquidated by anyone.

| Param Name | Type    | Description                                                              |
| ---------- | ------- | ------------------------------------------------------------------------ |
| vaultId    | nat     | The id of the vault to be mark for liquidation                           |
| vaultOwner | address | The address of the vault owner of the vault to be marked for liquidation |

#### liquidateVault

`function liquidateVault(nat vaultId, address vaultOwner, nat amount)`

Liquidates a vault based on the total amount of loan tokens sent by the liquidator.&#x20;

The total amount that can be liquidated from a vault is the maxVaultLiquidationPercent (initially set at 50% and configurable through governance) of its total loan outstanding amount.&#x20;

| Param Name | Type    | Description                                                                |
| ---------- | ------- | -------------------------------------------------------------------------- |
| vaultId    | nat     | The id of the vault to be liquidated                                       |
| vaultOwner | address | The address of the vault owner of the vault to be liquidated               |
| amount     | nat     | The total amount of loan tokens for which the vault will be liquidated by. |

#### borrow

`function borrow(nat vaultId, nat quantity)`

Borrows tokens from the Lending Controller loan token liquidity pool to the vault owner

{% hint style="info" %}
Can be called only by a Vault Owner
{% endhint %}

| Param Name | Type | Description                                    |
| ---------- | ---- | ---------------------------------------------- |
| vaultId    | nat  | The id of the vault                            |
| quantity   | nat  | The total amount of loan tokens to be borrowed |

#### repay

`function repay(nat vaultId, nat quantity)`

Repays tokens from the vault back to the Lending Controller loan token liquidity pool

{% hint style="info" %}
Can be called only by a Vault Owner
{% endhint %}

| Param Name | Type | Description                                                                                                                                                                              |
| ---------- | ---- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| vaultId    | nat  | The id of the vault                                                                                                                                                                      |
| quantity   | nat  | <p>The total amount of loan tokens to be repaid. <br><br>If the total amount is greater than the total loan outstanding amount, the excess will be refunded back to the vault owner.</p> |

#### vaultDepositStakedToken

`function vaultDepositStakedToken(string tokenName, nat vaultId, nat depositAmount)`

Handles the deposit of staked tokens (such as staked MVN) from the vault owner to the vault contract.

Valid staked token contracts have to be registered as a staked collateral token type on the Lending Controller and follow the convention in entrypoint names and types.&#x20;

{% hint style="info" %}
Can be called only by a Vault Owner
{% endhint %}

| Param Name    | Type   | Description                                      |
| ------------- | ------ | ------------------------------------------------ |
| tokenName     | string | The name of the collateral token to be deposited |
| vaultId       | nat    | The id of the vault                              |
| depositAmount | nat    | The total amount to be deposited                 |

#### vaultWithdrawStakedToken

`function vaultWithdrawStakedToken(string tokenName, nat vaultId, nat depositAmount)`

Handles the withdrawal of staked tokens (such as staked MVN) from the vault contract to the vault owner.

{% hint style="info" %}
Can be called only by a Vault Owner
{% endhint %}

| Param Name     | Type   | Description                                      |
| -------------- | ------ | ------------------------------------------------ |
| tokenName      | string | The name of the collateral token to be withdrawn |
| vaultId        | nat    | The id of the vault                              |
| withdrawAmount | nat    | The total amount to be withdrawn                 |

### Lending Admin Entrypoints

#### setLoanToken

`function setLoanToken(setLoanTokenActionType setLoanTokenAction)`

Sets a loan token on the Lending Controller contract

{% hint style="info" %}
Can be called only by the admin
{% endhint %}

<table><thead><tr><th width="223.33333333333331">Param Name</th><th width="347">Type</th><th>Description</th></tr></thead><tbody><tr><td>setLoanTokenAction</td><td>setLoanTokenActionType:<br>| createLoanTokenActionType createLoanToken<br>| updateLoanTokenActionType updateLoanToken</td><td>Specify the action variant to be taken for the loan token: Create or Update</td></tr><tr><td>createLoanToken</td><td>createLoanTokenActionType:<br>string tokenName,<br>nat tokenDecimals,<br>address oracleAddress,<br>address mTokenAddress,<br>nat reserveRatio,<br>nat optimalUtilisationRate,<br>nat baseInterestRate,<br>nat maxInterestRate,<br>nat interestRateBelowOptimalUtilisation,<br>nat interestRateAboveOptimalUtilisation,<br>nat minRepaymentAmount, <br>tokenType token</td><td>Parameters for creating a new loan token</td></tr><tr><td>updateLoanToken</td><td>updateLoanTokenActionType:<br>string tokenName,<br>address oracleAddress,<br>nat reserveRatio,<br>nat optimalUtilisationRate,<br>nat baseInterestRate,<br>nat maxInterestRate,<br>nat interestRateBelowOptimalUtilisation,<br>nat interestRateAboveOptimalUtilisation,<br>nat minRepaymentAmount,<br>bool isPaused</td><td>Parameters for updating an existing loan token</td></tr><tr><td>tokenName</td><td>string</td><td>The reference name of the loan token</td></tr><tr><td>tokenDecimals</td><td>nat</td><td>The number of decimals used by the loan token contract</td></tr><tr><td>oracleAddress</td><td>address</td><td>The oracle address providing data on the price of the loan token</td></tr><tr><td>mTokenAddress</td><td>address</td><td>The mToken contract address corresponding to a 1-to-1 ratio to the amount of loan tokens in the Lending Controller.<br><br>The mToken contract address may not be changed once set</td></tr><tr><td>reserveRatio</td><td>nat</td><td>Specifies the amount of reserves required (that cannot be loaned out)</td></tr><tr><td>optimalUtilisationRatio</td><td>nat</td><td>Specifies the optimal utilisation ratio with varying interest rates below and above it</td></tr><tr><td>baseInterestRate</td><td>nat</td><td>Specifies the base interest rate used for loans</td></tr><tr><td>maxInterestRate</td><td>nat</td><td>Specifies the maximum interest rate allowed</td></tr><tr><td>interestRateBelowOptimalUtilisation</td><td>nat</td><td>Specifies the interest rate below the optimal utilisation ratio</td></tr><tr><td>interestRateAboveOptimalUtilisation</td><td>nat</td><td>Specifies the interest rate above the optimal utilisation ratio</td></tr><tr><td>minRepaymentAmount</td><td>nat</td><td>Specifies the minimum amount that can be repaid in each call</td></tr><tr><td>isPaused</td><td>bool</td><td>Specifies if the loan token should be paused.<br><br>If set to True, adding liquidity or borrowing this loan token will be paused. Removing liquidity and repaying loans will still function as normal.</td></tr><tr><td>token</td><td>tokenType: <br>| unit Mavv <br>| (address tokenContractAddress) Fa12 <br>| (address tokenContractAddress, nat tokenId) MRC-20</td><td>The token type of the loan token, corresponding to either Mav, MRC-10 OR MRC-20</td></tr><tr><td></td><td></td><td></td></tr></tbody></table>

#### setCollateralToken

`function setCollateralToken(setCollateralTokenActionType setCollateralTokenAction)`

Sets a collateral token on the Lending Controller contract

{% hint style="info" %}
Can be called only by the admin
{% endhint %}

<table><thead><tr><th width="231.33333333333331">Param Name</th><th width="355">Type</th><th>Description</th></tr></thead><tbody><tr><td>setCollateralTokenAction</td><td>setCollateralTokenActionType:<br>| createCollateralTokenActionType createCollateralToken<br>| updateCollateralTokenActionType updateCollateralToken</td><td>Specify the action variant to be taken for the collateral token: Create or Update</td></tr><tr><td>createCollateralToken</td><td>createCollateralTokenActionType:<br>string tokenName,<br>address tokenContractAddress,<br>nat tokenDecimals,<br>address oracleAddress,<br>bool protected,<br>bool isScaledToken,<br>bool isStakedToken,<br>option(address) stakingContractAddress<br>option(nat) maxDepositAmount<br>tokenType token</td><td>Parameters for creating a new collateral token</td></tr><tr><td>updateCollateralToken</td><td>updateCollateralTokenActionType:<br>string tokenName,<br>address oracleAddress,<br>bool isPaused,<br>option(address) stakingContractAddress,<br>option(nat) maxStakingAmount</td><td>Parameters for updating an existing collateral token</td></tr><tr><td>tokenName</td><td>string</td><td>The reference name of the collateral token</td></tr><tr><td>tokenContractAddress</td><td>address</td><td>The contract address of the collateral token</td></tr><tr><td>tokenDecimals</td><td>nat</td><td>The number of decimals used by the collateral token contract</td></tr><tr><td>oracleAddress</td><td>address</td><td>The oracle address providing data on the price of the loan token</td></tr><tr><td>protected</td><td>bool</td><td>Specifies if a collateral token is protected. <br><br>If set to true, collateral tokens have to be deposited or withdrawn using special entrypoints such as vaultDepositStakedToken and vaultWithdrawStakedToken on the Lending Controller</td></tr><tr><td>isScaledToken</td><td>bool</td><td>Specifies if the collateral token is a scaled token (similar to mToken)</td></tr><tr><td>isStakedToken</td><td>bool</td><td>Specifies if the collateral token is a staked token (similar to staked MVN)</td></tr><tr><td>stakingContractAddress</td><td>option(address)</td><td>An optional contract address to be set only if the collateral token is a staked token</td></tr><tr><td>maxDepositAmount</td><td>nat</td><td>An optional amount to specify the maximum amount of collateral token that can be deposited by all users</td></tr><tr><td>isPaused</td><td>bool</td><td>Specifies</td></tr><tr><td>isPaused</td><td>bool</td><td>Specifies if the collateral token should be paused.<br><br>If set to True, depositing this collateral tokens into vaults will be paused. Withdraws will still function as normal.</td></tr><tr><td>token</td><td>tokenType: <br>| unit Mav<br>| (address tokenContractAddress) Fa12 <br>| (address tokenContractAddress, nat tokenId)  MRC-20</td><td>The token type of the collateral token, corresponding to either Mav, MRC-10 OR MRC-20</td></tr></tbody></table>

#### registerVaultCreation

`function registerVaultCreation(address vaultOwner, nat vaultId, address vaultAddress, string loanTokenName)`

Registers the creation of a new Vault Contract from the Vault Factory Contract

{% hint style="info" %}
Can be called only by the Vault Factory Contract
{% endhint %}

| Param Name    | Type    | Description                                                  |
| ------------- | ------- | ------------------------------------------------------------ |
| vaultOwner    | address | The address of the vault owner                               |
| vaultId       | nat     | The id of the vault                                          |
| vaultAddress  | address | The contract address of the vault contract                   |
| loanTokenName | string  | The loan token that the vault will be allowed to borrow from |

### Housekeeping **Entrypoints**

#### setAdmin

`function setAdmin(address newAdminAddress)`

Sets a new admin address for the contract

{% hint style="info" %}
Can be called only by the admin or the governance contract address
{% endhint %}

| Param Name      | Type    | Description                  |
| --------------- | ------- | ---------------------------- |
| newAdminAddress | address | The address of the new admin |

#### setGovernance

`function setGovernance(address newGovernanceAddress)`

Sets a new governance contract address

{% hint style="info" %}
Can be called only by the admin or the governance contract address
{% endhint %}

| Param Name           | Type    | Description                                |
| -------------------- | ------- | ------------------------------------------ |
| newGovernanceAddress | address | The address of the new governance contract |

#### updateConfig

`function updateConfig(nat newConfigValue, lendingControllerConfigActionType lendingControllerConfigAction)`

Updates the config variables on the LendingController Contract

{% hint style="info" %}
Can be called only by the admin (i.e. the governance proxy contract)
{% endhint %}

<table><thead><tr><th width="232">Param Name</th><th width="364.3333333333333">Type</th><th>Description</th></tr></thead><tbody><tr><td>newConfigValue</td><td>nat</td><td>The new value of the config parameter</td></tr><tr><td>lendingControllerConfigAction</td><td>lendingControllerConfigActionType: <br>| unit ConfigCollateralRatio<br>| unit ConfigLiquidationRatio<br>| unit ConfigLiquidationFeePercent<br>| unit ConfigAdminLiquidationFee<br>| unit ConfigMinimumLoanFeePercent<br>| unit ConfigMinLoanFeeTreasuryShare<br>| unit ConfigInterestTreasuryShare</td><td>The variant config variable to be updated</td></tr></tbody></table>

#### setLambda

`function setLambda(string lambdaName, bytes func_bytes)`

Sets a lambda in the contract with the given bytes and name

{% hint style="info" %}
Can be called only by the admin (i.e. the governance proxy contract)
{% endhint %}

<table><thead><tr><th width="249.33333333333331">Param Name</th><th>Type</th><th>Description</th></tr></thead><tbody><tr><td>lambdaName</td><td>string</td><td>The name of the lambda to be set</td></tr><tr><td>func_bytes</td><td>bytes</td><td>The data of the lambda in Michelson bytes format</td></tr></tbody></table>

### BreakGlass **Entrypoints**

#### pauseAll

`function pauseAll()`

Pauses all entrypoints in the contract.&#x20;

{% hint style="info" %}
Can be called only by the admin or the governance contract address
{% endhint %}

#### unpauseAll

`function unpauseAll()`

Unpauses all entrypoints in the contract.&#x20;

{% hint style="info" %}
Can be called only by the admin or the governance contract address
{% endhint %}

#### togglePauseEntrypoint

`function togglePauseEntrypoint(lendingControllerTogglePauseEntrypointType targetEntrypoint, unit empty)`

Toggles the pausing of a specific entrypoint in the contract

{% hint style="info" %}
Can be called only by the admin (i.e. the governance proxy contract)
{% endhint %}

<table><thead><tr><th width="176.33333333333331">Param Name</th><th width="379">Type</th><th>Description</th></tr></thead><tbody><tr><td>targetEntrypoint</td><td>lendingControllerTogglePauseEntrypointType: <br>| bool SetLoanToken <br>| bool SetCollateralToken <br>| bool AddLiquidity <br>| bool RemoveLiquidity <br>| bool RegisterVaultCreation <br>| bool CloseVault<br>| bool RegisterDeposit<br>| bool RegisterWithdrawal<br>| bool MarkForLiquidation<br>| bool LiquidateVault<br>| bool Borrow<br>| bool Repay<br>| bool VaultDeposit<br>| bool VaultWithdraw<br>| bool VaultOnLiquidate<br>| bool VaultDepositStakedToken<br>| bool VaultWithdrawStakedToken</td><td>The target entrypoint to be paused, and its corresponding pause boolean. If the boolean is set to True, the entrypoint will be paused. </td></tr><tr><td>empty</td><td>unit</td><td>A null param used to prettify interactions with this entrypoint on blockchain explorers such as better-call-dev</td></tr></tbody></table>

### View Methods

#### getAdmin

`function getAdmin()`

Returns the contract admin

#### getGovernanceAddress

`function getGovernanceAddress()`

Returns the contract governance address

#### getConfig

`function getConfig()`

Returns the contract configuration parameters

#### getBreakGlassConfig

`function getBreakGlassConfig()`

Returns the break glass config parameters (which shows the pause status of entrypoints)

#### getColTokenRecordByNameOpt

`function getColTokenRecordByNameOpt(string tokenName)`

Returns the collateral token record by its reference name if it exists, else returns none

#### getLoanTokenRecordOpt

`function getLoanTokenRecordOpt(string tokenName)`

Returns the loan token record by its reference name if it exists, else returns none

#### getOwnedVaultsByUserOpt

`function getOwnedVaultsByUserOpt(address userAddress)`

Returns a set of vault ids where the given userAddress is the vault owner

#### getVaultOpt

`function getVaultOpt(nat vaultId, address vaultOwnerAddress)`

Returns a vault record given its vault id and vault owner address if it exists, else returns none

#### getLambdaOpt

`function getLambdaOpt(string lambdaName)`

Returns a lambda in the contract for the given lambda name, else returns none
