# Introduction

{% hint style="info" %}
General information about mStable can be found in the general [mStable Docs](https://app.gitbook.com/@mstable/s/mstable-docs/). These Docs here are for Developers and give an overview of the smart contracts.
{% endhint %}

## Smart Contract Dependency Tree

{% tabs %}
{% tab title="Ethereum Mainnet" %}
![](https://1563241728-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MgJxLWD6SqMELu7agWt%2Fuploads%2Fbu4ak8ttV0LiRZYzL4GK%2FmStableLogicalContractDiagram.png?alt=media\&token=e9a99f7f-c56b-41b0-a691-1c12bb1ca706)
{% endtab %}

{% tab title="Polygon" %}
![](https://1563241728-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MgJxLWD6SqMELu7agWt%2Fuploads%2Fwl5HZPJDUaTs1vz4a6Ex%2FPolygonContractDiagram.png?alt=media\&token=c4ee9518-5c93-4046-8953-e6cdcfaa832a)
{% endtab %}
{% endtabs %}

## Smart Contract Overview

mStable's smart contracts can be divided into 5 categories that serve different purposes:

* **mAssets** (e.g. mUSD and mBTC) are meta Assets that combine 2 or more assets into a new one. Such as DAI, USDT, USDC and sUSD are being composed into mUSD. mAsset contracts hold the logic for minting, swapping the underlying, and redeeming mAssets back to the underlying.
* **imAssets** (e.g. imUSD and imBTC) are interest-bearing meta Assets, that earn interest from third-party lending platforms and swaps. In the front-end, this is denoted as the SAVE. imAssets smart contracts are used for depositing mAssets into SAVE and minting imAssets and also redeeming back to mAssets.
* **Feeder Pools** (e.g. mUSD/alUSD) are 50/50 AMM pool that consists of one mAsset and one other similar asset. This has to be an asset that is not part of the mAsset basket but holds the same price. Feeder Pool contracts allow to deposit, redeem and swap.
* **Vaults** are the contracts for staking Feeder Pool tokens or imAssets in order to earn and claim MTA rewards. The tokens in the Vault are non-transferable but tokens can be staked and unstaked at any time.
* **Save Wrapper** is a utility smart contract that allows combining a multistep process into one smart contract call. E.g. Deposit into SAVE and stake with one single call.&#x20;

The mStable contracts can be found on [Github here](https://github.com/mstable/mStable-contracts).

### Price function: Stableswap AMM

* mAssets price function is based on the Stableswap AMM invariant. The price for minting, redeeming, and swapping is determined by that formula. **It does not use any oracles to price the assets.**
* The implementation is similar to Curve's Stableswap: <https://curve.fi/files/stableswap-paper.pdf>.
* An adjustment was made to accommodate the min and max weights of each asset. In case a mint, swap, or redeem will result in the weights being out of bound, the transaction would revert. However, given the design of the AMM, this would practically not be the case, since arbitrage would occur much sooner than those limits could be hit.


# USDC 3Pool Convex Meta Vault

### 3Pool Convex Meta Vault Contract Overview

This Meta Vault is composed of several components:

* The top-level Meta Vault: *USDC 3Pool Convex Meta Vault*
  * Accepts $USDC and returns Vault Shares ($mvUSDC-3PCV)
  * Deposits $USDC in 3Pool, passes $3CRV token to second level Meta Vault
  * [ERC-4626 Compatible](/meta-vaults/general-erc-4626-vault-interface)
  * [Detailed Contract and Capabilities](/meta-vaults/usdc-3pool-convex-meta-vault/3pool-convex-meta-vault)
* The second-level Meta Vault: 3CRV Convex Meta Vault
  * Accepts $3CRV and returns Vault Shares ($mv3CRV-CVX)
  * Periodically settles and allocates 3CRV to 3 underlying Basic Vaults (Convex 3CRV)
  * [ERC-4626 Compatible](/meta-vaults/general-erc-4626-vault-interface)
  * [Detailed Contract and Capabilities](/meta-vaults/usdc-3pool-convex-meta-vault/meta-vault-of-convex-3crv-vaults)
* Third level Basic Vault:
  * 3CRV Convex mUSD Vault
  * 3CRV Convex BUSD Vault
  * 3CRV Convex FRAX Vault
  * Allocates 3CRV to 3Pool Metapools on Curve and Stakes in Convex
  * [ERC-4626 Compatible](/meta-vaults/general-erc-4626-vault-interface)
  * [Detailed Contract and Capabilities](#convex-3crv-vaults)

<figure><img src="https://1563241728-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MgJxLWD6SqMELu7agWt%2Fuploads%2F9FOPIk7ChvYI3RUcw7wj%2Fimage.png?alt=media&amp;token=1f450579-6187-49bc-b380-a12e3532a7d8" alt=""><figcaption></figcaption></figure>

### Convex 3Crv Vaults

<table><thead><tr><th width="243.5">Contract</th><th>Address</th></tr></thead><tbody><tr><td><a href="https://github.com/mstable/metavaults/blob/main/contracts/vault/liquidity/curve/Curve3CrvBasicMetaVault.sol">USDC 3Pool Convex Meta Vault</a></td><td><a href="https://etherscan.io/address/0x455fB969dC06c4Aa77e7db3f0686CC05164436d2">0x455fB969dC06c4Aa77e7db3f0686CC05164436d2</a></td></tr><tr><td><a href="https://github.com/mstable/metavaults/blob/main/contracts/vault/meta/PeriodicAllocationPerfFeeMetaVault.sol">3CRV Convex Meta Vault</a></td><td><a href="https://etherscan.io/address/0x9614a4C61E45575b56c7e0251f63DCDe797d93C5">0x9614a4C61E45575b56c7e0251f63DCDe797d93C5</a></td></tr><tr><td><a href="https://github.com/mstable/metavaults/blob/main/contracts/vault/liquidity/convex/Convex3CrvLiquidatorVault.sol">3Crv Convex mUSD Vault</a></td><td><a href="https://etherscan.io/address/0xB9B47E72819934d7A5d60Bf08cD2C78072383EBb">0xB9B47E72819934d7A5d60Bf08cD2C78072383EBb</a></td></tr><tr><td><a href="https://github.com/mstable/metavaults/blob/main/contracts/vault/liquidity/convex/Convex3CrvLiquidatorVault.sol">3Crv Convex FRAX Vault</a></td><td><a href="https://etherscan.io/address/0x98c5910823C2E67d54e4e0C03de44043DbfA7ca8">0x98c5910823C2E67d54e4e0C03de44043DbfA7ca8</a></td></tr><tr><td><a href="https://github.com/mstable/metavaults/blob/main/contracts/vault/liquidity/convex/Convex3CrvLiquidatorVault.sol">3Crv Convex BUSD Vault</a></td><td><a href="https://etherscan.io/address/0x87Ed92648fAE3b3930577c92c8A247b127ED8949">0x87Ed92648fAE3b3930577c92c8A247b127ED8949</a></td></tr></tbody></table>


# 3Pool Convex Meta Vault

Abstract ERC-4626 vaults with DAI, USDC or USDT asset invested in Curve's [3Pool](https://curve.fi/3pool), and then the 3Pool LP token (3Crv) is invested in an underlying 3Pool-based (3Crv) Meta Vault.

## Capabilities

* [ERC-4626](https://eips.ethereum.org/EIPS/eip-4626) compliant tokenized vault.
* [ERC-20](https://eips.ethereum.org/EIPS/eip-20) compliant token.
* Invests DAI, USDC or USDT in Curve's 3Pool and then invests the 3Crv LP token in an underlying ERC4626 vault.
* Sandwich attack protection on ERC4626 operations `deposit`, `mint`, `withdraw` and `redeem`.
* Vault operations are pausable by the `Governor`.
* Emergency asset recovery by the `Governor`. This will be removed after 2 months.
* Vault configuration is controlled by a protocol `Governor`. This includes:
  * Setting the slippage limits for mint, deposit, redeem and withdraw.
* Initially the `Governor` can upgrade the contracts via a proxy without a time delay. After 6 weeks, this will be changed to a one week time delay.

## Contract Interface

See the metavaults github repository for [contract diagrams](https://github.com/mstable/metavaults/tree/main/contracts/vault/liquidity/curve#diagrams) and [process diagrams](https://github.com/mstable/metavaults/tree/main/contracts/vault/liquidity/curve#processes).

See [General ERC-4626 Vault Interface](/meta-vaults/general-erc-4626-vault-interface) for the standard ERC-4626 functions.

### Variables

#### BASIS\_SCALE

```solidity
uint256 BASIS_SCALE
```

Basis points calculation scale. 100% = 10000. 1% = 100

#### redeemSlippage

```solidity
uint256 redeemSlippage
```

Redeem slippage in basis points i.e. 1% = 100

#### depositSlippage

```solidity
uint256 depositSlippage
```

Deposit slippage in basis points i.e. 1% = 100

#### withdrawSlippage

```solidity
uint256 withdrawSlippage
```

Withdraw slippage in basis points i.e. 1% = 100

#### mintSlippage

```solidity
uint256 mintSlippage
```

Mint slippage in basis points i.e. 1% = 100

#### assetScale

```solidity
uint256 assetScale
```

Scale of one asset. eg 1e18 if asset has 18 decimal places.

#### assetFromUsdScale

```solidity
uint256 assetFromUsdScale
```

Converts USD value with 18 decimals back down to asset/vault scale. For example, convert 18 decimal USD value back down to USDC which only has 6 decimal places. Will be 1 for DAI, 1e12 for USDC and USDT.

#### threeCrvTokenScale

```solidity
uint256 threeCrvTokenScale
```

Scale of the Curve.fi 3Crv token. 1e18 = 18 decimal places

#### metaVault

```solidity
contract IERC4626Vault metaVault
```

Address of the underlying Meta Vault that implements ERC-4626.

#### assetPoolIndex

```solidity
uint256 assetPoolIndex
```

The index of underlying asset DAI, USDC or USDT in 3Pool. DAI = 0, USDC = 1 and USDT = 2

### Functions

#### liquidateVault

```solidity
function liquidateVault(uint256 minAssets) external
```

Governor liquidates all the vault's assets and send to the governor. Only to be used in an emergency. eg whitehat protection against a hack.

**Parameters**

<table><thead><tr><th width="127.33333333333331">Name</th><th width="93">Type</th><th>Description</th></tr></thead><tbody><tr><td>minAssets</td><td>uint256</td><td>Minimum amount of asset tokens to receive from removing liquidity from the Curve 3Pool. This provides sandwich attack protection.</td></tr></tbody></table>

#### resetAllowances

```solidity
function resetAllowances() external
```

Approves Curve's 3Pool contract to transfer assets (DAI, USDC or USDT) from this vault. Also approves the underlying Meta Vault to transfer 3Crv from this vault.

#### setRedeemSlippage

```solidity
function setRedeemSlippage(uint256 _slippage) external
```

Governor function to set redeem slippage.

**Parameters**

<table><thead><tr><th width="135.33333333333331">Name</th><th width="103">Type</th><th>Description</th></tr></thead><tbody><tr><td>_slippage</td><td>uint256</td><td>Redeem slippage to apply as basis points i.e. 1% = 100</td></tr></tbody></table>

#### setDepositSlippage

```solidity
function setDepositSlippage(uint256 _slippage) external
```

Governor function to set deposit slippage.

**Parameters**

<table><thead><tr><th width="126.33333333333331">Name</th><th width="120">Type</th><th>Description</th></tr></thead><tbody><tr><td>_slippage</td><td>uint256</td><td>Deposit slippage to apply as basis points i.e. 1% = 100</td></tr></tbody></table>

#### setWithdrawSlippage

```solidity
function setWithdrawSlippage(uint256 _slippage) external
```

Governor function to set withdraw slippage.

**Parameters**

<table><thead><tr><th width="149.33333333333331">Name</th><th width="93">Type</th><th>Description</th></tr></thead><tbody><tr><td>_slippage</td><td>uint256</td><td>Withdraw slippage to apply as basis points i.e. 1% = 100</td></tr></tbody></table>

#### setMintSlippage

```solidity
function setMintSlippage(uint256 _slippage) external
```

Governor function to set mint slippage.

**Parameters**

<table><thead><tr><th width="135">Name</th><th width="91.33333333333331">Type</th><th>Description</th></tr></thead><tbody><tr><td>_slippage</td><td>uint256</td><td>Mint slippage to apply as basis points i.e. 1% = 100</td></tr></tbody></table>


# Meta Vault of Convex 3Crv Vaults

ERC-4626 vault with Curve's [3Pool](https://curve.fi/3pool) liquidity provider token (3Crv) as an asset. The 3Crv is invested in underlying Convex 3Crv Basic Vaults.

Deposits of assets (3Crv) are allocated to the underlying vaults based on weights set by the Vault Manager. Withdraw of assets (3Crv) are proportionally withdrawn from the underlying assets. This may not match the weights set by the Vault Manager.

## Capabilities

* [ERC-4626](https://eips.ethereum.org/EIPS/eip-4626) compliant tokenized vault.
* [ERC-20](https://eips.ethereum.org/EIPS/eip-20) compliant token.
* Assets are invested across multiple underlying ERC-4626 vaults of the same asset type.
* Investment of deposited assets to the underlying vaults is batched in a `settle` process.
* `deposit` and `mint` use minimal gas as the investment is done separately.
* The `VaultManager` directs the deposited assets to the underlying vaults.
* Assets in underlying vaults can be redistributed by the `VaultManager`.
* Small withdrawals are taken from a single configured underlying vault to save gas.
* Large withdraws are proportionally taken from all underlying vaults.
* Performance fee periodically charged on assets per share increases.
* Vault operations are pausable by the `Governor`.
* Vault configuration is controlled by a protocol `Governor`. This includes:
  * Which underlying vaults are used.
  * Which vault small withdrawals are taken from.
  * The threshold for large withdraws as a percentage of shares.
  * Setting the account that receives the performance fee.
* Initially the `Governor` can upgrade the contracts via a proxy without a time delay. After 6 weeks, this will be changed to a one week time delay.

## Contract Interface

See the Metavaults github repository for [contract diagrams](https://github.com/mstable/metavaults/tree/develop/contracts/vault/meta#diagrams) and [process diagrams](https://github.com/mstable/metavaults/tree/develop/contracts/vault/meta#periodicallocationperffeemetavault-processes).

See [General ERC-4626 Vault Interface](/meta-vaults/general-erc-4626-vault-interface) for the standard ERC-4626 functions.

### Structs

#### Settlement

```solidity
struct Settlement {
  uint256 vaultIndex;
  uint256 assets;
}
```

#### AssetSourcingParams

```solidity
struct AssetSourcingParams {
  uint32 singleVaultSharesThreshold;
  uint32 singleSourceVaultIndex;
}
```

#### Swap

```solidity
struct Swap {
  uint256 fromVaultIndex;
  uint256 toVaultIndex;
  uint256 shares;
  uint256 assets;
}
```

### Variables

#### sourceParams

```solidity
struct AssetSourcingParams sourceParams
```

Params related to sourcing of assets.

#### assetsTransferred

```solidity
uint256 assetsTransferred
```

Amount of assets that are transferred from/to the vault.

#### assetPerShareUpdateThreshold

```solidity
uint256 assetPerShareUpdateThreshold
```

Threshold amount of transfers to/from for `assetPerShareUpdate`.

#### performanceFee

```solidity
uint256 performanceFee
```

Performance fee scaled to 6 decimal places. 1% = 10000, 0.01% = 100

#### perfFeesAssetPerShare

```solidity
uint256 perfFeesAssetPerShare
```

Assets per shares used to calculate performance fees scaled to 26 decimal places.

#### feeReceiver

```solidity
address feeReceiver
```

Account that receives the performance fee as shares.

### Functions

#### settle

```solidity
function settle(struct PeriodicAllocationAbstractVault.Settlement[] settlements) external virtual
```

Invests the assets sitting in the vault from previous deposits and mints into the nominated underlying vaults.

**Parameters**

<table><thead><tr><th width="145.33333333333331">Name</th><th width="278">Type</th><th>Description</th></tr></thead><tbody><tr><td>settlements</td><td>struct PeriodicAllocationAbstractVault.Settlement[]</td><td>A list of asset amounts and underlying vault indices to deposit the assets sitting in the vault.</td></tr></tbody></table>

#### setSingleVaultSharesThreshold

```solidity
function setSingleVaultSharesThreshold(uint32 _singleVaultSharesThreshold) external
```

`Governor` sets the threshold for large withdrawals that withdraw proportionally from all underlying vaults instead of just from a single configured vault. This means smaller `redeem` and `withdraw` txs pay a lot less gas.

**Parameters**

<table><thead><tr><th width="282.3333333333333">Name</th><th width="88">Type</th><th>Description</th></tr></thead><tbody><tr><td>_singleVaultSharesThreshold</td><td>uint32</td><td>Percentage of shares being redeemed in basis points. eg 20% = 2000, 5% = 500</td></tr></tbody></table>

#### setSingleSourceVaultIndex

```solidity
function setSingleSourceVaultIndex(uint32 _singleSourceVaultIndex) external
```

`Governor` sets the underlying vault that small withdrawals are redeemed from.

**Parameters**

<table><thead><tr><th width="231">Name</th><th width="88.33333333333331">Type</th><th>Description</th></tr></thead><tbody><tr><td>_singleSourceVaultIndex</td><td>uint32</td><td>the underlying vault's index position in <code>underlyingVaults</code>. This starts from index 0.</td></tr></tbody></table>

#### setAssetPerShareUpdateThreshold

```solidity
function setAssetPerShareUpdateThreshold(uint256 _assetPerShareUpdateThreshold) external
```

Governor sets the threshold asset amount of cumulative transfers to/from the vault before the assets per share is updated.

**Parameters**

<table><thead><tr><th width="303">Name</th><th width="98.33333333333331">Type</th><th>Description</th></tr></thead><tbody><tr><td>_assetPerShareUpdateThreshold</td><td>uint256</td><td>cumulative asset transfers amount.</td></tr></tbody></table>

#### chargePerformanceFee

```solidity
function chargePerformanceFee() external virtual
```

Vault Manager charges a performance fee since the last time a fee was charged.

As an example, if the assets per share increased by 0.1% in the last week and the performance fee is 4%, the vault shares will be increased by 0.1% \* 4% = 0.004% as a fee. If there was 100,000 vault shares, 4 (100,000 \* 0.004%) vault shares will be minted as a performance fee. This dilutes the assets per shares of the existing vault shareholders by 0.004%. No performance fee is charged if the assets per share drops.

#### setPerformanceFee

```solidity
function setPerformanceFee(uint256 _performanceFee) external
```

Sets a new performance fee after charging to now using the old performance fee.

**Parameters**

<table><thead><tr><th width="186.33333333333331">Name</th><th width="97">Type</th><th>Description</th></tr></thead><tbody><tr><td>_performanceFee</td><td>uint256</td><td>Performance fee scaled to 6 decimal places. 1% = 10000, 0.01% = 100</td></tr></tbody></table>

#### activeUnderlyingVaults

```solidity
function activeUnderlyingVaults() external view virtual returns (uint256 activeVaults)
```

Returns the active number of underlying vaults. This excludes any vaults that have been removed.

**Return Values**

<table><thead><tr><th width="157.33333333333331">Name</th><th width="110">Type</th><th>Description</th></tr></thead><tbody><tr><td>activeVaults</td><td>uint256</td><td>The number of active underlying vaults.</td></tr></tbody></table>

#### totalUnderlyingVaults

```solidity
function totalUnderlyingVaults() external view virtual returns (uint256 totalVaults)
```

Returns the total number of underlying vaults, both active and inactive. The next vault added will have a vault index of this value.

**Return Values**

<table><thead><tr><th width="144.33333333333331">Name</th><th width="112">Type</th><th>Description</th></tr></thead><tbody><tr><td>totalVaults</td><td>uint256</td><td>The number of active and inactive underlying vaults.</td></tr></tbody></table>

#### resolveVaultIndex

```solidity
function resolveVaultIndex(uint256 vaultIndex) public view virtual returns (contract IERC4626Vault vault)
```

Resolves a vault index to an active underlying vault address. This only works for active vaults. A `Inactive vault` error will be thrown if the vault index has not been used or the underlying vault is now inactive.s

**Parameters**

<table><thead><tr><th width="147.33333333333331">Name</th><th width="102">Type</th><th>Description</th></tr></thead><tbody><tr><td>vaultIndex</td><td>uint256</td><td>External vault index used to identify the underlying vault.</td></tr></tbody></table>

**Return Values**

<table><thead><tr><th width="139.33333333333331">Name</th><th width="226">Type</th><th>Description</th></tr></thead><tbody><tr><td>vault</td><td>contract IERC4626Vault</td><td>Address of the underlying vault.</td></tr></tbody></table>

#### rebalance

```solidity
function rebalance(struct SameAssetUnderlyingsAbstractVault.Swap[] swaps) external virtual
```

`VaultManager` rebalances the assets in the underlying vaults. This can be moving assets between underlying vaults, moving assets in underlying vaults back to this vault, or moving assets in this vault to underlying vaults.

#### addVault

```solidity
function addVault(address _underlyingVault) external
```

Adds a new underlying ERC-4626 compliant vault. This Meta Vault approves the new underlying vault to transfer max assets. There is a limit of 15 active underlying vaults. If more vaults are needed, another active vaults will need to be removed first. There is also a limit of 62 underlying vaults that can be used by this Meta Vault over its lifetime. That's both active and inactive vaults.

**Parameters**

<table><thead><tr><th width="194.33333333333331">Name</th><th width="110">Type</th><th>Description</th></tr></thead><tbody><tr><td>_underlyingVault</td><td>address</td><td>Address of a ERC-4626 compliant vault.</td></tr></tbody></table>

#### removeVault

```solidity
function removeVault(uint256 vaultIndex) external
```

Removes an underlying ERC-4626 compliant vault. All underlying shares are redeemed with the assets transferred to this vault.

**Parameters**

<table><thead><tr><th width="145.33333333333331">Name</th><th width="102">Type</th><th>Description</th></tr></thead><tbody><tr><td>vaultIndex</td><td>uint256</td><td>Index of the underlying vault starting from 0.</td></tr></tbody></table>

#### setFeeReceiver

```solidity
function setFeeReceiver(address _feeReceiver) external
```

Called by the protocol Governor to set the fee receiver address.

**Parameters**

<table><thead><tr><th width="164.33333333333331">Name</th><th width="124">Type</th><th>Description</th></tr></thead><tbody><tr><td>_feeReceiver</td><td>address</td><td>Address that will receive the fees.</td></tr></tbody></table>

#### updateAssetPerShare

```solidity
function updateAssetPerShare() external
```

VaultManager can update the `assetPerShare`.

#### calculateAssetPerShare

```solidity
function calculateAssetPerShare() public view returns (uint256 assetsPerShare_, uint256 totalAssets_)
```

calculates current assetsPerShare

**Return Values**

<table><thead><tr><th width="184.33333333333331">Name</th><th width="127">Type</th><th>Description</th></tr></thead><tbody><tr><td>assetsPerShare_</td><td>uint256</td><td>current assetsPerShare</td></tr><tr><td>totalAssets_</td><td>uint256</td><td>totalAssets of the vault</td></tr></tbody></table>


# Convex 3Crv Vaults

ERC-4626 vaults that deposits Curve 3Pool LP tokens (3Crv) in a Curve 3Pool-based Metapool, eg musd3Crv; deposits the Metapool LP token in a [Convex](https://www.convexfinance.com/) pool; and stakes the Convex LP token, eg cvxmusd3Crv, for CRV and CVX rewards.

The Convex rewards are swapped for a Curve 3Pool token, eg DAI, USDC or USDT, using the `Liquidator` module and donated back to the vault. On donation back to the vault, the DAI, USDC or USDT is deposited into the underlying Curve Metapool; the Curve Metapool LP token is deposited into the corresponding Convex pool and the Convex LP token staked.

## Capabilities

* [ERC-4626](https://eips.ethereum.org/EIPS/eip-4626) compliant tokenized vault.
* [ERC-20](https://eips.ethereum.org/EIPS/eip-20) compliant token.
* Invests 3Crv assets in a Curve Metapool and LP token staked in Convex for boosted returns.
* Sandwich attack protection on ERC4626 operations `deposit`, `mint`, `withdraw` and `redeem`.
* Liquidation of Convex rewards like CRV and CVX for more reinvested 3Crv assets.
* Front-running protection against liquidation of rewards by streaming the increase in assets per share.
* Fee charged on liquidated Convex rewards.
* Vault operations are pausable by the `Governor`.
* Emergency asset recovery by the `Governor`. This will be removed after 2 months.
* Vault configuration is controlled by a protocol `Governor`. This includes:
  * Setting the slippage limits for mint, deposit, redeem and withdraw.
  * Setting the account that receives the liquidation fee.
* Initially the `Governor` can upgrade the contracts via a proxy without a time delay. After 6 weeks, this will be changed to a one week time delay.

## Contract Interface

See mStable's metavaults github repository for [contract diagrams](https://github.com/mstable/metavaults/tree/develop/contracts/vault/liquidity/convex#convex-vault-for-3pool-based-curve-metapools-3crv-1) and [process diagrams](https://github.com/mstable/metavaults/tree/develop/contracts/vault/liquidity/convex#processes).

See [General ERC-4626 Vault Interface](/meta-vaults/general-erc-4626-vault-interface) for the standard ERC-4626 functions.

### Variables

#### ASSET\_SCALE

```solidity
uint256 ASSET_SCALE
```

3CRV token scale

#### VIRTUAL\_PRICE\_SCALE

```solidity
uint256 VIRTUAL_PRICE_SCALE
```

#### metapool

```solidity
address metapool
```

Curve.fi pool the 3Crv asset is deposited into. eg musd3CRV, MIM-3LP3CRV-f or usdp3CRV.

#### metapoolToken

```solidity
address metapoolToken
```

Curve.fi Metapool liquidity provider token. eg Curve.fi MUSD/3Crv (musd3CRV)

#### metapoolTokenScale

```solidity
uint256 metapoolTokenScale
```

Scale of the metapool liquidity provider token. eg 1e18 if 18 decimal places.

#### basePool

```solidity
address basePool
```

Curve's 3Pool used as a base pool by the Curve metapools.

#### booster

```solidity
contract IConvexBooster booster
```

Convex's Booster contract that contains the Curve.fi LP pools.

#### convexPoolId

```solidity
uint256 convexPoolId
```

Convex's pool identifier. eg 14 for the musd3CRV pool.

#### baseRewardPool

```solidity
contract IConvexRewardsPool baseRewardPool
```

Convex's base rewards contract for staking Convex's LP token. eg staking cvxmusd3CRV

#### DAI

```solidity
address DAI
```

#### USDC

```solidity
address USDC
```

#### USDT

```solidity
address USDT
```

#### redeemSlippage

```solidity
uint256 redeemSlippage
```

Redeem slippage in basis points i.e. 1% = 100

#### depositSlippage

```solidity
uint256 depositSlippage
```

Deposit slippage in basis points i.e. 1% = 100

#### withdrawSlippage

```solidity
uint256 withdrawSlippage
```

Withdraw slippage in basis points i.e. 1% = 100

#### mintSlippage

```solidity
uint256 mintSlippage
```

Mint slippage in basis points i.e. 1% = 100

### Functions

#### liquidateVault

```solidity
function liquidateVault(uint256 minAssets) external
```

Governor liquidates all the vault's assets and send to the governor. Only to be used in an emergency. eg whitehat protection against a hack.

**Parameters**

<table><thead><tr><th width="126.33333333333331">Name</th><th width="96">Type</th><th>Description</th></tr></thead><tbody><tr><td>minAssets</td><td>uint256</td><td>Minimum amount of asset tokens to receive from removing liquidity from the Curve 3Pool. This provides sandwich attack protection.</td></tr></tbody></table>

#### resetAllowances

```solidity
function resetAllowances() external
```

Approves Curve's 3Pool contract to transfer assets (DAI, USDC or USDT) from this vault. Also approves the underlying Meta Vault to transfer 3Crv from this vault.

#### setDonateToken

```solidity
function setDonateToken(address __donateToken) external
```

Vault manager or governor sets the token the rewards are swapped for and donated back to the vault.

**Parameters**

<table><thead><tr><th width="168.33333333333331">Name</th><th width="123">Type</th><th>Description</th></tr></thead><tbody><tr><td>__donateToken</td><td>address</td><td>a token in the 3Pool (DAI, USDC or USDT).</td></tr></tbody></table>

#### setRedeemSlippage

```solidity
function setRedeemSlippage(uint256 _slippage) external
```

Governor function to set redeem slippage.

**Parameters**

<table><thead><tr><th width="121">Name</th><th width="120">Type</th><th>Description</th></tr></thead><tbody><tr><td>_slippage</td><td>uint256</td><td>Redeem slippage to apply as basis points i.e. 1% = 100</td></tr></tbody></table>

#### setDepositSlippage

```solidity
function setDepositSlippage(uint256 _slippage) external
```

Governor function to set deposit slippage.

**Parameters**

<table><thead><tr><th width="147.33333333333331">Name</th><th width="150">Type</th><th>Description</th></tr></thead><tbody><tr><td>_slippage</td><td>uint256</td><td>Deposit slippage to apply as basis points i.e. 1% = 100</td></tr></tbody></table>

#### setWithdrawSlippage

```solidity
function setWithdrawSlippage(uint256 _slippage) external
```

Governor function to set withdraw slippage.

**Parameters**

<table><thead><tr><th width="137.33333333333331">Name</th><th width="119">Type</th><th>Description</th></tr></thead><tbody><tr><td>_slippage</td><td>uint256</td><td>Withdraw slippage to apply as basis points i.e. 1% = 100</td></tr></tbody></table>

#### setMintSlippage

```solidity
function setMintSlippage(uint256 _slippage) external
```

Governor function to set mint slippage.

**Parameters**

<table><thead><tr><th width="140.33333333333331">Name</th><th width="109">Type</th><th>Description</th></tr></thead><tbody><tr><td>_slippage</td><td>uint256</td><td>Mint slippage to apply as basis points i.e. 1% = 100</td></tr></tbody></table>


# General ERC-4626 Vault Interface

Generic interface for [ERC-4626](https://eips.ethereum.org/EIPS/eip-4626) vaults.

## Contract Interface

### Events

#### Deposit

```solidity
event Deposit(address sender, address receiver, uint256 assets, uint256 shares)
```

#### Withdraw

```solidity
event Withdraw(address sender, address receiver, address owner, uint256 assets, uint256 shares)
```

### Functions

#### asset

```solidity
function asset() external view returns (address assetTokenAddress)
```

The address of the underlying token used by the Vault for valuing, depositing, and withdrawing.

#### totalAssets

```solidity
function totalAssets() external view returns (uint256 totalManagedAssets)
```

Total amount of the underlying asset that is “managed” by vault.

#### convertToShares

```solidity
function convertToShares(uint256 assets) external view returns (uint256 shares)
```

The amount of shares that the Vault would exchange for the amount of assets provided, in an ideal scenario where all the conditions are met.

**Parameters**

<table><thead><tr><th width="101.33333333333331">Name</th><th width="116">Type</th><th>Description</th></tr></thead><tbody><tr><td>assets</td><td>uint256</td><td>The amount of underlying assets to be convert to vault shares.</td></tr></tbody></table>

**Return Values**

<table><thead><tr><th width="118.33333333333331">Name</th><th width="97">Type</th><th>Description</th></tr></thead><tbody><tr><td>shares</td><td>uint256</td><td>The amount of vault shares converted from the underlying assets.</td></tr></tbody></table>

#### convertToAssets

```solidity
function convertToAssets(uint256 shares) external view returns (uint256 assets)
```

The amount of assets that the Vault would exchange for the amount of shares provided, in an ideal scenario where all the conditions are met.

**Parameters**

<table><thead><tr><th width="106.33333333333331">Name</th><th width="115">Type</th><th>Description</th></tr></thead><tbody><tr><td>shares</td><td>uint256</td><td>The amount of vault shares to be converted to the underlying assets.</td></tr></tbody></table>

**Return Values**

<table><thead><tr><th width="106.33333333333331">Name</th><th width="94">Type</th><th>Description</th></tr></thead><tbody><tr><td>assets</td><td>uint256</td><td>The amount of underlying assets converted from the vault shares.</td></tr></tbody></table>

#### maxDeposit

```solidity
function maxDeposit(address caller) external view returns (uint256 maxAssets)
```

The maximum number of underlying assets that caller can deposit.

**Parameters**

<table><thead><tr><th width="107.33333333333331">Name</th><th width="128">Type</th><th>Description</th></tr></thead><tbody><tr><td>caller</td><td>address</td><td>Account that the assets will be transferred from.</td></tr></tbody></table>

**Return Values**

<table><thead><tr><th width="132.33333333333331">Name</th><th width="100">Type</th><th>Description</th></tr></thead><tbody><tr><td>maxAssets</td><td>uint256</td><td>The maximum amount of underlying assets the caller can deposit.</td></tr></tbody></table>

#### previewDeposit

```solidity
function previewDeposit(uint256 assets) external view returns (uint256 shares)
```

Allows an on-chain or off-chain user to simulate the effects of their deposit at the current transaction, given current on-chain conditions.

**Parameters**

<table><thead><tr><th width="106.33333333333331">Name</th><th width="117">Type</th><th>Description</th></tr></thead><tbody><tr><td>assets</td><td>uint256</td><td>The amount of underlying assets to be transferred.</td></tr></tbody></table>

**Return Values**

<table><thead><tr><th width="115.33333333333331">Name</th><th width="111">Type</th><th>Description</th></tr></thead><tbody><tr><td>shares</td><td>uint256</td><td>The amount of vault shares that will be minted.</td></tr></tbody></table>

#### deposit

```solidity
function deposit(uint256 assets, address receiver) external returns (uint256 shares)
```

Mint vault shares to receiver by transferring exact amount of underlying asset tokens from the caller.

**Parameters**

<table><thead><tr><th width="123.33333333333331">Name</th><th width="100">Type</th><th>Description</th></tr></thead><tbody><tr><td>assets</td><td>uint256</td><td>The amount of underlying assets to be transferred to the vault.</td></tr><tr><td>receiver</td><td>address</td><td>The account that the vault shares will be minted to.</td></tr></tbody></table>

**Return Values**

<table><thead><tr><th width="125.33333333333331">Name</th><th width="126">Type</th><th>Description</th></tr></thead><tbody><tr><td>shares</td><td>uint256</td><td>The amount of vault shares that were minted.</td></tr></tbody></table>

#### maxMint

```solidity
function maxMint(address caller) external view returns (uint256 maxShares)
```

The maximum number of vault shares that caller can mint.

**Parameters**

<table><thead><tr><th width="127.33333333333331">Name</th><th width="119">Type</th><th>Description</th></tr></thead><tbody><tr><td>caller</td><td>address</td><td>Account that the underlying assets will be transferred from.</td></tr></tbody></table>

**Return Values**

<table><thead><tr><th width="136.33333333333331">Name</th><th>Type</th><th width="502.66666666666674">Description</th></tr></thead><tbody><tr><td>maxShares</td><td>uint256</td><td>The maximum amount of vault shares the caller can mint.</td></tr></tbody></table>

#### previewMint

```solidity
function previewMint(uint256 shares) external view returns (uint256 assets)
```

Allows an on-chain or off-chain user to simulate the effects of their mint at the current transaction, given current on-chain conditions.

**Parameters**

<table><thead><tr><th width="118.33333333333331">Name</th><th width="91">Type</th><th>Description</th></tr></thead><tbody><tr><td>shares</td><td>uint256</td><td>The amount of vault shares to be minted.</td></tr></tbody></table>

**Return Values**

<table><thead><tr><th width="112.33333333333331">Name</th><th width="96">Type</th><th>Description</th></tr></thead><tbody><tr><td>assets</td><td>uint256</td><td>The amount of underlying assests that will be transferred from the caller.</td></tr></tbody></table>

#### mint

```solidity
function mint(uint256 shares, address receiver) external returns (uint256 assets)
```

Mint exact amount of vault shares to the receiver by transferring enough underlying asset tokens from the caller.

**Parameters**

<table><thead><tr><th width="121.33333333333331">Name</th><th width="94">Type</th><th>Description</th></tr></thead><tbody><tr><td>shares</td><td>uint256</td><td>The amount of vault shares to be minted.</td></tr><tr><td>receiver</td><td>address</td><td>The account the vault shares will be minted to.</td></tr></tbody></table>

**Return Values**

<table><thead><tr><th width="106.33333333333331">Name</th><th width="94">Type</th><th>Description</th></tr></thead><tbody><tr><td>assets</td><td>uint256</td><td>The amount of underlying assets that were transferred from the caller.</td></tr></tbody></table>

#### maxWithdraw

```solidity
function maxWithdraw(address owner) external view returns (uint256 maxAssets)
```

The maximum number of underlying assets that owner can withdraw.

**Parameters**

<table><thead><tr><th width="141.33333333333331">Name</th><th width="138">Type</th><th>Description</th></tr></thead><tbody><tr><td>owner</td><td>address</td><td>Account that owns the vault shares.</td></tr></tbody></table>

**Return Values**

<table><thead><tr><th width="137.33333333333331">Name</th><th width="105">Type</th><th>Description</th></tr></thead><tbody><tr><td>maxAssets</td><td>uint256</td><td>The maximum amount of underlying assets the owner can withdraw.</td></tr></tbody></table>

#### previewWithdraw

```solidity
function previewWithdraw(uint256 assets) external view returns (uint256 shares)
```

Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current transaction, given current on-chain conditions.

**Parameters**

<table><thead><tr><th width="124.33333333333331">Name</th><th width="114">Type</th><th>Description</th></tr></thead><tbody><tr><td>assets</td><td>uint256</td><td>The amount of underlying assets to be withdrawn.</td></tr></tbody></table>

**Return Values**

<table><thead><tr><th width="120.33333333333331">Name</th><th width="116">Type</th><th>Description</th></tr></thead><tbody><tr><td>shares</td><td>uint256</td><td>The amount of vault shares that will be burnt.</td></tr></tbody></table>

#### withdraw

```solidity
function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares)
```

Burns enough vault shares from owner and transfers the exact amount of underlying asset tokens to the receiver.

**Parameters**

<table><thead><tr><th width="113.33333333333331">Name</th><th width="112">Type</th><th>Description</th></tr></thead><tbody><tr><td>assets</td><td>uint256</td><td>The amount of underlying assets to be withdrawn from the vault.</td></tr><tr><td>receiver</td><td>address</td><td>The account that the underlying assets will be transferred to.</td></tr><tr><td>owner</td><td>address</td><td>Account that owns the vault shares to be burnt.</td></tr></tbody></table>

**Return Values**

<table><thead><tr><th width="122.33333333333331">Name</th><th width="116">Type</th><th>Description</th></tr></thead><tbody><tr><td>shares</td><td>uint256</td><td>The amount of vault shares that were burnt.</td></tr></tbody></table>

#### maxRedeem

```solidity
function maxRedeem(address owner) external view returns (uint256 maxShares)
```

The maximum number of shares an owner can redeem for underlying assets.

**Parameters**

<table><thead><tr><th width="129.33333333333331">Name</th><th width="113">Type</th><th>Description</th></tr></thead><tbody><tr><td>owner</td><td>address</td><td>Account that owns the vault shares.</td></tr></tbody></table>

**Return Values**

<table><thead><tr><th width="141.33333333333331">Name</th><th width="100">Type</th><th>Description</th></tr></thead><tbody><tr><td>maxShares</td><td>uint256</td><td>The maximum amount of shares the owner can redeem.</td></tr></tbody></table>

#### previewRedeem

```solidity
function previewRedeem(uint256 shares) external view returns (uint256 assets)
```

Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current transaction, given current on-chain conditions.

**Parameters**

<table><thead><tr><th width="115.33333333333331">Name</th><th width="97">Type</th><th>Description</th></tr></thead><tbody><tr><td>shares</td><td>uint256</td><td>The amount of vault shares to be burnt.</td></tr></tbody></table>

**Return Values**

<table><thead><tr><th width="108.33333333333331">Name</th><th width="108">Type</th><th>Description</th></tr></thead><tbody><tr><td>assets</td><td>uint256</td><td>The amount of underlying assests that will transferred to the receiver.</td></tr></tbody></table>

#### redeem

```solidity
function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets)
```

Burns exact amount of vault shares from owner and transfers the underlying asset tokens to the receiver.

**Parameters**

<table><thead><tr><th width="121.33333333333331">Name</th><th width="104">Type</th><th>Description</th></tr></thead><tbody><tr><td>shares</td><td>uint256</td><td>The amount of vault shares to be burnt.</td></tr><tr><td>receiver</td><td>address</td><td>The account the underlying assets will be transferred to.</td></tr><tr><td>owner</td><td>address</td><td>The account that owns the vault shares to be burnt.</td></tr></tbody></table>

**Return Values**

<table><thead><tr><th width="104.33333333333331">Name</th><th width="97">Type</th><th>Description</th></tr></thead><tbody><tr><td>assets</td><td>uint256</td><td>The amount of underlying assets that were transferred to the receiver.</td></tr></tbody></table>


# Liquidator

The Liquidator module is responsible for collecting reward tokens from vaults, swapping them and donating back the purchased tokens to the vaults. Typically, this is swapping reward tokens to vault assets which are donated back to the vaults to increase their assets per share. For example, swapping $CRV earned in a Curve pool back to a vault asset like $DAI. There can be multiple reward tokens collected from a vault and different target tokens can be specified for each reward token.

The Liquidator's main task is to batch the swapping of rewards collected from multiple vaults. This socializes the gas costs in swapping rewards across multiple vaults.

The Liquidator uses a [Swapper](https://github.com/mstable/metavaults/blob/main/contracts/vault/swap/README.md) module to do on-chain token swaps. A swapper typically uses a swap aggregator like 1Inch or CowSwap but can use decentralized exchanges like Uniswap or Balancer.

## Liquidator Contracts

<table><thead><tr><th width="161">Contract</th><th>Address</th></tr></thead><tbody><tr><td><a href="https://github.com/mstable/metavaults/blob/main/contracts/vault/liquidator/Liquidator.sol">Liquidator</a></td><td><a href="https://etherscan.io/address/0xD298291059aed77686037aEfFCf497A321A4569e">0xD298291059aed77686037aEfFCf497A321A4569e</a></td></tr><tr><td><a href="https://github.com/mstable/metavaults/blob/main/contracts/vault/swap/CowSwapDex.sol">CowSwapDex</a></td><td><a href="https://etherscan.io/address/0xB305372B12Fd5d736EcB6BF903eaA844f2a23112">0xB305372B12Fd5d736EcB6BF903eaA844f2a23112</a></td></tr></tbody></table>

### Contract Interface

See the metavaults github repository for [contract diagrams](https://github.com/mstable/metavaults/tree/main/contracts/vault/liquidator#diagrams) and [process diagrams](https://github.com/mstable/metavaults/tree/main/contracts/vault/liquidator#processes).

### Variables

#### syncSwapper

```solidity
contract IDexSwap syncSwapper
```

Contract that implements on-chain swaps

#### asyncSwapper

```solidity
contract IDexAsyncSwap asyncSwapper
```

Contract that implements on-chain async swaps

### Functions

#### collectRewards

```solidity
function collectRewards(address[] vaults) external returns (address[][] rewardTokens, uint256[][] rewards, address[][] purchaseTokens)
```

The keeper or governor can collect different rewards from a list of vaults. The Liquidator calls each vault to collect their rewards. The vaults transfer the rewards to themselves first and then the Liquidator transfers each reward from each vault to the Liquidator. Vault rewards can be collect multiple times before they are swapped for the vault asset. It's the responsibility of the Liquidator to account for how many rewards were collected from each vault.

**Parameters**

<table><thead><tr><th width="185.33333333333331">Name</th><th width="128">Type</th><th>Description</th></tr></thead><tbody><tr><td>vaults</td><td>address[]</td><td>List of vault addresses to collect rewards from.</td></tr></tbody></table>

**Return Values**

<table><thead><tr><th width="184.33333333333331">Name</th><th width="128">Type</th><th>Description</th></tr></thead><tbody><tr><td>rewardTokens</td><td>address[][]</td><td>Reward token addresses for each vault. The first dimension is vault from the <code>vaults</code> param. The second dimension is the index of the reward token within the vault.</td></tr><tr><td>rewards</td><td>uint256[][]</td><td>Amount of reward tokens collected for each vault. The first dimension is vault from the <code>vaults</code> param. The second dimension is the index of the reward token within the vault.</td></tr><tr><td>purchaseTokens</td><td>address[][]</td><td>The token to purchase for each of the rewards. The first dimension is vault from the <code>vaults</code> param. The second dimension is the index of the reward token within the vault.</td></tr></tbody></table>

#### donateTokens

```solidity
function donateTokens(address[] rewardTokens, address[] purchaseTokens, address[] vaults) external returns (uint256[] assets)
```

The protocol Governor or Keeper can send the purchased assets in a batch back to the vaults. The order of the input elements is important to aggreate multiple deposits of the same asset to the vault.

ie. Vault 1 has Reward A, Reward B, both rewards are swapped for the same donated Token T.

* donateTokens(\[rewardA.address, rewardB.address], \[tokenT.address, tokenT.address], \[vault1.Address, vault1.Address] Only triggers one deposit of Token T to the underlying vault

**Parameters**

<table><thead><tr><th width="179.33333333333331">Name</th><th width="108">Type</th><th>Description</th></tr></thead><tbody><tr><td>rewardTokens</td><td>address[]</td><td>List of addresses of the reward token that was sold.</td></tr><tr><td>purchaseTokens</td><td>address[]</td><td>List of addresses of the token that was purchased.</td></tr><tr><td>vaults</td><td>address[]</td><td>List of addresses for the vaults with the reward to asset pair.</td></tr></tbody></table>

**Return Values**

<table><thead><tr><th width="107.33333333333331">Name</th><th width="120">Type</th><th>Description</th></tr></thead><tbody><tr><td>assets</td><td>uint256[]</td><td>Amount of asset tokens purchased for each different vault in the <code>vaults</code> parameter.</td></tr></tbody></table>

#### claimAssets

```solidity
function claimAssets(uint256 batch, address rewardToken, address assetToken) external returns (uint256 assets)
```

Vault claims the purchased assets in a batch back. Separate transactions are required if a vault has multiple reward tokens.

**Parameters**

<table><thead><tr><th width="154.33333333333331">Name</th><th width="102">Type</th><th>Description</th></tr></thead><tbody><tr><td>batch</td><td>uint256</td><td>Liquidation batch index from the previously executed <code>swap</code>.</td></tr><tr><td>rewardToken</td><td>address</td><td>Address of the reward token that was sold.</td></tr><tr><td>assetToken</td><td>address</td><td>Address of the asset token that was purchased.</td></tr></tbody></table>

**Return Values**

<table><thead><tr><th width="122.33333333333331">Name</th><th width="107">Type</th><th>Description</th></tr></thead><tbody><tr><td>assets</td><td>uint256</td><td>Amount of asset tokens purchased in the batch.</td></tr></tbody></table>

#### pendingRewards

```solidity
function pendingRewards(address rewardToken, address assetToken) external view returns (uint256 batch, uint256 rewards)
```

**Parameters**

<table><thead><tr><th width="145.33333333333331">Name</th><th width="110">Type</th><th>Description</th></tr></thead><tbody><tr><td>rewardToken</td><td>address</td><td>Address of the rewards being sold.</td></tr><tr><td>assetToken</td><td>address</td><td>Address of the assets being purchased.</td></tr></tbody></table>

**Return Values**

<table><thead><tr><th width="116.33333333333331">Name</th><th width="98">Type</th><th>Description</th></tr></thead><tbody><tr><td>batch</td><td>uint256</td><td>Current liquidation batch index.</td></tr><tr><td>rewards</td><td>uint256</td><td>Amount of reward tokens that are waiting to be swapped.</td></tr></tbody></table>

#### pendingVaultRewards

```solidity
function pendingVaultRewards(address rewardToken, address assetToken, address vault) external view returns (uint256 batch, uint256 rewards)
```

**Parameters**

<table><thead><tr><th width="143.33333333333331">Name</th><th width="103">Type</th><th>Description</th></tr></thead><tbody><tr><td>rewardToken</td><td>address</td><td>Address of the rewards being sold.</td></tr><tr><td>assetToken</td><td>address</td><td>Address of the assets being purchased.</td></tr><tr><td>vault</td><td>address</td><td>Address of the vault with the reward to asset pair.</td></tr></tbody></table>

**Return Values**

<table><thead><tr><th width="123.33333333333331">Name</th><th width="104">Type</th><th>Description</th></tr></thead><tbody><tr><td>batch</td><td>uint256</td><td>Current liquidation batch index.</td></tr><tr><td>rewards</td><td>uint256</td><td>Amount of reward tokens that are waiting to be swapped.</td></tr></tbody></table>

#### purchasedAssets

```solidity
function purchasedAssets(uint256 batch, address rewardToken, address assetToken, address vault) external view returns (uint256 assets)
```

**Parameters**

<table><thead><tr><th width="149.33333333333331">Name</th><th width="97">Type</th><th>Description</th></tr></thead><tbody><tr><td>batch</td><td>uint256</td><td>Liquidation batch index from the previously executed <code>swap</code>.</td></tr><tr><td>rewardToken</td><td>address</td><td>Address of the reward token that was sold.</td></tr><tr><td>assetToken</td><td>address</td><td>Address of the asset token that was purchased.</td></tr><tr><td>vault</td><td>address</td><td>Address of the vault with the reward to asset pair.</td></tr></tbody></table>

**Return Values**

<table><thead><tr><th width="104.33333333333331">Name</th><th width="95">Type</th><th>Description</th></tr></thead><tbody><tr><td>assets</td><td>uint256</td><td>Amount of asset tokens purchased and not yet claimed. It is zero if assets have already been claimed.</td></tr></tbody></table>

#### swap

```solidity
function swap(address rewardToken, address assetToken, uint256 minAssets, bytes data) external returns (uint256 batch, uint256 rewards, uint256 assets)
```

Swap the collected rewards to desired asset.

**Parameters**

<table><thead><tr><th width="148.33333333333331">Name</th><th width="96">Type</th><th>Description</th></tr></thead><tbody><tr><td>rewardToken</td><td>address</td><td>Address of the rewards being sold.</td></tr><tr><td>assetToken</td><td>address</td><td>Address of the assets being purchased.</td></tr><tr><td>minAssets</td><td>uint256</td><td>Minimum amount of assets that can be returned from the swap.</td></tr><tr><td>data</td><td>bytes</td><td>Is specific for the swap implementation. eg 1Inch, Cowswap, Matcha...</td></tr></tbody></table>

#### initiateSwap

```solidity
function initiateSwap(address rewardToken, address assetToken, bytes data) external returns (uint256 batch, uint256 rewards)
```

Swap the collected rewards to desired asset. Off-chain order must be created providing a "receiver" of the swap.

**Parameters**

<table><thead><tr><th width="148.33333333333331">Name</th><th width="100">Type</th><th>Description</th></tr></thead><tbody><tr><td>rewardToken</td><td>address</td><td>Address of the rewards being sold.</td></tr><tr><td>assetToken</td><td>address</td><td>Address of the assets being purchased.</td></tr><tr><td>data</td><td>bytes</td><td>Is specific for the swap implementation. eg Cowswap, Matcha...</td></tr></tbody></table>

#### initiateSwaps

```solidity
function initiateSwaps(address[] rewardTokens, address[] assetTokens, bytes[] datas) external returns (uint256[] batchs, uint256[] rewards)
```

Swaps the collected rewards to desired assets. Off-chain order must be created providing a "receiver" of the swap.

**Parameters**

<table><thead><tr><th width="162.33333333333331">Name</th><th width="109">Type</th><th>Description</th></tr></thead><tbody><tr><td>rewardTokens</td><td>address[]</td><td>Address of the rewards being sold.</td></tr><tr><td>assetTokens</td><td>address[]</td><td>Address of the assets being purchased.</td></tr><tr><td>datas</td><td>bytes[]</td><td>Is specific for the swap implementation. eg Cowswap, Matcha...</td></tr></tbody></table>

#### settleSwap

```solidity
function settleSwap(address rewardToken, address assetToken, uint256 assets, bytes data) external returns (uint256 batch, uint256 rewards)
```

settles the last batch swap of rewards for assets. `initiateSwap` must be called and the swap executed before `settleSwap`.

**Parameters**

<table><thead><tr><th width="150.33333333333331">Name</th><th width="104">Type</th><th>Description</th></tr></thead><tbody><tr><td>rewardToken</td><td>address</td><td>Address of the rewards being sold.</td></tr><tr><td>assetToken</td><td>address</td><td>Address of the assets being purchased.</td></tr><tr><td>assets</td><td>uint256</td><td>Amount of purchaed assets received from the swap.</td></tr><tr><td>data</td><td>bytes</td><td></td></tr></tbody></table>

#### settleSwaps

```solidity
function settleSwaps(address[] rewardTokens, address[] assetTokens, uint256[] assets, bytes[] datas) external returns (uint256[] batchs, uint256[] rewards)
```

Swaps the collected rewards to desired assets. initiateSwap must be called first before settleSwap

**Parameters**

<table><thead><tr><th width="163.33333333333331">Name</th><th width="119">Type</th><th>Description</th></tr></thead><tbody><tr><td>rewardTokens</td><td>address[]</td><td>Address of the rewards being sold.</td></tr><tr><td>assetTokens</td><td>address[]</td><td>Address of the assets being purchased.</td></tr><tr><td>assets</td><td>uint256[]</td><td>Amount of assets to swapped.</td></tr><tr><td>datas</td><td>bytes[]</td><td>Custom data for the swap.</td></tr></tbody></table>

#### setSyncSwapper

```solidity
function setSyncSwapper(address _syncSwapper) external
```

Sets a new implementation of the DEX syncSwapper.

**Parameters**

<table><thead><tr><th width="168.33333333333331">Name</th><th width="103">Type</th><th>Description</th></tr></thead><tbody><tr><td>_syncSwapper</td><td>address</td><td>Address of the DEX syncSwapper.</td></tr></tbody></table>

#### setAsyncSwapper

```solidity
function setAsyncSwapper(address _asyncSwapper) external
```

Sets a new implementation of the DEX asyncSwapper.

**Parameters**

<table><thead><tr><th width="177.33333333333331">Name</th><th width="121">Type</th><th>Description</th></tr></thead><tbody><tr><td>_asyncSwapper</td><td>address</td><td>Address of the DEX asyncSwapper.</td></tr></tbody></table>

#### rescueToken

```solidity
function rescueToken(address token, uint256 amount) external
```

Governor rescues tokens from the liquidator in case a vault's donateToken is failing.


# mAssets

Meta Assets (mAssets) are assets that are composed of other underlying similar assets. Currently, deployed mAssets are mUSD and mBTC.

An incentivised constant sum market maker with hard limits at max region. This supports low slippage swaps and applies penalties towards min and max regions. AMM produces a stablecoin (mAsset) and redirects lending market interest and swap fees to the savings contract, producing a second yield-bearing asset.

`_minOutputQuantity` is used to limit slippage when swapping, minting or redeeming. Useful for preventing Sandwich and Frontrunning attacks.

Contracts are upgradable except for integration contracts. The ProtocolDAO multisig can migrate the assets from one integration contract to another.

{% tabs %}
{% tab title="Ethereum Mainnet" %}

| Contracts                                                                                                                                      | Address                                                                                                               |
| ---------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| [mUSD](https://github.com/mstable/mStable-contracts/blob/master/contracts%2Fmasset%2FMasset.sol)                                               | [0xe2f2a5c287993345a840db3b0845fbc70f5935a5](https://etherscan.io/address/0xe2f2a5c287993345a840db3b0845fbc70f5935a5) |
| [mBTC](https://github.com/mstable/mStable-contracts/blob/master/contracts%2Fmasset%2FMasset.sol)                                               | [0x945facb997494cc2570096c74b5f66a3507330a1](https://etherscan.io/token/0x945facb997494cc2570096c74b5f66a3507330a1)   |
| [mUSD Aave V2 Integration](https://github.com/mstable/mStable-contracts/blob/master/contracts%2Fmasset%2Fperipheral%2FAaveV2Integration.sol)   | [0xa2a3cae63476891ab2d640d9a5a800755ee79d6e](https://etherscan.io/address/0xa2a3cae63476891ab2d640d9a5a800755ee79d6e) |
| [mUSD Compound Integration](https://github.com/mstable/mStable-contracts/blob/master/contracts%2Fmasset%2Fperipheral%2FCompoundInegration.sol) | [0xd55684f4369040c12262949ff78299f2bc9db735](https://etherscan.io/address/0xd55684f4369040c12262949ff78299f2bc9db735) |
| [mBTC Aave V2 Integration](https://github.com/mstable/mStable-contracts/blob/master/contracts%2Fmasset%2Fperipheral%2FAaveV2Integration.sol)   | [0xC9451a4483d1752a3E9A3f5D6b1C7A6c34621fC6](https://etherscan.io/address/0xC9451a4483d1752a3E9A3f5D6b1C7A6c34621fC6) |
| {% endtab %}                                                                                                                                   |                                                                                                                       |

{% tab title="Ropsten Testnet" %}

| Contract                      | Address                                    |
| ----------------------------- | ------------------------------------------ |
| mUSD                          | 0x4E1000616990D83e56f4b5fC6CC8602DcfD20459 |
| Interest Bearing mUSD (imUSD) | 0x5b7f01dAe6BCE656c9cA4175Eb3E406ADC6c7957 |
| imUSD Savings Vault (v-imUSD) | 0xDEFc008BAC1e38F13F081DDD20acf89985DFa7C8 |
| mBTC                          | 0x4A677A48A790f26eac4c97f495E537558Abf6A79 |
| {% endtab %}                  |                                            |
| {% endtabs %}                 |                                            |

Both mAssets (mUSD and mBTC) follow the ERC20 standard. The non-standard [`decreaseAllowance`](https://docs.openzeppelin.com/contracts/2.x/api/token/erc20#ERC20-decreaseAllowance-address-uint256-) and [`increaseAllowance`](https://docs.openzeppelin.com/contracts/2.x/api/token/erc20#ERC20-increaseAllowance-address-uint256-) functions have been added to mitigate the well-known issues around setting allowances. These are based on the OpenZeppelin ERC20 implementation.

The following list describes functions that are part of this implementation and cover both assets.

## ERC-20 Functions

### totalSupply()

`function totalSupply () external returns (uint256)`

Returns the amount of tokens in existence.

### balanceOf()

`function balanceOf () external returns (uint256)`

Returns the amount of tokens owned by `account`.

### transfer()

`function transfer () external returns (bool)`

Moves `amount` tokens from the caller's account to `recipient`.

Returns a boolean value indicating whether the operation succeeded.

Emits a {Transfer} event.

### allowance()

`function allowance () external returns (uint256)`

Returns the remaining number of tokens that`spender`will be allowed to spend on behalf of`owner`through {transferFrom}. This is zero by default.

This value changes when {approve} or {transferFrom} are called.

### approve()

`function approve () external returns (bool)`

Sets `amount` as the allowance of `spender` over the caller's tokens.

Returns a boolean value indicating whether the operation succeeded.

IMPORTANT: Beware that changing an allowance with this method brings the risk that someone may use both the old and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: <https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729>

Emits an {Approval} event.

### transferFrom()

`function transferFrom () external returns (bool)`

Moves `amount` tokens from `sender` to `recipient` using the allowance mechanism. `amount` is then deducted from the caller's allowance.

Returns a boolean value indicating whether the operation succeeded.

Emits a {Transfer} event.&#x20;

### increaseAllowance()

`function increaseAllowance () public returns (bool)`

Atomically increases the allowance granted to `spender` by the caller.

This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}.

Emits an {Approval} event indicating the updated allowance.

Requirements:

* `spender` cannot be the zero address.

### decreaseAllowance()

`function decreaseAllowance () public returns (bool)`

Atomically decreases the allowance granted to `spender` by the caller.

This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}.

Emits an {Approval} event indicating the updated allowance.

Requirements:

* `spender` cannot be the zero address.
* `spender` must have allowance for the caller of at least

  `subtractedValue`.

## mAsset Functions

### mint()

`function mint (address _input, uint256 _inputQuantity, uint256 _minOutputQuantity, address _recipient) external returns (uint256 mintOutput)`

Mint a single bAsset, at a 1:1 ratio with the bAsset. This contract must have approval to spend the senders bAsset

| Parameter            | Type    | Description                                                           |
| -------------------- | ------- | --------------------------------------------------------------------- |
| `_input`             | address | Address of the bAsset to deposit for the minted mAsset.               |
| `_inputQuantity`     | uint256 | Quantity in bAsset units                                              |
| `_minOutputQuantity` | uint256 | Minimum mAsset quantity to be minted. This protects against slippage. |
| `_recipient`         | address | Recipient of the newly minted mAsset tokens                           |

### mintMulti()

`function mintMulti (address[] _inputs, uint256[] _inputQuantities, uint256 _minOutputQuantity, address _recipient) external returns (uint256 mintOutput)`

Mint with multiple bAssets, at a 1:1 ratio to mAsset. This contract must have approval to spend the senders bAssets

| Parameter            | Type       | Description                                                                                                        |
| -------------------- | ---------- | ------------------------------------------------------------------------------------------------------------------ |
| `_inputs`            | address\[] | Non-duplicate address array of bASset addresses to deposit for the minted mAsset tokens.                           |
| `_inputQuantities`   | uint256\[] | Quantity of each bAsset to deposit for the minted mAsset. Order of array should mirror the above bAsset addresses. |
| `_minOutputQuantity` | uint256    | Minimum mAsset quantity to be minted. This protects against slippage.                                              |
| `_recipient`         | address    | Address to receive the newly minted mAsset tokens                                                                  |

### getMintOutput()

`function getMintOutput (address _input, uint256 _inputQuantity) external returns (uint256 mintOutput)`

Get the projected output of a given mint

| Parameter        | Type    | Description                                            |
| ---------------- | ------- | ------------------------------------------------------ |
| `_input`         | address | Address of the bAsset to deposit for the minted mAsset |
| `_inputQuantity` | uint256 | Quantity in bAsset units                               |

### getMintMultiOutput()

`function getMintMultiOutput (address[] _inputs, uint256[] _inputQuantities) external returns (uint256 mintOutput)`

Get the projected output of a given mint

| Parameter          | Type       | Description                                                                                  |
| ------------------ | ---------- | -------------------------------------------------------------------------------------------- |
| `_inputs`          | address\[] | Non-duplicate address array of addresses to bAssets to deposit for the minted mAsset tokens. |
| `_inputQuantities` | uint256\[] | Quantity of each bAsset to deposit for the minted mAsset.                                    |

### swap()

`function swap (address _input, address _output, uint256 _inputQuantity, uint256 _minOutputQuantity, address _recipient) external returns (uint256 swapOutput)`

Swaps one bAsset for another bAsset using the bAsset addresses. bAsset <> bAsset swaps will incur a small fee (swapFee()).

| Parameter            | Type    | Description                                                               |
| -------------------- | ------- | ------------------------------------------------------------------------- |
| `_input`             | address | Address of bAsset to deposit                                              |
| `_output`            | address | Address of bAsset to receive                                              |
| `_inputQuantity`     | uint256 | Units of input bAsset to swap                                             |
| `_minOutputQuantity` | uint256 | Minimum quantity of the swap output asset. This protects against slippage |
| `_recipient`         | address | Address to transfer output asset to                                       |

### getSwapOutput()

`function getSwapOutput (address _input, address _output, uint256 _inputQuantity) external returns (uint256 swapOutput)`

Determines both if a trade is valid, and the expected fee or output. Swap is valid if it does not result in the input asset exceeding its maximum weight.

| Parameter        | Type    | Description                   |
| ---------------- | ------- | ----------------------------- |
| `_input`         | address | Address of bAsset to deposit  |
| `_output`        | address | Address of bAsset to receive  |
| `_inputQuantity` | uint256 | Units of input bAsset to swap |

### redeem()

`function redeem (address _output, uint256 _mAssetQuantity, uint256 _minOutputQuantity, address _recipient) external returns (uint256 outputQuantity)`

Redeems a specified quantity of mAsset in return for a bAsset specified by bAsset address. The bAsset is sent to the specified recipient. The bAsset quantity is relative to current vault balance levels and desired mAsset quantity. The quantity of mAsset is burnt as payment. A minimum quantity of bAsset is specified to protect against price slippage between the mAsset and bAsset.

| Parameter            | Type    | Description                                                                               |
| -------------------- | ------- | ----------------------------------------------------------------------------------------- |
| `_output`            | address | Address of the bAsset to receive                                                          |
| `_mAssetQuantity`    | uint256 | Quantity of mAsset to redeem                                                              |
| `_minOutputQuantity` | uint256 | Minimum bAsset quantity to receive for the burnt mAssets. This protects against slippage. |
| `_recipient`         | address | Address to transfer the withdrawn bAssets to.                                             |

### redeemMasset()

`function redeemMasset (uint256 _mAssetQuantity, uint256[] _minOutputQuantities, address _recipient) external returns (uint256[] outputQuantities)`

Credits a recipient with a proportionate amount of bAssets, relative to current vault balance levels and desired mAsset quantity. Burns the mAsset as payment.

| Parameter              | Type       | Description                             |
| ---------------------- | ---------- | --------------------------------------- |
| `_mAssetQuantity`      | uint256    | Quantity of mAsset to redeem            |
| `_minOutputQuantities` | uint256\[] | Min units of output to receive          |
| `_recipient`           | address    | Address to credit the withdrawn bAssets |

### redeemExactBassets()

`function redeemExactBassets (address[] _outputs, uint256[] _outputQuantities, uint256 _maxMassetQuantity, address _recipient) external returns (uint256 mAssetQuantity)`

Credits a recipient with a certain quantity of selected bAssets, in exchange for burning the relative Masset quantity from the sender. Sender also incurs a small fee on the outgoing asset.

| Parameter            | Type       | Description                                                                               |
| -------------------- | ---------- | ----------------------------------------------------------------------------------------- |
| `_outputs`           | address\[] | Addresses of the bAssets to receive                                                       |
| `_outputQuantities`  | uint256\[] | Units of the bAssets to redeem                                                            |
| `_maxMassetQuantity` | uint256    | Maximum mAsset quantity to burn for the received bAssets. This protects against slippage. |
| `_recipient`         | address    | Address to receive the withdrawn bAssets                                                  |

### getRedeemOutput()

`function getRedeemOutput (address _output, uint256 _mAssetQuantity) external returns (uint256 bAssetOutput)`

Gets the estimated output from a given redeem

| Parameter         | Type    | Description                      |
| ----------------- | ------- | -------------------------------- |
| `_output`         | address | Address of the bAsset to receive |
| `_mAssetQuantity` | uint256 | Quantity of mAsset to redeem     |

### getRedeemExactBassetsOutput()

`function getRedeemExactBassetsOutput (address[] _outputs, uint256[] _outputQuantities) external returns (uint256 mAssetQuantity)`

Gets the estimated output from a given redeem

| Parameter           | Type       | Description                        |
| ------------------- | ---------- | ---------------------------------- |
| `_outputs`          | address\[] | Addresses of the bAsset to receive |
| `_outputQuantities` | uint256\[] | Quantities of bAsset to redeem     |

### getBasket()

`function getBasket () external returns (bool, bool)`

Get basket details for `Masset_MassetStructs.Basket`

### getBassets()

`function getBassets () external returns (struct MassetStructs.BassetPersonal[] personal, struct MassetStructs.BassetData[] data)`

Get data for a all bAssets in basket

### getBasset()

`function getBasset (address _bAsset) external returns (struct MassetStructs.BassetPersonal personal, struct MassetStructs.BassetData data)`

Get data for a specific bAsset, if it exists

| Parameter | Type    | Description       |
| --------- | ------- | ----------------- |
| `_bAsset` | address | Address of bAsset |

### getConfig()

`function getConfig () external returns (struct MassetStructs.InvariantConfig config)`

Gets all config needed for general InvariantValidator calls


# imAssets (SAVE)

imAssets are interest-bearing mAssets. They represent the deposited mAsset in SAVE and accrue in value.

Contracts are upgradable.

{% tabs %}
{% tab title="Ethereum Mainnet" %}

| Contracts                                                                                                   | Address                                                                                                             |
| ----------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
| [imUSD](https://github.com/mstable/mStable-contracts/blob/master/contracts%2Fsavings%2FSavingsContract.sol) | [0x30647a72dc82d7fbb1123ea74716ab8a317eac19](https://etherscan.io/token/0x30647a72dc82d7fbb1123ea74716ab8a317eac19) |
| [imBTC](https://github.com/mstable/mStable-contracts/blob/master/contracts%2Fsavings%2FSavingsContract.sol) | [0x17d8cbb6bce8cee970a4027d1198f6700a7a6c24](https://etherscan.io/token/0x17d8cbb6bce8cee970a4027d1198f6700a7a6c24) |
| {% endtab %}                                                                                                |                                                                                                                     |

{% tab title="Ropsten Testnet" %}

| Contract      | Address                                    |
| ------------- | ------------------------------------------ |
| imUSD         | 0x5b7f01dAe6BCE656c9cA4175Eb3E406ADC6c7957 |
| imBTC         | 0xBfe31D984d688628d06Ae2Da1D640Cf5D9e242A5 |
| {% endtab %}  |                                            |
| {% endtabs %} |                                            |

Both imAssets (imUSD and imBTC) follow the ERC20 and ERC4626 standards:&#x20;

For ERC20, the non-standard [`decreaseAllowance`](https://docs.openzeppelin.com/contracts/2.x/api/token/erc20#ERC20-decreaseAllowance-address-uint256-) and [`increaseAllowance`](https://docs.openzeppelin.com/contracts/2.x/api/token/erc20#ERC20-increaseAllowance-address-uint256-) functions have been added to mitigate the well-known issues around setting allowances. These are based on the OpenZeppelin ERC20 implementation.

For [ERC4626: Tokenized Vault Standard](https://eips.ethereum.org/EIPS/eip-4626), the non-standard functions `deposit(uint256 assets, address receiver, address referrer)` and `shares(uint256 shares, address receiver, address referrer)`  have been added to be used with the [Alliance Referral program](https://mips.mstable.org/MIPS/mip-22.html)

The following list describes functions that are part of this implementation and cover both assets.

## ERC-4626 Functions&#x20;

### asset()

`function asset() external view returns (address assetTokenAddress);`

The address of the underlying token used for the Vault uses for accounting, depositing, and withdrawing.

### totalAssets()

`function totalAssets() external view returns (uint256 totalManagedAssets);`

Total amount of the underlying asset that is “managed” by Vault.

### convertToShares()

`function convertToShares(uint256 assets) external view returns (uint256 shares);`

The amount of shares that the Vault would exchange for the amount of assets provided, in an ideal scenario where all the conditions are met.

<table data-header-hidden><thead><tr><th>Parameter</th><th width="150">Type</th><th>Description</th></tr></thead><tbody><tr><td>Parameter</td><td>Type</td><td>Description</td></tr><tr><td><code>assets</code></td><td>uint256</td><td>The amount of underlying assets to be convert to vault shares.</td></tr></tbody></table>

### convertToAssets()

`function convertToAssets(uint256 shares) external view returns (uint256 assets);`

The amount of assets that the Vault would exchange for the amount of shares provided, in an ideal scenario where all the conditions are met.

<table data-header-hidden><thead><tr><th>Parameter</th><th width="150">Type</th><th>Description</th></tr></thead><tbody><tr><td>Parameter</td><td>Type</td><td>Description</td></tr><tr><td><code>shares</code></td><td>uint256</td><td>The amount of vault shares to be converted to the underlying assets.</td></tr></tbody></table>

### maxDeposit()

`function maxDeposit(address caller) external view returns (uint256 maxAssets);`

The maximum number of underlying assets that caller can deposit.

<table data-header-hidden><thead><tr><th>Parameter</th><th width="150">Type</th><th>Description</th></tr></thead><tbody><tr><td>Parameter</td><td>Type</td><td>Description</td></tr><tr><td><code>caller</code></td><td>address</td><td>Account that the assets will be transferred from.</td></tr></tbody></table>

### previewDeposit()

`function previewDeposit(uint256 assets) external view returns (uint256 shares);`

Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given current on-chain conditions.

<table data-header-hidden><thead><tr><th>Parameter</th><th width="150">Type</th><th>Description</th></tr></thead><tbody><tr><td>Parameter</td><td>Type</td><td>Description</td></tr><tr><td><code>assets</code></td><td>uint256</td><td>The amount of underlying assets to be convert to vault shares.</td></tr></tbody></table>

### deposit()

`function deposit(uint256 assets, address receiver) external returns (uint256 shares);`

Mint vault shares to receiver by transferring exact amount of underlying asset tokens from the caller.

<table data-header-hidden><thead><tr><th>Parameter</th><th width="150">Type</th><th>Description</th></tr></thead><tbody><tr><td>Parameter</td><td>Type</td><td>Description</td></tr><tr><td><code>assets</code></td><td>uint256</td><td>The amount of underlying assets to be convert to vault shares.</td></tr><tr><td><code>receiver</code></td><td>address</td><td>The account that the vault shares will be minted to.</td></tr></tbody></table>

### deposit()

`function deposit(uint256 assets, address receiver, address referrer) external returns (uint256 shares);`

Overloaded  non-standard `deposit` method with an optional referrer address

<table data-header-hidden><thead><tr><th>Parameter</th><th width="150">Type</th><th>Description</th></tr></thead><tbody><tr><td>Parameter</td><td>Type</td><td>Description</td></tr><tr><td><code>assets</code></td><td>uint256</td><td>The amount of underlying assets to be convert to vault shares.</td></tr><tr><td><code>receiver</code></td><td>address</td><td>The account that the vault shares will be minted to.</td></tr><tr><td><code>referrer</code></td><td>address</td><td>Referrer address for this deposit.</td></tr></tbody></table>

### maxMint()

`function maxMint(address caller) external view returns (uint256 maxShares);`

The maximum number of vault shares that caller can mint.

<table data-header-hidden><thead><tr><th>Parameter</th><th width="150">Type</th><th>Description</th></tr></thead><tbody><tr><td>Parameter</td><td>Type</td><td>Description</td></tr><tr><td><code>caller</code></td><td>address</td><td>Account that the underlying assets will be transferred from.</td></tr></tbody></table>

### previewMint()

`function previewMint(uint256 shares) external view returns (uint256 assets);`

Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given current on-chain conditions.

<table data-header-hidden><thead><tr><th>Parameter</th><th width="150">Type</th><th>Description</th></tr></thead><tbody><tr><td>Parameter</td><td>Type</td><td>Description</td></tr><tr><td><code>shares</code></td><td>uint256</td><td>The amount of vault shares to be minted</td></tr></tbody></table>

### mint()

`function mint(uint256 shares, address receiver) external returns (uint256 shares);`

Mint exact amount of vault shares to the receiver by transferring enough underlying asset tokens from the caller.

<table data-header-hidden><thead><tr><th>Parameter</th><th width="150">Type</th><th>Description</th></tr></thead><tbody><tr><td>Parameter</td><td>Type</td><td>Description</td></tr><tr><td><code>shares</code></td><td>uint256</td><td>The amount of vault shares to be minted</td></tr><tr><td><code>receiver</code></td><td>address</td><td>The account that the vault shares will be minted to.</td></tr></tbody></table>

### mint()

`function mint(uint256 shares, address receiver, address referrer) external returns (uint256 shares);`

Overloaded  non-standard  `mint` method with an optional referrer address

<table data-header-hidden><thead><tr><th>Parameter</th><th width="150">Type</th><th>Description</th></tr></thead><tbody><tr><td>Parameter</td><td>Type</td><td>Description</td></tr><tr><td><code>shares</code></td><td>uint256</td><td>The amount of vault shares to be minted</td></tr><tr><td><code>receiver</code></td><td>address</td><td>The account that the vault shares will be minted to.</td></tr><tr><td><code>referrer</code></td><td>address</td><td>Referrer address for this mint.</td></tr></tbody></table>

### maxWithdraw()

`function maxWithdraw(address owner) external view returns (uint256 maxAssets);`

The maximum number of underlying assets that owner can withdraw.

<table data-header-hidden><thead><tr><th>Parameter</th><th width="150">Type</th><th>Description</th></tr></thead><tbody><tr><td>Parameter</td><td>Type</td><td>Description</td></tr><tr><td><code>owner</code></td><td>address</td><td>Account that owns the vault shares.</td></tr></tbody></table>

### previewWithdraw()

`function previewWithdraw(uint256 assets) external view returns (uint256 shares);`

Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block, given current on-chain conditions.

<table data-header-hidden><thead><tr><th>Parameter</th><th width="150">Type</th><th>Description</th></tr></thead><tbody><tr><td>Parameter</td><td>Type</td><td>Description</td></tr><tr><td><code>assets</code></td><td>uint256</td><td>The amount of underlying assets to be withdrawn.</td></tr></tbody></table>

### withdraw()

`function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);`

Burns enough vault shares from owner and transfers the exact amount of underlying asset tokens to the receiver.

<table data-header-hidden><thead><tr><th>Parameter</th><th width="150">Type</th><th>Description</th></tr></thead><tbody><tr><td>Parameter</td><td>Type</td><td>Description</td></tr><tr><td><code>assets</code></td><td>uint256</td><td>The amount of underlying assets to be withdrawn from the vault.</td></tr><tr><td><code>receiver</code></td><td>address</td><td>The account that the underlying assets will be transferred to.</td></tr><tr><td><code>owner</code></td><td>address</td><td>Account that owns the vault shares to be burnt</td></tr></tbody></table>

### maxRedeem()

`function maxRedeem(address owner) external view returns (uint256 maxShares);`

The maximum number of shares an owner can redeem for underlying assets.

<table data-header-hidden><thead><tr><th>Parameter</th><th width="150">Type</th><th>Description</th></tr></thead><tbody><tr><td>Parameter</td><td>Type</td><td>Description</td></tr><tr><td><code>owner</code></td><td>address</td><td>Account that owns the vault shares.</td></tr></tbody></table>

### previewRedeem()

`function previewRedeem(uint256 shares) external view returns (uint256 assets);`

Allows an on-chain or off-chain user to simulate the effects of their redemption at the current block, given current on-chain conditions.

<table data-header-hidden><thead><tr><th>Parameter</th><th width="150">Type</th><th>Description</th></tr></thead><tbody><tr><td>Parameter</td><td>Type</td><td>Description</td></tr><tr><td><code>shares</code></td><td>uint256</td><td>The amount of vault shares to be burnt.</td></tr></tbody></table>

### redeem()

`function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);`

Burns exact amount of vault shares from owner and transfers the underlying asset tokens to the receiver.

<table data-header-hidden><thead><tr><th>Parameter</th><th width="180.33333333333331">Type</th><th>Description</th></tr></thead><tbody><tr><td>Parameter</td><td>Type</td><td>Description</td></tr><tr><td><code>shares</code></td><td>uint256</td><td>The amount of vault shares to be burnt.</td></tr><tr><td><code>receiver</code></td><td>address</td><td>he account the underlying assets will be transferred to.</td></tr><tr><td><code>owner</code></td><td>address</td><td>The account that owns the vault shares to be burnt</td></tr></tbody></table>

## ERC-20 Functions

### totalSupply()

`function totalSupply () external returns (uint256)`

Returns the amount of tokens in existence.

### balanceOf()

`function balanceOf () external returns (uint256)`

Returns the amount of tokens owned by `account`.

### transfer()

`function transfer () external returns (bool)`

Moves `amount` tokens from the caller's account to `recipient`.

Returns a boolean value indicating whether the operation succeeded.

Emits a {Transfer} event.

### allowance()

`function allowance () external returns (uint256)`

Returns the remaining number of tokens that`spender`will be allowed to spend on behalf of`owner`through {transferFrom}. This is zero by default.

This value changes when {approve} or {transferFrom} are called.

### approve()

`function approve () external returns (bool)`

Sets `amount` as the allowance of `spender` over the caller's tokens.

Returns a boolean value indicating whether the operation succeeded.

IMPORTANT: Beware that changing an allowance with this method brings the risk that someone may use both the old and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: <https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729>

Emits an {Approval} event.

### transferFrom()

`function transferFrom () external returns (bool)`

Moves `amount` tokens from `sender` to `recipient` using the allowance mechanism. `amount` is then deducted from the caller's allowance.

Returns a boolean value indicating whether the operation succeeded.

Emits a {Transfer} event.&#x20;

### increaseAllowance()

`function increaseAllowance () public returns (bool)`

Atomically increases the allowance granted to `spender` by the caller.

This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}.

Emits an {Approval} event indicating the updated allowance.

Requirements:

* `spender` cannot be the zero address.

### decreaseAllowance()

`function decreaseAllowance () public returns (bool)`

Atomically decreases the allowance granted to `spender` by the caller.

This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}.

Emits an {Approval} event indicating the updated allowance.

Requirements:

* `spender` cannot be the zero address.
* `spender` must have allowance for the caller of at least

  `subtractedValue`.

## Save functions

### balanceOfUnderlying()

`function balanceOfUnderlying (address _user) external returns (uint256 balance)`

Returns the underlying balance of a given user

| Parameter | Type    | Description                  |
| --------- | ------- | ---------------------------- |
| `_user`   | address | Address of the user to check |

### underlyingToCredits()

`function underlyingToCredits (uint256 _underlying) external returns (uint256 credits)`

Converts a given underlying amount into credits

| Parameter     | Type    | Description         |
| ------------- | ------- | ------------------- |
| `_underlying` | uint256 | Units of underlying |

### creditsToUnderlying()

`function creditsToUnderlying (uint256 _credits) external returns (uint256 amount)`

Converts a given credit amount into underlying

| Parameter  | Type    | Description      |
| ---------- | ------- | ---------------- |
| `_credits` | uint256 | Units of credits |

### creditBalances()

Deprecated in favour of \`balanceOf(address)\`. Maintained for backwards compatibility. Returns the credit balance of a given user

`function creditBalances (address _user) external returns (uint256)`

### depositSavings()

`function depositSavings (uint256 _underlying) external returns (uint256 creditsIssued)`

Deposit the senders savings to the vault, and credit them internally with "credits". Credit amount is calculated as a ratio of deposit amount and exchange rate: credits = underlying / exchangeRate We will first update the internal exchange rate by collecting any interest generated on the underlying.

<table data-header-hidden><thead><tr><th>Parameter</th><th width="150">Type</th><th>Description</th></tr></thead><tbody><tr><td>Parameter</td><td>Type</td><td>Description</td></tr><tr><td><code>_underlying</code></td><td>uint256</td><td>Units of underlying to deposit into savings vault</td></tr></tbody></table>

### depositSavings()

`function depositSavings (uint256 _underlying, address _beneficiary) external returns (uint256 creditsIssued)`

Deposit the senders savings to the vault, and credit them internally with "credits". Credit amount is calculated as a ratio of deposit amount and exchange rate: credits = underlying / exchangeRate We will first update the internal exchange rate by collecting any interest generated on the underlying.

| Parameter      | Type    | Description                                                      |
| -------------- | ------- | ---------------------------------------------------------------- |
| `_underlying`  | uint256 | Units of underlying to deposit into savings vault                |
| `_beneficiary` | address | Immediately transfer the imUSD token to this beneficiary address |

### depositSavings()

`function depositSavings (uint256 _underlying, address _beneficiary, address _referrer) external returns (uint256 creditsIssued)`

Overloaded `depositSavings` method with an optional referrer address.

| Parameter      | Type    | Description                                                        |
| -------------- | ------- | ------------------------------------------------------------------ |
| `_underlying`  | uint256 | Units of underlying to deposit into savings vault. eg mUSD or mBTC |
| `_beneficiary` | address | Address to the new credits will be issued to.                      |
| `_referrer`    | address | Referrer address for this deposit.                                 |

### redeem()

`function redeem () external returns (uint256 massetReturned)`

### redeemCredits()

`function redeemCredits (uint256 _credits) external returns (uint256 massetReturned)`

Redeem specific number of the senders "credits" in exchange for underlying. Payout amount is calculated as a ratio of credits and exchange rate: payout = credits \* exchangeRate

| Parameter  | Type    | Description                 |
| ---------- | ------- | --------------------------- |
| `_credits` | uint256 | Amount of credits to redeem |

### redeemUnderlying()

`function redeemUnderlying (uint256 _underlying) external returns (uint256 creditsBurned)`

Redeem credits into a specific amount of underlying. Credits needed to burn is calculated using: credits = underlying / exchangeRate

| Parameter     | Type    | Description                    |
| ------------- | ------- | ------------------------------ |
| `_underlying` | uint256 | Amount of underlying to redeem |

### redeemAndUnwrap()

`function redeemAndUnwrap (uint256 _amount, bool _isCreditAmt, uint256 _minAmountOut, address _output, address _beneficiary, address _router, bool _isBassetOut) external returns (uint256 creditsBurned, uint256 massetReturned, uint256 outputQuantity)`

Redeem credits into a specific amount of underlying, unwrap into a selected output asset, and send to a beneficiary Credits needed to burn is calculated using: credits = underlying / exchangeRate

| Parameter       | Type    | Description                                                                                                                                                                                                                                                                                                                                                                               |
| --------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `_amount`       | uint256 | Units to redeem (either underlying or credit amount).                                                                                                                                                                                                                                                                                                                                     |
| `_isCreditAmt`  | bool    | `true` if `amount` is in credits. eg imUSD. `false` if `amount` is in underlying. eg mUSD.                                                                                                                                                                                                                                                                                                |
| `_minAmountOut` | uint256 | Minimum amount of `output` tokens to unwrap for. This is to the same decimal places as the `output` token.                                                                                                                                                                                                                                                                                |
| `_output`       | address | <p>Asset to receive in exchange for the redeemed mAssets. This can be a bAsset or a fAsset. For example:<br>- bAssets (USDC, DAI, sUSD or USDT) or fAssets (GUSD, BUSD, alUSD, FEI or RAI) for mainnet imUSD Vault.<br>- bAssets (USDC, DAI or USDT) or fAsset FRAX for Polygon imUSD Vault.<br>- bAssets (WBTC, sBTC or renBTC) or fAssets (HBTC or TBTCV2) for mainnet imBTC Vault.</p> |
| `_beneficiary`  | address | Address to send `output` tokens to.                                                                                                                                                                                                                                                                                                                                                       |
| `_router`       | address | mAsset address if the output is a bAsset. Feeder Pool address if the output is a fAsset.                                                                                                                                                                                                                                                                                                  |
| `_isBassetOut`  | bool    | `true` if `output` is a bAsset. `false` if `output` is a fAsset.                                                                                                                                                                                                                                                                                                                          |

### poke()

`function poke () external`

External poke function allows for the redistribution of collateral between here and the current&#x20;


# Feeder Pools

Feeder Pools are 50/50 AMMs, usually consisting of one mAsset and another mAsset-like asset. Feeder Pools are an extension of the mStable ecosystem and allow for more assets to swap and mint.

{% tabs %}
{% tab title="Ethereum Mainnet" %}

#### Main Contracts

<table data-header-hidden><thead><tr><th>Contracts</th><th>Address</th><th data-hidden></th></tr></thead><tbody><tr><td><a href="https://github.com/mstable/mStable-contracts/blob/master/contracts%2Ffeeders%2FFeederPool.sol">mUSD/alUSD Feeder Pool</a></td><td><a href="https://etherscan.io/address/0x4eaa01974b6594c0ee62ffd7fee56cf11e6af936">0x4eaa01974B6594C0Ee62fFd7FEE56CF11E6af936</a></td><td></td></tr><tr><td><a href="https://github.com/mstable/mStable-contracts/blob/master/contracts%2Ffeeders%2FFeederPool.sol">mUSD/GUSD Feeder Pool</a></td><td><a href="https://etherscan.io/address/0x4fb30c5a3ac8e85bc32785518633303c4590752d">0x4fb30c5a3ac8e85bc32785518633303c4590752d</a></td><td></td></tr><tr><td><a href="https://github.com/mstable/mStable-contracts/blob/master/contracts%2Ffeeders%2FFeederPool.sol">mUSD/BUSD Feeder Pool</a></td><td><a href="https://etherscan.io/address/0xfe842e95f8911dcc21c943a1daa4bd641a1381c6">0xfe842e95f8911dcc21c943a1daa4bd641a1381c6</a></td><td></td></tr><tr><td><a href="https://github.com/mstable/mStable-contracts/blob/master/contracts%2Ffeeders%2FNonPeggedFeederPool.sol">mUSD/RAI Feeder Pool (NonPeggedFeederPool)</a></td><td><a href="https://etherscan.io/address/0x36f944b7312eac89381bd78326df9c84691d8a5b#code">0x36f944b7312eac89381bd78326df9c84691d8a5b</a></td><td></td></tr><tr><td><a href="https://github.com/mstable/mStable-contracts/blob/master/contracts%2Ffeeders%2FFeederPool.sol">mUSD/FEI Feeder Pool</a></td><td><a href="https://etherscan.io/address/0x2F1423D27f9B20058d9D1843E342726fDF985Eb4">0x2F1423D27f9B20058d9D1843E342726fDF985Eb4</a></td><td></td></tr><tr><td><a href="https://github.com/mstable/mStable-contracts/blob/master/contracts%2Ffeeders%2FFeederPool.sol">mBTC/HBTC Feeder Pool</a></td><td><a href="https://etherscan.io/address/0x48c59199da51b7e30ea200a74ea07974e62c4ba7">0x48c59199da51b7e30ea200a74ea07974e62c4ba7</a></td><td></td></tr><tr><td><a href="https://github.com/mstable/mStable-contracts/blob/master/contracts%2Ffeeders%2FFeederPool.sol">mBTC/TBTC Feeder Pool (deprecated)</a></td><td><a href="https://etherscan.io/address/0xb61a6f928b3f069a68469ddb670f20eeeb4921e0">0xb61a6f928b3f069a68469ddb670f20eeeb4921e0</a></td><td></td></tr><tr><td><a href="https://github.com/mstable/mStable-contracts/blob/master/contracts%2Ffeeders%2FFeederPool.sol">mBTC/tBTCv2 Feeder Pool</a></td><td><a href="https://etherscan.io/address/0xc3280306b6218031E61752d060b091278d45c329">0xc3280306b6218031E61752d060b091278d45c329</a></td><td></td></tr><tr><td></td><td></td><td></td></tr></tbody></table>

#### Peripheral Contracts

| Contracts                                                                                                                         | Address                                                                                                               |
| --------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| [Feeder Wrapper](https://github.com/mstable/mStable-contracts/blob/master/contracts%2Ffeeders%2Fperipheral%2FFeederWrapper.sol)   | [0x7C1fD068CE739A4687BEe9F69e5FD2275C7372d4](https://etherscan.io/address/0x7C1fD068CE739A4687BEe9F69e5FD2275C7372d4) |
| [Feeder Interest Validator](https://github.com/mstable/mStable-contracts/blob/master/contracts%2Ffeeders%2FInterestValidator.sol) | [0xf1049aeD858C4eAd6df1de4dbE63EF607CfF3262](https://etherscan.io/address/0xf1049aeD858C4eAd6df1de4dbE63EF607CfF3262) |
| [Feeder Logic](https://github.com/mstable/mStable-contracts/blob/master/contracts%2Ffeeders%2FFeederLogic.sol)                    | [0x2837C77527c37d61D9763F53005211dACB4125dE](https://etherscan.io/address/0x2837C77527c37d61D9763F53005211dACB4125dE) |
| [Feeder Manager](https://github.com/mstable/mStable-contracts/blob/master/contracts%2Ffeeders%2FFeederManager.sol)                | [0x90aE544E8cc76d2867987Ee4f5456C02C50aBd8B](https://etherscan.io/address/0x90aE544E8cc76d2867987Ee4f5456C02C50aBd8B) |
| {% endtab %}                                                                                                                      |                                                                                                                       |

{% tab title="Ethereum Mainnet Integration Contracts" %}

#### Integration Contracts

| Contracts                                                                                                                                                                    | Address                                                                                                               |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| [BUSD Feeder Pool Aave Integration](https://github.com/mstable/mStable-contracts/blob/master/contracts%2Fpolygon%2FPAaveIntegration.sol)                                     | [0xac98ffc901d6bB634be06f6d3fE63893b1aF6535](https://etherscan.io/address/0xac98ffc901d6bB634be06f6d3fE63893b1aF6535) |
| [BUSD Feeder Pool Iron Bank (CREAM) Integration for mUSD](https://github.com/mstable/mStable-contracts/blob/master/contracts%2Fmasset%2Fperipheral%2FCompoundInegration.sol) | [0x2A15794575e754244F9C0A15F504607c201f8AfD](https://etherscan.io/address/0x2A15794575e754244F9C0A15F504607c201f8AfD) |
| [GUSD Feeder Pool Aave Integration](https://github.com/mstable/mStable-contracts/blob/master/contracts%2Fpolygon%2FPAaveIntegration.sol)                                     | [0xd51f062104D7c8eE7dB100878A454451ADFD2811](https://etherscan.io/address/0xd51f062104D7c8eE7dB100878A454451ADFD2811) |
| [GUSD Feeder Pool Iron Bank (CREAM) Integration for mUSD](https://github.com/mstable/mStable-contracts/blob/master/contracts%2Fmasset%2Fperipheral%2FCompoundInegration.sol) | [0xaF007D4ec9a13116035a2131EA1C9bc0B751E3cf](https://etherscan.io/address/0xaF007D4ec9a13116035a2131EA1C9bc0B751E3cf) |
| [RAI Feeder Pool Aave Integration](https://github.com/mstable/mStable-contracts/blob/master/contracts%2Fpolygon%2FPAaveIntegration.sol)                                      | [0x8cc6a1ae38743d453f2522c5228b775d145f43b7](https://etherscan.io/address/0x8cc6a1ae38743d453f2522c5228b775d145f43b7) |
| [FEI Feeder Pool Aave Integration](https://github.com/mstable/mStable-contracts/blob/master/contracts%2Fpolygon%2FPAaveIntegration.sol)                                      | [0x4094AeC22f40F11c29941d144C3DC887B33f5504](https://etherscan.io/address/0x4094AeC22f40F11c29941d144C3DC887B33f5504) |
| {% endtab %}                                                                                                                                                                 |                                                                                                                       |
| {% endtabs %}                                                                                                                                                                |                                                                                                                       |

Feeder Pool tokens follow the ERC20 standard. The non-standard [`decreaseAllowance`](https://docs.openzeppelin.com/contracts/2.x/api/token/erc20#ERC20-decreaseAllowance-address-uint256-) and [`increaseAllowance`](https://docs.openzeppelin.com/contracts/2.x/api/token/erc20#ERC20-increaseAllowance-address-uint256-) functions have been added to mitigate the well-known issues around setting allowances. These are based on the OpenZeppelin ERC20 implementation.

## ERC-20 Functions

### totalSupply()

`function totalSupply () external returns (uint256)`

Returns the amount of tokens in existence.

### balanceOf()

`function balanceOf () external returns (uint256)`

Returns the amount of tokens owned by `account`.

### transfer()

`function transfer () external returns (bool)`

Moves `amount` tokens from the caller's account to `recipient`.

Returns a boolean value indicating whether the operation succeeded.

Emits a {Transfer} event.

### allowance()

`function allowance () external returns (uint256)`

Returns the remaining number of tokens that`spender`will be allowed to spend on behalf of`owner`through {transferFrom}. This is zero by default.

This value changes when {approve} or {transferFrom} are called.

### approve()

`function approve () external returns (bool)`

Sets `amount` as the allowance of `spender` over the caller's tokens.

Returns a boolean value indicating whether the operation succeeded.

IMPORTANT: Beware that changing an allowance with this method brings the risk that someone may use both the old and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: <https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729>

Emits an {Approval} event.

### transferFrom()

`function transferFrom () external returns (bool)`

Moves `amount` tokens from `sender` to `recipient` using the allowance mechanism. `amount` is then deducted from the caller's allowance.

Returns a boolean value indicating whether the operation succeeded.

Emits a {Transfer} event.&#x20;

### increaseAllowance()

`function increaseAllowance () public returns (bool)`

Atomically increases the allowance granted to `spender` by the caller.

This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}.

Emits an {Approval} event indicating the updated allowance.

Requirements:

* `spender` cannot be the zero address.

### decreaseAllowance()

`function decreaseAllowance () public returns (bool)`

Atomically decreases the allowance granted to `spender` by the caller.

This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}.

Emits an {Approval} event indicating the updated allowance.

Requirements:

* `spender` cannot be the zero address.
* `spender` must have allowance for the caller of at least

  `subtractedValue`.

## Feeder Pool Functions

### mint()

`function mint (address _input, uint256 _inputQuantity, uint256 _minOutputQuantity, address _recipient) external returns (uint256 mintOutput)`

Mint fpTokens with a single bAsset. This contract must have approval to spend the senders bAsset. Supports either fAsset, mAsset or mpAsset as input - with mpAssets used to mint mAsset before depositing.

| Parameter            | Type    | Description                                                            |
| -------------------- | ------- | ---------------------------------------------------------------------- |
| `_input`             | address | Address of the bAsset to deposit.                                      |
| `_inputQuantity`     | uint256 | Quantity in input token units.                                         |
| `_minOutputQuantity` | uint256 | Minimum fpToken quantity to be minted. This protects against slippage. |
| `_recipient`         | address | Receipient of the newly minted fpTokens                                |

### mintMulti()

`function mintMulti (address[] _inputs, uint256[] _inputQuantities, uint256 _minOutputQuantity, address _recipient) external returns (uint256 mintOutput)`

Mint fpTokens with multiple bAssets. This contract must have approval to spend the senders bAssets. Supports only fAsset or mAsset as inputs.

| Parameter            | Type       | Description                                                            |
| -------------------- | ---------- | ---------------------------------------------------------------------- |
| `_inputs`            | address\[] | Address of the bAssets to deposit.                                     |
| `_inputQuantities`   | uint256\[] | Quantity in input token units.                                         |
| `_minOutputQuantity` | uint256    | Minimum fpToken quantity to be minted. This protects against slippage. |
| `_recipient`         | address    | Receipient of the newly minted fpTokens                                |

### getMintOutput()

`function getMintOutput (address _input, uint256 _inputQuantity) external returns (uint256 mintOutput)`

Get the projected output of a given mint.

| Parameter        | Type    | Description                      |
| ---------------- | ------- | -------------------------------- |
| `_input`         | address | Address of the bAsset to deposit |
| `_inputQuantity` | uint256 | Quantity in bAsset units         |

### getMintMultiOutput()

`function getMintMultiOutput (address[] _inputs, uint256[] _inputQuantities) external returns (uint256 mintOutput)`

Get the projected output of a given mint

| Parameter          | Type       | Description                                                                                  |
| ------------------ | ---------- | -------------------------------------------------------------------------------------------- |
| `_inputs`          | address\[] | Non-duplicate address array of addresses to bAssets to deposit for the minted mAsset tokens. |
| `_inputQuantities` | uint256\[] | Quantity of each bAsset to deposit for the minted fpToken.                                   |

### swap()

`function swap (address _input, address _output, uint256 _inputQuantity, uint256 _minOutputQuantity, address _recipient) external returns (uint256 swapOutput)`

Swaps two assets - either internally between fAsset<>mAsset, or between fAsset<>mpAsset by first routing through the mAsset pool.

| Parameter            | Type    | Description                                                               |
| -------------------- | ------- | ------------------------------------------------------------------------- |
| `_input`             | address | Address of bAsset to deposit                                              |
| `_output`            | address | Address of bAsset to withdraw                                             |
| `_inputQuantity`     | uint256 | Units of input bAsset to swap in                                          |
| `_minOutputQuantity` | uint256 | Minimum quantity of the swap output asset. This protects against slippage |
| `_recipient`         | address | Address to transfer output asset to                                       |

### getSwapOutput()

`function getSwapOutput (address _input, address _output, uint256 _inputQuantity) external returns (uint256 swapOutput)`

Determines both if a trade is valid, and the expected fee or output. Swap is valid if it does not result in the input asset exceeding its maximum weight.

| Parameter        | Type    | Description                   |
| ---------------- | ------- | ----------------------------- |
| `_input`         | address | Address of bAsset to deposit  |
| `_output`        | address | Address of bAsset to receive  |
| `_inputQuantity` | uint256 | Units of input bAsset to swap |

### redeem()

`function redeem (address _output, uint256 _fpTokenQuantity, uint256 _minOutputQuantity, address _recipient) external returns (uint256 outputQuantity)`

Burns a specified quantity of the senders fpToken in return for a bAsset. The output amount is derived from the invariant. Supports redemption into either the fAsset, mAsset or assets in the mAsset basket.

| Parameter            | Type    | Description                                                                               |
| -------------------- | ------- | ----------------------------------------------------------------------------------------- |
| `_output`            | address | Address of the bAsset to withdraw                                                         |
| `_fpTokenQuantity`   | uint256 | Quantity of LP Token to burn                                                              |
| `_minOutputQuantity` | uint256 | Minimum bAsset quantity to receive for the burnt fpToken. This protects against slippage. |
| `_recipient`         | address | Address to transfer the withdrawn bAssets to.                                             |

### redeemProportionately()

`function redeemProportionately (uint256 _inputQuantity, uint256[] _minOutputQuantities, address _recipient) external returns (uint256[] outputQuantities)`

Credits a recipient with a proportionate amount of bAssets, relative to current vault balance levels and desired fpToken quantity. Burns the fpToken as payment. Only fAsset & mAsset are supported in this path.

| Parameter              | Type       | Description                             |
| ---------------------- | ---------- | --------------------------------------- |
| `_inputQuantity`       | uint256    | Quantity of fpToken to redeem           |
| `_minOutputQuantities` | uint256\[] | Min units of output to receive          |
| `_recipient`           | address    | Address to credit the withdrawn bAssets |

### redeemExactBassets()

`function redeemExactBassets (address[] _outputs, uint256[] _outputQuantities, uint256 _maxInputQuantity, address _recipient) external returns (uint256 fpTokenQuantity)`

Credits a recipient with a certain quantity of selected bAssets, in exchange for burning the relative fpToken quantity from the sender. Only fAsset & mAsset (0,1) are supported in this path.

| Parameter           | Type       | Description                                                                                |
| ------------------- | ---------- | ------------------------------------------------------------------------------------------ |
| `_outputs`          | address\[] | Addresses of the bAssets to receive                                                        |
| `_outputQuantities` | uint256\[] | Units of the bAssets to receive                                                            |
| `_maxInputQuantity` | uint256    | Maximum fpToken quantity to burn for the received bAssets. This protects against slippage. |
| `_recipient`        | address    | Address to receive the withdrawn bAssets                                                   |

### getRedeemOutput()

`function getRedeemOutput (address _output, uint256 _fpTokenQuantity) external returns (uint256 bAssetOutput)`

Gets the estimated output from a given redeem

| Parameter          | Type    | Description                      |
| ------------------ | ------- | -------------------------------- |
| `_output`          | address | Address of the bAsset to receive |
| `_fpTokenQuantity` | uint256 | Quantity of fpToken to redeem    |

### getRedeemExactBassetsOutput()

`function getRedeemExactBassetsOutput (address[] _outputs, uint256[] _outputQuantities) external returns (uint256 fpTokenQuantity)`

Gets the estimated output from a given redeem

| Parameter           | Type       | Description                        |
| ------------------- | ---------- | ---------------------------------- |
| `_outputs`          | address\[] | Addresses of the bAsset to receive |
| `_outputQuantities` | uint256\[] | Quantities of bAsset to redeem     |

### getPrice()

`function getPrice () public returns (uint256 price, uint256 k)`

Gets the price of the fpToken, and invariant value k

### getConfig()

`function getConfig () external returns (struct FeederConfig config)`

Gets all config needed for general InvariantValidator calls

### getBasset()

`function getBasset (address _bAsset) external returns (struct BassetPersonal personal, struct BassetData vaultData)`

Get data for a specific bAsset, if it exists

| Parameter | Type    | Description       |
| --------- | ------- | ----------------- |
| `_bAsset` | address | Address of bAsset |

### getBassets()

`function getBassets () external returns (struct BassetPersonal[], struct BassetData[] vaultData)`

Get data for a all bAssets in basket


# Vaults

GUSD Feeder Pool Iron Bank (CREAM) Integration for mUSDVaults are used to earn rewards. Tokens such as imUSD or Feeder Pool tokens can be deposited to earn additional MTA rewards. On Ethereum mainnet two versions of these contracts are deployed. **BoostedSavingsVault** is used for single token rewards (MTA) and **BoostedDualVault** is used for 2 reward tokens. However, only one reward token can be used for the **BoostedDualVault** as well.  The *Boosted* in the name implies that this contract reacts to the staked MTA balance and receives a boost from that.&#x20;

Contracts are upgradable.

The following table lays out the currently deployed vaults and what contract is used.

{% tabs %}
{% tab title="Ethereum Mainnet" %}

| Vault                         | Contract                                                     |
| ----------------------------- | ------------------------------------------------------------ |
| imUSD Vault                   | [BoostedSavingsVault](/contracts/vaults/boostedsavingsvault) |
| imBTC Vault                   | [BoostedSavingsVault](/contracts/vaults/boostedsavingsvault) |
| mUSD/GUSD Feeder Pool Vault   | [BoostedSavingsVault](/contracts/vaults/boostedsavingsvault) |
| mUSD/BUSD Feeder Pool Vault   | [BoostedSavingsVault](/contracts/vaults/boostedsavingsvault) |
| mUSD/alUSD Feeder Pool Vault  | [BoostedDualVault](/contracts/vaults/boosteddualvault)       |
| mUSD/RAI Feeder Pool Vault    | [BoostedDualVault](/contracts/vaults/boosteddualvault)       |
| mUSD/FEI Feeder Pool Vault    | [BoostedDualVault](/contracts/vaults/boosteddualvault)       |
| mBTC/HBTC Feeder Pool Vault   | [BoostedSavingsVault](/contracts/vaults/boostedsavingsvault) |
| mBTC/TBTC Feeder Pool Vault   | [BoostedSavingsVault](/contracts/vaults/boostedsavingsvault) |
| mBTC/tBTCv2 Feeder Pool Vault | [BoostedDualVault](/contracts/vaults/boosteddualvault)       |
| {% endtab %}                  |                                                              |

{% tab title="Ropsten Testnet" %}

| Contract      | Address                                    |
| ------------- | ------------------------------------------ |
| imUSD Vault   | 0xDEFc008BAC1e38F13F081DDD20acf89985DFa7C8 |
| imBTC Vault   | 0x7799BEEAf20120CC78f5cF2EB9C85e395B43bF4D |
| {% endtab %}  |                                            |
| {% endtabs %} |                                            |

##


# BoostedSavingsVault

{% tabs %}
{% tab title="Ethereum Mainnet" %}

| Contract                                                                                                                                         | Address                                                                                                               |
| ------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------- |
| [mUSD/GUSD Feeder Pool Vault](https://github.com/mstable/mStable-contracts/blob/master/contracts%2Frewards%2Fboosted-staking%2FBoostedVault.sol) | [0xadeedd3e5768f7882572ad91065f93ba88343c99](https://etherscan.io/address/0xadeedd3e5768f7882572ad91065f93ba88343c99) |
| [mUSD/BUSD Feeder Pool Vault](https://github.com/mstable/mStable-contracts/blob/master/contracts/rewards/boosted-staking/BoostedVault.sol)       | [0xd124b55f70d374f58455c8aedf308e52cf2a6207](https://etherscan.io/address/0xd124b55f70d374f58455c8aedf308e52cf2a6207) |
| [mBTC/HBTC Feeder Pool Vault](https://github.com/mstable/mStable-contracts/blob/master/contracts/rewards/boosted-staking/BoostedVault.sol)       | [0xf65d53aa6e2e4a5f4f026e73cb3e22c22d75e35c](https://etherscan.io/address/0xf65d53aa6e2e4a5f4f026e73cb3e22c22d75e35c) |
| [mBTC/TBTC Feeder Pool Vault](https://github.com/mstable/mStable-contracts/blob/master/contracts/rewards/boosted-staking/BoostedVault.sol)       | [0x760ea8cfdcc4e78d8b9ca3088ecd460246dc0731](https://etherscan.io/address/0x760ea8cfdcc4e78d8b9ca3088ecd460246dc0731) |
| {% endtab %}                                                                                                                                     |                                                                                                                       |
| {% endtabs %}                                                                                                                                    |                                                                                                                       |

## Functions

### stake()

`function stake (uint256 _amount) external`

Stakes a given amount of the StakingToken for the sender

| Parameter | Type    | Description           |
| --------- | ------- | --------------------- |
| `_amount` | uint256 | Units of StakingToken |

### stake()

`function stake (address _beneficiary, uint256 _amount) external`

Stakes a given amount of the StakingToken for a given beneficiary

| Parameter      | Type    | Description                                |
| -------------- | ------- | ------------------------------------------ |
| `_beneficiary` | address | Staked tokens are credited to this address |
| `_amount`      | uint256 | Units of StakingToken                      |

### exit()

`function exit () external`

Withdraws stake from pool and claims any unlocked rewards.Note, this function is costly - the args for \_claimRewardsshould be determined off chain and then passed to other fn

### exit()

`function exit (uint256 _first, uint256 _last) external`

Withdraws stake from pool and claims any unlocked rewards.

| Parameter | Type    | Description                               |
| --------- | ------- | ----------------------------------------- |
| `_first`  | uint256 | Index of the first array element to claim |
| `_last`   | uint256 | Index of the last array element to claim  |

### withdraw()

`function withdraw (uint256 _amount) external`

Withdraws given stake amount from the pool

| Parameter | Type    | Description                           |
| --------- | ------- | ------------------------------------- |
| `_amount` | uint256 | Units of the staked token to withdraw |

### claimReward()

`function claimReward () external`

Claims only the tokens that have been immediately unlocked, not includingthose that are in the lockers.

### claimRewards()

`function claimRewards () external`

Claims all unlocked rewards for sender.Note, this function is costly - the args for \_claimRewardsshould be determined off chain and then passed to other fn

### claimRewards()

`function claimRewards (uint256 _first, uint256 _last) external`

Claims all unlocked rewards for sender. Both immediately unlockedrewards and also locked rewards past their time lock.

| Parameter | Type    | Description                               |
| --------- | ------- | ----------------------------------------- |
| `_first`  | uint256 | Index of the first array element to claim |
| `_last`   | uint256 | Index of the last array element to claim  |

### pokeBoost()

`function pokeBoost () external`

Pokes a given account to reset the boost

### getRewardToken()

`function getRewardToken () external returns (contract IERC20)`

Gets the RewardsToken

### lastTimeRewardApplicable()

`function lastTimeRewardApplicable () public returns (uint256)`

Gets the last applicable timestamp for this reward period

### rewardPerToken()

`function rewardPerToken () public returns (uint256)`

Calculates the amount of unclaimed rewards per token since last update,and sums with stored to give the new cumulative reward per token

### earned()

`function earned (address _account) public returns (uint256)`

Returned the units of IMMEDIATELY claimable rewards a user has to receive. Note - thisdoes NOT include the majority of rewards which will be locked up.

| Parameter  | Type    | Description  |
| ---------- | ------- | ------------ |
| `_account` | address | User address |

### unclaimedRewards()

`function unclaimedRewards (address _account) external returns (uint256 amount, uint256 first, uint256 last)`

Calculates all unclaimed reward data, finding both immediately unlocked rewardsand those that have passed their time lock.

| Parameter  | Type    | Description  |
| ---------- | ------- | ------------ |
| `_account` | address | User address |

### notifyRewardAmount()

`function notifyRewardAmount (uint256 _reward) external`

Notifies the contract that new rewards have been added.Calculates an updated rewardRate based on the rewards in period.

| Parameter | Type    | Description                                           |
| --------- | ------- | ----------------------------------------------------- |
| `_reward` | uint256 | Units of RewardToken that have been added to the pool |


# BoostedSavingsVault V2

{% tabs %}
{% tab title="Ethereum Mainnet" %}

| Contract                                                                                                                   | Address                                                                                                               |
| -------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| [imUSD Vault](https://github.com/mstable/mStable-contracts/blob/master/contracts/rewards/boosted-staking/BoostedVault.sol) | [0x78befca7de27d07dc6e71da295cc2946681a6c7b](https://etherscan.io/address/0x78befca7de27d07dc6e71da295cc2946681a6c7b) |
| [imBTC Vault](https://github.com/mstable/mStable-contracts/blob/master/contracts/rewards/boosted-staking/BoostedVault.sol) | [0xf38522f63f40f9dd81abafd2b8efc2ec958a3016](https://etherscan.io/address/0xf38522f63f40f9dd81abafd2b8efc2ec958a3016) |
| {% endtab %}                                                                                                               |                                                                                                                       |
| {% endtabs %}                                                                                                              |                                                                                                                       |

## Functions

### stake()

`function stake (uint256 _amount) external`

Stakes a given amount of the StakingToken for the sender

| Parameter | Type    | Description           |
| --------- | ------- | --------------------- |
| `_amount` | uint256 | Units of StakingToken |

### stake()

`function stake (address _beneficiary, uint256 _amount) external`

Stakes a given amount of the StakingToken for a given beneficiary

| Parameter      | Type    | Description                                |
| -------------- | ------- | ------------------------------------------ |
| `_beneficiary` | address | Staked tokens are credited to this address |
| `_amount`      | uint256 | Units of StakingToken                      |

### exit()

`function exit () external`

Withdraws stake from pool and claims any unlocked rewards.Note, this function is costly - the args for \_claimRewardsshould be determined off chain and then passed to other fn

### exit()

`function exit (uint256 _first, uint256 _last) external`

Withdraws stake from pool and claims any unlocked rewards.

| Parameter | Type    | Description                               |
| --------- | ------- | ----------------------------------------- |
| `_first`  | uint256 | Index of the first array element to claim |
| `_last`   | uint256 | Index of the last array element to claim  |

### withdraw()

`function withdraw (uint256 _amount) external`

Withdraws given stake amount from the pool

| Parameter | Type    | Description                           |
| --------- | ------- | ------------------------------------- |
| `_amount` | uint256 | Units of the staked token to withdraw |

### withdrawAndUnwrap()

1. Redeems the underlying mAsset tokens for bAsset tokens.
2. Swaps the underlying mAsset tokens for fAsset tokens in a Feeder Pool.

Redeems staked interest-bearing asset tokens for either bAsset or fAsset tokens. Withdraws a given staked amount of interest-bearing assets from the vault, redeems the interest-bearing asset for the underlying mAsset and either

`function withdrawAndUnwrap (uint256 _amount, uint256 _minAmountOut, address _output, address _beneficiary, address _router, bool _isBassetOut) external returns (uint256 outputQuantity)`

| Parameter       | Type    | Description                                                                                                                                                                                                                                                                                                                                                                                           |            |
| --------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- |
| `_amount`       | uint256 | Units of the staked interest-bearing asset tokens to withdraw. eg imUSD or imBTC.                                                                                                                                                                                                                                                                                                                     |            |
| `_minAmountOut` | uint256 | Minimum units of `output` tokens to be received by the beneficiary. This is to the same decimal places as the `output` token.                                                                                                                                                                                                                                                                         |            |
| `_output`       | address | <p>Asset to receive in exchange for the redeemed mAssets. This can be a bAsset or a fAsset. For example:    </p><ul><li>bAssets (USDC, DAI, sUSD or USDT) or fAssets (GUSD, BUSD, alUSD, FEI or RAI) for mainnet imUSD Vault.</li><li>bAssets (USDC, DAI or USDT) or fAsset FRAX for Polygon imUSD Vault.</li><li>bAssets (WBTC, sBTC or renBTC) or fAssets (HBTC or TBTCV2) for mainnet imBTC Vault. | </li></ul> |
| `_beneficiary`  | address | Address to send `output` tokens to.                                                                                                                                                                                                                                                                                                                                                                   |            |
| `_router`       | address | mAsset address if the `output` is a bAsset. Feeder Pool address if the `output` is a fAsset.                                                                                                                                                                                                                                                                                                          |            |
| `_isBassetOut`  | bool    | `true` if `output` is a bAsset. `false` if `output` is a fAsset                                                                                                                                                                                                                                                                                                                                       |            |

### claimReward()

`function claimReward () external`

Claims only the tokens that have been immediately unlocked, not includingthose that are in the lockers.

### claimRewards()

`function claimRewards () external`

Claims all unlocked rewards for sender.Note, this function is costly - the args for \_claimRewardsshould be determined off chain and then passed to other fn

### claimRewards()

`function claimRewards (uint256 _first, uint256 _last) external`

Claims all unlocked rewards for sender. Both immediately unlockedrewards and also locked rewards past their time lock.

| Parameter | Type    | Description                               |
| --------- | ------- | ----------------------------------------- |
| `_first`  | uint256 | Index of the first array element to claim |
| `_last`   | uint256 | Index of the last array element to claim  |

### pokeBoost()

`function pokeBoost () external`

Pokes a given account to reset the boost

### getRewardToken()

`function getRewardToken () external returns (contract IERC20)`

Gets the RewardsToken

### lastTimeRewardApplicable()

`function lastTimeRewardApplicable () public returns (uint256)`

Gets the last applicable timestamp for this reward period

### rewardPerToken()

`function rewardPerToken () public returns (uint256)`

Calculates the amount of unclaimed rewards per token since last update,and sums with stored to give the new cumulative reward per token

### earned()

`function earned (address _account) public returns (uint256)`

Returned the units of IMMEDIATELY claimable rewards a user has to receive. Note - thisdoes NOT include the majority of rewards which will be locked up.

| Parameter  | Type    | Description  |
| ---------- | ------- | ------------ |
| `_account` | address | User address |

### unclaimedRewards()

`function unclaimedRewards (address _account) external returns (uint256 amount, uint256 first, uint256 last)`

Calculates all unclaimed reward data, finding both immediately unlocked rewardsand those that have passed their time lock.

| Parameter  | Type    | Description  |
| ---------- | ------- | ------------ |
| `_account` | address | User address |

### notifyRewardAmount()

`function notifyRewardAmount (uint256 _reward) external`

Notifies the contract that new rewards have been added.Calculates an updated rewardRate based on the rewards in period.

| Parameter | Type    | Description                                           |
| --------- | ------- | ----------------------------------------------------- |
| `_reward` | uint256 | Units of RewardToken that have been added to the pool |


# BoostedDualVault

{% tabs %}
{% tab title="Ethereum Mainnet" %}

| Contract                                                                                                                                               | Address                                                                                                               |
| ------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------- |
| [mUSD/alUSD Feeder Pool Vault](https://github.com/mstable/mStable-contracts/blob/master/contracts%2Frewards%2Fboosted-staking%2FBoostedDualVault.sol)  | [0x0997dddc038c8a958a3a3d00425c16f8eca87deb](https://etherscan.io/address/0x0997dddc038c8a958a3a3d00425c16f8eca87deb) |
| [mUSD/RAI Feeder Pool Vault](https://github.com/mstable/mStable-contracts/blob/master/contracts%2Frewards%2Fboosted-staking%2FBoostedDualVault.sol)    | [0xF93e0ddE0F7C48108abbD880DB7697A86169f13b](https://etherscan.io/address/0xF93e0ddE0F7C48108abbD880DB7697A86169f13b) |
| [mUSD/FEI Feeder Pool Vault](https://github.com/mstable/mStable-contracts/blob/master/contracts%2Frewards%2Fboosted-staking%2FBoostedDualVault.sol)    | [0xD24099Eb4CD604198071958655E4f2D263a5539B](https://etherscan.io/address/0xD24099Eb4CD604198071958655E4f2D263a5539B) |
| [mBTC/tBTCv2 Feeder Pool Vault](https://github.com/mstable/mStable-contracts/blob/master/contracts%2Frewards%2Fboosted-staking%2FBoostedDualVault.sol) | [0x97e2a2f97a2e9a4cfb462a49ab7c8d205abb9ed9](https://etherscan.io/token/0x97e2a2f97a2e9a4cfb462a49ab7c8d205abb9ed9)   |
| {% endtab %}                                                                                                                                           |                                                                                                                       |
| {% endtabs %}                                                                                                                                          |                                                                                                                       |

## Functions

### stake()

`function stake (uint256 _amount) external`

Stakes a given amount of the StakingToken for the sender

| Parameter | Type    | Description           |
| --------- | ------- | --------------------- |
| `_amount` | uint256 | Units of StakingToken |

### stake()

`function stake (address _beneficiary, uint256 _amount) external`

Stakes a given amount of the StakingToken for a given beneficiary

| Parameter      | Type    | Description                                |
| -------------- | ------- | ------------------------------------------ |
| `_beneficiary` | address | Staked tokens are credited to this address |
| `_amount`      | uint256 | Units of StakingToken                      |

### exit()

`function exit () external`

Withdraws stake from pool and claims any unlocked rewards. Note, this function is costly - the args for \_claimRewards should be determined off chain and then passed to other fn

### exit()

`function exit (uint256 _first, uint256 _last) external`

Withdraws stake from pool and claims any unlocked rewards.

| Parameter | Type    | Description                               |
| --------- | ------- | ----------------------------------------- |
| `_first`  | uint256 | Index of the first array element to claim |
| `_last`   | uint256 | Index of the last array element to claim  |

### withdraw()

`function withdraw (uint256 _amount) external`

Withdraws given stake amount from the pool

| Parameter | Type    | Description                           |
| --------- | ------- | ------------------------------------- |
| `_amount` | uint256 | Units of the staked token to withdraw |

### claimReward()

`function claimReward () external`

Claims only the tokens that have been immediately unlocked, not including those that are in the lockers.

### claimRewards()

`function claimRewards () external`

Claims all unlocked rewards for sender. Note, this function is costly - the args for \_claimRewards should be determined off chain and then passed to other fn

### claimRewards()

`function claimRewards (uint256 _first, uint256 _last) external`

Claims all unlocked rewards for sender. Both immediately unlocked rewards and also locked rewards past their time lock.

| Parameter | Type    | Description                               |
| --------- | ------- | ----------------------------------------- |
| `_first`  | uint256 | Index of the first array element to claim |
| `_last`   | uint256 | Index of the last array element to claim  |

### pokeBoost()

`function pokeBoost () external`

Pokes a given account to reset the boost

### getRewardToken()

`function getRewardToken () external returns (contract IERC20)`

Gets the RewardsToken

### getPlatformToken()

`function getPlatformToken () external returns (contract IERC20)`

Gets the PlatformToken

### lastTimeRewardApplicable()

`function lastTimeRewardApplicable () public returns (uint256)`

Gets the last applicable timestamp for this reward period

### rewardPerToken()

`function rewardPerToken () public returns (uint256, uint256)`

Calculates the amount of unclaimed rewards per token since last update, and sums with stored to give the new cumulative reward per token

### earned()

`function earned (address _account) public returns (uint256, uint256)`

Returned the units of IMMEDIATELY claimable rewards a user has to receive. Note - this does NOT include the majority of rewards which will be locked up.

| Parameter  | Type    | Description  |
| ---------- | ------- | ------------ |
| `_account` | address | User address |

### unclaimedRewards()

`function unclaimedRewards (address _account) external returns (uint256 amount, uint256 first, uint256 last, uint256 platformAmount)`

Calculates all unclaimed reward data, finding both immediately unlocked rewards and those that have passed their time lock.

| Parameter  | Type    | Description  |
| ---------- | ------- | ------------ |
| `_account` | address | User address |

### notifyRewardAmount()

`function notifyRewardAmount (uint256 _reward) external`

Notifies the contract that new rewards have been added. Calculates an updated rewardRate based on the rewards in period.

| Parameter | Type    | Description                                           |
| --------- | ------- | ----------------------------------------------------- |
| `_reward` | uint256 | Units of RewardToken that have been added to the pool |


# Shared Addresses

These contracts are used in multiple other components of the mStable protocol.

These Contracts are used in other parts of the Protocol. To replace them, a Module has to be proposed in the Nexus contract.

{% tabs %}
{% tab title="Ethereum Mainnet" %}

<table data-header-hidden><thead><tr><th width="246">Contract</th><th>Address</th></tr></thead><tbody><tr><td>Contract</td><td>Address</td></tr><tr><td><a href="https://github.com/mstable/mStable-contracts/blob/master/contracts%2Fnexus%2FNexus.sol">Nexus</a></td><td><a href="https://etherscan.io/address/0xAFcE80b19A8cE13DEc0739a1aaB7A028d6845Eb3">0xAFcE80b19A8cE13DEc0739a1aaB7A028d6845Eb3</a></td></tr><tr><td><a href="https://github.com/mstable/mStable-contracts/blob/master/contracts/masset/liquidator/Unliquidator.sol">Unliquidator</a></td><td><a href="https://etherscan.io/address/0xC643B9D66C68d06EA844251a441A0a1211E60656#code">0xC643B9D66C68d06EA844251a441A0a1211E60656</a></td></tr><tr><td><a href="https://github.com/mstable/mStable-contracts/blob/master/contracts%2Fmasset%2Fliquidator%2FLiquidator.sol">Liquidator</a> (deprecated)</td><td><a href="https://etherscan.io/address/0xe595d67181d701a5356e010d9a58eb9a341f1dbd">0xe595D67181D701A5356e010D9a58EB9A341f1DbD</a></td></tr><tr><td><a href="https://github.com/mstable/mStable-contracts/blob/master/contracts%2Fsavings%2FSavingsManager.sol">Savings Manager</a></td><td><a href="https://etherscan.io/address/0xBC3B550E0349D74bF5148D86114A48C3B4Aa856F">0xBC3B550E0349D74bF5148D86114A48C3B4Aa856F</a></td></tr><tr><td><a href="https://github.com/mstable/mStable-contracts/blob/master/contracts%2Frewards%2FBoostDirectorV2.sol">Boost Director</a></td><td><a href="https://etherscan.io/address/0xba05fd2f20ae15b0d3f20ddc6870feca6acd3592">0xBa05FD2f20AE15B0D3f20DDc6870FeCa6ACd3592</a></td></tr><tr><td><a href="https://github.com/mstable/mStable-contracts/blob/master/contracts%2Fbuy-and-make%2FRevenueRecipient.sol">Revenue Recipient (Buy &#x26; Make)</a></td><td><a href="https://etherscan.io/address/0xA7824292efDee1177a1C1BED0649cfdD6114fed5">0xA7824292efDee1177a1C1BED0649cfdD6114fed5</a></td></tr><tr><td><a href="https://github.com/mstable/mStable-contracts/blob/master/contracts%2Fbuy-and-make%2FCollector.sol">Collector (Buy &#x26; Make)</a></td><td><a href="https://etherscan.io/address/0x3F63e5bbB53e46F8B21F67C25Bf2dd78BC6C0e43">0x3F63e5bbB53e46F8B21F67C25Bf2dd78BC6C0e43</a></td></tr></tbody></table>
{% endtab %}

{% tab title="Ropsten Testnet" %}

| Contract             | Address                                      |
| -------------------- | -------------------------------------------- |
| Nexus                | 0xeD04Cd19f50F893792357eA53A549E23Baf3F6cB   |
| Emissions Controller | *0x973E0B9E1b0bf43B1B8dDf9D6A2f817138cf3C10* |
| RevenueBuyBack       | 0x51E014D7862d4Ba8A14a778dA59890264458F5E4   |
| {% endtab %}         |                                              |
| {% endtabs %}        |                                              |


# Governance

{% tabs %}
{% tab title="Ethereum Mainnet" %}

<table data-header-hidden><thead><tr><th width="247">Contract</th><th>Address</th></tr></thead><tbody><tr><td>Contract</td><td>Address</td></tr><tr><td><a href="https://github.com/mstable/mStable-contracts/blob/master/contracts%2Fshared%2FMetaToken.sol">Meta (MTA)</a></td><td><a href="https://etherscan.io/token/0xa3BeD4E1c75D00fa6f4E5E6922DB7261B5E9AcD2">0xa3BeD4E1c75D00fa6f4E5E6922DB7261B5E9AcD2</a></td></tr><tr><td>Voting Meta Token (vMTA, deprecated) V1</td><td><a href="https://etherscan.io/address/0xae8bc96da4f9a9613c323478be181fdb2aa0e1bf">0xaE8bC96DA4F9A9613c323478BE181FDb2Aa0E1BF</a></td></tr><tr><td><a href="https://github.com/mstable/mStable-contracts/blob/master/contracts%2Fgovernance%2Fstaking%2FStakedTokenMTA.sol">Staked Token MTA (stkMTA) V2</a></td><td><a href="https://etherscan.io/address/0x8f2326316ec696f6d023e37a9931c2b2c177a3d7">0x8f2326316eC696F6d023E37A9931c2b2C177a3D7</a></td></tr><tr><td><a href="https://github.com/mstable/mStable-contracts/blob/master/contracts%2Fgovernance%2Fstaking%2FStakedTokenBPT.sol">Staked Token BPT (stkBPT) V2</a></td><td><a href="https://etherscan.io/address/0xeFbe22085D9f29863Cfb77EEd16d3cC0D927b011">0xeFbe22085D9f29863Cfb77EEd16d3cC0D927b011</a></td></tr><tr><td><a href="https://github.com/mstable/mStable-contracts/blob/master/contracts%2Fgovernance%2Fstaking%2FQuestManager.sol">Quest Manager</a></td><td><a href="https://etherscan.io/address/0x861f12764780896FD783eA615Dd55Df0FF865752">0x861f12764780896FD783eA615Dd55Df0FF865752</a></td></tr><tr><td><a href="https://github.com/mstable/mStable-contracts/blob/master/contracts%2Fupgradability%2FDelayedProxyAdmin.sol">Delayed Proxy Admin</a></td><td><a href="https://etherscan.io/address/0x5C8eb57b44C1c6391fC7a8A0cf44d26896f92386">0x5C8eb57b44C1c6391fC7a8A0cf44d26896f92386</a></td></tr><tr><td><a href="https://github.com/mstable/mStable-contracts/blob/master/contracts%2Frewards%2FRewardsDistributor.sol">Rewards Distributor</a></td><td><a href="https://etherscan.io/address/0x04dfDfa471b79cc9E6E8C355e6C71F8eC4916C50">0x04dfDfa471b79cc9E6E8C355e6C71F8eC4916C50</a></td></tr><tr><td>Protocol DAO Gnosis Safe</td><td><a href="https://etherscan.io/address/0xF6FF1F7FCEB2cE6d26687EaaB5988b445d0b94a2">0xF6FF1F7FCEB2cE6d26687EaaB5988b445d0b94a2</a></td></tr><tr><td>Treasury DAO Gnosis Safe</td><td><a href="https://etherscan.io/address/0x3dd46846eed8D147841AE162C8425c08BD8E1b41">0x3dd46846eed8D147841AE162C8425c08BD8E1b41</a></td></tr><tr><td><a href="https://github.com/mstable/mStable-contracts/blob/master/contracts%2Fsavings%2FPoker.sol">Poker of Boosted Savings Vaults</a></td><td><a href="https://etherscan.io/address/0x8E1Fd7F5ea7f7760a83222d3d470dFBf8493A03F">0x8E1Fd7F5ea7f7760a83222d3d470dFBf8493A03F</a></td></tr></tbody></table>
{% endtab %}

{% tab title="Ropsten Testnet" %}

| Contract                 | Address                                    |
| ------------------------ | ------------------------------------------ |
| Meta (MTA)               | 0x273bc479E5C21CAA15aA8538DecBF310981d14C0 |
| Voting Meta Token (vMTA) | 0x77f9bf80e0947408f64faa07fd150920e6b52015 |
| Delayed Proxy Admin      | 0x2d369F83E9DC764a759a74e87a9Bc542a2BbfdF0 |
| Rewards Distributor      | 0x683eB4a6Ddd554A0dB1837E3981be6FFd2C8F333 |
| {% endtab %}             |                                            |
| {% endtabs %}            |                                            |


# stkMTA

This contract handles the staking functionality for the Staked MTA. Contracts are upgradable.

Contract: [StakedTokenMTA.sol](https://github.com/mstable/mStable-contracts/blob/master/contracts%2Fgovernance%2Fstaking%2FStakedTokenMTA.sol)

{% hint style="warning" %}
Some functions of this token contract can only be called from a whitelisted smart contract. Please contract mStable directly if an integration should be whitelisted.
{% endhint %}

## Functions Staked Token

`function stake (uint256 _amount) external`

Stake an `_amount` of STAKED\_TOKEN in the system. This amount is added to the users stake andboosts their voting power.

| Parameter | Type    | Description                     |
| --------- | ------- | ------------------------------- |
| `_amount` | uint256 | Units of STAKED\_TOKEN to stake |

### stake()

`function stake (uint256 _amount, bool _exitCooldown) external`

Stake an `_amount` of STAKED\_TOKEN in the system. This amount is added to the users stake andboosts their voting power.

| Parameter       | Type    | Description                                                                                                                         |
| --------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| `_amount`       | uint256 | Units of STAKED\_TOKEN to stake                                                                                                     |
| `_exitCooldown` | bool    | Bool signalling whether to take this opportunity to end any outstanding cooldown andreturn the user back to their full voting power |

### stake()

`function stake (uint256 _amount, address _delegatee) external`

Stake an `_amount` of STAKED\_TOKEN in the system. This amount is added to the users stake andboosts their voting power. Take the opportunity to change delegatee.

| Parameter    | Type    | Description                                                                      |
| ------------ | ------- | -------------------------------------------------------------------------------- |
| `_amount`    | uint256 | Units of STAKED\_TOKEN to stake                                                  |
| `_delegatee` | address | Address of the user to whom the sender would like to delegate their voting power |

### withdraw()

`function withdraw (uint256 _amount, address _recipient, bool _amountIncludesFee, bool _exitCooldown) external`

Withdraw raw tokens from the system, following an elapsed cooldown period.Note - May be subject to a transfer fee, depending on the users weightedTimestamp

| Parameter            | Type    | Description                                                            |
| -------------------- | ------- | ---------------------------------------------------------------------- |
| `_amount`            | uint256 | Units of raw token to withdraw                                         |
| `_recipient`         | address | Address of beneficiary who will receive the raw tokens                 |
| `_amountIncludesFee` | bool    | Is the `_amount` specified inclusive of any applicable redemption fee? |
| `_exitCooldown`      | bool    | Should we take this opportunity to exit the cooldown period?           |

### startCooldown()

`function startCooldown (uint256 _units) external`

Enters a cooldown period, after which (and before the unstake window elapses) a user will be ableto withdraw part or all of their staked tokens. Note, during this period, a users voting power is significantly reduced.If a user already has a cooldown period, then it will reset to the current block timestamp, so use wisely.

| Parameter | Type    | Description                    |
| --------- | ------- | ------------------------------ |
| `_units`  | uint256 | Units of stake to cooldown for |

### endCooldown()

`function endCooldown () external`

Ends the cooldown of the sender and give them back their full voting power. This can be used to signal thatthe user no longer wishes to exit the system. Note, the cooldown can also be reset, more smoothly, as part of a stake orwithdraw transaction.

### createLock()

`function createLock (uint256 _value) external`

Allows for backwards compatibility with createLock fn, giving basic args to stake

| Parameter | Type    | Description    |
| --------- | ------- | -------------- |
| `_value`  | uint256 | Units to stake |

### increaseLockAmount()

`function increaseLockAmount (uint256 _value) external`

Allows for backwards compatibility with increaseLockAmount fn by simply staking more

| Parameter | Type    | Description    |
| --------- | ------- | -------------- |
| `_value`  | uint256 | Units to stake |

### exit()

`function exit () external`

Backwards compatibility. Previously a lock would run out and a user would call this. Now, it will take 2 callsto exit in order to leave. The first will initiate the cooldown period, and the second will execute a full withdrawal.

### calcRedemptionFeeRate()

`function calcRedemptionFeeRate (uint32 _weightedTimestamp) public returns (uint256 _feeRate)`

fee = sqrt(300/x)-2.5, where x = weeks since user has staked

| Parameter            | Type   | Description                 |
| -------------------- | ------ | --------------------------- |
| `_weightedTimestamp` | uint32 | The users weightedTimestamp |

### claimBal()

`function claimBal () external`

Claims any $BAL tokens present on this address as part of any potential liquidity mining program

### convertFees()

`function convertFees () external`

Converts fees accrued in BPT into MTA, before depositing to the rewards contract

### getProspectivePriceCoefficient()

`function getProspectivePriceCoefficient () public returns (uint256 newPriceCoeff)`

Fetches most recent priceCoeff from the balancer pool.

PriceCoeff = units of MTA per BPT, scaled to 1:1 = 10000Assuming an 80/20 BPT, it is possible to calculatePriceCoeff (p) = balanceOfMTA in pool (b) / bpt supply (s) / 0.8p = b \* 1.25 / s

## Functions Gamified Token

### name()

`function name () public returns (string)`

### symbol()

`function symbol () public returns (string)`

### balanceOf()

`function balanceOf () public returns (uint256)`

Simply gets scaled balance

### rawBalanceOf()

`function rawBalanceOf () public returns (uint256, uint256)`

Simply gets raw balance

### balanceData()

`function balanceData () external returns (struct Balance)`

Raw staked balance without any multipliers

### userPriceCoeff()

`function userPriceCoeff () external returns (uint256)`

Raw staked balance without any multipliers

### reviewTimestamp()

`function reviewTimestamp () external`

Called by anyone to poke the timestamp of a given account. This allows users to effectively 'claim' any new time Multiplier but will revert if there is no change there.

## Function Gamified Voting Token

### checkpoints()

`function checkpoints () public returns (struct GamifiedVotingToken.Checkpoint)`

Get the `pos`-th checkpoint for `account`.

### numCheckpoints()

`function numCheckpoints () public returns (uint32)`

Get number of checkpoints for `account`.

### delegates()

`function delegates (address delegator) public returns (address)`

Get the address the `delegator` is currently delegating to. Return the `delegator` account if not delegating to anyone.

| Parameter   | Type    | Description                                   |
| ----------- | ------- | --------------------------------------------- |
| `delegator` | address | the account that is delegating the votes from |

### getVotes()

`function getVotes () public returns (uint256)`

Gets the current votes balance for `account`

### getPastVotes()

`function getPastVotes () public returns (uint256)`

Retrieve the number of votes for `account` at the end of `blockNumber`.Requirements:- `blockNumber` must have been already mined

### getPastTotalSupply()

`function getPastTotalSupply () public returns (uint256)`

Retrieve the `totalSupply` at the end of `blockNumber`. Note, this value is the sum of all balances. It is but NOT the sum of all the delegated votes! Requirements:- `blockNumber` must have been already mined

### totalSupply()

`function totalSupply () public returns (uint256)`

Total sum of all scaled balances

### delegate()

`function delegate (address delegatee) public`

Delegate votes from the sender to `delegatee`.If `delegatee` is zero, the sender gets the voting power.

| Parameter   | Type    | Description                         |
| ----------- | ------- | ----------------------------------- |
| `delegatee` | address | account that gets the voting power. |


# stkBPT

This contract handles the staking functionality for the Balancer Pool Tokens. Contracts are upgradable.

Contract: [StakedTokenBPT.sol](https://github.com/mstable/mStable-contracts/blob/master/contracts%2Fgovernance%2Fstaking%2FStakedTokenBPT.sol)

{% hint style="warning" %}
Some functions of this token contract can only be called from a whitelisted smart contract. Please contract mStable directly if an integration should be whitelisted.
{% endhint %}

## Functions Staked Token

`function stake (uint256 _amount) external`

Stake an `_amount` of STAKED\_TOKEN in the system. This amount is added to the users stake andboosts their voting power.

| Parameter | Type    | Description                     |
| --------- | ------- | ------------------------------- |
| `_amount` | uint256 | Units of STAKED\_TOKEN to stake |

### stake()

`function stake (uint256 _amount, bool _exitCooldown) external`

Stake an `_amount` of STAKED\_TOKEN in the system. This amount is added to the users stake andboosts their voting power.

| Parameter       | Type    | Description                                                                                                                         |
| --------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| `_amount`       | uint256 | Units of STAKED\_TOKEN to stake                                                                                                     |
| `_exitCooldown` | bool    | Bool signalling whether to take this opportunity to end any outstanding cooldown andreturn the user back to their full voting power |

### stake()

`function stake (uint256 _amount, address _delegatee) external`

Stake an `_amount` of STAKED\_TOKEN in the system. This amount is added to the users stake andboosts their voting power. Take the opportunity to change delegatee.

| Parameter    | Type    | Description                                                                      |
| ------------ | ------- | -------------------------------------------------------------------------------- |
| `_amount`    | uint256 | Units of STAKED\_TOKEN to stake                                                  |
| `_delegatee` | address | Address of the user to whom the sender would like to delegate their voting power |

### withdraw()

`function withdraw (uint256 _amount, address _recipient, bool _amountIncludesFee, bool _exitCooldown) external`

Withdraw raw tokens from the system, following an elapsed cooldown period.Note - May be subject to a transfer fee, depending on the users weightedTimestamp

| Parameter            | Type    | Description                                                            |
| -------------------- | ------- | ---------------------------------------------------------------------- |
| `_amount`            | uint256 | Units of raw token to withdraw                                         |
| `_recipient`         | address | Address of beneficiary who will receive the raw tokens                 |
| `_amountIncludesFee` | bool    | Is the `_amount` specified inclusive of any applicable redemption fee? |
| `_exitCooldown`      | bool    | Should we take this opportunity to exit the cooldown period?           |

### startCooldown()

`function startCooldown (uint256 _units) external`

Enters a cooldown period, after which (and before the unstake window elapses) a user will be ableto withdraw part or all of their staked tokens. Note, during this period, a users voting power is significantly reduced.If a user already has a cooldown period, then it will reset to the current block timestamp, so use wisely.

| Parameter | Type    | Description                    |
| --------- | ------- | ------------------------------ |
| `_units`  | uint256 | Units of stake to cooldown for |

### endCooldown()

`function endCooldown () external`

Ends the cooldown of the sender and give them back their full voting power. This can be used to signal thatthe user no longer wishes to exit the system. Note, the cooldown can also be reset, more smoothly, as part of a stake orwithdraw transaction.

### createLock()

`function createLock (uint256 _value) external`

Allows for backwards compatibility with createLock fn, giving basic args to stake

| Parameter | Type    | Description    |
| --------- | ------- | -------------- |
| `_value`  | uint256 | Units to stake |

### increaseLockAmount()

`function increaseLockAmount (uint256 _value) external`

Allows for backwards compatibility with increaseLockAmount fn by simply staking more

| Parameter | Type    | Description    |
| --------- | ------- | -------------- |
| `_value`  | uint256 | Units to stake |

### exit()

`function exit () external`

Backwards compatibility. Previously a lock would run out and a user would call this. Now, it will take 2 callsto exit in order to leave. The first will initiate the cooldown period, and the second will execute a full withdrawal.

### calcRedemptionFeeRate()

`function calcRedemptionFeeRate (uint32 _weightedTimestamp) public returns (uint256 _feeRate)`

fee = sqrt(300/x)-2.5, where x = weeks since user has staked

| Parameter            | Type   | Description                 |
| -------------------- | ------ | --------------------------- |
| `_weightedTimestamp` | uint32 | The users weightedTimestamp |

### convertFees()

`function convertFees () external`

Converts fees accrued in BPT into MTA, before depositing to the rewards contract

### getProspectivePriceCoefficient()

`function getProspectivePriceCoefficient () public returns (uint256 newPriceCoeff)`

Fetches most recent priceCoeff from the balancer pool.

PriceCoeff = units of MTA per BPT, scaled to 1:1 = 10000Assuming an 80/20 BPT, it is possible to calculatePriceCoeff (p) = balanceOfMTA in pool (b) / bpt supply (s) / 0.8p = b \* 1.25 / s

## Functions Gamified Token

### name()

`function name () public returns (string)`

### symbol()

`function symbol () public returns (string)`

### balanceOf()

`function balanceOf () public returns (uint256)`

Simply gets scaled balance

### rawBalanceOf()

`function rawBalanceOf () public returns (uint256, uint256)`

Simply gets raw balance

### balanceData()

`function balanceData () external returns (struct Balance)`

Raw staked balance without any multipliers

### userPriceCoeff()

`function userPriceCoeff () external returns (uint256)`

Raw staked balance without any multipliers

### reviewTimestamp()

`function reviewTimestamp () external`

Called by anyone to poke the timestamp of a given account. This allows users to effectively 'claim' any new time Multiplier but will revert if there is no change there.

## Function Gamified Voting Token

### checkpoints()

`function checkpoints () public returns (struct GamifiedVotingToken.Checkpoint)`

Get the `pos`-th checkpoint for `account`.

### numCheckpoints()

`function numCheckpoints () public returns (uint32)`

Get number of checkpoints for `account`.

### delegates()

`function delegates (address delegator) public returns (address)`

Get the address the `delegator` is currently delegating to. Return the `delegator` account if not delegating to anyone.

| Parameter   | Type    | Description                                   |
| ----------- | ------- | --------------------------------------------- |
| `delegator` | address | the account that is delegating the votes from |

### getVotes()

`function getVotes () public returns (uint256)`

Gets the current votes balance for `account`

### getPastVotes()

`function getPastVotes () public returns (uint256)`

Retrieve the number of votes for `account` at the end of `blockNumber`.Requirements:- `blockNumber` must have been already mined

### getPastTotalSupply()

`function getPastTotalSupply () public returns (uint256)`

Retrieve the `totalSupply` at the end of `blockNumber`. Note, this value is the sum of all balances. It is but NOT the sum of all the delegated votes! Requirements:- `blockNumber` must have been already mined

### totalSupply()

`function totalSupply () public returns (uint256)`

Total sum of all scaled balances

### delegate()

`function delegate (address delegatee) public`

Delegate votes from the sender to `delegatee`.If `delegatee` is zero, the sender gets the voting power.

| Parameter   | Type    | Description                         |
| ----------- | ------- | ----------------------------------- |
| `delegatee` | address | account that gets the voting power. |

## Function Headless Staking Reward

### claimReward()

`function claimReward () public`

Claims outstanding rewards for the sender.First updates outstanding reward allocation and then transfers.

### getRewardToken()

`function getRewardToken () external returns (contract IERC20)`

Gets the RewardsToken

### lastTimeRewardApplicable()

`function lastTimeRewardApplicable () public returns (uint256)`

Gets the last applicable timestamp for this reward period

### rewardPerToken()

`function rewardPerToken () public returns (uint256)`

Calculates the amount of unclaimed rewards per token since last update,and sums with stored to give the new cumulative reward per token

### earned()

`function earned (address _account) public returns (uint256)`

Calculates the amount of unclaimed rewards a user has earned

| Parameter  | Type    | Description  |
| ---------- | ------- | ------------ |
| `_account` | address | User address |


# Quest Manager

Centralised place to track quest management and completion status. Contracts are upgradable.

Contract: [QuestManager.sol](https://github.com/mstable/mStable-contracts/blob/master/contracts%2Fgovernance%2Fstaking%2FQuestManager.sol)

### getQuest()

`function getQuest () external returns (struct Quest)`

Gets raw quest data

### hasCompleted()

`function hasCompleted (address _account, uint256 _id) public returns (bool)`

Simply checks if a given user has already completed a given quest

| Parameter  | Type    | Description                |
| ---------- | ------- | -------------------------- |
| `_account` | address | User address               |
| `_id`      | uint256 | Position of quest in array |

### balanceData()

`function balanceData () external returns (struct QuestBalance)`

Raw quest balance

### completeUserQuests()

`function completeUserQuests (address _account, uint256[] _ids, bytes _signature) external`

Called by anyone to complete one or more quests for a staker. The user must first collect a signed message from the whitelisted \_signer.

| Parameter    | Type       | Description                                                                        |
| ------------ | ---------- | ---------------------------------------------------------------------------------- |
| `_account`   | address    | Account that has completed the quest                                               |
| `_ids`       | uint256\[] | Quest IDs (its position in the array)                                              |
| `_signature` | bytes      | Signature from the verified \_questSigner, containing keccak hash of account & ids |

### checkForSeasonFinish()

`function checkForSeasonFinish (address _account) public returns (uint8 newQuestMultiplier)`

Checks if the season has just finished between now and the users last action. If it has, we reset the seasonMultiplier. Either way, we update the lastAction for the user. NOTE - it is important that this is called as a hook before each state change operation

| Parameter  | Type    | Description                            |
| ---------- | ------- | -------------------------------------- |
| `_account` | address | Address of user that should be updated |


# Save Wrapper

The Save Wrapper bundles utility functions together to simplify multiple interactions with mStable's smart contract calls into one single call. Contract is immutable.

{% tabs %}
{% tab title="Ethereum Mainnet" %}

| Name          | Contract                                                                                                             | Address                                                                                                               |
| ------------- | -------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| Save Wrapper  | [SaveWrapper](https://github.com/mstable/mStable-contracts/blob/master/contracts/savings/peripheral/SaveWrapper.sol) | [0x1f2d51eadf24BfcC6Eeb8318D0408dFD9Fbd05d9](https://etherscan.io/address/0x1f2d51eadf24BfcC6Eeb8318D0408dFD9Fbd05d9) |
| {% endtab %}  |                                                                                                                      |                                                                                                                       |
| {% endtabs %} |                                                                                                                      |                                                                                                                       |

## Functions

### saveAndStake()

`function saveAndStake (address _mAsset, address _save, address _vault, uint256 _amount) external`

Simply saves an mAsset and then into the vault

| Parameter | Type    | Description                           |
| --------- | ------- | ------------------------------------- |
| `_mAsset` | address | mAsset address                        |
| `_save`   | address | Save address                          |
| `_vault`  | address | Boosted Savings Vault address         |
| `_amount` | uint256 | Units of mAsset to deposit to savings |

### saveAndStake()

`function saveAndStake (address _mAsset, address _save, address _vault, uint256 _amount, address _referrer) external`

Simply saves an mAsset and then into the vault

| Parameter   | Type    | Description                           |
| ----------- | ------- | ------------------------------------- |
| `_mAsset`   | address | mAsset address                        |
| `_save`     | address | Save address                          |
| `_vault`    | address | Boosted Savings Vault address         |
| `_amount`   | uint256 | Units of mAsset to deposit to savings |
| `_referrer` | address | Referrer address for this deposit.    |

### saveViaMint()

`function saveViaMint (address _mAsset, address _bAsset, address _save, address _vault, uint256 _amount, uint256 _minOut, bool _stake) external`

Mints an mAsset and then deposits to Save/Savings Vault

| Parameter | Type    | Description                                   |
| --------- | ------- | --------------------------------------------- |
| `_mAsset` | address | mAsset address                                |
| `_bAsset` | address | bAsset address                                |
| `_save`   | address | Save address                                  |
| `_vault`  | address | Boosted Savings Vault address                 |
| `_amount` | uint256 | Amount of bAsset to mint with                 |
| `_minOut` | uint256 | Min amount of mAsset to get back              |
| `_stake`  | bool    | Add the imAsset to the Boosted Savings Vault? |

### saveViaMint()

`function saveViaMint (address _mAsset, address _bAsset, address _save, address _vault, uint256 _amount, uint256 _minOut, bool _stake, address _referrer) external`

Mints an mAsset and then deposits to Save/Savings Vault

| Parameter   | Type    | Description                                  |
| ----------- | ------- | -------------------------------------------- |
| `_mAsset`   | address | mAsset address                               |
| `_bAsset`   | address | bAsset address                               |
| `_save`     | address | Save address                                 |
| `_vault`    | address | Boosted Savings Vault address                |
| `_amount`   | uint256 | Amount of bAsset to mint with                |
| `_minOut`   | uint256 | Min amount of mAsset to get back             |
| `_stake`    | bool    | Add the imAsset to the Boosted Savings Vault |
| `_referrer` | address | Referrer address for this deposit.           |

### saveViaSwap()

`function saveViaSwap (address _mAsset, address _save, address _vault, address _feeder, address _fAsset, uint256 _fAssetQuantity, uint256 _minOutputQuantity, bool _stake) external`

Swaps fAsset for mAsset and then deposits to Save/Savings Vault

| Parameter            | Type    | Description                                      |
| -------------------- | ------- | ------------------------------------------------ |
| `_mAsset`            | address | mAsset address                                   |
| `_save`              | address | Save address                                     |
| `_vault`             | address | Boosted Savings Vault address                    |
| `_feeder`            | address | Feeder Pool address                              |
| `_fAsset`            | address | fAsset address                                   |
| `_fAssetQuantity`    | uint256 | Quantity of fAsset sent                          |
| `_minOutputQuantity` | uint256 | Min amount of mAsset to be swapped and deposited |
| `_stake`             | bool    | Deposit the imAsset in the Savings Vault?        |

### saveViaSwap()

`function saveViaSwap (address _mAsset, address _save, address _vault, address _feeder, address _fAsset, uint256 _fAssetQuantity, uint256 _minOutputQuantity, bool _stake, address _referrer) external`

Swaps fAsset for mAsset and then deposits to Save/Savings Vault

| Parameter            | Type    | Description                                      |
| -------------------- | ------- | ------------------------------------------------ |
| `_mAsset`            | address | mAsset address                                   |
| `_save`              | address | Save address                                     |
| `_vault`             | address | Boosted Savings Vault address                    |
| `_feeder`            | address | Feeder Pool address                              |
| `_fAsset`            | address | fAsset address                                   |
| `_fAssetQuantity`    | uint256 | Quantity of fAsset sent                          |
| `_minOutputQuantity` | uint256 | Min amount of mAsset to be swapped and deposited |
| `_stake`             | bool    | Deposit the imAsset in the Savings Vault?        |
| `_referrer`          | address | Referrer address for this deposit.               |

### saveViaUniswapETH()

`function saveViaUniswapETH (address _mAsset, address _save, address _vault, address _uniswap, uint256 _amountOutMin, address[] _path, uint256 _minOutMStable, bool _stake) external`

Buys a bAsset on Uniswap with ETH, then mints imAsset via mAsset, optionally staking in the Boosted Savings Vault

| Parameter        | Type       | Description                              |
| ---------------- | ---------- | ---------------------------------------- |
| `_mAsset`        | address    | mAsset address                           |
| `_save`          | address    | Save address                             |
| `_vault`         | address    | Boosted vault address                    |
| `_uniswap`       | address    | Uniswap router address                   |
| `_amountOutMin`  | uint256    | Min uniswap output in bAsset units       |
| `_path`          | address\[] | Sell path on Uniswap (e.g. \[WETH, DAI]) |
| `_minOutMStable` | uint256    | Min amount of mAsset to receive          |
| `_stake`         | bool       | Add the imAsset to the Savings Vault?    |

### saveViaUniswapETH()

`function saveViaUniswapETH (address _mAsset, address _save, address _vault, address _uniswap, uint256 _amountOutMin, address[] _path, uint256 _minOutMStable, bool _stake, address _referrer) external`

Buys a bAsset on Uniswap with ETH, then mints imAsset via mAsset,optionally staking in the Boosted Savings Vault

| Parameter        | Type       | Description                              |
| ---------------- | ---------- | ---------------------------------------- |
| `_mAsset`        | address    | mAsset address                           |
| `_save`          | address    | Save address                             |
| `_vault`         | address    | Boosted vault address                    |
| `_uniswap`       | address    | Uniswap router address                   |
| `_amountOutMin`  | uint256    | Min uniswap output in bAsset units       |
| `_path`          | address\[] | Sell path on Uniswap (e.g. \[WETH, DAI]) |
| `_minOutMStable` | uint256    | Min amount of mAsset to receive          |
| `_stake`         | bool       | Add the imAsset to the Savings Vault?    |
| `_referrer`      | address    | Referrer address for this deposit.       |

### estimate\_saveViaUniswapETH()

`function estimate_saveViaUniswapETH (address _mAsset, address _uniswap, uint256 _ethAmount, address[] _path) external returns (uint256 out)`

Gets estimated mAsset output from a WETH > bAsset > mAsset trade

| Parameter    | Type       | Description                              |
| ------------ | ---------- | ---------------------------------------- |
| `_mAsset`    | address    | mAsset address                           |
| `_uniswap`   | address    | Uniswap router address                   |
| `_ethAmount` | uint256    | ETH amount to sell                       |
| `_path`      | address\[] | Sell path on Uniswap (e.g. \[WETH, DAI]) |


# Emissions Controller

{% tabs %}
{% tab title="Ethereum Mainnet" %}

| Contract                                                                                                                                            | Address                                                                                                                    |
| --------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| [EmissionsController](https://github.com/mstable/mStable-contracts/blob/master/contracts%2Femissions%2FEmissionsController.sol)                     | [0xBa69e6FC7Df49a3b75b565068Fb91ff2d9d91780](https://etherscan.io/address/0xBa69e6FC7Df49a3b75b565068Fb91ff2d9d91780)      |
| [RevenueSplitBuyBack](https://github.com/mstable/mStable-contracts/blob/master/contracts/buy-and-make/RevenueSplitBuyBack.sol)                      | [0x0E423505A4EB417a75b21f7A35E84ae378e665b9](https://etherscan.io/address/0x0E423505A4EB417a75b21f7A35E84ae378e665b9)      |
| [BasicRewardsForwarder - Treasury DAO](https://github.com/mstable/mStable-contracts/blob/master/contracts%2Femissions%2FBasicRewardsForwarder.sol)  | [0x4b27BaD829092229D2461633A3c08e284BdcBC3A](https://etherscan.io/address/0x4b27BaD829092229D2461633A3c08e284BdcBC3A)      |
| [BasicRewardsForwarder - Visor Finance](https://github.com/mstable/mStable-contracts/blob/master/contracts%2Femissions%2FBasicRewardsForwarder.sol) | [0xceF5df9d514bF0619c2ee87e2dDF1Af93FfAc0F6](https://etherscan.io/address/0xceF5df9d514bF0619c2ee87e2dDF1Af93FfAc0F6)      |
| [VotiumBribeForwarder](https://github.com/mstable/mStable-contracts/blob/master/contracts%2Femissions%2FVotiumBribeForwarder.sol)                   | [0xb6d519a0D616f6F5Fac2b1dBC5bcb92ea58EDa4a](https://etherscan.io/address/0xb6d519a0D616f6F5Fac2b1dBC5bcb92ea58EDa4a)      |
| [BasicRewardsForwarder - Idle Finance](https://github.com/mstable/mStable-contracts/blob/master/contracts%2Femissions%2FBasicRewardsForwarder.sol)  | [0xD2192aa940588851541086D03942572E02CF71B4](https://etherscan.io/address/0xD2192aa940588851541086D03942572E02CF71B4#code) |

{% endtab %}

{% tab title="Ropsten" %}

| Contract             | Address                                    |
| -------------------- | ------------------------------------------ |
| Emissions Controller | 0x2d1864922c7C9B9f9a3609ceA70101b638Aac63C |
| {% endtab %}         |                                            |
| {% endtabs %}        |                                            |


# EmissionsController

Allows governors to vote on the weekly distribution of `MTA` rewards. Rewards are distributed between `n` "Dials" proportionately to the % of votes the dial receives.

Vote weight derives from multiple whitelisted "Staking contracts". Voters can distribute their vote across (0 <= n <= 16 dials), at 0.5% increments in voting weight.

Once their preferences are cast, each time their voting weight changes it is reflected here through a hook.

The staking contracts are capped at 10% of the weekly distribution.

Contracts are upgradable.

## Process

![](https://1563241728-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MgJxLWD6SqMELu7agWt%2Fuploads%2FwbmVytYrILlzKHUpAAFH%2FweeklyEmissions.png?alt=media\&token=28ae2343-0805-4d54-893a-2dbc2ae933ba)

## Functions

### getVotes()

`function getVotes (address account) public returns (uint256 votingPower)`

Gets the users aggregate voting power across all voting contracts.

Voting power can be from staking or it could be delegated to the account.

| Parameter | Type    | Description                      |
| --------- | ------- | -------------------------------- |
| `account` | address | For which to fetch voting power. |

### topLineEmission()

`function topLineEmission (uint32 epoch) public returns (uint256 emissionForEpoch)`

Calculates top line distribution amount for the current epoch as per the polynomial `(f(x)=A*(x/div)^3+B*(x/div)^2+C*(x/div)+D)`.

Values are effectively scaled to 1e12 to avoid integer overflow on pow.

| Parameter | Type   | Description                           |
| --------- | ------ | ------------------------------------- |
| `epoch`   | uint32 | The number of weeks since 1 Jan 1970. |

### getDialRecipient()

`function getDialRecipient (uint256 dialId) public returns (address recipient)`

Gets a dial's recipient address.

| Parameter | Type    | Description                      |
| --------- | ------- | -------------------------------- |
| `dialId`  | uint256 | Dial identifier starting from 0. |

### getDialVoteHistory()

`function getDialVoteHistory (uint256 dialId) public returns (struct HistoricVotes[] voteHistory)`

Gets a dial's weighted votes for each distribution period.

| Parameter | Type    | Description                      |
| --------- | ------- | -------------------------------- |
| `dialId`  | uint256 | Dial identifier starting from 0. |

### getDialVotes()

`function getDialVotes () public returns (uint256[] dialVotes)`

Gets the latest weighted votes for each dial. This will include disabled dials and their current weighted votes.

### getVoterPreferences()

`function getVoterPreferences (address voter) public returns (struct Preference[16] preferences)`

Gets a voter's weights for each dial.

A dial identifier of 255 marks the end of the array. It should be ignored.

| Parameter | Type    | Description                                |
| --------- | ------- | ------------------------------------------ |
| `voter`   | address | Address of the voter that has set weights. |

### addDial()

`function addDial (address _recipient, uint8 _cap, bool _notify) external`

Adds a new dial that can be voted on to receive weekly rewards. Callable by system governor.

| Parameter    | Type    | Description                                                                  |
| ------------ | ------- | ---------------------------------------------------------------------------- |
| `_recipient` | address | Address of the contract that will receive rewards.                           |
| `_cap`       | uint8   | Cap where 0 = uncapped and 10 = 10%.                                         |
| `_notify`    | bool    | If true, `notifyRewardAmount` is called in the `distributeRewards` function. |

### updateDial()

`function updateDial (uint256 _dialId, bool _disabled, bool _notify) external`

Updates a dials recipient contract and/or disabled flag.

| Parameter   | Type    | Description                                                             |
| ----------- | ------- | ----------------------------------------------------------------------- |
| `_dialId`   | uint256 | Dial identifier which is the index of the dials array.                  |
| `_disabled` | bool    | If true, no rewards will be distributed to this dial.                   |
| `_notify`   | bool    | If true, `notifyRewardAmount` is called on the dial recipient contract. |

### addStakingContract()

`function addStakingContract (address _stakingContract) external`

Adds a new contract to the list of approved staking contracts.

| Parameter          | Type    | Description                         |
| ------------------ | ------- | ----------------------------------- |
| `_stakingContract` | address | Address of the new staking contract |

### donate()

`function donate (uint256[] _dialIds, uint256[] _amounts) external`

Allows arbitrary reward donation to a dial on top of the weekly rewards.

| Parameter  | Type       | Description                                                  |
| ---------- | ---------- | ------------------------------------------------------------ |
| `_dialIds` | uint256\[] | Dial identifiers that will receive donated rewards.          |
| `_amounts` | uint256\[] | Units of rewards to be sent to each dial including decimals. |

### calculateRewards()

`function calculateRewards () external`

Calculates the rewards to be distributed to each dial for the next weekly period.

Callable once an epoch has fully passed. Top level emission for the epoch is distributed proportionately to vote count with the following exceptions: - Disabled dials are ignored and votes not counted. - Dials with a cap are capped and their votes/emission removed (effectively redistributing rewards).

### distributeRewards()

`function distributeRewards (uint256[] _dialIds) external`

Transfers all accrued rewards to dials and notifies them of the amount.

| Parameter  | Type       | Description                                       |
| ---------- | ---------- | ------------------------------------------------- |
| `_dialIds` | uint256\[] | Dial identifiers for which to distribute rewards. |

### pokeSources()

`function pokeSources (address _voter) public`

Re-cast a voters votes by retrieving balance across all staking contracts and updating `lastSourcePoke`.

This would need to be called if a staking contract was added to the emissions controller when a voter already had voting power in the new staking contract and they had already set voting preferences.

| Parameter | Type    | Description                                |
| --------- | ------- | ------------------------------------------ |
| `_voter`  | address | Address of the voter for which to re-cast. |

### setVoterDialWeights()

`function setVoterDialWeights (struct Preference[] _preferences) external`

Allows a staker to cast their voting power across a number of dials.

A staker can proportion their voting power even if they currently have zero voting power. For example, they have delegated their votes. When they do have voting power (e.g. they undelegate), their set weights will proportion their voting power.

| Parameter      | Type                 | Description                                                            |
| -------------- | -------------------- | ---------------------------------------------------------------------- |
| `_preferences` | struct Preference\[] | Structs containing dialId & voting weights, with 0 <= n <= 16 entries. |

### moveVotingPowerHook()

`function moveVotingPowerHook (address from, address to, uint256 amount) external`

Called by the staking contracts when a staker has modified voting power.

```
This can be called when staking, cooling down for withdraw or delegating.
```

| Parameter | Type    | Description                                                                  |
| --------- | ------- | ---------------------------------------------------------------------------- |
| `from`    | address | Account that votes moved from. If a mint the account will be a zero address. |
| `to`      | address | Account that votes moved to. If a burn the account will be a zero address.   |
| `amount`  | uint256 | The number of votes moved including the decimal places.                      |


# Polygon Integration

Polygon's [Proof of Stake (PoS) Bridge](https://docs.polygon.technology/docs/develop/ethereum-polygon/pos/getting-started) will be used by the Emissions Controller to send MTA to the existing child MTA token on Polygon. This will be done indirectly using a dial recipient contract that interfaces with the PoS Bridge.

{% tabs %}
{% tab title="Mainnet" %}

| Contract                                                                                                                                                                   | Address                                                                                                               |
| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| [Bridge Forwarder - imUSD Vault](https://github.com/mstable/mStable-contracts/blob/master/contracts%2Femissions%2FBridgeForwarder.sol)                                     | [0x7206A7eB2fe1B8a66D4d35db98d68Cadc890FAca](https://etherscan.io/address/0x7206A7eB2fe1B8a66D4d35db98d68Cadc890FAca) |
| [Bridge Forwarder - FRAX Farm](https://github.com/mstable/mStable-contracts/blob/master/contracts%2Femissions%2FBridgeForwarder.sol)                                       | [0x38dD64B51C1808b04493324f334350eBB3AE8d11](https://etherscan.io/address/0x38dD64B51C1808b04493324f334350eBB3AE8d11) |
| [Bridge Forwarder - Disperser for Balancer Pool liquidity providers](https://github.com/mstable/mStable-contracts/blob/master/contracts%2Femissions%2FBridgeForwarder.sol) | [0x4e649Fa2f3C0Ff18b7695d1e1fa371a1999187Dc](https://etherscan.io/address/0x4e649Fa2f3C0Ff18b7695d1e1fa371a1999187Dc) |
| [RootChainManager](https://github.com/mstable/mStable-contracts/blob/master/contracts%2Finterfaces%2FIRootChainManager.sol)                                                | [0xA0c68C638235ee32657e8f720a23ceC1bFc77C77](https://etherscan.io/address/0xA0c68C638235ee32657e8f720a23ceC1bFc77C77) |
| {% endtab %}                                                                                                                                                               |                                                                                                                       |

{% tab title="Polygon" %}

| Contract                                               | Address                                                                                                                  |
| ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------ |
| Child Chain Manager                                    | [0xA6FA4fB5f76172d178d61B04b0ecd319C5d1C0aa](https://polygonscan.com/address/0xA6FA4fB5f76172d178d61B04b0ecd319C5d1C0aa) |
| Bridged MTA Token                                      | [0xF501dd45a1198C2E1b5aEF5314A68B9006D842E0](https://polygonscan.com/address/0xF501dd45a1198C2E1b5aEF5314A68B9006D842E0) |
| L2 Emissions Controller                                | [0x82182Ac492fef111FB458FCe8f4228553Ed59a19](https://polygonscan.com/address/0x82182Ac492fef111FB458FCe8f4228553Ed59a19) |
| L2 Bridge Recipient - imUSD Vault                      | [0xd3778a18Ee00a6368A0e5D545cB3412886e5a04c](https://polygonscan.com/address/0xd3778a18Ee00a6368A0e5D545cB3412886e5a04c) |
| Disperse Forwarder - Balancer Pool liquidity providers | [0x5783458E67B380d19a84514F11054ABDc326EB07](https://polygonscan.com/address/0x5783458E67B380d19a84514F11054ABDc326EB07) |
| {% endtab %}                                           |                                                                                                                          |
| {% endtabs %}                                          |                                                                                                                          |

## Processes

### Polygon imUSD Vault

![](https://1563241728-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MgJxLWD6SqMELu7agWt%2Fuploads%2FFUBtjVqZpZE5YuZEwZvm%2FpolygonBridge_vimUSD.png?alt=media\&token=b2c3fcf1-2c8f-473f-9570-8eff6b085f75)

### Polygon FRAX Farm

![](https://1563241728-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MgJxLWD6SqMELu7agWt%2Fuploads%2FptAGbOIEQWoMha5KNYzT%2FpolygonBridge_frax.png?alt=media\&token=af207e51-a313-47af-a906-1cfcf8d13ee1)

## Polygon Balancer Pool liquidity providers

![](https://1563241728-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MgJxLWD6SqMELu7agWt%2Fuploads%2FwGUjOEjBqhfRSBkCvUls%2FpolygonBridge_balancer.png?alt=media\&token=caf0964d-1bc6-4a6f-98f0-731038c97a51)


# Bridge Forwarder

Are separate Mainnet contracts for each L2 recipient contracts on Polygon. Initially, there would be a contract for the Polygon imUSD Vault, FRAX Vault and Polygon Balancer Pool liquidity providers.

## Functions

### notifyRewardAmount()

`function notifyRewardAmount (uint256 _rewards) external`

Called by the Emissions Controller to trigger the processing of the weekly rewards.

The Emissions Controller has already transferred the MTA to this contract.

| Parameter  | Type    | Description                                                        |
| ---------- | ------- | ------------------------------------------------------------------ |
| `_rewards` | uint256 | The amount of reward tokens that were distributed to this contract |

### getRewardToken()

`function getRewardToken () external returns (contract IERC20)`

Gets the RewardsToken


# L2 Bridge Recipient

Receives bridged tokens from the PoS Bridge before the L2 Emissions Controller transfers the bridged tokens to the end recipient.

## Functions

### constructor()

`function constructor (address _rewardsToken, address _l2EmissionsController) public`

| Parameter                | Type    | Description                                                                 |
| ------------------------ | ------- | --------------------------------------------------------------------------- |
| `_rewardsToken`          | address | Bridged rewards token on the Polygon chain.                                 |
|                          |         |                                                                             |
| `_l2EmissionsController` | address | Polygon contract that will distribute bridged rewards on the Polygon chain. |


# L2 Emissions Controller

This contract distributes the bridged rewards from the L2 Bridge Recipients to the end recipients.

## Functions

### addRecipient()

`function addRecipient (address _bridgeRecipient, address _endRecipient) external`

Adds a new mapping of a contract that receives rewards from the PoS Bridge to the contract that ultimately receives the rewards.

| Parameter          | Type    | Description                                                                                                           |
| ------------------ | ------- | --------------------------------------------------------------------------------------------------------------------- |
| `_bridgeRecipient` | address | Address of the contract that will receive rewards from the bridge                                                     |
| `_endRecipient`    | address | Address of the contract that ultimately receive rewards and implements the `IRewardsDistributionRecipient` interface. |

### distributeRewards()

`function distributeRewards (address[] _endRecipients) external`

Transfers bridged rewards sitting in the child recipient contracts to the end recipient contracts and the notifys them of the amount of rewards received.

| Parameter        | Type       | Description                                                  |
| ---------------- | ---------- | ------------------------------------------------------------ |
| `_endRecipients` | address\[] | List of contract addressess that ultimately receive rewards. |


# Disperse Forwarder

Transfers reward tokens to a list of off-chain calculated recipients and amounts.

## Functions

### disperseToken()

`function disperseToken (address[] recipients, uint256[] values) external`

Transfers reward tokens to a list of recipients with amounts.

| Parameter    | Type       | Description                                                                |
| ------------ | ---------- | -------------------------------------------------------------------------- |
| `recipients` | address\[] | Array of address that are to receive token rewards.                        |
| `values`     | uint256\[] | Array of reward token amounts for each recipient including decimal places. |


# RevenueSplitBuyBack

Uses 50% of protocol revenue to buy MTA rewards for stakers and 50% to mStable Treasury.

## Process

![](https://1563241728-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MgJxLWD6SqMELu7agWt%2Fuploads%2FL15VD5RSWEar5JI3hvLh%2FbuyBackForStakers.png?alt=media\&token=c1eb0f2e-3da1-4a93-8123-54c7984d9900)

## Functions

### notifyRedistributionAmount()

`function notifyRedistributionAmount (address _mAsset, uint256 _amount) external`

Simply transfers the mAsset from the sender to here

| Parameter | Type    | Description               |
| --------- | ------- | ------------------------- |
| `_mAsset` | address | Address of mAsset         |
| `_amount` | uint256 | Units of mAsset collected |

### buyBackRewards()

`function buyBackRewards (address[] mAssets, uint256[] minBassetsAmount, uint256[] minRewardsAmounts, bytes[] uniswapPaths) external`

Buys reward tokens, eg MTA, using mAssets like mUSD or mBTC from protocol governance fees.

| Parameter           | Type       | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| ------------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `mAssets`           | address\[] | Addresses of mAssets that are to be sold for rewards. eg mUSD and mBTC.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `minBassetsAmount`  | uint256\[] | <p>Minimum amount of bAsset tokens to receive for each redeem of mAssets. </p><p></p><p>The amount uses the decimal places of the bAsset. </p><p>Example 1: Redeeming 10,000 mUSD with a min 2% slippage to USDC which has 6 decimal places.</p><p>minBassetsAmounts = 10,000 mAssets \* slippage 0.98 \* USDC decimals 1e6 = 1e4 \* 0.98 \* 1e6 = 1e10 \* 0.98 = 98e8</p><p></p><p>Example 2: Redeeming 1 mBTC with a min 5% slippage to WBTC which has 8 decimal places. minBassetsAmounts = 1 mAsset \* slippage 0.95 \* WBTC decimals 1e8 = 0.95 \* 1e8 = 95e6</p>                                                                      |
| `minRewardsAmounts` | uint256\[] | <p>Minimum amount of reward tokens received from the sale of bAssets. The amount uses the decimal places of the rewards token.</p><p></p><p>Example 1: Swapping 10,000 USDC with a min 1% slippage to MTA which has 18 decimal places. minRewardsAmounts = 10,000 USDC \* slippage 0.99 \* MTA decimals 1e18 \* MTA/USD rate 1.2 = 1e4 \* 0.99 \* 1e18 \* 1.2 = 1e22 \* 0.99 = 99e20 </p><p></p><p>Example 1: Swapping 1 WBTC with a min 3% slippage to MTA which has 18 decimal places. minRewardsAmounts = 1 WBTC \* slippage 0.97 \* MTA decimals 1e18 \* MTA/BTC rate 0.00001 = 1 \* 0.97 \* 1e18 \* 0.00001 = 0.97 \* 1e13 = 97e11</p> |
| `uniswapPaths`      | bytes\[]   | The Uniswap V3 bytes encoded paths.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |

### donateRewards()

`function donateRewards () external`

Donates purchased rewards, eg MTA, to staking contracts via the Emissions Controller.

### addStakingContract()

`function addStakingContract (uint16 _stakingDialId) external`

Adds a new staking contract that will receive MTA rewards

| Parameter        | Type   | Description                                                            |
| ---------------- | ------ | ---------------------------------------------------------------------- |
| `_stakingDialId` | uint16 | dial identifier from the Emissions Controller of the staking contract. |


# BasicRewardsForwarder

Transfers any received reward tokens to another contract or account.

## Process

![](https://1563241728-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MgJxLWD6SqMELu7agWt%2Fuploads%2Fj0VFOO2m7pIHomV4GCeL%2FweeklyEmissions2TreasuryDAO.png?alt=media\&token=b6e2e1e0-ae57-440f-b13f-f216509b5d48)

## Functions

### notifyRewardAmount()

`function notifyRewardAmount (uint256 _rewards) external`

Called by the Emissions Controller to trigger the processing of the weekly rewards.

The Emissions Controller has already transferred the MTA to this contract.

| Parameter  | Type    | Description                                                   |
| ---------- | ------- | ------------------------------------------------------------- |
| `_rewards` | uint256 | Units of reward tokens that were distributed to this contract |

### setEndRecipient()

`function setEndRecipient (address _endRecipient) external`

Change the endRecipient. Can only be called by mStable governor.

| Parameter       | Type    | Description                               |
| --------------- | ------- | ----------------------------------------- |
| `_endRecipient` | address | The account the reward tokens are sent to |

### getRewardToken()

`function getRewardToken () external returns (contract IERC20)`

Gets the RewardsToken


# VotiumBribeForwarder

Uses reward tokens to bribe vlCVX holders to vote for a Curve gauge using Votium.

## Process

![](https://1563241728-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MgJxLWD6SqMELu7agWt%2Fuploads%2FESzbo9UlLZVASaodiYaB%2FweeklyEmissions2Votium.png?alt=media\&token=1bddf17e-5622-498b-9f43-2df3011e520a)

## Functions

### depositBribe()

`function depositBribe (uint256 amount, bytes32 proposal) external`

Deposits a bribe into Votium, choiceIndex must be set previously.

| Parameter  | Type    | Description                                                      |
| ---------- | ------- | ---------------------------------------------------------------- |
| `amount`   | uint256 | the amount of reward tokens to deposit including decimal places. |
| `proposal` | bytes32 | votium brive proposal                                            |

### updateChoiceIndex()

`function updateChoiceIndex (uint256 _choiceIndex) public`

Updates the choice index used for the bribe.

| Parameter      | Type    | Description            |
| -------------- | ------- | ---------------------- |
| `_choiceIndex` | uint256 | the bribe choice index |


# mUSD

mUSD is a Meta Assets (mAssets) that is composed of USD stablecoin assets. The basket contains DAI, USDC and USDT.

An incentivised constant sum market maker with hard limits at max region. This supports low slippage swaps and applies penalties towards min and max regions. AMM produces a stablecoin (mAsset) and redirects lending market interest and swap fees to the savings contract, producing a second yield-bearing asset.

`_minOutputQuantity` is used to limit slippage when swapping, minting or redeeming. Useful for preventing Sandwich and Frontrunning attacks.

Contracts are upgradable except for integration contracts. The ProtocolDAO multisig can migrate the assets from one integration contract to another.

{% hint style="warning" %}
Note that the mUSD on Ethereum mainnet is not fungible with the mUSD on Polygon. This is due to the fact that the basket of underlying assets is separate and the composition is different.

On Ethereum mUSD is composed of DAI, USDC, USDT and sUSD. \
On Polygon mUSD is composed of DAI, USDC and USDT.
{% endhint %}

{% tabs %}
{% tab title="Polygon" %}

| Contracts                                                                                        | Address                                                                                                                  |
| ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------ |
| [mUSD](https://github.com/mstable/mStable-contracts/blob/master/contracts%2Fmasset%2FMasset.sol) | [0xe840b73e5287865eec17d250bfb1536704b43b21](https://polygonscan.com/address/0xe840b73e5287865eec17d250bfb1536704b43b21) |
| {% endtab %}                                                                                     |                                                                                                                          |
| {% endtabs %}                                                                                    |                                                                                                                          |

mUSD follows the ERC20 standard. The non-standard [`decreaseAllowance`](https://docs.openzeppelin.com/contracts/2.x/api/token/erc20#ERC20-decreaseAllowance-address-uint256-) and [`increaseAllowance`](https://docs.openzeppelin.com/contracts/2.x/api/token/erc20#ERC20-increaseAllowance-address-uint256-) functions have been added to mitigate the well-known issues around setting allowances. These are based on the OpenZeppelin ERC20 implementation.

## ERC-20 Functions

### totalSupply()

`function totalSupply () external returns (uint256)`

Returns the amount of tokens in existence.

### balanceOf()

`function balanceOf () external returns (uint256)`

Returns the amount of tokens owned by `account`.

### transfer()

`function transfer () external returns (bool)`

Moves `amount` tokens from the caller's account to `recipient`.

Returns a boolean value indicating whether the operation succeeded.

Emits a {Transfer} event.

### allowance()

`function allowance () external returns (uint256)`

Returns the remaining number of tokens that`spender`will be allowed to spend on behalf of`owner`through {transferFrom}. This is zero by default.

This value changes when {approve} or {transferFrom} are called.

### approve()

`function approve () external returns (bool)`

Sets `amount` as the allowance of `spender` over the caller's tokens.

Returns a boolean value indicating whether the operation succeeded.

IMPORTANT: Beware that changing an allowance with this method brings the risk that someone may use both the old and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: <https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729>

Emits an {Approval} event.

### transferFrom()

`function transferFrom () external returns (bool)`

Moves `amount` tokens from `sender` to `recipient` using the allowance mechanism. `amount` is then deducted from the caller's allowance.

Returns a boolean value indicating whether the operation succeeded.

Emits a {Transfer} event.&#x20;

### increaseAllowance()

`function increaseAllowance () public returns (bool)`

Atomically increases the allowance granted to `spender` by the caller.

This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}.

Emits an {Approval} event indicating the updated allowance.

Requirements:

* `spender` cannot be the zero address.

### decreaseAllowance()

`function decreaseAllowance () public returns (bool)`

Atomically decreases the allowance granted to `spender` by the caller.

This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}.

Emits an {Approval} event indicating the updated allowance.

Requirements:

* `spender` cannot be the zero address.
* `spender` must have allowance for the caller of at least

  `subtractedValue`.

## Functions

### mint()

`function mint (address _input, uint256 _inputQuantity, uint256 _minOutputQuantity, address _recipient) external returns (uint256 mintOutput)`

Mint a single bAsset, at a 1:1 ratio with the bAsset. This contract must have approval to spend the senders bAsset

| Parameter            | Type    | Description                                                           |
| -------------------- | ------- | --------------------------------------------------------------------- |
| `_input`             | address | Address of the bAsset to deposit for the minted mAsset.               |
| `_inputQuantity`     | uint256 | Quantity in bAsset units                                              |
| `_minOutputQuantity` | uint256 | Minimum mAsset quantity to be minted. This protects against slippage. |
| `_recipient`         | address | Recipient of the newly minted mAsset tokens                           |

### mintMulti()

`function mintMulti (address[] _inputs, uint256[] _inputQuantities, uint256 _minOutputQuantity, address _recipient) external returns (uint256 mintOutput)`

Mint with multiple bAssets, at a 1:1 ratio to mAsset. This contract must have approval to spend the senders bAssets

<table data-header-hidden><thead><tr><th width="250.5076452599389">Parameter</th><th>Type</th><th>Description</th></tr></thead><tbody><tr><td>Parameter</td><td>Type</td><td>Description</td></tr><tr><td><code>_inputs</code></td><td>address[]</td><td>Non-duplicate address array of bASset addresses to deposit for the minted mAsset tokens.</td></tr><tr><td><code>_inputQuantities</code></td><td>uint256[]</td><td>Quantity of each bAsset to deposit for the minted mAsset. Order of array should mirror the above bAsset addresses.</td></tr><tr><td><code>_minOutputQuantity</code> </td><td>uint256</td><td>Minimum mAsset quantity to be minted. This protects against slippage.</td></tr><tr><td><code>_recipient</code></td><td>address</td><td>Address to receive the newly minted mAsset tokens</td></tr></tbody></table>

### getMintOutput()

`function getMintOutput (address _input, uint256 _inputQuantity) external returns (uint256 mintOutput)`

Get the projected output of a given mint

| Parameter        | Type    | Description                                            |
| ---------------- | ------- | ------------------------------------------------------ |
| `_input`         | address | Address of the bAsset to deposit for the minted mAsset |
| `_inputQuantity` | uint256 | Quantity in bAsset units                               |

### getMintMultiOutput()

`function getMintMultiOutput (address[] _inputs, uint256[] _inputQuantities) external returns (uint256 mintOutput)`

Get the projected output of a given mint

| Parameter          | Type       | Description                                                                                  |
| ------------------ | ---------- | -------------------------------------------------------------------------------------------- |
| `_inputs`          | address\[] | Non-duplicate address array of addresses to bAssets to deposit for the minted mAsset tokens. |
| `_inputQuantities` | uint256\[] | Quantity of each bAsset to deposit for the minted mAsset.                                    |

### swap()

`function swap (address _input, address _output, uint256 _inputQuantity, uint256 _minOutputQuantity, address _recipient) external returns (uint256 swapOutput)`

Swaps one bAsset for another bAsset using the bAsset addresses. bAsset <> bAsset swaps will incur a small fee (swapFee()).

| Parameter            | Type    | Description                                                               |
| -------------------- | ------- | ------------------------------------------------------------------------- |
| `_input`             | address | Address of bAsset to deposit                                              |
| `_output`            | address | Address of bAsset to receive                                              |
| `_inputQuantity`     | uint256 | Units of input bAsset to swap                                             |
| `_minOutputQuantity` | uint256 | Minimum quantity of the swap output asset. This protects against slippage |
| `_recipient`         | address | Address to transfer output asset to                                       |

### getSwapOutput()

`function getSwapOutput (address _input, address _output, uint256 _inputQuantity) external returns (uint256 swapOutput)`

Determines both if a trade is valid, and the expected fee or output. Swap is valid if it does not result in the input asset exceeding its maximum weight.

| Parameter        | Type    | Description                   |
| ---------------- | ------- | ----------------------------- |
| `_input`         | address | Address of bAsset to deposit  |
| `_output`        | address | Address of bAsset to receive  |
| `_inputQuantity` | uint256 | Units of input bAsset to swap |

### redeem()

`function redeem (address _output, uint256 _mAssetQuantity, uint256 _minOutputQuantity, address _recipient) external returns (uint256 outputQuantity)`

Redeems a specified quantity of mAsset in return for a bAsset specified by bAsset address. The bAsset is sent to the specified recipient. The bAsset quantity is relative to current vault balance levels and desired mAsset quantity. The quantity of mAsset is burnt as payment. A minimum quantity of bAsset is specified to protect against price slippage between the mAsset and bAsset.

| Parameter            | Type    | Description                                                                               |
| -------------------- | ------- | ----------------------------------------------------------------------------------------- |
| `_output`            | address | Address of the bAsset to receive                                                          |
| `_mAssetQuantity`    | uint256 | Quantity of mAsset to redeem                                                              |
| `_minOutputQuantity` | uint256 | Minimum bAsset quantity to receive for the burnt mAssets. This protects against slippage. |
| `_recipient`         | address | Address to transfer the withdrawn bAssets to.                                             |

### redeemMasset()

`function redeemMasset (uint256 _mAssetQuantity, uint256[] _minOutputQuantities, address _recipient) external returns (uint256[] outputQuantities)`

Credits a recipient with a proportionate amount of bAssets, relative to current vault balance levels and desired mAsset quantity. Burns the mAsset as payment.

| Parameter              | Type       | Description                             |
| ---------------------- | ---------- | --------------------------------------- |
| `_mAssetQuantity`      | uint256    | Quantity of mAsset to redeem            |
| `_minOutputQuantities` | uint256\[] | Min units of output to receive          |
| `_recipient`           | address    | Address to credit the withdrawn bAssets |

### redeemExactBassets()

`function redeemExactBassets (address[] _outputs, uint256[] _outputQuantities, uint256 _maxMassetQuantity, address _recipient) external returns (uint256 mAssetQuantity)`

Credits a recipient with a certain quantity of selected bAssets, in exchange for burning the relative Masset quantity from the sender. Sender also incurs a small fee on the outgoing asset.

| Parameter            | Type       | Description                                                                               |
| -------------------- | ---------- | ----------------------------------------------------------------------------------------- |
| `_outputs`           | address\[] | Addresses of the bAssets to receive                                                       |
| `_outputQuantities`  | uint256\[] | Units of the bAssets to redeem                                                            |
| `_maxMassetQuantity` | uint256    | Maximum mAsset quantity to burn for the received bAssets. This protects against slippage. |
| `_recipient`         | address    | Address to receive the withdrawn bAssets                                                  |

### getRedeemOutput()

`function getRedeemOutput (address _output, uint256 _mAssetQuantity) external returns (uint256 bAssetOutput)`

Gets the estimated output from a given redeem

| Parameter         | Type    | Description                      |
| ----------------- | ------- | -------------------------------- |
| `_output`         | address | Address of the bAsset to receive |
| `_mAssetQuantity` | uint256 | Quantity of mAsset to redeem     |

### getRedeemExactBassetsOutput()

`function getRedeemExactBassetsOutput (address[] _outputs, uint256[] _outputQuantities) external returns (uint256 mAssetQuantity)`

Gets the estimated output from a given redeem

| Parameter           | Type       | Description                        |
| ------------------- | ---------- | ---------------------------------- |
| `_outputs`          | address\[] | Addresses of the bAsset to receive |
| `_outputQuantities` | uint256\[] | Quantities of bAsset to redeem     |

### getBasket()

`function getBasket () external returns (bool, bool)`

Get basket details for `Masset_MassetStructs.Basket`

### getBassets()

`function getBassets () external returns (struct BassetPersonal[] personal, struct BassetData[] bData)`

Get data for a all bAssets in basket

### getBasset()

`function getBasset (address _bAsset) external returns (struct BassetPersonal personal, struct BassetData bData)`

Get data for a specific bAsset, if it exists

| Parameter | Type    | Description       |
| --------- | ------- | ----------------- |
| `_bAsset` | address | Address of bAsset |

### getConfig()

`function getConfig () external returns (struct InvariantConfig config)`

Gets all config needed for general InvariantValidator calls

### getPrice()

`function getPrice () external returns (uint256 price, uint256 k)`

Gets the price of the fpToken, and invariant value k


# imUSD

imUSD is the interest-bearing mUSD. This asset represent the deposited mUSD in SAVE and accrues in value.

Contracts are upgradable.

{% tabs %}
{% tab title="Polygon" %}

| Contracts                                                                                                   | Address                                                                                                                  |
| ----------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| [imUSD](https://github.com/mstable/mStable-contracts/blob/master/contracts%2Fsavings%2FSavingsContract.sol) | [0x5290ad3d83476ca6a2b178cd9727ee1ef72432af](https://polygonscan.com/address/0x5290ad3d83476ca6a2b178cd9727ee1ef72432af) |
| {% endtab %}                                                                                                |                                                                                                                          |
| {% endtabs %}                                                                                               |                                                                                                                          |

imUSD follows the ERC20 and ERC4626 standards:&#x20;

For ERC20, the non-standard [`decreaseAllowance`](https://docs.openzeppelin.com/contracts/2.x/api/token/erc20#ERC20-decreaseAllowance-address-uint256-) and [`increaseAllowance`](https://docs.openzeppelin.com/contracts/2.x/api/token/erc20#ERC20-increaseAllowance-address-uint256-) functions have been added to mitigate the well-known issues around setting allowances. These are based on the OpenZeppelin ERC20 implementation.

For [ERC4626: Tokenized Vault Standard](https://eips.ethereum.org/EIPS/eip-4626), the non-standard functions `deposit(uint256 assets, address receiver, address referrer)` and `shares(uint256 shares, address receiver, address referrer)`  have been added to be use with the [Alliance Referral program](https://mips.mstable.org/MIPS/mip-22.html).

## ERC-4626 Functions&#x20;

### asset()

`function asset() external view returns (address assetTokenAddress);`

The address of the underlying token used for the Vault uses for accounting, depositing, and withdrawing.

### totalAssets()

`function totalAssets() external view returns (uint256 totalManagedAssets);`

Total amount of the underlying asset that is “managed” by Vault.

### convertToShares()

`function convertToShares(uint256 assets) external view returns (uint256 shares);`

The amount of shares that the Vault would exchange for the amount of assets provided, in an ideal scenario where all the conditions are met.

<table data-header-hidden><thead><tr><th>Parameter</th><th width="150">Type</th><th>Description</th></tr></thead><tbody><tr><td>Parameter</td><td>Type</td><td>Description</td></tr><tr><td><code>assets</code></td><td>uint256</td><td>The amount of underlying assets to be convert to vault shares.</td></tr></tbody></table>

### convertToAssets()

`function convertToAssets(uint256 shares) external view returns (uint256 assets);`

The amount of assets that the Vault would exchange for the amount of shares provided, in an ideal scenario where all the conditions are met.

<table data-header-hidden><thead><tr><th>Parameter</th><th width="150">Type</th><th>Description</th></tr></thead><tbody><tr><td>Parameter</td><td>Type</td><td>Description</td></tr><tr><td><code>shares</code></td><td>uint256</td><td>The amount of vault shares to be converted to the underlying assets.</td></tr></tbody></table>

### maxDeposit()

`function maxDeposit(address caller) external view returns (uint256 maxAssets);`

The maximum number of underlying assets that caller can deposit.

<table data-header-hidden><thead><tr><th>Parameter</th><th width="150">Type</th><th>Description</th></tr></thead><tbody><tr><td>Parameter</td><td>Type</td><td>Description</td></tr><tr><td><code>caller</code></td><td>address</td><td>Account that the assets will be transferred from.</td></tr></tbody></table>

### previewDeposit()

`function previewDeposit(uint256 assets) external view returns (uint256 shares);`

Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given current on-chain conditions.

<table data-header-hidden><thead><tr><th>Parameter</th><th width="150">Type</th><th>Description</th></tr></thead><tbody><tr><td>Parameter</td><td>Type</td><td>Description</td></tr><tr><td><code>assets</code></td><td>uint256</td><td>The amount of underlying assets to be convert to vault shares.</td></tr></tbody></table>

### deposit()

`function deposit(uint256 assets, address receiver) external returns (uint256 shares);`

Mint vault shares to receiver by transferring exact amount of underlying asset tokens from the caller.

<table data-header-hidden><thead><tr><th>Parameter</th><th width="150">Type</th><th>Description</th></tr></thead><tbody><tr><td>Parameter</td><td>Type</td><td>Description</td></tr><tr><td><code>assets</code></td><td>uint256</td><td>The amount of underlying assets to be convert to vault shares.</td></tr><tr><td><code>receiver</code></td><td>address</td><td>The account that the vault shares will be minted to.</td></tr></tbody></table>

### deposit()

`function deposit(uint256 assets, address receiver, address referrer) external returns (uint256 shares);`

Overloaded non-standard `deposit` method with an optional referrer address

<table data-header-hidden><thead><tr><th>Parameter</th><th width="150">Type</th><th>Description</th></tr></thead><tbody><tr><td>Parameter</td><td>Type</td><td>Description</td></tr><tr><td><code>assets</code></td><td>uint256</td><td>The amount of underlying assets to be convert to vault shares.</td></tr><tr><td><code>receiver</code></td><td>address</td><td>The account that the vault shares will be minted to.</td></tr><tr><td><code>referrer</code></td><td>address</td><td>Referrer address for this deposit.</td></tr></tbody></table>

### maxMint()

`function maxMint(address caller) external view returns (uint256 maxShares);`

The maximum number of vault shares that caller can mint.

<table data-header-hidden><thead><tr><th>Parameter</th><th width="150">Type</th><th>Description</th></tr></thead><tbody><tr><td>Parameter</td><td>Type</td><td>Description</td></tr><tr><td><code>caller</code></td><td>address</td><td>Account that the underlying assets will be transferred from.</td></tr></tbody></table>

### previewMint()

`function previewMint(uint256 shares) external view returns (uint256 assets);`

Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given current on-chain conditions.

<table data-header-hidden><thead><tr><th>Parameter</th><th width="150">Type</th><th>Description</th></tr></thead><tbody><tr><td>Parameter</td><td>Type</td><td>Description</td></tr><tr><td><code>shares</code></td><td>uint256</td><td>The amount of vault shares to be minted</td></tr></tbody></table>

### mint()

`function mint(uint256 shares, address receiver) external returns (uint256 shares);`

Mint exact amount of vault shares to the receiver by transferring enough underlying asset tokens from the caller.

<table data-header-hidden><thead><tr><th>Parameter</th><th width="150">Type</th><th>Description</th></tr></thead><tbody><tr><td>Parameter</td><td>Type</td><td>Description</td></tr><tr><td><code>shares</code></td><td>uint256</td><td>The amount of vault shares to be minted</td></tr><tr><td><code>receiver</code></td><td>address</td><td>The account that the vault shares will be minted to.</td></tr></tbody></table>

### mint()

`function mint(uint256 shares, address receiver, address referrer) external returns (uint256 shares);`

Overloaded  non-standard `mint` method with an optional referrer address

<table data-header-hidden><thead><tr><th>Parameter</th><th width="150">Type</th><th>Description</th></tr></thead><tbody><tr><td>Parameter</td><td>Type</td><td>Description</td></tr><tr><td><code>shares</code></td><td>uint256</td><td>The amount of vault shares to be minted</td></tr><tr><td><code>receiver</code></td><td>address</td><td>The account that the vault shares will be minted to.</td></tr><tr><td><code>referrer</code></td><td>address</td><td>Referrer address for this mint.</td></tr></tbody></table>

### maxWithdraw()

`function maxWithdraw(address owner) external view returns (uint256 maxAssets);`

The maximum number of underlying assets that owner can withdraw.

<table data-header-hidden><thead><tr><th>Parameter</th><th width="150">Type</th><th>Description</th></tr></thead><tbody><tr><td>Parameter</td><td>Type</td><td>Description</td></tr><tr><td><code>owner</code></td><td>address</td><td>Account that owns the vault shares.</td></tr></tbody></table>

### previewWithdraw()

`function previewWithdraw(uint256 assets) external view returns (uint256 shares);`

Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block, given current on-chain conditions.

<table data-header-hidden><thead><tr><th>Parameter</th><th width="150">Type</th><th>Description</th></tr></thead><tbody><tr><td>Parameter</td><td>Type</td><td>Description</td></tr><tr><td><code>assets</code></td><td>uint256</td><td>The amount of underlying assets to be withdrawn.</td></tr></tbody></table>

### withdraw()

`function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);`

Burns enough vault shares from owner and transfers the exact amount of underlying asset tokens to the receiver.

<table data-header-hidden><thead><tr><th>Parameter</th><th width="150">Type</th><th>Description</th></tr></thead><tbody><tr><td>Parameter</td><td>Type</td><td>Description</td></tr><tr><td><code>assets</code></td><td>uint256</td><td>The amount of underlying assets to be withdrawn from the vault.</td></tr><tr><td><code>receiver</code></td><td>address</td><td>The account that the underlying assets will be transferred to.</td></tr><tr><td><code>owner</code></td><td>address</td><td>Account that owns the vault shares to be burnt</td></tr></tbody></table>

### maxRedeem()

`function maxRedeem(address owner) external view returns (uint256 maxShares);`

The maximum number of shares an owner can redeem for underlying assets.

<table data-header-hidden><thead><tr><th>Parameter</th><th width="150">Type</th><th>Description</th></tr></thead><tbody><tr><td>Parameter</td><td>Type</td><td>Description</td></tr><tr><td><code>owner</code></td><td>address</td><td>Account that owns the vault shares.</td></tr></tbody></table>

### previewRedeem()

`function previewRedeem(uint256 shares) external view returns (uint256 assets);`

Allows an on-chain or off-chain user to simulate the effects of their redemption at the current block, given current on-chain conditions.

<table data-header-hidden><thead><tr><th>Parameter</th><th width="150">Type</th><th>Description</th></tr></thead><tbody><tr><td>Parameter</td><td>Type</td><td>Description</td></tr><tr><td><code>shares</code></td><td>uint256</td><td>The amount of vault shares to be burnt.</td></tr></tbody></table>

### redeem()

`function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);`

Burns exact amount of vault shares from owner and transfers the underlying asset tokens to the receiver.

<table data-header-hidden><thead><tr><th>Parameter</th><th width="180.33333333333331">Type</th><th>Description</th></tr></thead><tbody><tr><td>Parameter</td><td>Type</td><td>Description</td></tr><tr><td><code>shares</code></td><td>uint256</td><td>The amount of vault shares to be burnt.</td></tr><tr><td><code>receiver</code></td><td>address</td><td>he account the underlying assets will be transferred to.</td></tr><tr><td><code>owner</code></td><td>address</td><td>The account that owns the vault shares to be burnt</td></tr></tbody></table>

## ERC-20 Functions

### totalSupply()

`function totalSupply () external returns (uint256)`

Returns the amount of tokens in existence.

### balanceOf()

`function balanceOf () external returns (uint256)`

Returns the amount of tokens owned by `account`.

### transfer()

`function transfer () external returns (bool)`

Moves `amount` tokens from the caller's account to `recipient`.

Returns a boolean value indicating whether the operation succeeded.

Emits a {Transfer} event.

### allowance()

`function allowance () external returns (uint256)`

Returns the remaining number of tokens that`spender`will be allowed to spend on behalf of`owner`through {transferFrom}. This is zero by default.

This value changes when {approve} or {transferFrom} are called.

### approve()

`function approve () external returns (bool)`

Sets `amount` as the allowance of `spender` over the caller's tokens.

Returns a boolean value indicating whether the operation succeeded.

IMPORTANT: Beware that changing an allowance with this method brings the risk that someone may use both the old and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: <https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729>

Emits an {Approval} event.

### transferFrom()

`function transferFrom () external returns (bool)`

Moves `amount` tokens from `sender` to `recipient` using the allowance mechanism. `amount` is then deducted from the caller's allowance.

Returns a boolean value indicating whether the operation succeeded.

Emits a {Transfer} event.&#x20;

### increaseAllowance()

`function increaseAllowance () public returns (bool)`

Atomically increases the allowance granted to `spender` by the caller.

This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}.

Emits an {Approval} event indicating the updated allowance.

Requirements:

* `spender` cannot be the zero address.

### decreaseAllowance()

`function decreaseAllowance () public returns (bool)`

Atomically decreases the allowance granted to `spender` by the caller.

This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}.

Emits an {Approval} event indicating the updated allowance.

Requirements:

* `spender` cannot be the zero address.
* `spender` must have allowance for the caller of at least

  `subtractedValue`.

## **Save** Functions

### balanceOfUnderlying()

`function balanceOfUnderlying (address _user) external returns (uint256 balance)`

Returns the underlying balance of a given user

| Parameter | Type    | Description                  |
| --------- | ------- | ---------------------------- |
| `_user`   | address | Address of the user to check |

### underlyingToCredits()

`function underlyingToCredits (uint256 _underlying) external returns (uint256 credits)`

Converts a given underlying amount into credits

| Parameter     | Type    | Description         |
| ------------- | ------- | ------------------- |
| `_underlying` | uint256 | Units of underlying |

### creditsToUnderlying()

`function creditsToUnderlying (uint256 _credits) external returns (uint256 amount)`

Converts a given credit amount into underlying

| Parameter  | Type    | Description      |
| ---------- | ------- | ---------------- |
| `_credits` | uint256 | Units of credits |

### creditBalances()

Deprecated in favour of \`balanceOf(address)\`. Maintained for backwards compatibility. Returns the credit balance of a given user

`function creditBalances (address _user) external returns (uint256)`

### depositSavings()

`function depositSavings (uint256 _underlying) external returns (uint256 creditsIssued)`

Deposit the senders savings to the vault, and credit them internally with "credits". Credit amount is calculated as a ratio of deposit amount and exchange rate: credits = underlying / exchangeRate We will first update the internal exchange rate by collecting any interest generated on the underlying.

| Parameter     | Type    | Description                                       |
| ------------- | ------- | ------------------------------------------------- |
| `_underlying` | uint256 | Units of underlying to deposit into savings vault |

### depositSavings()

`function depositSavings (uint256 _underlying, address _beneficiary) external returns (uint256 creditsIssued)`

Deposit the senders savings to the vault, and credit them internally with "credits". Credit amount is calculated as a ratio of deposit amount and exchange rate: credits = underlying / exchangeRate We will first update the internal exchange rate by collecting any interest generated on the underlying.

| Parameter      | Type    | Description                                                      |
| -------------- | ------- | ---------------------------------------------------------------- |
| `_underlying`  | uint256 | Units of underlying to deposit into savings vault                |
| `_beneficiary` | address | Immediately transfer the imUSD token to this beneficiary address |

### depositSavings()

`function depositSavings (uint256 _underlying, address _beneficiary, address _referrer) external returns (uint256 creditsIssued)`

Overloaded `depositSavings` method with an optional referrer address.

| Parameter      | Type    | Description                                                        |
| -------------- | ------- | ------------------------------------------------------------------ |
| `_underlying`  | uint256 | Units of underlying to deposit into savings vault. eg mUSD or mBTC |
| `_beneficiary` | address | Address to the new credits will be issued to.                      |
| `_referrer`    | address | Referrer address for this deposit.                                 |

###

### redeem()

`function redeem () external returns (uint256 massetReturned)`

### redeemCredits()

`function redeemCredits (uint256 _credits) external returns (uint256 massetReturned)`

Redeem specific number of the senders "credits" in exchange for underlying. Payout amount is calculated as a ratio of credits and exchange rate: payout = credits \* exchangeRate

| Parameter  | Type    | Description                 |
| ---------- | ------- | --------------------------- |
| `_credits` | uint256 | Amount of credits to redeem |

### redeemUnderlying()

`function redeemUnderlying (uint256 _underlying) external returns (uint256 creditsBurned)`

Redeem credits into a specific amount of underlying. Credits needed to burn is calculated using: credits = underlying / exchangeRate

| Parameter     | Type    | Description                    |
| ------------- | ------- | ------------------------------ |
| `_underlying` | uint256 | Amount of underlying to redeem |

### redeemAndUnwrap()

`function redeemAndUnwrap (uint256 _amount, bool _isCreditAmt, uint256 _minAmountOut, address _output, address _beneficiary, address _router, bool _isBassetOut) external returns (uint256 creditsBurned, uint256 massetReturned, uint256 outputQuantity)`

Redeem credits into a specific amount of underlying, unwrap into a selected output asset, and send to a beneficiary Credits needed to burn is calculated using: credits = underlying / exchangeRate

| Parameter       | Type    | Description                                                                                                                                                                                                                                                                                                                                                                               |
| --------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `_amount`       | uint256 | Units to redeem (either underlying or credit amount).                                                                                                                                                                                                                                                                                                                                     |
| `_isCreditAmt`  | bool    | `true` if `amount` is in credits. eg imUSD. `false` if `amount` is in underlying. eg mUSD.                                                                                                                                                                                                                                                                                                |
| `_minAmountOut` | uint256 | Minimum amount of `output` tokens to unwrap for. This is to the same decimal places as the `output` token.                                                                                                                                                                                                                                                                                |
| `_output`       | address | <p>Asset to receive in exchange for the redeemed mAssets. This can be a bAsset or a fAsset. For example:<br>- bAssets (USDC, DAI, sUSD or USDT) or fAssets (GUSD, BUSD, alUSD, FEI or RAI) for mainnet imUSD Vault.<br>- bAssets (USDC, DAI or USDT) or fAsset FRAX for Polygon imUSD Vault.<br>- bAssets (WBTC, sBTC or renBTC) or fAssets (HBTC or TBTCV2) for mainnet imBTC Vault.</p> |
| `_beneficiary`  | address | Address to send `output` tokens to.                                                                                                                                                                                                                                                                                                                                                       |
| `_router`       | address | mAsset address if the output is a bAsset. Feeder Pool address if the output is a fAsset.                                                                                                                                                                                                                                                                                                  |
| `_isBassetOut`  | bool    | `true` if `output` is a bAsset. `false` if `output` is a fAsset.                                                                                                                                                                                                                                                                                                                          |

###

### poke()

`function poke () external`

External poke function allows for the redistribution of collateral between here and the current connector, setting the ratio back to the defined optimal.


# Feeder Pool

Feeder Pools are 50/50 AMMs, usually consisting of one mAsset and another mAsset-like asset. Feeder Pools are an extension of the mStable ecosystem and allow for more assets to swap and mint.

Contracts are upgradable except for integration contracts. The ProtocolDAO multisig can migrate the assets from one integration contract to another.

{% tabs %}
{% tab title="Polygon" %}

| Contracts                                                                                                                         | Address                                                                                                                  |
| --------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| [mUSD/FRAX Feeder Pool](https://github.com/mstable/mStable-contracts/blob/master/contracts%2Ffeeders%2FFeederPool.sol)            | [0xb30a907084ac8a0d25dddab4e364827406fd09f0](https://polygonscan.com/address/0xb30a907084ac8a0d25dddab4e364827406fd09f0) |
| mUSD/FRAX Farm (FRAX Contract)                                                                                                    | [0xc425Fd9Ed3C892d849C9E1a971516da1C1B29696](https://polygonscan.com/address/0xc425Fd9Ed3C892d849C9E1a971516da1C1B29696) |
| [Feeder Interest Validator](https://github.com/mstable/mStable-contracts/blob/master/contracts%2Ffeeders%2FInterestValidator.sol) | [0x4A268958BC2f0173CDd8E0981C4c0a259b5cA291](https://polygonscan.com/address/0x4A268958BC2f0173CDd8E0981C4c0a259b5cA291) |
| {% endtab %}                                                                                                                      |                                                                                                                          |
| {% endtabs %}                                                                                                                     |                                                                                                                          |

Feeder Pool tokens follow the ERC20 standard. The non-standard [`decreaseAllowance`](https://docs.openzeppelin.com/contracts/2.x/api/token/erc20#ERC20-decreaseAllowance-address-uint256-) and [`increaseAllowance`](https://docs.openzeppelin.com/contracts/2.x/api/token/erc20#ERC20-increaseAllowance-address-uint256-) functions have been added to mitigate the well-known issues around setting allowances. These are based on the OpenZeppelin ERC20 implementation.

## ERC-20 Functions

### totalSupply()

`function totalSupply () external returns (uint256)`

Returns the amount of tokens in existence.

### balanceOf()

`function balanceOf () external returns (uint256)`

Returns the amount of tokens owned by `account`.

### transfer()

`function transfer () external returns (bool)`

Moves `amount` tokens from the caller's account to `recipient`.

Returns a boolean value indicating whether the operation succeeded.

Emits a {Transfer} event.

### allowance()

`function allowance () external returns (uint256)`

Returns the remaining number of tokens that`spender`will be allowed to spend on behalf of`owner`through {transferFrom}. This is zero by default.

This value changes when {approve} or {transferFrom} are called.

### approve()

`function approve () external returns (bool)`

Sets `amount` as the allowance of `spender` over the caller's tokens.

Returns a boolean value indicating whether the operation succeeded.

IMPORTANT: Beware that changing an allowance with this method brings the risk that someone may use both the old and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: <https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729>

Emits an {Approval} event.

### transferFrom()

`function transferFrom () external returns (bool)`

Moves `amount` tokens from `sender` to `recipient` using the allowance mechanism. `amount` is then deducted from the caller's allowance.

Returns a boolean value indicating whether the operation succeeded.

Emits a {Transfer} event.&#x20;

### increaseAllowance()

`function increaseAllowance () public returns (bool)`

Atomically increases the allowance granted to `spender` by the caller.

This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}.

Emits an {Approval} event indicating the updated allowance.

Requirements:

* `spender` cannot be the zero address.

### decreaseAllowance()

`function decreaseAllowance () public returns (bool)`

Atomically decreases the allowance granted to `spender` by the caller.

This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}.

Emits an {Approval} event indicating the updated allowance.

Requirements:

* `spender` cannot be the zero address.
* `spender` must have allowance for the caller of at least

  `subtractedValue`.

## Feeder Pool Functions

### mint()

`function mint (address _input, uint256 _inputQuantity, uint256 _minOutputQuantity, address _recipient) external returns (uint256 mintOutput)`

Mint fpTokens with a single bAsset. This contract must have approval to spend the senders bAsset. Supports either fAsset, mAsset or mpAsset as input - with mpAssets used to mint mAsset before depositing.

| Parameter            | Type    | Description                                                            |
| -------------------- | ------- | ---------------------------------------------------------------------- |
| `_input`             | address | Address of the bAsset to deposit.                                      |
| `_inputQuantity`     | uint256 | Quantity in input token units.                                         |
| `_minOutputQuantity` | uint256 | Minimum fpToken quantity to be minted. This protects against slippage. |
| `_recipient`         | address | Receipient of the newly minted fpTokens                                |

### mintMulti()

`function mintMulti (address[] _inputs, uint256[] _inputQuantities, uint256 _minOutputQuantity, address _recipient) external returns (uint256 mintOutput)`

Mint fpTokens with multiple bAssets. This contract must have approval to spend the senders bAssets. Supports only fAsset or mAsset as inputs.

| Parameter            | Type       | Description                                                            |
| -------------------- | ---------- | ---------------------------------------------------------------------- |
| `_inputs`            | address\[] | Address of the bAssets to deposit.                                     |
| `_inputQuantities`   | uint256\[] | Quantity in input token units.                                         |
| `_minOutputQuantity` | uint256    | Minimum fpToken quantity to be minted. This protects against slippage. |
| `_recipient`         | address    | Receipient of the newly minted fpTokens                                |

### getMintOutput()

`function getMintOutput (address _input, uint256 _inputQuantity) external returns (uint256 mintOutput)`

Get the projected output of a given mint.

| Parameter        | Type    | Description                      |
| ---------------- | ------- | -------------------------------- |
| `_input`         | address | Address of the bAsset to deposit |
| `_inputQuantity` | uint256 | Quantity in bAsset units         |

### getMintMultiOutput()

`function getMintMultiOutput (address[] _inputs, uint256[] _inputQuantities) external returns (uint256 mintOutput)`

Get the projected output of a given mint

| Parameter          | Type       | Description                                                                                  |
| ------------------ | ---------- | -------------------------------------------------------------------------------------------- |
| `_inputs`          | address\[] | Non-duplicate address array of addresses to bAssets to deposit for the minted mAsset tokens. |
| `_inputQuantities` | uint256\[] | Quantity of each bAsset to deposit for the minted fpToken.                                   |

### swap()

`function swap (address _input, address _output, uint256 _inputQuantity, uint256 _minOutputQuantity, address _recipient) external returns (uint256 swapOutput)`

Swaps two assets - either internally between fAsset<>mAsset, or between fAsset<>mpAsset by first routing through the mAsset pool.

| Parameter            | Type    | Description                                                               |
| -------------------- | ------- | ------------------------------------------------------------------------- |
| `_input`             | address | Address of bAsset to deposit                                              |
| `_output`            | address | Address of bAsset to withdraw                                             |
| `_inputQuantity`     | uint256 | Units of input bAsset to swap in                                          |
| `_minOutputQuantity` | uint256 | Minimum quantity of the swap output asset. This protects against slippage |
| `_recipient`         | address | Address to transfer output asset to                                       |

### getSwapOutput()

`function getSwapOutput (address _input, address _output, uint256 _inputQuantity) external returns (uint256 swapOutput)`

Determines both if a trade is valid, and the expected fee or output. Swap is valid if it does not result in the input asset exceeding its maximum weight.

| Parameter        | Type    | Description                   |
| ---------------- | ------- | ----------------------------- |
| `_input`         | address | Address of bAsset to deposit  |
| `_output`        | address | Address of bAsset to receive  |
| `_inputQuantity` | uint256 | Units of input bAsset to swap |

### redeem()

`function redeem (address _output, uint256 _fpTokenQuantity, uint256 _minOutputQuantity, address _recipient) external returns (uint256 outputQuantity)`

Burns a specified quantity of the senders fpToken in return for a bAsset. The output amount is derived from the invariant. Supports redemption into either the fAsset, mAsset or assets in the mAsset basket.

| Parameter            | Type    | Description                                                                               |
| -------------------- | ------- | ----------------------------------------------------------------------------------------- |
| `_output`            | address | Address of the bAsset to withdraw                                                         |
| `_fpTokenQuantity`   | uint256 | Quantity of LP Token to burn                                                              |
| `_minOutputQuantity` | uint256 | Minimum bAsset quantity to receive for the burnt fpToken. This protects against slippage. |
| `_recipient`         | address | Address to transfer the withdrawn bAssets to.                                             |

### redeemProportionately()

`function redeemProportionately (uint256 _inputQuantity, uint256[] _minOutputQuantities, address _recipient) external returns (uint256[] outputQuantities)`

Credits a recipient with a proportionate amount of bAssets, relative to current vault balance levels and desired fpToken quantity. Burns the fpToken as payment. Only fAsset & mAsset are supported in this path.

| Parameter              | Type       | Description                             |
| ---------------------- | ---------- | --------------------------------------- |
| `_inputQuantity`       | uint256    | Quantity of fpToken to redeem           |
| `_minOutputQuantities` | uint256\[] | Min units of output to receive          |
| `_recipient`           | address    | Address to credit the withdrawn bAssets |

### redeemExactBassets()

`function redeemExactBassets (address[] _outputs, uint256[] _outputQuantities, uint256 _maxInputQuantity, address _recipient) external returns (uint256 fpTokenQuantity)`

Credits a recipient with a certain quantity of selected bAssets, in exchange for burning the relative fpToken quantity from the sender. Only fAsset & mAsset (0,1) are supported in this path.

| Parameter           | Type       | Description                                                                                |
| ------------------- | ---------- | ------------------------------------------------------------------------------------------ |
| `_outputs`          | address\[] | Addresses of the bAssets to receive                                                        |
| `_outputQuantities` | uint256\[] | Units of the bAssets to receive                                                            |
| `_maxInputQuantity` | uint256    | Maximum fpToken quantity to burn for the received bAssets. This protects against slippage. |
| `_recipient`        | address    | Address to receive the withdrawn bAssets                                                   |

### getRedeemOutput()

`function getRedeemOutput (address _output, uint256 _fpTokenQuantity) external returns (uint256 bAssetOutput)`

Gets the estimated output from a given redeem

| Parameter          | Type    | Description                      |
| ------------------ | ------- | -------------------------------- |
| `_output`          | address | Address of the bAsset to receive |
| `_fpTokenQuantity` | uint256 | Quantity of fpToken to redeem    |

### getRedeemExactBassetsOutput()

`function getRedeemExactBassetsOutput (address[] _outputs, uint256[] _outputQuantities) external returns (uint256 fpTokenQuantity)`

Gets the estimated output from a given redeem

| Parameter           | Type       | Description                        |
| ------------------- | ---------- | ---------------------------------- |
| `_outputs`          | address\[] | Addresses of the bAsset to receive |
| `_outputQuantities` | uint256\[] | Quantities of bAsset to redeem     |

### getPrice()

`function getPrice () public returns (uint256 price, uint256 k)`

Gets the price of the fpToken, and invariant value k

### getConfig()

`function getConfig () external returns (struct FeederConfig config)`

Gets all config needed for general InvariantValidator calls

### getBasset()

`function getBasset (address _bAsset) external returns (struct BassetPersonal personal, struct BassetData vaultData)`

Get data for a specific bAsset, if it exists

| Parameter | Type    | Description       |
| --------- | ------- | ----------------- |
| `_bAsset` | address | Address of bAsset |

### getBassets()

`function getBassets () external returns (struct BassetPersonal[], struct BassetData[] vaultData)`

Get data for a all bAssets in basket


# Vaults

Vaults are used to earn rewards. Tokens such as imUSD or Feeder Pool tokens can be deposited to earn additional MTA rewards. On Polygon the contract `HeadlessRewardToken` is used. This allows for accrual of 2 Rewards and does not contain the Boost functionality that is present on Ethereum Mainnet. Contracts are upgradable.

{% hint style="warning" %}
The Feeder Pool Vault for mUSD/FRAX has been developed by frax.finance and is not part of these docs.
{% endhint %}

The following table lays out the currently deployed vaults and what contract is used.

{% tabs %}
{% tab title="Polygon" %}

| Vault                                                                                                                                 | Address                                                                                                                  |
| ------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| [imUSD Vault](https://github.com/mstable/mStable-contracts/blob/master/contracts/rewards/staking/StakingRewardsWithPlatformToken.sol) | [0x32aba856dc5ffd5a56bcd182b13380e5c855aa29](https://polygonscan.com/address/0x32aba856dc5ffd5a56bcd182b13380e5c855aa29) |
| mUSD/FRAX Feeder Pool Vault (FRAX Contract)                                                                                           | [0xc425fd9ed3c892d849c9e1a971516da1c1b29696](https://polygonscan.com/address/0xc425fd9ed3c892d849c9e1a971516da1c1b29696) |
| {% endtab %}                                                                                                                          |                                                                                                                          |
| {% endtabs %}                                                                                                                         |                                                                                                                          |

## imUSD Vault

### stake()

`function stake (uint256 _amount) external`

Stakes a given amount of the StakingToken for the sender

| Parameter | Type    | Description           |
| --------- | ------- | --------------------- |
| `_amount` | uint256 | Units of StakingToken |

### stake()

`function stake (address _beneficiary, uint256 _amount) external`

Stakes a given amount of the StakingToken for a given beneficiary

| Parameter      | Type    | Description                                |
| -------------- | ------- | ------------------------------------------ |
| `_beneficiary` | address | Staked tokens are credited to this address |
| `_amount`      | uint256 | Units of StakingToken                      |

### exit()

`function exit () external`

Withdraws stake from pool and claims any rewards

### withdraw()

`function withdraw (uint256 _amount) external`

Withdraws given stake amount from the pool

### withdrawAndUnwrap()

`function withdrawAndUnwrap (uint256 _amount, uint256 _minAmountOut, address _output, address _beneficiary, address _router, bool _isBassetOut) external returns (uint256 outputQuantity)`

Redeems staked interest-bearing asset tokens for either bAsset or fAsset tokens. Withdraws a given staked amount of interest-bearing assets from the vault, redeems the interest-bearing asset for the underlying mAsset and either

1. Redeems the underlying mAsset tokens for bAsset tokens.
2. Swaps the underlying mAsset tokens for fAsset tokens in a Feeder Pool.

| Parameter       | Type    | Description                                                                                                                                                                                                                                                                                                                                                                                      |      |
| --------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---- |
| `_amount`       | uint256 | Units of the staked interest-bearing asset tokens to withdraw. eg imUSD or imBTC.                                                                                                                                                                                                                                                                                                                |      |
| `_minAmountOut` | uint256 | Minimum units of `output` tokens to be received by the beneficiary. This is to the same decimal places as the `output` token.                                                                                                                                                                                                                                                                    |      |
| `_output`       | address | <p>Asset to receive in exchange for the redeemed mAssets. This can be a bAsset or a fAsset. For example: <br>    - bAssets (USDC, DAI, sUSD or USDT) or fAssets (GUSD, BUSD, alUSD, FEI or RAI) for mainnet imUSD Vault.</p><p>- bAssets (USDC, DAI or USDT) or fAsset FRAX for Polygon imUSD Vault.</p><p>- bAssets (WBTC, sBTC or renBTC) or fAssets (HBTC or TBTCV2) for mainnet imBTC Vault. | </p> |
| `_beneficiary`  | address | Address to send `output` tokens to.                                                                                                                                                                                                                                                                                                                                                              |      |
| `_router`       | address | mAsset address if the `output` is a bAsset. Feeder Pool address if the `output` is a fAsset.                                                                                                                                                                                                                                                                                                     |      |
| `_isBassetOut`  | bool    | `true` if `output` is a bAsset. `false` if `output` is a fAsset                                                                                                                                                                                                                                                                                                                                  |      |

### claimReward()

`function claimReward () external`

Claims outstanding rewards (both platform and native) for the sender. First updates outstanding reward allocation and then transfers.

### claimRewardOnly()

`function claimRewardOnly () external`

Claims outstanding rewards for the sender. Only the native rewards token, and not the platform rewards

### getRewardToken()

`function getRewardToken () external returns (contract IERC20)`

Gets the RewardsToken

### getPlatformToken()

`function getPlatformToken () external returns (contract IERC20)`

Gets the PlatformToken

### lastTimeRewardApplicable()

`function lastTimeRewardApplicable () public returns (uint256)`

Gets the last applicable timestamp for this reward period

### rewardPerToken()

`function rewardPerToken () public returns (uint256, uint256)`

Calculates the amount of unclaimed rewards a user has earned

### earned()

`function earned (address _account) public returns (uint256, uint256)`

Calculates the amount of unclaimed rewards a user has earned

| Parameter  | Type    | Description  |
| ---------- | ------- | ------------ |
| `_account` | address | User address |

### notifyRewardAmount()

`function notifyRewardAmount (uint256 _reward) external`

Notifies the contract that new rewards have been added. Calculates an updated rewardRate based on the rewards in period.

| Parameter | Type    | Description                                           |
| --------- | ------- | ----------------------------------------------------- |
| `_reward` | uint256 | Units of RewardToken that have been added to the pool |

### totalSupply()

`function totalSupply () public returns (uint256)`

Get the total amount of the staked token

### balanceOf()

`function balanceOf (address _account) public returns (uint256)`

Get the balance of a given account

<table data-header-hidden><thead><tr><th width="403.3333333333333">Parameter</th><th>Type</th><th>Description</th></tr></thead><tbody><tr><td>Parameter</td><td>Type</td><td>Description</td></tr><tr><td><code>_account</code></td><td>address</td><td>User for which to retrieve balance</td></tr></tbody></table>


# Save Wrapper

The Save Wrapper bundles utility functions together to simplify multiple interactions with mStable's smart contract calls into one single call. This contract is immutable.

{% tabs %}
{% tab title="Polygon Mainnet" %}

| Name                                                                                                                        | Contract                                                                                                             | Address                                                                                                                  |
| --------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| [Save Wrapper](https://github.com/mstable/mStable-contracts/blob/master/contracts%2Fsavings%2Fperipheral%2FSaveWrapper.sol) | [SaveWrapper](https://github.com/mstable/mStable-contracts/blob/master/contracts/savings/peripheral/SaveWrapper.sol) | [0xfd8932F4887E39D8EeD05dc407924124026bD902](https://polygonscan.com/address/0xfd8932F4887E39D8EeD05dc407924124026bD902) |
| {% endtab %}                                                                                                                |                                                                                                                      |                                                                                                                          |
| {% endtabs %}                                                                                                               |                                                                                                                      |                                                                                                                          |

## Functions

### saveAndStake()

`function saveAndStake (address _mAsset, address _save, address _vault, uint256 _amount) external`

Simply saves an mAsset and then into the vault

| Parameter | Type    | Description                           |
| --------- | ------- | ------------------------------------- |
| `_mAsset` | address | mAsset address                        |
| `_save`   | address | Save address                          |
| `_vault`  | address | Boosted Savings Vault address         |
| `_amount` | uint256 | Units of mAsset to deposit to savings |

### saveAndStake()

`function saveAndStake (address _mAsset, address _save, address _vault, uint256 _amount, address _referrer) external`

Simply saves an mAsset and then into the vault

| Parameter   | Type    | Description                           |
| ----------- | ------- | ------------------------------------- |
| `_mAsset`   | address | mAsset address                        |
| `_save`     | address | Save address                          |
| `_vault`    | address | Boosted Savings Vault address         |
| `_amount`   | uint256 | Units of mAsset to deposit to savings |
| `_referrer` | address | Referrer address for this deposit.    |

### saveViaMint()

`function saveViaMint (address _mAsset, address _bAsset, address _save, address _vault, uint256 _amount, uint256 _minOut, bool _stake) external`

Mints an mAsset and then deposits to Save/Savings Vault

| Parameter | Type    | Description                                   |
| --------- | ------- | --------------------------------------------- |
| `_mAsset` | address | mAsset address                                |
| `_bAsset` | address | bAsset address                                |
| `_save`   | address | Save address                                  |
| `_vault`  | address | Boosted Savings Vault address                 |
| `_amount` | uint256 | Amount of bAsset to mint with                 |
| `_minOut` | uint256 | Min amount of mAsset to get back              |
| `_stake`  | bool    | Add the imAsset to the Boosted Savings Vault? |

### saveViaMint()

`function saveViaMint (address _mAsset, address _bAsset, address _save, address _vault, uint256 _amount, uint256 _minOut, bool _stake, address _referrer) external`

Mints an mAsset and then deposits to Save/Savings Vault

| Parameter   | Type    | Description                                  |
| ----------- | ------- | -------------------------------------------- |
| `_mAsset`   | address | mAsset address                               |
| `_bAsset`   | address | bAsset address                               |
| `_save`     | address | Save address                                 |
| `_vault`    | address | Boosted Savings Vault address                |
| `_amount`   | uint256 | Amount of bAsset to mint with                |
| `_minOut`   | uint256 | Min amount of mAsset to get back             |
| `_stake`    | bool    | Add the imAsset to the Boosted Savings Vault |
| `_referrer` | address | Referrer address for this deposit.           |

### saveViaSwap()

`function saveViaSwap (address _mAsset, address _save, address _vault, address _feeder, address _fAsset, uint256 _fAssetQuantity, uint256 _minOutputQuantity, bool _stake) external`

Swaps fAsset for mAsset and then deposits to Save/Savings Vault

| Parameter            | Type    | Description                                      |
| -------------------- | ------- | ------------------------------------------------ |
| `_mAsset`            | address | mAsset address                                   |
| `_save`              | address | Save address                                     |
| `_vault`             | address | Boosted Savings Vault address                    |
| `_feeder`            | address | Feeder Pool address                              |
| `_fAsset`            | address | fAsset address                                   |
| `_fAssetQuantity`    | uint256 | Quantity of fAsset sent                          |
| `_minOutputQuantity` | uint256 | Min amount of mAsset to be swapped and deposited |
| `_stake`             | bool    | Deposit the imAsset in the Savings Vault?        |

### saveViaSwap()

`function saveViaSwap (address _mAsset, address _save, address _vault, address _feeder, address _fAsset, uint256 _fAssetQuantity, uint256 _minOutputQuantity, bool _stake, address _referrer) external`

Swaps fAsset for mAsset and then deposits to Save/Savings Vault

| Parameter            | Type    | Description                                      |
| -------------------- | ------- | ------------------------------------------------ |
| `_mAsset`            | address | mAsset address                                   |
| `_save`              | address | Save address                                     |
| `_vault`             | address | Boosted Savings Vault address                    |
| `_feeder`            | address | Feeder Pool address                              |
| `_fAsset`            | address | fAsset address                                   |
| `_fAssetQuantity`    | uint256 | Quantity of fAsset sent                          |
| `_minOutputQuantity` | uint256 | Min amount of mAsset to be swapped and deposited |
| `_stake`             | bool    | Deposit the imAsset in the Savings Vault?        |
| `_referrer`          | address | Referrer address for this deposit.               |

### saveViaUniswapETH()

`function saveViaUniswapETH (address _mAsset, address _save, address _vault, address _uniswap, uint256 _amountOutMin, address[] _path, uint256 _minOutMStable, bool _stake) external`

Buys a bAsset on Uniswap with ETH, then mints imAsset via mAsset, optionally staking in the Boosted Savings Vault

| Parameter        | Type       | Description                              |
| ---------------- | ---------- | ---------------------------------------- |
| `_mAsset`        | address    | mAsset address                           |
| `_save`          | address    | Save address                             |
| `_vault`         | address    | Boosted vault address                    |
| `_uniswap`       | address    | Uniswap router address                   |
| `_amountOutMin`  | uint256    | Min uniswap output in bAsset units       |
| `_path`          | address\[] | Sell path on Uniswap (e.g. \[WETH, DAI]) |
| `_minOutMStable` | uint256    | Min amount of mAsset to receive          |
| `_stake`         | bool       | Add the imAsset to the Savings Vault?    |

### saveViaUniswapETH()

`function saveViaUniswapETH (address _mAsset, address _save, address _vault, address _uniswap, uint256 _amountOutMin, address[] _path, uint256 _minOutMStable, bool _stake, address _referrer) external`

Buys a bAsset on Uniswap with ETH, then mints imAsset via mAsset,optionally staking in the Boosted Savings Vault

| Parameter        | Type       | Description                              |
| ---------------- | ---------- | ---------------------------------------- |
| `_mAsset`        | address    | mAsset address                           |
| `_save`          | address    | Save address                             |
| `_vault`         | address    | Boosted vault address                    |
| `_uniswap`       | address    | Uniswap router address                   |
| `_amountOutMin`  | uint256    | Min uniswap output in bAsset units       |
| `_path`          | address\[] | Sell path on Uniswap (e.g. \[WETH, DAI]) |
| `_minOutMStable` | uint256    | Min amount of mAsset to receive          |
| `_stake`         | bool       | Add the imAsset to the Savings Vault?    |
| `_referrer`      | address    | Referrer address for this deposit.       |

### estimate\_saveViaUniswapETH()

`function estimate_saveViaUniswapETH (address _mAsset, address _uniswap, uint256 _ethAmount, address[] _path) external returns (uint256 out)`

Gets estimated mAsset output from a WETH > bAsset > mAsset trade

| Parameter    | Type       | Description                              |
| ------------ | ---------- | ---------------------------------------- |
| `_mAsset`    | address    | mAsset address                           |
| `_uniswap`   | address    | Uniswap router address                   |
| `_ethAmount` | uint256    | ETH amount to sell                       |
| `_path`      | address\[] | Sell path on Uniswap (e.g. \[WETH, DAI]) |


# Shared Addresses

These Contracts are used in other parts of the Protocol. To replace them, a Module has to be proposed in the Nexus contract.

{% tabs %}
{% tab title="Polygon" %}

| Contract                                                                                                                | Address                                                                                                                                            |
| ----------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| [Meta (MTA)](https://github.com/mstable/mStable-contracts/blob/master/contracts%2Fshared%2FMetaToken.sol)               | [0xf501dd45a1198c2e1b5aef5314a68b9006d842e0](https://polygonscan.com/token/0xf501dd45a1198c2e1b5aef5314a68b9006d842e0)                             |
| [Nexus](https://github.com/mstable/mStable-contracts/blob/master/contracts%2Fnexus%2FNexus.sol)                         | [0x3C6fbB8cbfCB75ecEC5128e9f73307f2cB33f2f6](https://explorer-mainnet.maticvigil.com/address/0x3C6fbB8cbfCB75ecEC5128e9f73307f2cB33f2f6/contracts) |
| [Savings Manager](https://github.com/mstable/mStable-contracts/blob/master/contracts%2Fsavings%2FSavingsManager.sol)    | [0x10bFcCae079f31c451033798a4Fd9D2c33Ea5487](https://explorer-mainnet.maticvigil.com/address/0x10bFcCae079f31c451033798a4Fd9D2c33Ea5487)           |
| [Liquidator](https://github.com/mstable/mStable-contracts/blob/master/contracts%2Fmasset%2Fliquidator%2FLiquidator.sol) | [0x9F1C06CC13EDc7691a2Cf02E31FaAA64d57867e2](https://explorer-mainnet.maticvigil.com/address/0x9F1C06CC13EDc7691a2Cf02E31FaAA64d57867e2)           |
| {% endtab %}                                                                                                            |                                                                                                                                                    |

{% tab title="Mumbai Testnet" %}

| Contract        | Address                                    |
| --------------- | ------------------------------------------ |
| Nexus           | 0xCB4aabDb4791B35bDc9348bb68603a68a59be28E |
| Savings Manager | 0x86818a2EACcDC6e1C2d7A301E4Ebb394a3c61b85 |
| Liquidator      | 0x42fdF7abe24387b786ca317B46945F2792A964e1 |
| {% endtab %}    |                                            |
| {% endtabs %}   |                                            |


# Multisig Admin Rights

The ProtocolDAO is a Gnosis Safe multisig 4/6 to be found on&#x20;

* Ethereum Mainnet: [0xF6FF1F7FCEB2cE6d26687EaaB5988b445d0b94a2](https://etherscan.io/address/0xF6FF1F7FCEB2cE6d26687EaaB5988b445d0b94a2)
* Polygon: [0x429F29A3A36B1B977C3d4Ec77C695c3391e7B9ED](https://polygonscan.com/address/0x429F29A3A36B1B977C3d4Ec77C695c3391e7B9ED)

{% hint style="info" %}
Each Signer is responsible to check that a transaction has governance approval. The Signer-Group consists of Core Contributors and Community Members.
{% endhint %}

The Multisig has the following admin functions with Timelocks:

* Propose and Accept new Implementation Contract of Upgradable Contracts (Proxy Contract, 7 days time-lock), see [Proxy Contracts](#proxy-contracts-with-7-days-time-lock)
* Propose and Accept new Modules in the Nexus Contract (7 days time-lock), see [Nexus Modules](#undefined)

### Pause Controls for unhealthy basket

* The Multisig can Pause the following contracts in case the basket of mAssets is undercollaterized and therefore becomes unhealthy:
  * mAssets (mUSD and mBTC)
  * FeederPool and NonPeggedFeederPool
  * SavingsManager (to collect and distribute interest to the SavingsContract)
  * SavingsContract (if flag to collect and stream interesting is true, see SavingsManager)

### Proxy contracts with 7 days time-lock

* mAsset (mUSD and mBTC)
* imAsset (SavingsContract)
* FeederPools
* NonPeggedFeederPool
* BoostedSavingsVault
* BoostedSavingsVault V2
* BoostedDualVault
* LiquidatorProxy
* Staked MTA (stkMTA)
* Staked mBPT (stkBPT)
* Quest Manager

### Proxy contracts with no time-lock

These will be changed to a 7 day time-lock after 2 months of usage.

* Convex 3Crv Vaults
* Meta Vault of Convex 3Crv Vaults
* USDC 3Pool Convex Meta Vault
* CowSwapDex
* Liquidator

### Immutable Contracts

* Nexus
* MetaToken
* Aave Integrations
* CREAM integrations
* Compound Integrations
* Governance Collector
* Revenue Recipient
* BoostDirector V2
* SavingsManager
* DelayedProxyAdmin
* Reward Distributor
* Poker of Boosted Vaults
* Save Wrapper
* Emissions Controller
* VotiumBribeForwarder
* BasicRewardsForwarder
* RevenueBuyBack

### Nexus modules

* MetaToken
* SavingsManager
* Liquidator
* LiquidatorV2
* Treasury
* InterestValidator
* Keeper
* Governor
* ProxyAdmin


# Security Audits

#### Audits can be found here:

{% embed url="<https://consensys.net/diligence/audits/2020/07/mstable-1.1>" %}

{% embed url="<https://www.certik.org/projects/mstable>" %}

{% content-ref url="/pages/av30ipRt2r0sz7VRKAxT" %}
[Hacken Vault Security Audit](/security/security-audits/hacken-vault-security-audit)
{% endcontent-ref %}

#### Also, Defi safety rated mStable:

{% embed url="<https://docs.defisafety.com/finished-reviews/mstable-process-quality-review-v0.7-update>" %}


# Hacken Vault Security Audit

{% embed url="<https://hacken.io/wp-content/uploads/2022/12/mStable_01122022_SCAudit_Report.pdf>" %}


# Bug Bounty

Open reward pool for discovering and reporting vulnerabilities in the mStable protocol.

Our awesome friends over at **Immunefi.com** are the best place to see a quick breakdown of mStable's bug bounty. Check it out [here](https://immunefi.com/bounty/mstable/).

An **ongoing** bug bounty for the smart contracts of the mStable protocol is now live. mStable intends for hackers to look for smart contract vulnerabilities in our system that can lead to loss of collateral, unfair payouts or locked components. mStable must be as resilient as possible. Please submit a bug and earn a reward of up to US$25,000 **\*\*(or more in extreme circumstances)**.\*\*

*Submissions \*\*must adhere to the* [*bug bounty rules*](https://developers.mstable.org/security/bug-bounty#rules)***.**\*\*\*\**

{% hint style="info" %}
Found a bug? Follow the [responsible disclosure guidelines](https://developers.mstable.org/security/bug-bounty#responsible-disclosure) to submit to mStable
{% endhint %}

## **Rewards**

Rewards will be awarded at the sole discretion of the mStableDAO. The quality of the report and reproduction instructions can impact the reward. Rewards are denominated mUSD and will be paid out in mUSD.

The bug bounty program is ongoing and has been running since June 05th, 2020.

NB: Payout amounts increased (max 25k) as of July 14th, 2020.

**The reward will be based on the following severity scheme, based on the** [**OWASP risk rating**](https://owasp.org/www-community/OWASP_Risk_Rating_Methodology) **methodology:**

![](https://1563241728-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MgJxLWD6SqMELu7agWt%2F-MlJMx7td8w4JoWSPs_u%2F-MlJNFGM6d1SEBYiJZfF%2FScreen%20Shot%202021-01-30%20at%201.05.59%20pm.png?alt=media\&token=292d88a1-d9fc-4dcd-8a15-6d2ce3b77dcd)

## **Reporting**

{% hint style="info" %}
Found a bug? Follow the [responsible disclosure guidelines](https://developers.mstable.org/security/bug-bounty#responsible-disclosure) to submit to the team at [Immunefi](https://immunefi.com/bounty/mstable/) or directly to the mStable team.

Failure to following the guidelines will result in a finding being ineligible for any bounties
{% endhint %}

## **Scope**

The bug bounty is applicable to mStable's solidity contract suite, specifically any contracts residing in [**mstable/mStable-contracts/contracts**](https://github.com/mstable/mStable-contracts/tree/master/contracts) *\*\**&#x6F;n "master" branch (excluding the "z\_mocks" sub-folder).

{% embed url="<https://github.com/mstable/mstable-contracts>" %}

### Out of scope

* Any front-end applications or client-side code interacting with the contracts, as well as testing code
* Mismatch of the functionality of the contracts and outdated spec documents

### Areas of interest

* **Loss of collateral or stealing of funds from the mAsset, resulting in it becoming under-collateralised** (*related: `contracts/masset/*/*`)*
* Unfair payouts through SAVE, MINT, REDEEM or SWAP functionalities that results in under-collateralised or affected system (*related: `contracts/masset/**/*`, `contracts/savings/*`)*
* Manipulating or circumvention of mStable governance mechanism *(related: `contracts/nexus/Nexus.sol`, `contracts/governance/*`)*
* Locking or freezing or any of the mStable contracts or inability to upgrade (*related: `contracts/upgradability/*`*)
* Ineffective or error prone forge validation mechanisms (*related: `contracts/masset/forge-validator/*`*)

## Resources

[mStable Docs - GitBook](https://docs.mstable.org)

\*\*\*\*[**mStable GitHub**](https://github.com/mstable/mstable-contracts)\*\*\*\*

\*\*\*\*[Immunefi](https://immunefi.com/)

## Rules

* Public disclosure of the vulnerability, before explicit consent from mStable to do so, will make the vulnerability ineligible for a bounty
* Attempting to exploit the vulnerability in any public Ethereum network will also make it ineligible for a bounty
* Only unknown vulnerabilities will be awarded a bounty; in case of duplicate reports, the first report will be awarded the bounty
* If you want to add more information to a provided issue, create a new submission giving reference to the initial one
* Rewards will be decided on a case by case basis and the bug bounty program, terms, and conditions are at the sole discretion of mStable
* Submissions need to be related with the Bounty [Scope](https://developers.mstable.org/security/bug-bounty#scope). Submissions out of the Bounty Scope won’t be eligible for a reward
* Any interference with the protocol, client or platform services, on purpose or not during the process will make the submission invalid
* Terms and conditions of the bug bounty process may vary over time
* It is mandatory to read and follow the [responsible disclosure policy](https://developers.mstable.org/security/bug-bounty#responsible-disclosure) available in the references. Submissions not following the disclosure policy will not be eligible for a reward

### **Exclusions**

While researching, we’d like to ask you to refrain from:

* Denial of service
* Spamming
* Social engineering (including phishing) of mStable staff or contractors

### Responsible disclosure

In case you discover a vulnerability, we would like to know about it immediately so we can take steps to address it as quickly as possible.

**If you discover a vulnerability, please do the following**:

* E-mail your findings to[ security@mstable.org](mailto:security@mstable.org) with the subject "Bug bounty"
* **Do not** take advantage of the vulnerability or problem you have discovered
* **Do not** reveal the problem to others **until** it has been resolved
* **Do not** use attacks on physical security, social engineering, distributed denial of service, spam or applications of third parties;
* **Do** provide sufficient information to reproduce the problem, so we will be able to resolve it as quickly as possible. Complex vulnerabilities may require further explanation so we might ask you for additional information

**We promise the following:**

* We will respond to your report with a confirmation of receipt, followed by our evaluation of the report and an expected resolution date within 3 business days&#x20;
* If you have followed the [instructions above](https://app.gitbook.com/@mstable/s/mstable/protocol/security/mstable-bug-bounty#rules), we will not take any legal action against you in regard to the report
* We will handle your report with strict confidentiality, and not pass on your personal details to third parties without your permission
* If you so wish we will keep you informed of the progress towards resolving the problem;
* In the public information concerning the problem reported, we will give your name as the discoverer of the problem (unless you desire otherwise)
* We offer a reward for every report of a security problem that was not yet known to us. The amount of the reward will be determined based on the severity of the leak, the quality of the report and any additional assistance you provide

{% hint style="info" %}
Questions? Reach out to us on [Discord](https://discord.com/invite/pgCVG7e) or via [Email](mailto:info@mstable.org)
{% endhint %}


