# Mune.Finance

Degen for Everyone.

Proudly facilitating flashloans for charity !


# About Mune

\[🌑]

[Mune is a *for-profit, positive-impact DAO.*](https://munedao.medium.com/introducing-mune-8305fa87ea11) &#x20;

Our first product is Mune.Finance-- an automated market maker (AMM) on the Polygon network, designed to enable efficient trading between pegged value crypto assets, and facilitate flashloans for charity. Built through [b4b](https://saddle.finance/#/b4b), and with ongoing support from [Saddle](https://saddle.finance) through project SEMPI, we hope to bring their revolutionary opensource stableswap implementation to polygon for years to come. Supporting low-slippage trades, capital efficient metaswaps, and low-fee flashloans on the future ecosystem of pegged value crypto assets, both native and bridged.

We believe that DeFi represents what could be the greatest wealth transfer in human history-- we want at least some of that money to go to something meaningful.&#x20;

Each quarter the community will vote for one nonprofit organization to receive 50% of the admin fees, generated over that period:

inquiries: <munefinance@protonmail.com>&#x20;

## Understanding pegged value crypto assets

### What are pegged value crypto assets ?

Pegged value crypto assets are tokens that have their value pegged to an underlying asset by some means. For example, the value of a stablecoin or tokenized bitcoin is supposed to be $1 or 1 BTC, respectively.

However, pegged value crypto assets fix this value using different mechanisms. Some assets, like Synthetix sBTC or sUSD, maintain their peg synthetically (in this case, via collateralization of SNX). Other assets maintain their peg by being backed by and redeemable for the actual underlying asset, either permissionlessly (e.g. tBTC) or through a centralized custodian (e.g. WBTC, USDC).

These different approaches and the associated risks are why the prices of pegged value crypto assets of the same type can vary slightly.

### What’s the issue with pegged value crypto assets ?

Trading among and in between these types of assets can be expensive and inefficient, resulting in lost capital due to high slippage and transaction fees.

### How does Mune address this ?

The math powering Mune is specifically tailored to allow users to trade between these assets with minimal slippage-- and thanks to Polygon; no contract calls on Mune should ever cost anything noticeable.&#x20;

## Notable Mune Info

### Rewards

At this time, outside of fees-- LPs are rewarded with a warm fuzzy feeling in their hearts. Financial incentives to LP are soon to come, and our earliest users will not be forgotten for their kindness🤫

### Security

The security of user funds is our top priority. Mune is built on Saddle's new Solidity implementation of the [StableSwap](https://curve.fi/files/stableswap-paper.pdf) algorithm by Curve. Security audits were preformed by [Certik](https://certik.foundation/), [Quantstamp](https://quantstamp.com/), and [OpenZeppelin](https://openzeppelin.com/). Read the audits [here](https://github.com/saddle-finance/saddle-audits), and the audits for Curve [here](https://curve.fi/audits).

All the Mune contracts are verified on Polygonscan and open-sourced with an MIT license. Users are free to launch the contracts on a private network with Hardhat for [testing](https://github.com/MuneFinance/MuneFinance/blob/main/README.md), or redistribute them with any modifications as they see fit.

## Keeping up with Mune

Find us on [Discord](https://discord.gg/ZB2t26MtgX), [Twitter](https://twitter.com/MuneFinance), [Telegram](https://t.me/munetalk), [Github](https://github.com/MuneFinance), and [Medium](https://munedao.medium.com/).


# How To Use Mune.Finance

\[🌘]

Mune is an automated market maker optimized for pegged value crypto assets. With Mune, there are two general actions users can first take: **swap** or **deposit**. Swapping between two assets on Mune gives users efficient trading and low slippage. Depositing assets into a pool on Mune allows users to participate in the protocol as liquidity providers and [earn reward incentives](https://gysr.io).

Head to [m](https://mune.finance)[une.finance ](https://mune.finance)to get started!

### Swap on Mune

1. Select “Swap” on the top navigation bar.
2. Select the currency you’re exchanging, and the one you want to receive. (Tip: swaping from overweight assets into underweight assets will result in a bonus.)
3. Enter the amount you’d like to exchange.
4. Click “Advanced” to select options like slippage, gas, or transaction deadline.
5. Click “Swap”, review the details, and confirm the transaction.

### Deposit on Mune

1. Select “Pools” on the top navigation bar, Select "Deposit"
2. Enter the amount(s) you’d like to deposit of one or more of the assets listed (Tip: deposit underweight assets to receive an LP token bonus).
3. Click “Advanced” to select options like slippage and gas.
4. Click “Deposit” review the details, and confirm the transaction.
5. After the transaction is confirmed, stake your LP tokens \[*coming soon*]
6. Keep track of your rewards!

### Withdraw from Mune

1. Select “Pools” on the top navigation bar, Select "Withdraw"
2. Enter the amount(s) you’d like to withdraw of one or more of the assets listed (Tip: withdraw overweight assets to receive a bonus).
3. Click “Advanced” to select options like transaction deadline and gas.
4. Click “Withdraw” review the details, and confirm the transaction.


# How To Flashloan Assets From Mune

\[🌗]

```typescript
function flashLoan(
    address receiver,
    IERC20 token,
    uint256 amount,
    bytes memory params
) external;
```

Caller must provide a valid receiver address that inherits [IFlashLoanReceiver interface](https://github.com/MuneFinance/MuneFinance/blob/main/contracts/interfaces/IFlashLoanReceiver.sol).

```typescript
function executeOperation(
    address pool,
    address token,
    uint256 amount,
    uint256 fee,
    bytes calldata params
) external;
```

Upon finishing `executeOperation`, the pool must have the initial liquidity back along with the associated fee. If the requirement is not met, then the transaction will fail.

Here is a basic example of a flash-loan borrower contract:

```typescript
// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../interfaces/IFlashLoanReceiver.sol";
import "../interfaces/ISwapFlashLoan.sol";
import "hardhat/console.sol";

contract FlashLoanBorrowerExample is IFlashLoanReceiver {
    using SafeMath for uint256;

    // Typical executeOperation function should do the 3 following actions
    // 1. Check if the flashLoan was successful
    // 2. Do actions with the borrowed tokens
    // 3. Repay the debt to the `pool`
    function executeOperation(
        address pool,
        address token,
        uint256 amount,
        uint256 fee,
        bytes calldata params
    ) external override {
        // 1. Check if the flashLoan was valid
        require(
            IERC20(token).balanceOf(address(this)) >= amount,
            "flashloan is broken?"
        );

        // 2. Do actions with the borrowed token
        bytes32 paramsHash = keccak256(params);
        if (paramsHash == keccak256(bytes("dontRepayDebt"))) {
            return;
        } else if (paramsHash == keccak256(bytes("reentrancy_addLiquidity"))) {
            ISwapFlashLoan(pool).addLiquidity(
                new uint256[](0),
                0,
                block.timestamp
            );
        } else if (paramsHash == keccak256(bytes("reentrancy_swap"))) {
            ISwapFlashLoan(pool).swap(1, 0, 1e6, 0, now);
        } else if (
            paramsHash == keccak256(bytes("reentrancy_removeLiquidity"))
        ) {
            ISwapFlashLoan(pool).removeLiquidity(1e18, new uint256[](0), now);
        } else if (
            paramsHash == keccak256(bytes("reentrancy_removeLiquidityOneToken"))
        ) {
            ISwapFlashLoan(pool).removeLiquidityOneToken(1e18, 0, 1e18, now);
        }

        // 3. Payback debt
        uint256 totalDebt = amount.add(fee);
        IERC20(token).transfer(pool, totalDebt);
    }

    function flashLoan(
        ISwapFlashLoan swap,
        IERC20 token,
        uint256 amount,
        bytes memory params
    ) external {
        swap.flashLoan(address(this), token, amount, params);
    }
}
```


# FAQ

\[🌖]

Answers to your questions about AMMs, tokenized assets, the Mune.Finance app, and more.

Still have questions? Join our[ Discord,](https://discord.gg/ZB2t26MtgX) or reach out on [Telegram](https://t.me/munetalk).

## Questions

### What is Mune.Finance?

Mune.Finance is an automated market maker (AMM) for pegged value crypto assets. Mune.Finance enables anyone holding a pegged value crypto asset to trade in between other pegged assets with minimal slippage, ensuring users don’t lose value while trading.

50% of our admin fees go to a community chosen non-profit each quarter. We are-- as far as we know-- the first platform to facilitate flashloans for charity.&#x20;

### What are pegged value crypto assets?

Pegged value crypto assets are tokens that have their value pegged to an underlying asset by some means. For example, the value of a stablecoin or tokenized bitcoin is supposed to be $1 or 1 BTC, respectively.

However, pegged value crypto assets fix this value using different mechanisms. Some assets, like Synthetix sBTC or sUSD, maintain their peg synthetically (in this case, via collateralization of SNX). Other assets maintain their peg by being backed by and redeemable for the actual underlying asset, either permissionlessly (e.g. tBTC) or through a centralized custodian (e.g. WBTC, USDC).

These different approaches and the associated risks are why the prices of pegged value crypto assets of the same type can vary slightly.

### What is price impact?

Price impact is the difference between the current market price and estimated execution price due to order size.

### What is max slippage?

Max slippage is the maximum percentage the execution price can change unfavorably by, if exceeded your transaction will revert.

Slippage occurs when other trades change the price during the window between when your transaction is submitted and actually executed.

### What is the A parameter (amplification coefficient)?

The A parameter, or amplification coefficient, is a configurable setting that determines how flat the liquidity curve for each pool is. For example, consider A = 1 vs. A = 10:

![](https://2540360731-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-Mh54yrV4ZyPNALT0Au6%2F-Mh9z6cDAgPaHDdaTG9J%2F-MhA27yfEySd7FFdzrKh%2Fimage.png?alt=media\&token=d214f1cc-604b-47d9-bb18-025aebfac2cd)

Pools with more volatile assets will use lower A values. (note: USD pool has a current A = 200)

### What tokens does Mune.Finance currently support?

| Token | Homepage                     |
| ----- | ---------------------------- |
| DAI   | <https://makerdao.com/>      |
| USDC  | <https://www.centre.io/usdc> |
| USDT  | <https://tether.to/>         |
| FRAX  | <https://frax.finance/>      |

### Will Mune.Finance support other asset pools?

Yes !

### Does Mune have a token?

No. 👀

### Who can use Mune.Finance?

At launch, **everyone** will be able to use Mune’s AMM to trade stablecoin pairs.

At launch, only **developers** will be able to flashloan from Mune's pool.

### What are the Mune.Finance liquidity provider rewards?

At this time, outside of fees-- LPs are rewarded with a warm fuzzy feeling in their hearts. Financial incentives to LP are soon to come, and our earliest users will not be forgotten for the size of their hearts 🤫

### What are the fees for using Mune.Finance?

There is an industry standard 0.04% fee on all swaps-- 50% of which is charged as an admin fee for charity and users.

A competitive 6bps fee is applied to flashloans.

### Is Mune.Finance safe?

Mune.Finance is built on the contracts developed by the amazing team at Saddle (based on the work done by the amazing team at Curve), which have been audited by Certik, Quantstamp, and OpenZeppelin. Read the audits [here](https://github.com/saddle-finance/saddle-audits).  There is also a comprehensive breakdown of the math behind all our platforms from [Curve](https://curve.fi/files/stableswap-paper.pdf) \[*warning:* link will download a PDF]-- or, for the more [visually inclined](https://www.youtube.com/watch?v=GuD3jkPgPgU).

### Where is the snapshot voting?

Snapshot voting will be enabled prior to the first donation.

### Who built Mune?

Mune was built by oldschool mainnet enthusiasts, and new parents.&#x20;


# Contract Addresses

\[🌕]

## Utils

| Contract Name         | Contract Address                                                                                                              |
| --------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| `SafeMath[MathUtils]` | [0x58c5A9d904411EbFBCf2A1c7aC14b86cFa88af9C](https://polygonscan.com/address/0x58c5A9d904411EbFBCf2A1c7aC14b86cFa88af9C#code) |
| `SwapUtils`           | [0x66b1920B61651A422BD32C91C79aCBf32fB0dEF1](https://polygonscan.com/address/0x66b1920B61651A422BD32C91C79aCBf32fB0dEF1#code) |
| `SwapFlashLoan`       | [0x63C0c411F591fB0F157E70c1129D632090E2F84e](https://polygonscan.com/address/0x63C0c411F591fB0F157E70c1129D632090E2F84e#code) |
| `LPToken`             | [0x3a53d3a8Ac2a686448496F3B08A23DA1110B0172](https://polygonscan.com/address/0x3a53d3a8Ac2a686448496F3B08A23DA1110B0172#code) |
| `MetaSwapUtils`       | [0x3165e09CA44B52b4dC40eaB8D867a39910c1D53f](https://polygonscan.com/address/0x3165e09CA44B52b4dC40eaB8D867a39910c1D53f#code) |

## USD Pool

| Contract Name        | Contract Address                                                                                                              |
| -------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| `MuneUSDPool`        | [0xc03DB5066571D4334D4aC7379145A867DD4d5480](https://polygonscan.com/address/0xc03DB5066571D4334D4aC7379145A867DD4d5480#code) |
| `MuneUSDPoolLPToken` | [0x2B333A621dDC34C4fA12c9B088AbA30BBCd55179](https://polygonscan.com/address/0x2B333A621dDC34C4fA12c9B088AbA30BBCd55179#code) |

## DAI Metapool

| Contract Name            | Contract Address                                                                                                              |
| ------------------------ | ----------------------------------------------------------------------------------------------------------------------------- |
| `MuneDAIMetaPool`        | [0xF1759bd517DcC2938043c55BfAAE096A7C7C24Fb](https://polygonscan.com/address/0xF1759bd517DcC2938043c55BfAAE096A7C7C24Fb#code) |
| `MuneDAIMetaPoolLPToken` | [0x48AD165409350AE84c5F8F4B8249833aF075c27c](https://polygonscan.com/address/0x48AD165409350AE84c5F8F4B8249833aF075c27c#code) |
| `MuneDAIMetaPoolDeposit` | [0xF7a9D62A9b5Fb3B74F3f21B3B47FDB481767Ae5b](https://polygonscan.com/address/0xF7a9D62A9b5Fb3B74F3f21B3B47FDB481767Ae5b#code) |

## USDT Metapool

| Contract Name             | Contract Address                                                                                                              |
| ------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| `MuneUSDTMetaPool`        | [0xb00982846ED52D3e0109A907aeaAE7Be24F602DF](https://polygonscan.com/address/0xb00982846ED52D3e0109A907aeaAE7Be24F602DF#code) |
| `MuneUSDTMetaPoolLPToken` | [0x9bc778aBb2D4217b6613b6D2166478b777A8780b](https://polygonscan.com/address/0x9bc778aBb2D4217b6613b6D2166478b777A8780b#code) |
| `MuneUSDTMetaPoolDeposit` | [0x49FC44b4c555c07fF88151B2FA7382E0b07513B7](https://polygonscan.com/address/0x49FC44b4c555c07fF88151B2FA7382E0b07513B7#code) |


# Past Donations

This page includes the history of past donations: Recipient organization, value of donation in USD, and a link to all relevant transactions on Polygonscan and Etherscan.

| Recipient | Amount | Transaction Hashes (polygon) | Transaction Hashes (mainnet) |
| --------- | ------ | ---------------------------- | ---------------------------- |
|           |        |                              |                              |
|           |        |                              |                              |
|           |        |                              |                              |
|           |        |                              |                              |
|           |        |                              |                              |


# App

A link to the Mune.

#### <https://app.mune.finance>


# Website

A link back to Earth.

#### [https://mune.finance](https://www.mune.finance)


# NFTs

The Mune.Finance Waterburbs, by DaeBee

[**https://opensea.io/collection/munefinance**](https://opensea.io/collection/munefinance)


# SwapUtils

A library to be used within Swap.sol. Contains functions responsible for custody and AMM functionalities.

Contracts relying on this library must initialize SwapUtils.Swap struct then use this library for SwapUtils.Swap struct. Note that this library contains both functions called by users and admins. Admin functions should be protected within contracts using this library.

## Functions:

* [`getA(struct SwapUtils.Swap self)`](broken://pages/-Mh9Wx9ciEsnsH-trhzM#SwapUtils-getA-struct-SwapUtils-Swap-)
* [`getAPrecise(struct SwapUtils.Swap self)`](broken://pages/-Mh9Wx9ciEsnsH-trhzM#SwapUtils-getAPrecise-struct-SwapUtils-Swap-)
* [`getDepositTimestamp(struct SwapUtils.Swap self, address user)`](broken://pages/-Mh9Wx9ciEsnsH-trhzM#SwapUtils-getDepositTimestamp-struct-SwapUtils-Swap-address-)
* [`calculateWithdrawOneToken(struct SwapUtils.Swap self, address account, uint256 tokenAmount, uint8 tokenIndex)`](broken://pages/-Mh9Wx9ciEsnsH-trhzM#SwapUtils-calculateWithdrawOneToken-struct-SwapUtils-Swap-address-uint256-uint8-)
* [`getVirtualPrice(struct SwapUtils.Swap self)`](broken://pages/-Mh9Wx9ciEsnsH-trhzM#SwapUtils-getVirtualPrice-struct-SwapUtils-Swap-)
* [`calculateSwap(struct SwapUtils.Swap self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx)`](broken://pages/-Mh9Wx9ciEsnsH-trhzM#SwapUtils-calculateSwap-struct-SwapUtils-Swap-uint8-uint8-uint256-)
* [`calculateRemoveLiquidity(struct SwapUtils.Swap self, address account, uint256 amount)`](broken://pages/-Mh9Wx9ciEsnsH-trhzM#SwapUtils-calculateRemoveLiquidity-struct-SwapUtils-Swap-address-uint256-)
* [`calculateCurrentWithdrawFee(struct SwapUtils.Swap self, address user)`](broken://pages/-Mh9Wx9ciEsnsH-trhzM#SwapUtils-calculateCurrentWithdrawFee-struct-SwapUtils-Swap-address-)
* [`calculateTokenAmount(struct SwapUtils.Swap self, address account, uint256[] amounts, bool deposit)`](broken://pages/-Mh9Wx9ciEsnsH-trhzM#SwapUtils-calculateTokenAmount-struct-SwapUtils-Swap-address-uint256---bool-)
* [`getAdminBalance(struct SwapUtils.Swap self, uint256 index)`](broken://pages/-Mh9Wx9ciEsnsH-trhzM#SwapUtils-getAdminBalance-struct-SwapUtils-Swap-uint256-)
* [`swap(struct SwapUtils.Swap self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy)`](broken://pages/-Mh9Wx9ciEsnsH-trhzM#SwapUtils-swap-struct-SwapUtils-Swap-uint8-uint8-uint256-uint256-)
* [`addLiquidity(struct SwapUtils.Swap self, uint256[] amounts, uint256 minToMint, bytes32[] merkleProof)`](broken://pages/-Mh9Wx9ciEsnsH-trhzM#SwapUtils-addLiquidity-struct-SwapUtils-Swap-uint256---uint256-bytes32---)
* [`updateUserWithdrawFee(struct SwapUtils.Swap self, address user, uint256 toMint)`](broken://pages/-Mh9Wx9ciEsnsH-trhzM#SwapUtils-updateUserWithdrawFee-struct-SwapUtils-Swap-address-uint256-)
* [`removeLiquidity(struct SwapUtils.Swap self, uint256 amount, uint256[] minAmounts)`](broken://pages/-Mh9Wx9ciEsnsH-trhzM#SwapUtils-removeLiquidity-struct-SwapUtils-Swap-uint256-uint256---)
* [`removeLiquidityOneToken(struct SwapUtils.Swap self, uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount)`](broken://pages/-Mh9Wx9ciEsnsH-trhzM#SwapUtils-removeLiquidityOneToken-struct-SwapUtils-Swap-uint256-uint8-uint256-)
* [`removeLiquidityImbalance(struct SwapUtils.Swap self, uint256[] amounts, uint256 maxBurnAmount)`](broken://pages/-Mh9Wx9ciEsnsH-trhzM#SwapUtils-removeLiquidityImbalance-struct-SwapUtils-Swap-uint256---uint256-)
* [`withdrawAdminFees(struct SwapUtils.Swap self, address to)`](broken://pages/-Mh9Wx9ciEsnsH-trhzM#SwapUtils-withdrawAdminFees-struct-SwapUtils-Swap-address-)
* [`setAdminFee(struct SwapUtils.Swap self, uint256 newAdminFee)`](broken://pages/-Mh9Wx9ciEsnsH-trhzM#SwapUtils-setAdminFee-struct-SwapUtils-Swap-uint256-)
* [`setSwapFee(struct SwapUtils.Swap self, uint256 newSwapFee)`](broken://pages/-Mh9Wx9ciEsnsH-trhzM#SwapUtils-setSwapFee-struct-SwapUtils-Swap-uint256-)
* [`setDefaultWithdrawFee(struct SwapUtils.Swap self, uint256 newWithdrawFee)`](broken://pages/-Mh9Wx9ciEsnsH-trhzM#SwapUtils-setDefaultWithdrawFee-struct-SwapUtils-Swap-uint256-)
* [`rampA(struct SwapUtils.Swap self, uint256 futureA_, uint256 futureTime_)`](broken://pages/-Mh9Wx9ciEsnsH-trhzM#SwapUtils-rampA-struct-SwapUtils-Swap-uint256-uint256-)
* [`stopRampA(struct SwapUtils.Swap self)`](broken://pages/-Mh9Wx9ciEsnsH-trhzM#SwapUtils-stopRampA-struct-SwapUtils-Swap-)

## Events:

* [`TokenSwap(address buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId)`](broken://pages/-Mh9Wx9ciEsnsH-trhzM#SwapUtils-TokenSwap-address-uint256-uint256-uint128-uint128-)
* [`AddLiquidity(address provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply)`](broken://pages/-Mh9Wx9ciEsnsH-trhzM#SwapUtils-AddLiquidity-address-uint256---uint256---uint256-uint256-)
* [`RemoveLiquidity(address provider, uint256[] tokenAmounts, uint256 lpTokenSupply)`](broken://pages/-Mh9Wx9ciEsnsH-trhzM#SwapUtils-RemoveLiquidity-address-uint256---uint256-)
* [`RemoveLiquidityOne(address provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought)`](broken://pages/-Mh9Wx9ciEsnsH-trhzM#SwapUtils-RemoveLiquidityOne-address-uint256-uint256-uint256-uint256-)
* [`RemoveLiquidityImbalance(address provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply)`](broken://pages/-Mh9Wx9ciEsnsH-trhzM#SwapUtils-RemoveLiquidityImbalance-address-uint256---uint256---uint256-uint256-)
* [`NewAdminFee(uint256 newAdminFee)`](broken://pages/-Mh9Wx9ciEsnsH-trhzM#SwapUtils-NewAdminFee-uint256-)
* [`NewSwapFee(uint256 newSwapFee)`](broken://pages/-Mh9Wx9ciEsnsH-trhzM#SwapUtils-NewSwapFee-uint256-)
* [`NewWithdrawFee(uint256 newWithdrawFee)`](broken://pages/-Mh9Wx9ciEsnsH-trhzM#SwapUtils-NewWithdrawFee-uint256-)
* [`RampA(uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime)`](broken://pages/-Mh9Wx9ciEsnsH-trhzM#SwapUtils-RampA-uint256-uint256-uint256-uint256-)
* [`StopRampA(uint256 currentA, uint256 time)`](broken://pages/-Mh9Wx9ciEsnsH-trhzM#SwapUtils-StopRampA-uint256-uint256-)

## Function `getA(struct SwapUtils.Swap self) → uint256`

Return A, the amplification coefficient *n* (n - 1)

See the StableSwap paper for details

### Parameters:

* `self`: Swap struct to read from

### Return Values:

* A parameter

## Function `getAPrecise(struct SwapUtils.Swap self) → uint256`

Return A in its raw precision

See the StableSwap paper for details

### Parameters:

* `self`: Swap struct to read from

### Return Values:

* A parameter in its raw precision form

## Function `getDepositTimestamp(struct SwapUtils.Swap self, address user) → uint256`

Retrieves the timestamp of last deposit made by the given address

### Parameters:

* `self`: Swap struct to read from

### Return Values:

* timestamp of last deposit

## Function `calculateWithdrawOneToken(struct SwapUtils.Swap self, address account, uint256 tokenAmount, uint8 tokenIndex) → uint256, uint256`

Calculate the dy, the amount of selected token that user receives and the fee of withdrawing in one token

### Parameters:

* `account`: the address that is withdrawing
* `tokenAmount`: the amount to withdraw in the pool's precision
* `tokenIndex`: which token will be withdrawn
* `self`: Swap struct to read from

### Return Values:

* the amount of token user will receive and the associated swap fee

## Function `getVirtualPrice(struct SwapUtils.Swap self) → uint256`

Get the virtual price, to help calculate profit

### Parameters:

* `self`: Swap struct to read from

### Return Values:

* the virtual price, scaled to precision of POOL\_PRECISION\_DECIMALS

## Function `calculateSwap(struct SwapUtils.Swap self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx) → uint256 dy`

Externally calculates a swap between two tokens.

### Parameters:

* `self`: Swap struct to read from
* `tokenIndexFrom`: the token to sell
* `tokenIndexTo`: the token to buy
* `dx`: the number of tokens to sell. If the token charges a fee on transfers, use the amount that gets transferred after the fee.

### Return Values:

* dy the number of tokens the user will get

## Function `calculateRemoveLiquidity(struct SwapUtils.Swap self, address account, uint256 amount) → uint256[]`

A simple method to calculate amount of each underlying tokens that is returned upon burning given amount of LP tokens

### Parameters:

* `account`: the address that is removing liquidity. required for withdraw fee calculation
* `amount`: the amount of LP tokens that would to be burned on withdrawal

### Return Values:

* array of amounts of tokens user will receive

## Function `calculateCurrentWithdrawFee(struct SwapUtils.Swap self, address user) → uint256`

Calculate the fee that is applied when the given user withdraws. Withdraw fee decays linearly over 4 weeks.

### Parameters:

* `user`: address you want to calculate withdraw fee of

### Return Values:

* current withdraw fee of the user

## Function `calculateTokenAmount(struct SwapUtils.Swap self, address account, uint256[] amounts, bool deposit) → uint256`

A simple method to calculate prices from deposits or withdrawals, excluding fees but including slippage. This is helpful as an input into the various "min" parameters on calls to fight front-running

This shouldn't be used outside frontends for user estimates.

### Parameters:

* `self`: Swap struct to read from
* `account`: address of the account depositing or withdrawing tokens
* `amounts`: an array of token amounts to deposit or withdrawal, corresponding to pooledTokens. The amount should be in each pooled token's native precision. If a token charges a fee on transfers, use the amount that gets transferred after the fee.
* `deposit`: whether this is a deposit or a withdrawal

### Return Values:

* if deposit was true, total amount of lp token that will be minted and if

  deposit was false, total amount of lp token that will be burned

## Function `getAdminBalance(struct SwapUtils.Swap self, uint256 index) → uint256`

return accumulated amount of admin fees of the token with given index

### Parameters:

* `self`: Swap struct to read from
* `index`: Index of the pooled token

### Return Values:

* admin balance in the token's precision

## Function `swap(struct SwapUtils.Swap self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy) → uint256`

swap two tokens in the pool

### Parameters:

* `self`: Swap struct to read from and write to
* `tokenIndexFrom`: the token the user wants to sell
* `tokenIndexTo`: the token the user wants to buy
* `dx`: the amount of tokens the user wants to sell
* `minDy`: the min amount the user would like to receive, or revert.

### Return Values:

* amount of token user received on swap

## Function `addLiquidity(struct SwapUtils.Swap self, uint256[] amounts, uint256 minToMint, bytes32[] merkleProof) → uint256`

Add liquidity to the pool

### Parameters:

* `self`: Swap struct to read from and write to
* `amounts`: the amounts of each token to add, in their native precision
* `minToMint`: the minimum LP tokens adding this amount of liquidity should mint, otherwise revert. Handy for front-running mitigation
* `merkleProof`: bytes32 array that will be used to prove the existence of the caller's address in the list of allowed addresses. If the pool is not in the guarded launch phase, this parameter will be ignored.

### Return Values:

* amount of LP token user received

## Function `updateUserWithdrawFee(struct SwapUtils.Swap self, address user, uint256 toMint)`

Update the withdraw fee for `user`. If the user is currently not providing liquidity in the pool, sets to default value. If not, recalculate the starting withdraw fee based on the last deposit's time & amount relative to the new deposit.

### Parameters:

* `self`: Swap struct to read from and write to
* `user`: address of the user depositing tokens
* `toMint`: amount of pool tokens to be minted

## Function `removeLiquidity(struct SwapUtils.Swap self, uint256 amount, uint256[] minAmounts) → uint256[]`

Burn LP tokens to remove liquidity from the pool.

Liquidity can always be removed, even when the pool is paused.

### Parameters:

* `self`: Swap struct to read from and write to
* `amount`: the amount of LP tokens to burn
* `minAmounts`: the minimum amounts of each token in the pool acceptable for this burn. Useful as a front-running mitigation

### Return Values:

* amounts of tokens the user received

## Function `removeLiquidityOneToken(struct SwapUtils.Swap self, uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount) → uint256`

Remove liquidity from the pool all in one token.

### Parameters:

* `self`: Swap struct to read from and write to
* `tokenAmount`: the amount of the lp tokens to burn
* `tokenIndex`: the index of the token you want to receive
* `minAmount`: the minimum amount to withdraw, otherwise revert

### Return Values:

* amount chosen token that user received

## Function `removeLiquidityImbalance(struct SwapUtils.Swap self, uint256[] amounts, uint256 maxBurnAmount) → uint256`

Remove liquidity from the pool, weighted differently than the pool's current balances.

### Parameters:

* `self`: Swap struct to read from and write to
* `amounts`: how much of each token to withdraw
* `maxBurnAmount`: the max LP token provider is willing to pay to remove liquidity. Useful as a front-running mitigation.

### Return Values:

* actual amount of LP tokens burned in the withdrawal

## Function `withdrawAdminFees(struct SwapUtils.Swap self, address to)`

withdraw all admin fees to a given address

### Parameters:

* `self`: Swap struct to withdraw fees from
* `to`: Address to send the fees to

## Function `setAdminFee(struct SwapUtils.Swap self, uint256 newAdminFee)`

Sets the admin fee

adminFee cannot be higher than 100% of the swap fee

### Parameters:

* `self`: Swap struct to update
* `newAdminFee`: new admin fee to be applied on future transactions

## Function `setSwapFee(struct SwapUtils.Swap self, uint256 newSwapFee)`

update the swap fee

fee cannot be higher than 1% of each swap

### Parameters:

* `self`: Swap struct to update
* `newSwapFee`: new swap fee to be applied on future transactions

## Function `setDefaultWithdrawFee(struct SwapUtils.Swap self, uint256 newWithdrawFee)`

update the default withdraw fee. This also affects deposits made in the past as well.

### Parameters:

* `self`: Swap struct to update
* `newWithdrawFee`: new withdraw fee to be applied

## Function `rampA(struct SwapUtils.Swap self, uint256 futureA_, uint256 futureTime_)`

Start ramping up or down A parameter towards given futureA *and futureTime* Checks if the change is too rapid, and commits the new A value only when it falls under the limit range.

### Parameters:

* `self`: Swap struct to update
* `futureA_`: the new A to ramp towards
* `futureTime_`: timestamp when the new A should be reached

## Function `stopRampA(struct SwapUtils.Swap self)`

Stops ramping A immediately. Once this function is called, rampA() cannot be called for another 24 hours

### Parameters:

* `self`: Swap struct to update

## Event `TokenSwap(address buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId)`

No description

## Event `AddLiquidity(address provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply)`

No description

## Event `RemoveLiquidity(address provider, uint256[] tokenAmounts, uint256 lpTokenSupply)`

No description

## Event `RemoveLiquidityOne(address provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought)`

No description

## Event `RemoveLiquidityImbalance(address provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply)`

No description

## Event `NewAdminFee(uint256 newAdminFee)`

No description

## Event `NewSwapFee(uint256 newSwapFee)`

No description

## Event `NewWithdrawFee(uint256 newWithdrawFee)`

No description

## Event `RampA(uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime)`

No description

## Event `StopRampA(uint256 currentA, uint256 time)`

No description


# Swap

This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens in desired ratios for an exchange of the pool token that represents their share of the pool. Users can burn pool tokens and withdraw their share of token(s).

Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets distributed to the LPs.

In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which stops the ratio of the tokens in the pool from changing. Users can always withdraw their tokens via multi-asset withdraws.

Most of the logic is stored as a library `SwapUtils` for the sake of reducing contract's deployment size.

## Functions:

* [`constructor(contract IERC20[] _pooledTokens, uint8[] decimals, string lpTokenName, string lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, contract IAllowlist _allowlist)`](#function-constructor-contract-ierc20-_pooledtokens-uint8-decimals-string-lptokenname-string-lptokens)
* [`getA()`](broken://pages/-Mh9WmQ9IFPK_qLChngk#Swap-getA--)
* [`getAPrecise()`](broken://pages/-Mh9WmQ9IFPK_qLChngk#Swap-getAPrecise--)
* [`getToken(uint8 index)`](broken://pages/-Mh9WmQ9IFPK_qLChngk#Swap-getToken-uint8-)
* [`getTokenIndex(address tokenAddress)`](broken://pages/-Mh9WmQ9IFPK_qLChngk#Swap-getTokenIndex-address-)
* [`getAllowlist()`](broken://pages/-Mh9WmQ9IFPK_qLChngk#Swap-getAllowlist--)
* [`getDepositTimestamp(address user)`](broken://pages/-Mh9WmQ9IFPK_qLChngk#Swap-getDepositTimestamp-address-)
* [`getTokenBalance(uint8 index)`](broken://pages/-Mh9WmQ9IFPK_qLChngk#Swap-getTokenBalance-uint8-)
* [`getVirtualPrice()`](broken://pages/-Mh9WmQ9IFPK_qLChngk#Swap-getVirtualPrice--)
* [`calculateSwap(uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx)`](broken://pages/-Mh9WmQ9IFPK_qLChngk#Swap-calculateSwap-uint8-uint8-uint256-)
* [`calculateTokenAmount(address account, uint256[] amounts, bool deposit)`](broken://pages/-Mh9WmQ9IFPK_qLChngk#Swap-calculateTokenAmount-address-uint256---bool-)
* [`calculateRemoveLiquidity(address account, uint256 amount)`](broken://pages/-Mh9WmQ9IFPK_qLChngk#Swap-calculateRemoveLiquidity-address-uint256-)
* [`calculateRemoveLiquidityOneToken(address account, uint256 tokenAmount, uint8 tokenIndex)`](broken://pages/-Mh9WmQ9IFPK_qLChngk#Swap-calculateRemoveLiquidityOneToken-address-uint256-uint8-)
* [`getAdminBalance(uint256 index)`](broken://pages/-Mh9WmQ9IFPK_qLChngk#Swap-getAdminBalance-uint256-)
* [`swap(uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline)`](broken://pages/-Mh9WmQ9IFPK_qLChngk#Swap-swap-uint8-uint8-uint256-uint256-uint256-)
* [`addLiquidity(uint256[] amounts, uint256 minToMint, uint256 deadline, bytes32[] merkleProof)`](broken://pages/-Mh9WmQ9IFPK_qLChngk#Swap-addLiquidity-uint256---uint256-uint256-bytes32---)
* [`removeLiquidity(uint256 amount, uint256[] minAmounts, uint256 deadline)`](broken://pages/-Mh9WmQ9IFPK_qLChngk#Swap-removeLiquidity-uint256-uint256---uint256-)
* [`removeLiquidityOneToken(uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline)`](broken://pages/-Mh9WmQ9IFPK_qLChngk#Swap-removeLiquidityOneToken-uint256-uint8-uint256-uint256-)
* [`removeLiquidityImbalance(uint256[] amounts, uint256 maxBurnAmount, uint256 deadline)`](broken://pages/-Mh9WmQ9IFPK_qLChngk#Swap-removeLiquidityImbalance-uint256---uint256-uint256-)
* [`updateUserWithdrawFee(address recipient, uint256 transferAmount)`](broken://pages/-Mh9WmQ9IFPK_qLChngk#Swap-updateUserWithdrawFee-address-uint256-)
* [`withdrawAdminFees()`](broken://pages/-Mh9WmQ9IFPK_qLChngk#Swap-withdrawAdminFees--)
* [`setAdminFee(uint256 newAdminFee)`](broken://pages/-Mh9WmQ9IFPK_qLChngk#Swap-setAdminFee-uint256-)
* [`setSwapFee(uint256 newSwapFee)`](broken://pages/-Mh9WmQ9IFPK_qLChngk#Swap-setSwapFee-uint256-)
* [`rampA(uint256 futureA, uint256 futureTime)`](broken://pages/-Mh9WmQ9IFPK_qLChngk#Swap-rampA-uint256-uint256-)
* [`stopRampA()`](broken://pages/-Mh9WmQ9IFPK_qLChngk#Swap-stopRampA--)
* [`disableGuard()`](broken://pages/-Mh9WmQ9IFPK_qLChngk#Swap-disableGuard--)
* [`isGuarded()`](broken://pages/-Mh9WmQ9IFPK_qLChngk#Swap-isGuarded--)

## Events:

* [`TokenSwap(address buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId)`](broken://pages/-Mh9WmQ9IFPK_qLChngk#Swap-TokenSwap-address-uint256-uint256-uint128-uint128-)
* [`AddLiquidity(address provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply)`](broken://pages/-Mh9WmQ9IFPK_qLChngk#Swap-AddLiquidity-address-uint256---uint256---uint256-uint256-)
* [`RemoveLiquidity(address provider, uint256[] tokenAmounts, uint256 lpTokenSupply)`](broken://pages/-Mh9WmQ9IFPK_qLChngk#Swap-RemoveLiquidity-address-uint256---uint256-)
* [`RemoveLiquidityOne(address provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought)`](broken://pages/-Mh9WmQ9IFPK_qLChngk#Swap-RemoveLiquidityOne-address-uint256-uint256-uint256-uint256-)
* [`RemoveLiquidityImbalance(address provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply)`](broken://pages/-Mh9WmQ9IFPK_qLChngk#Swap-RemoveLiquidityImbalance-address-uint256---uint256---uint256-uint256-)
* [`NewAdminFee(uint256 newAdminFee)`](broken://pages/-Mh9WmQ9IFPK_qLChngk#Swap-NewAdminFee-uint256-)
* [`NewSwapFee(uint256 newSwapFee)`](broken://pages/-Mh9WmQ9IFPK_qLChngk#Swap-NewSwapFee-uint256-)
* [`RampA(uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime)`](broken://pages/-Mh9WmQ9IFPK_qLChngk#Swap-RampA-uint256-uint256-uint256-uint256-)
* [`StopRampA(uint256 currentA, uint256 time)`](broken://pages/-Mh9WmQ9IFPK_qLChngk#Swap-StopRampA-uint256-uint256-)

## Function `constructor(contract IERC20[] _pooledTokens, uint8[] decimals, string lpTokenName, string lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, contract IAllowlist _allowlist)`

Deploys this Swap contract with given parameters as default values. This will also deploy a LPToken that represents users LP position. The owner of LPToken will be this contract - which means only this contract is allowed to mint new tokens.

### Parameters:

* `_pooledTokens`: an array of ERC20s this pool will accept
* `decimals`: the decimals to use for each pooled token, eg 8 for WBTC. Cannot be larger than POOL\_PRECISION\_DECIMALS
* `lpTokenName`: the long-form name of the token to be deployed
* `lpTokenSymbol`: the short symbol for the token to be deployed
* `_a`: the amplification coefficient *n* (n - 1). See the StableSwap paper for details
* `_fee`: default swap fee to be initialized with
* `_adminFee`: default adminFee to be initialized with
* `_allowlist`: address of allowlist contract for guarded launch

## Function `getA() → uint256`

Return A, the amplification coefficient *n* (n - 1)

See the StableSwap paper for details

### Return Values:

* A parameter

## Function `getAPrecise() → uint256`

Return A in its raw precision form

See the StableSwap paper for details

### Return Values:

* A parameter in its raw precision form

## Function `getToken(uint8 index) → contract IERC20`

Return address of the pooled token at given index. Reverts if tokenIndex is out of range.

### Parameters:

* `index`: the index of the token

### Return Values:

* address of the token at given index

## Function `getTokenIndex(address tokenAddress) → uint8`

Return the index of the given token address. Reverts if no matching token is found.

### Parameters:

* `tokenAddress`: address of the token

### Return Values:

* the index of the given token address

## Function `getAllowlist() → contract IAllowlist`

Reads and returns the address of the allowlist that is set during deployment of this contract

### Return Values:

* the address of the allowlist contract casted to the IAllowlist interface

## Function `getDepositTimestamp(address user) → uint256`

Return timestamp of last deposit of given address

### Return Values:

* timestamp of the last deposit made by the given address

## Function `getTokenBalance(uint8 index) → uint256`

Return current balance of the pooled token at given index

### Parameters:

* `index`: the index of the token

### Return Values:

* current balance of the pooled token at given index with token's native precision

## Function `getVirtualPrice() → uint256`

Get the virtual price, to help calculate profit

### Return Values:

* the virtual price, scaled to the POOL\_PRECISION\_DECIMALS

## Function `calculateSwap(uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx) → uint256`

Calculate amount of tokens you receive on swap

### Parameters:

* `tokenIndexFrom`: the token the user wants to sell
* `tokenIndexTo`: the token the user wants to buy
* `dx`: the amount of tokens the user wants to sell. If the token charges a fee on transfers, use the amount that gets transferred after the fee.

### Return Values:

* amount of tokens the user will receive

## Function `calculateTokenAmount(address account, uint256[] amounts, bool deposit) → uint256`

A simple method to calculate prices from deposits or withdrawals, excluding fees but including slippage. This is helpful as an input into the various "min" parameters on calls to fight front-running

This shouldn't be used outside frontends for user estimates.

### Parameters:

* `account`: address that is depositing or withdrawing tokens
* `amounts`: an array of token amounts to deposit or withdrawal, corresponding to pooledTokens. The amount should be in each pooled token's native precision. If a token charges a fee on transfers, use the amount that gets transferred after the fee.
* `deposit`: whether this is a deposit or a withdrawal

### Return Values:

* token amount the user will receive

## Function `calculateRemoveLiquidity(address account, uint256 amount) → uint256[]`

A simple method to calculate amount of each underlying tokens that is returned upon burning given amount of LP tokens

### Parameters:

* `account`: the address that is withdrawing tokens
* `amount`: the amount of LP tokens that would be burned on withdrawal

### Return Values:

* array of token balances that the user will receive

## Function `calculateRemoveLiquidityOneToken(address account, uint256 tokenAmount, uint8 tokenIndex) → uint256 availableTokenAmount`

Calculate the amount of underlying token available to withdraw when withdrawing via only single token

### Parameters:

* `account`: the address that is withdrawing tokens
* `tokenAmount`: the amount of LP token to burn
* `tokenIndex`: index of which token will be withdrawn

### Return Values:

* availableTokenAmount calculated amount of underlying token

  available to withdraw

## Function `getAdminBalance(uint256 index) → uint256`

This function reads the accumulated amount of admin fees of the token with given index

### Parameters:

* `index`: Index of the pooled token

### Return Values:

* s token balance in the token's precision

## Function `swap(uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline) → uint256`

Swap two tokens using this pool

### Parameters:

* `tokenIndexFrom`: the token the user wants to swap from
* `tokenIndexTo`: the token the user wants to swap to
* `dx`: the amount of tokens the user wants to swap from
* `minDy`: the min amount the user would like to receive, or revert.
* `deadline`: latest timestamp to accept this transaction

## Function `addLiquidity(uint256[] amounts, uint256 minToMint, uint256 deadline, bytes32[] merkleProof) → uint256`

Add liquidity to the pool with given amounts during guarded launch phase. Only users with valid address and proof can successfully call this function. When this function is called after the guarded release phase is over, the merkleProof is ignored.

### Parameters:

* `amounts`: the amounts of each token to add, in their native precision
* `minToMint`: the minimum LP tokens adding this amount of liquidity should mint, otherwise revert. Handy for front-running mitigation
* `deadline`: latest timestamp to accept this transaction
* `merkleProof`: data generated when constructing the allowlist merkle tree. Users can get this data off chain. Even if the address is in the allowlist, users must include a valid proof for this call to succeed. If the pool is no longer in the guarded release phase, this parameter is ignored.

### Return Values:

* amount of LP token user minted and received

## Function `removeLiquidity(uint256 amount, uint256[] minAmounts, uint256 deadline) → uint256[]`

Burn LP tokens to remove liquidity from the pool.&#x20;

Liquidity can always be removed, even when the pool is paused.

### Parameters:

* `amount`: the amount of LP tokens to burn
* `minAmounts`: the minimum amounts of each token in the pool acceptable for this burn. Useful as a front-running mitigation
* `deadline`: latest timestamp to accept this transaction

### Return Values:

* amounts of tokens user received

## Function `removeLiquidityOneToken(uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline) → uint256`

Remove liquidity from the pool all in one token.&#x20;

### Parameters:

* `tokenAmount`: the amount of the token you want to receive
* `tokenIndex`: the index of the token you want to receive
* `minAmount`: the minimum amount to withdraw, otherwise revert
* `deadline`: latest timestamp to accept this transaction

### Return Values:

* amount of chosen token user received

## Function `removeLiquidityImbalance(uint256[] amounts, uint256 maxBurnAmount, uint256 deadline) → uint256`

Remove liquidity from the pool, weighted differently than the pool's current balances.

### Parameters:

* `amounts`: how much of each token to withdraw
* `maxBurnAmount`: the max LP token provider is willing to pay to remove liquidity. Useful as a front-running mitigation.
* `deadline`: latest timestamp to accept this transaction

### Return Values:

* amount of LP tokens burned

## Function `withdrawAdminFees()`

Withdraw all admin fees to the contract owner

## Function `setAdminFee(uint256 newAdminFee)`

Update the admin fee. Admin fee takes portion of the swap fee.

### Parameters:

* `newAdminFee`: new admin fee to be applied on future transactions

## Function `setSwapFee(uint256 newSwapFee)`

Update the swap fee to be applied on swaps

### Parameters:

* `newSwapFee`: new swap fee to be applied on future transactions

## Function `rampA(uint256 futureA, uint256 futureTime)`

Start ramping up or down A parameter towards given futureA and futureTime Checks if the change is too rapid, and commits the new A value only when it falls under the limit range.

### Parameters:

* `futureA`: the new A to ramp towards
* `futureTime`: timestamp when the new A should be reached

## Function `stopRampA()`

Stop ramping A immediately. Reverts if ramp A is already stopped.

## Function `disableGuard()`

Disables the guarded launch phase, removing any limits on deposit amounts and addresses

## Function `isGuarded() → bool`

Reads and returns current guarded status of the pool

### Return Values:

* guarded\_ boolean value indicating whether the deposits should be guarded

## Event `TokenSwap(address buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId)`

No description

## Event `AddLiquidity(address provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply)`

No description

## Event `RemoveLiquidity(address provider, uint256[] tokenAmounts, uint256 lpTokenSupply)`

No description

## Event `RemoveLiquidityOne(address provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought)`

No description

## Event `RemoveLiquidityImbalance(address provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply)`

No description

## Event `NewAdminFee(uint256 newAdminFee)`

No description

## Event `NewSwapFee(uint256 newSwapFee)`

No description

## Event `NewWithdrawFee(uint256 newWithdrawFee)`

No description

## Event `RampA(uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime)`

No description

## Event `StopRampA(uint256 currentA, uint256 time)`

No description


# LP Token

This token is an ERC20 detailed token with added capability to be minted by the owner. It is used to represent user's shares when providing liquidity to swap contracts.

### Functions:

* [`constructor(string name_, string symbol_, uint8 decimals_)`](broken://pages/-Mh9W1p5DCVTrS5bcc-2#LPToken-constructor-string-string-uint8-)
* [`mint(address recipient, uint256 amount, bytes32[] merkleProof)`](broken://pages/-Mh9W1p5DCVTrS5bcc-2#LPToken-mint-address-uint256-bytes32---)

### Function `constructor(string name_, string symbol_, uint8 decimals_)`

Deploys LPToken contract with given name, symbol, and decimals

the caller of this constructor will become the owner of this contract

#### Parameters:

* `name_`: name of this token
* `symbol_`: symbol of this token
* `decimals_`: number of decimals this token will be based on

### Function `mint(address recipient, uint256 amount, bytes32[] merkleProof)`

Mints the given amount of LPToken to the recipient. During the guarded release phase, the total supply and the maximum number of the tokens that a single account can mint are limited.

only owner can call this mint function

#### Parameters:

* `recipient`: address of account to receive the tokens
* `amount`: amount of tokens to mint
* `merkleProof`: the bytes32 array data that is used to prove recipient's address exists in the merkle tree stored in the allowlist contract. If the pool is not guarded, this parameter is ignored.


# ISwap

## Functions:

* [`getA()`](broken://pages/-Mh9X_-xHfPjcqb4OG1l#ISwap-getA--)
* [`getAllowlist()`](broken://pages/-Mh9X_-xHfPjcqb4OG1l#ISwap-getAllowlist--)
* [`getToken(uint8 index)`](broken://pages/-Mh9X_-xHfPjcqb4OG1l#ISwap-getToken-uint8-)
* [`getTokenIndex(address tokenAddress)`](broken://pages/-Mh9X_-xHfPjcqb4OG1l#ISwap-getTokenIndex-address-)
* [`getTokenBalance(uint8 index)`](broken://pages/-Mh9X_-xHfPjcqb4OG1l#ISwap-getTokenBalance-uint8-)
* [`getVirtualPrice()`](broken://pages/-Mh9X_-xHfPjcqb4OG1l#ISwap-getVirtualPrice--)
* [`isGuarded()`](broken://pages/-Mh9X_-xHfPjcqb4OG1l#ISwap-isGuarded--)
* [`calculateSwap(uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx)`](broken://pages/-Mh9X_-xHfPjcqb4OG1l#ISwap-calculateSwap-uint8-uint8-uint256-)
* [`calculateTokenAmount(uint256[] amounts, bool deposit)`](broken://pages/-Mh9X_-xHfPjcqb4OG1l#ISwap-calculateTokenAmount-uint256---bool-)
* [`calculateRemoveLiquidity(uint256 amount)`](broken://pages/-Mh9X_-xHfPjcqb4OG1l#ISwap-calculateRemoveLiquidity-uint256-)
* [`calculateRemoveLiquidityOneToken(uint256 tokenAmount, uint8 tokenIndex)`](broken://pages/-Mh9X_-xHfPjcqb4OG1l#ISwap-calculateRemoveLiquidityOneToken-uint256-uint8-)
* [`swap(uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline)`](broken://pages/-Mh9X_-xHfPjcqb4OG1l#ISwap-swap-uint8-uint8-uint256-uint256-uint256-)
* [`addLiquidity(uint256[] amounts, uint256 minToMint, uint256 deadline, bytes32[] merkleProof)`](broken://pages/-Mh9X_-xHfPjcqb4OG1l#ISwap-addLiquidity-uint256---uint256-uint256-bytes32---)
* [`removeLiquidity(uint256 amount, uint256[] minAmounts, uint256 deadline)`](broken://pages/-Mh9X_-xHfPjcqb4OG1l#ISwap-removeLiquidity-uint256-uint256---uint256-)
* [`removeLiquidityOneToken(uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline)`](broken://pages/-Mh9X_-xHfPjcqb4OG1l#ISwap-removeLiquidityOneToken-uint256-uint8-uint256-uint256-)
* [`removeLiquidityImbalance(uint256[] amounts, uint256 maxBurnAmount, uint256 deadline)`](broken://pages/-Mh9X_-xHfPjcqb4OG1l#ISwap-removeLiquidityImbalance-uint256---uint256-uint256-)
* [`updateUserWithdrawFee(address recipient, uint256 transferAmount)`](broken://pages/-Mh9X_-xHfPjcqb4OG1l#ISwap-updateUserWithdrawFee-address-uint256-)

## Function `getA() → uint256`

No description

## Function `getAllowlist() → contract IAllowlist`

No description

## Function `getToken(uint8 index) → contract IERC20`

No description

## Function `getTokenIndex(address tokenAddress) → uint8`

No description

## Function `getTokenBalance(uint8 index) → uint256`

No description

## Function `getVirtualPrice() → uint256`

No description

## Function `isGuarded() → bool`

No description

## Function `calculateSwap(uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx) → uint256`

No description

## Function `calculateTokenAmount(uint256[] amounts, bool deposit) → uint256`

No description

## Function `calculateRemoveLiquidity(uint256 amount) → uint256[]`

No description

## Function `calculateRemoveLiquidityOneToken(uint256 tokenAmount, uint8 tokenIndex) → uint256 availableTokenAmount`

No description

## Function `swap(uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline) → uint256`

No description

## Function `addLiquidity(uint256[] amounts, uint256 minToMint, uint256 deadline, bytes32[] merkleProof) → uint256`

No description

## Function `removeLiquidity(uint256 amount, uint256[] minAmounts, uint256 deadline) → uint256[]`

No description

## Function `removeLiquidityOneToken(uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline) → uint256`

No description

## Function `removeLiquidityImbalance(uint256[] amounts, uint256 maxBurnAmount, uint256 deadline) → uint256`

No description

## Function `updateUserWithdrawFee(address recipient, uint256 transferAmount)`

No description


# StakeableTokenWrapper

A wrapper for an ERC-20 that can be staked and withdrawn.

In this contract, staked tokens don't do anything- instead other contracts can inherit from this one to add functionality. / c

## Functions:

* [`constructor(contract IERC20 _stakedToken)`](broken://pages/-Mh9WZMCa1vWzwglB9XJ#StakeableTokenWrapper-constructor-contract-IERC20-)
* [`balanceOf(address account)`](broken://pages/-Mh9WZMCa1vWzwglB9XJ#StakeableTokenWrapper-balanceOf-address-)
* [`stake(uint256 amount)`](broken://pages/-Mh9WZMCa1vWzwglB9XJ#StakeableTokenWrapper-stake-uint256-)
* [`withdraw(uint256 amount)`](broken://pages/-Mh9WZMCa1vWzwglB9XJ#StakeableTokenWrapper-withdraw-uint256-)

## Events:

* [`Staked(address user, uint256 amount)`](broken://pages/-Mh9WZMCa1vWzwglB9XJ#StakeableTokenWrapper-Staked-address-uint256-)
* [`Withdrawn(address user, uint256 amount)`](broken://pages/-Mh9WZMCa1vWzwglB9XJ#StakeableTokenWrapper-Withdrawn-address-uint256-)

## Function `constructor(contract IERC20 _stakedToken)`

Creates a new StakeableTokenWrapper with given `_stakedToken` address

### Parameters:

* `_stakedToken`: address of a token that will be used to stake

  /

## Function `balanceOf(address account) → uint256`

Read how much `account` has staked in this contract

### Parameters:

* `account`: address of an account

### Return Values:

* amount of total staked ERC20(this.stakedToken) by `account`

  /

## Function `stake(uint256 amount)`

Stakes given `amount` in this contract

### Parameters:

* `amount`: amount of ERC20(this.stakedToken) to stake

  /

## Function `withdraw(uint256 amount)`

Withdraws given `amount` from this contract

### Parameters:

* `amount`: amount of ERC20(this.stakedToken) to withdraw

  /

## Event `Staked(address user, uint256 amount)`

No description

## Event `Withdrawn(address user, uint256 amount)`

No description


# OwnerPausable

An ownable contract allows the owner to pause and unpause the contract without a delay.

Only methods using the provided modifiers will be paused.

### Functions:

* [`pause()`](broken://pages/-Mh9WOphabkiCIIaf49d#OwnerPausable-pause--)
* [`unpause()`](broken://pages/-Mh9WOphabkiCIIaf49d#OwnerPausable-unpause--)

### Function `pause()`

Pause the contract. Revert if already paused.

### Function `unpause()`

Unpause the contract. Revert if already unpaused.


# MathUtils

A library to be used in conjunction with SafeMath. Contains functions for calculating differences between two uint256.

### Functions:

* [`within1(uint256 a, uint256 b)`](broken://pages/-Mh9WEafa5FqLGwkchC5#MathUtils-within1-uint256-uint256-)
* [`difference(uint256 a, uint256 b)`](broken://pages/-Mh9WEafa5FqLGwkchC5#MathUtils-difference-uint256-uint256-)

### Function `within1(uint256 a, uint256 b) → bool`

Compares a and b and returns true if the difference between a and b is less than 1 or equal to each other.

#### Parameters:

* `a`: uint256 to compare with
* `b`: uint256 to compare with

#### Return Values:

* True if the difference between a and b is less than 1 or equal,

  otherwise return false

### Function `difference(uint256 a, uint256 b) → uint256`

Calculates absolute difference between a and b

#### Parameters:

* `a`: uint256 to compare with
* `b`: uint256 to compare with

#### Return Values:

* Difference between a and b


