ETH Price: $3,413.01 (+3.88%)

Contract

0xaB9dEBAED21270832cCdf54a7461A8E4B133B57A
 

Overview

ETH Balance

0 ETH

Eth Value

$0.00

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To
Approve212501022024-11-23 11:20:118 hrs ago1732360811IN
0xaB9dEBAE...4B133B57A
0 ETH0.0004939810.6026115
Approve212457442024-11-22 20:45:5922 hrs ago1732308359IN
0xaB9dEBAE...4B133B57A
0 ETH0.0005411311.61468515
Approve212424382024-11-22 9:40:5934 hrs ago1732268459IN
0xaB9dEBAE...4B133B57A
0 ETH0.0005080110.90378677
Approve212388582024-11-21 21:40:5946 hrs ago1732225259IN
0xaB9dEBAE...4B133B57A
0 ETH0.0006236913.39006934
Approve212192202024-11-19 3:54:594 days ago1731988499IN
0xaB9dEBAE...4B133B57A
0 ETH0.000403888.66882978
Approve212180502024-11-19 0:00:114 days ago1731974411IN
0xaB9dEBAE...4B133B57A
0 ETH0.0005032910.80231971
Approve212131112024-11-18 7:28:475 days ago1731914927IN
0xaB9dEBAE...4B133B57A
0 ETH0.0004991110.71269326
Approve211991682024-11-16 8:49:357 days ago1731746975IN
0xaB9dEBAE...4B133B57A
0 ETH0.0005651112.20478054
Approve211988812024-11-16 7:51:477 days ago1731743507IN
0xaB9dEBAE...4B133B57A
0 ETH0.0005372311.60866681
Approve211973062024-11-16 2:35:597 days ago1731724559IN
0xaB9dEBAE...4B133B57A
0 ETH0.0006238313.47632308
Approve211968362024-11-16 1:01:237 days ago1731718883IN
0xaB9dEBAE...4B133B57A
0 ETH0.000388315.97498638
Approve211676202024-11-11 23:07:2311 days ago1731366443IN
0xaB9dEBAE...4B133B57A
0 ETH0.001511132.43351495
Approve211339192024-11-07 6:15:1116 days ago1730960111IN
0xaB9dEBAE...4B133B57A
0 ETH0.000334467.17882453
Approve211319222024-11-06 23:34:1116 days ago1730936051IN
0xaB9dEBAE...4B133B57A
0 ETH0.0007148415.3430357
Approve211307382024-11-06 19:35:5917 days ago1730921759IN
0xaB9dEBAE...4B133B57A
0 ETH0.0008954219.34348681
Approve211292372024-11-06 14:34:5917 days ago1730903699IN
0xaB9dEBAE...4B133B57A
0 ETH0.0008843218.98062597
Approve211233552024-11-05 18:51:4718 days ago1730832707IN
0xaB9dEBAE...4B133B57A
0 ETH0.0005005110.74274456
Approve211225062024-11-05 16:00:4718 days ago1730822447IN
0xaB9dEBAE...4B133B57A
0 ETH0.0006889714.879736
Approve211173382024-11-04 22:41:4718 days ago1730760107IN
0xaB9dEBAE...4B133B57A
0 ETH0.0005694612.22587137
Approve210842512024-10-31 7:54:2323 days ago1730361263IN
0xaB9dEBAE...4B133B57A
0 ETH0.000362347.82964953
Approve210807522024-10-30 20:10:3523 days ago1730319035IN
0xaB9dEBAE...4B133B57A
0 ETH0.0004669710.0227973
Approve210689122024-10-29 4:29:3525 days ago1730176175IN
0xaB9dEBAE...4B133B57A
0 ETH0.000449759.71578373
Approve210689122024-10-29 4:29:3525 days ago1730176175IN
0xaB9dEBAE...4B133B57A
0 ETH0.000449759.71578373
Approve210550922024-10-27 6:12:1127 days ago1730009531IN
0xaB9dEBAE...4B133B57A
0 ETH0.000190664.09238078
Approve210536882024-10-27 1:30:3527 days ago1729992635IN
0xaB9dEBAE...4B133B57A
0 ETH0.000085073.5
View all transactions

Latest 1 internal transaction

Advanced mode:
Parent Transaction Hash Block From To
205697112024-08-20 12:03:4795 days ago1724155427  Contract Creation0 ETH
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
PancakeStableSwapLP

Compiler Version
v0.8.10+commit.fc410830

Optimization Enabled:
Yes with 100 runs

Other Settings:
default evmVersion, MIT license
File 1 of 29 : PancakeStableSwapLP.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;

import "@openzeppelin-4.5.0/contracts/token/ERC20/ERC20.sol";

contract PancakeStableSwapLP is ERC20 {
    address public minter;

    constructor() ERC20("Pancake StableSwap LPs", "Stable-LP") {
        minter = msg.sender;
    }

    /**
     * @notice Checks if the msg.sender is the minter address.
     */
    modifier onlyMinter() {
        require(msg.sender == minter, "Not minter");
        _;
    }

    function setMinter(address _newMinter) external onlyMinter {
        minter = _newMinter;
    }

    function mint(address _to, uint256 _amount) external onlyMinter {
        _mint(_to, _amount);
    }

    function burnFrom(address _to, uint256 _amount) external onlyMinter {
        _burn(_to, _amount);
    }
}

File 2 of 29 : IPancakeStableSwap.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;

interface IPancakeStableSwap {
    function token() external view returns (address);

    function balances(uint256 i) external view returns (uint256);

    function N_COINS() external view returns (uint256);

    function RATES(uint256 i) external view returns (uint256);

    function coins(uint256 i) external view returns (address);

    function PRECISION_MUL(uint256 i) external view returns (uint256);

    function fee() external view returns (uint256);

    function admin_fee() external view returns (uint256);

    function A() external view returns (uint256);

    function get_D_mem(uint256[2] memory _balances, uint256 amp) external view returns (uint256);

    function get_y(
        uint256 i,
        uint256 j,
        uint256 x,
        uint256[2] memory xp_
    ) external view returns (uint256);

    function calc_withdraw_one_coin(uint256 _token_amount, uint256 i) external view returns (uint256);

    function add_liquidity(uint256[2] memory amounts, uint256 min_mint_amount) external payable;

    function remove_liquidity(uint256 _amount, uint256[2] memory min_amounts) external;

    function remove_liquidity_imbalance(uint256[2] memory amounts, uint256 max_burn_amount) external;

    function transferOwnership(address newOwner) external;
}

File 3 of 29 : PancakeStableSwapWBNBHelper.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
import "@openzeppelin-4.5.0/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin-4.5.0/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin-4.5.0/contracts/access/Ownable.sol";
import "../interfaces/IWBNB.sol";
import "../interfaces/IPancakeStableSwap.sol";

contract PancakeStableSwapWBNBHelper is Ownable {
    using SafeERC20 for IERC20;

    uint256 public constant N_COINS = 2;
    IWBNB public immutable WBNB;

    // Record whether approved for stable swap smart contract.
    mapping(address => bool) isApproved;

    mapping(address => bool) public isWhitelist;

    error NotWBNBPair();
    error NotWhitelist();
    error InvalidNCOINS();

    event UpdateWhitelist(address swap, bool status);

    constructor(IWBNB _WBNB) {
        WBNB = _WBNB;
    }

    function setWhiteList(address _swap, bool _status) external onlyOwner {
        isWhitelist[_swap] = _status;
        emit UpdateWhitelist(_swap, _status);
    }

    function initSwapPair(IPancakeStableSwap swap) internal {
        address token0 = swap.coins(0);
        address token1 = swap.coins(1);
        address LPToken = swap.token();
        IERC20(token0).safeApprove(address(swap), type(uint256).max);
        IERC20(token1).safeApprove(address(swap), type(uint256).max);
        IERC20(LPToken).safeApprove(address(swap), type(uint256).max);
        isApproved[address(swap)] = true;
    }

    function add_liquidity(
        IPancakeStableSwap swap,
        uint256[N_COINS] memory amounts,
        uint256 min_mint_amount
    ) external payable {
        if (!isWhitelist[address(swap)]) revert NotWhitelist();
        if (swap.N_COINS() != N_COINS) revert InvalidNCOINS();
        if (!isApproved[address(swap)]) initSwapPair(swap);

        address token0 = swap.coins(0);
        address token1 = swap.coins(1);
        uint256 WBNBIndex;
        if (token0 == address(WBNB)) {
            WBNBIndex = 0;
        } else if (token1 == address(WBNB)) {
            WBNBIndex = 1;
        } else {
            revert NotWBNBPair();
        }
        require(msg.value == amounts[WBNBIndex], "Inconsistent quantity");
        WBNB.deposit{value: msg.value}();
        if (WBNBIndex == 0) {
            IERC20(token1).safeTransferFrom(msg.sender, address(this), amounts[1]);
        } else {
            IERC20(token0).safeTransferFrom(msg.sender, address(this), amounts[0]);
        }
        swap.add_liquidity(amounts, min_mint_amount);

        address LPToken = swap.token();
        uint256 mintedLPAmount = IERC20(LPToken).balanceOf(address(this));
        IERC20(LPToken).safeTransfer(msg.sender, mintedLPAmount);
    }

    function remove_liquidity(
        IPancakeStableSwap swap,
        uint256 _amount,
        uint256[N_COINS] memory min_amounts
    ) external {
        if (!isWhitelist[address(swap)]) revert NotWhitelist();
        if (swap.N_COINS() != N_COINS) revert InvalidNCOINS();
        if (!isApproved[address(swap)]) initSwapPair(swap);

        address token0 = swap.coins(0);
        address token1 = swap.coins(1);
        uint256 WBNBIndex;
        if (token0 == address(WBNB)) {
            WBNBIndex = 0;
        } else if (token1 == address(WBNB)) {
            WBNBIndex = 1;
        } else {
            revert NotWBNBPair();
        }
        address LPToken = swap.token();
        IERC20(LPToken).safeTransferFrom(msg.sender, address(this), _amount);
        swap.remove_liquidity(_amount, min_amounts);

        uint256 WBNBBalance = WBNB.balanceOf(address(this));
        WBNB.withdraw(WBNBBalance);
        _safeTransferBNB(msg.sender, address(this).balance);
        if (WBNBIndex == 0) {
            uint256 token1Balance = IERC20(token1).balanceOf(address(this));
            IERC20(token1).safeTransfer(msg.sender, token1Balance);
        } else {
            uint256 token0Balance = IERC20(token0).balanceOf(address(this));
            IERC20(token0).safeTransfer(msg.sender, token0Balance);
        }
    }

    function _safeTransferBNB(address to, uint256 value) internal {
        (bool success, ) = to.call{gas: 2300, value: value}("");
        require(success, "TransferHelper: BNB_TRANSFER_FAILED");
    }

    receive() external payable {
        assert(msg.sender == address(WBNB)); // only accept BNB from the WBNB contract
    }
}

File 4 of 29 : IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the amount of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves `amount` tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 amount) external returns (bool);

    /**
     * @dev 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.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev 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.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `from` to `to` 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.
     */
    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) external returns (bool);

    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);
}

File 5 of 29 : SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";
import "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    using Address for address;

    function safeTransfer(
        IERC20 token,
        address to,
        uint256 value
    ) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
    }

    function safeTransferFrom(
        IERC20 token,
        address from,
        address to,
        uint256 value
    ) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
    }

    /**
     * @dev Deprecated. This function has issues similar to the ones found in
     * {IERC20-approve}, and its usage is discouraged.
     *
     * Whenever possible, use {safeIncreaseAllowance} and
     * {safeDecreaseAllowance} instead.
     */
    function safeApprove(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        // safeApprove should only be called when setting an initial allowance,
        // or when resetting it to zero. To increase and decrease it, use
        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
        require(
            (value == 0) || (token.allowance(address(this), spender) == 0),
            "SafeERC20: approve from non-zero to non-zero allowance"
        );
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
    }

    function safeIncreaseAllowance(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        uint256 newAllowance = token.allowance(address(this), spender) + value;
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
    }

    function safeDecreaseAllowance(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        unchecked {
            uint256 oldAllowance = token.allowance(address(this), spender);
            require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
            uint256 newAllowance = oldAllowance - value;
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
        if (returndata.length > 0) {
            // Return data is optional
            require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
        }
    }
}

File 6 of 29 : Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)

pragma solidity ^0.8.0;

import "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor() {
        _transferOwnership(_msgSender());
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
        _;
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions anymore. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby removing any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

File 7 of 29 : IWBNB.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;

interface IWBNB {
    function deposit() external payable;

    function transfer(address to, uint256 value) external returns (bool);

    function withdraw(uint256) external;

    function balanceOf(address account) external view returns (uint256);

    function approve(address spender, uint256 amount) external returns (bool);
}

File 8 of 29 : Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCall(target, data, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        require(isContract(target), "Address: call to non-contract");

        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        require(isContract(target), "Address: static call to non-contract");

        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(isContract(target), "Address: delegate call to non-contract");

        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            // Look for revert reason and bubble it up if present
            if (returndata.length > 0) {
                // The easiest way to bubble the revert reason is using memory via assembly

                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert(errorMessage);
            }
        }
    }
}

File 9 of 29 : Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }
}

File 10 of 29 : PancakeStableSwapTwoPoolDeployer.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;

import "@openzeppelin-4.5.0/contracts/access/Ownable.sol";
import "./PancakeStableSwapTwoPool.sol";

contract PancakeStableSwapTwoPoolDeployer is Ownable {
    uint256 public constant N_COINS = 2;

    /**
     * @notice constructor
     */
    constructor() {}

    // returns sorted token addresses, used to handle return values from pairs sorted in this order
    function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
        require(tokenA != tokenB, "IDENTICAL_ADDRESSES");
        (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
    }

    /**
     * @notice createSwapPair
     * @param _tokenA: Addresses of ERC20 conracts .
     * @param _tokenB: Addresses of ERC20 conracts .
     * @param _A: Amplification coefficient multiplied by n * (n - 1)
     * @param _fee: Fee to charge for exchanges
     * @param _admin_fee: Admin fee
     * @param _admin: Admin
     * @param _LP: LP
     */
    function createSwapPair(
        address _tokenA,
        address _tokenB,
        uint256 _A,
        uint256 _fee,
        uint256 _admin_fee,
        address _admin,
        address _LP
    ) external onlyOwner returns (address) {
        require(_tokenA != address(0) && _tokenB != address(0) && _tokenA != _tokenB, "Illegal token");
        (address t0, address t1) = sortTokens(_tokenA, _tokenB);
        address[N_COINS] memory coins = [t0, t1];
        // create swap contract
        bytes memory bytecode = type(PancakeStableSwapTwoPool).creationCode;
        bytes32 salt = keccak256(abi.encodePacked(t0, t1, msg.sender, block.timestamp, block.chainid));
        address swapContract;
        assembly {
            swapContract := create2(0, add(bytecode, 32), mload(bytecode), salt)
        }
        PancakeStableSwapTwoPool(swapContract).initialize(coins, _A, _fee, _admin_fee, _admin, _LP);

        return swapContract;
    }
}

File 11 of 29 : PancakeStableSwapTwoPool.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;

import "@openzeppelin-4.5.0/contracts/access/Ownable.sol";
import "@openzeppelin-4.5.0/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin-4.5.0/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "@openzeppelin-4.5.0/contracts/security/ReentrancyGuard.sol";
import "./interfaces/IPancakeStableSwapLP.sol";

contract PancakeStableSwapTwoPool is Ownable, ReentrancyGuard {
    using SafeERC20 for IERC20;

    uint256 public constant N_COINS = 2;

    uint256 public constant MAX_DECIMAL = 18;
    uint256 public constant FEE_DENOMINATOR = 1e10;
    uint256 public constant PRECISION = 1e18;
    uint256[N_COINS] public PRECISION_MUL;
    uint256[N_COINS] public RATES;

    uint256 public constant MAX_ADMIN_FEE = 1e10;
    uint256 public constant MAX_FEE = 5e9;
    uint256 public constant MAX_A = 1e6;
    uint256 public constant MAX_A_CHANGE = 10;
    uint256 public constant MIN_BNB_GAS = 2300;
    uint256 public constant MAX_BNB_GAS = 23000;

    uint256 public constant ADMIN_ACTIONS_DELAY = 3 days;
    uint256 public constant MIN_RAMP_TIME = 1 days;

    address[N_COINS] public coins;
    uint256[N_COINS] public balances;
    uint256 public fee; // fee * 1e10.
    uint256 public admin_fee; // admin_fee * 1e10.
    uint256 public bnb_gas = 4029; // transfer bnb gas.

    IPancakeStableSwapLP public token;

    address constant BNB_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;

    bool support_BNB;

    uint256 public initial_A;
    uint256 public future_A;
    uint256 public initial_A_time;
    uint256 public future_A_time;

    uint256 public admin_actions_deadline;
    uint256 public future_fee;
    uint256 public future_admin_fee;

    uint256 public kill_deadline;
    uint256 public constant KILL_DEADLINE_DT = 2 * 30 days;
    bool public is_killed;

    address public immutable STABLESWAP_FACTORY;
    bool public isInitialized;

    event TokenExchange(
        address indexed buyer,
        uint256 sold_id,
        uint256 tokens_sold,
        uint256 bought_id,
        uint256 tokens_bought
    );
    event AddLiquidity(
        address indexed provider,
        uint256[N_COINS] token_amounts,
        uint256[N_COINS] fees,
        uint256 invariant,
        uint256 token_supply
    );
    event RemoveLiquidity(
        address indexed provider,
        uint256[N_COINS] token_amounts,
        uint256[N_COINS] fees,
        uint256 token_supply
    );
    event RemoveLiquidityOne(address indexed provider, uint256 index, uint256 token_amount, uint256 coin_amount);
    event RemoveLiquidityImbalance(
        address indexed provider,
        uint256[N_COINS] token_amounts,
        uint256[N_COINS] fees,
        uint256 invariant,
        uint256 token_supply
    );
    event CommitNewFee(uint256 indexed deadline, uint256 fee, uint256 admin_fee);
    event NewFee(uint256 fee, uint256 admin_fee);
    event RampA(uint256 old_A, uint256 new_A, uint256 initial_time, uint256 future_time);
    event StopRampA(uint256 A, uint256 t);
    event SetBNBGas(uint256 bnb_gas);
    event RevertParameters();
    event DonateAdminFees();
    event Kill();
    event Unkill();

    /**
     * @notice constructor
     */
    constructor() {
        STABLESWAP_FACTORY = msg.sender;
    }

    /**
     * @notice initialize
     * @param _coins: Addresses of ERC20 conracts of coins (c-tokens) involved
     * @param _A: Amplification coefficient multiplied by n * (n - 1)
     * @param _fee: Fee to charge for exchanges
     * @param _admin_fee: Admin fee
     * @param _owner: Owner
     * @param _LP: LP address
     */
    function initialize(
        address[N_COINS] memory _coins,
        uint256 _A,
        uint256 _fee,
        uint256 _admin_fee,
        address _owner,
        address _LP
    ) external {
        require(!isInitialized, "Operations: Already initialized");
        require(msg.sender == STABLESWAP_FACTORY, "Operations: Not factory");
        require(_A <= MAX_A, "_A exceeds maximum");
        require(_fee <= MAX_FEE, "_fee exceeds maximum");
        require(_admin_fee <= MAX_ADMIN_FEE, "_admin_fee exceeds maximum");
        isInitialized = true;
        for (uint256 i = 0; i < N_COINS; i++) {
            require(_coins[i] != address(0), "ZERO Address");
            uint256 coinDecimal;
            if (_coins[i] == BNB_ADDRESS) {
                coinDecimal = 18;
                support_BNB = true;
            } else {
                coinDecimal = IERC20Metadata(_coins[i]).decimals();
            }
            require(coinDecimal <= MAX_DECIMAL, "The maximum decimal cannot exceed 18");
            //set PRECISION_MUL and  RATES
            PRECISION_MUL[i] = 10**(MAX_DECIMAL - coinDecimal);
            RATES[i] = PRECISION * PRECISION_MUL[i];
        }
        coins = _coins;
        initial_A = _A;
        future_A = _A;
        fee = _fee;
        admin_fee = _admin_fee;
        kill_deadline = block.timestamp + KILL_DEADLINE_DT;
        token = IPancakeStableSwapLP(_LP);

        transferOwnership(_owner);
    }

    function get_A() internal view returns (uint256) {
        //Handle ramping A up or down
        uint256 t1 = future_A_time;
        uint256 A1 = future_A;
        if (block.timestamp < t1) {
            uint256 A0 = initial_A;
            uint256 t0 = initial_A_time;
            // Expressions in uint256 cannot have negative numbers, thus "if"
            if (A1 > A0) {
                return A0 + ((A1 - A0) * (block.timestamp - t0)) / (t1 - t0);
            } else {
                return A0 - ((A0 - A1) * (block.timestamp - t0)) / (t1 - t0);
            }
        } else {
            // when t1 == 0 or block.timestamp >= t1
            return A1;
        }
    }

    function A() external view returns (uint256) {
        return get_A();
    }

    function _xp() internal view returns (uint256[N_COINS] memory result) {
        result = RATES;
        for (uint256 i = 0; i < N_COINS; i++) {
            result[i] = (result[i] * balances[i]) / PRECISION;
        }
    }

    function _xp_mem(uint256[N_COINS] memory _balances) internal view returns (uint256[N_COINS] memory result) {
        result = RATES;
        for (uint256 i = 0; i < N_COINS; i++) {
            result[i] = (result[i] * _balances[i]) / PRECISION;
        }
    }

    function get_D(uint256[N_COINS] memory xp, uint256 amp) internal pure returns (uint256) {
        uint256 S;
        for (uint256 i = 0; i < N_COINS; i++) {
            S += xp[i];
        }
        if (S == 0) {
            return 0;
        }

        uint256 Dprev;
        uint256 D = S;
        uint256 Ann = amp * N_COINS;
        for (uint256 j = 0; j < 255; j++) {
            uint256 D_P = D;
            for (uint256 k = 0; k < N_COINS; k++) {
                D_P = (D_P * D) / (xp[k] * N_COINS); // If division by 0, this will be borked: only withdrawal will work. And that is good
            }
            Dprev = D;
            D = ((Ann * S + D_P * N_COINS) * D) / ((Ann - 1) * D + (N_COINS + 1) * D_P);
            // Equality with the precision of 1
            if (D > Dprev) {
                if (D - Dprev <= 1) {
                    break;
                }
            } else {
                if (Dprev - D <= 1) {
                    break;
                }
            }
        }
        return D;
    }

    function get_D_mem(uint256[N_COINS] memory _balances, uint256 amp) internal view returns (uint256) {
        return get_D(_xp_mem(_balances), amp);
    }

    function get_virtual_price() external view returns (uint256) {
        /**
        Returns portfolio virtual price (for calculating profit)
        scaled up by 1e18
        */
        uint256 D = get_D(_xp(), get_A());
        /**
        D is in the units similar to DAI (e.g. converted to precision 1e18)
        When balanced, D = n * x_u - total virtual value of the portfolio
        */
        uint256 token_supply = token.totalSupply();
        return (D * PRECISION) / token_supply;
    }

    function calc_token_amount(uint256[N_COINS] memory amounts, bool deposit) external view returns (uint256) {
        /**
        Simplified method to calculate addition or reduction in token supply at
        deposit or withdrawal without taking fees into account (but looking at
        slippage).
        Needed to prevent front-running, not for precise calculations!
        */
        uint256[N_COINS] memory _balances = balances;
        uint256 amp = get_A();
        uint256 D0 = get_D_mem(_balances, amp);
        for (uint256 i = 0; i < N_COINS; i++) {
            if (deposit) {
                _balances[i] += amounts[i];
            } else {
                _balances[i] -= amounts[i];
            }
        }
        uint256 D1 = get_D_mem(_balances, amp);
        uint256 token_amount = token.totalSupply();
        uint256 difference;
        if (deposit) {
            difference = D1 - D0;
        } else {
            difference = D0 - D1;
        }
        return (difference * token_amount) / D0;
    }

    function add_liquidity(uint256[N_COINS] memory amounts, uint256 min_mint_amount) external payable nonReentrant {
        //Amounts is amounts of c-tokens
        require(!is_killed, "Killed");
        if (!support_BNB) {
            require(msg.value == 0, "Inconsistent quantity"); // Avoid sending BNB by mistake.
        }
        uint256[N_COINS] memory fees;
        uint256 _fee = (fee * N_COINS) / (4 * (N_COINS - 1));
        uint256 _admin_fee = admin_fee;
        uint256 amp = get_A();

        uint256 token_supply = token.totalSupply();
        //Initial invariant
        uint256 D0;
        uint256[N_COINS] memory old_balances = balances;
        if (token_supply > 0) {
            D0 = get_D_mem(old_balances, amp);
        }
        uint256[N_COINS] memory new_balances = [old_balances[0], old_balances[1]];

        for (uint256 i = 0; i < N_COINS; i++) {
            if (token_supply == 0) {
                require(amounts[i] > 0, "Initial deposit requires all coins");
            }
            // balances store amounts of c-tokens
            new_balances[i] = old_balances[i] + amounts[i];
        }

        // Invariant after change
        uint256 D1 = get_D_mem(new_balances, amp);
        require(D1 > D0, "D1 must be greater than D0");

        // We need to recalculate the invariant accounting for fees
        // to calculate fair user's share
        uint256 D2 = D1;
        if (token_supply > 0) {
            // Only account for fees if we are not the first to deposit
            for (uint256 i = 0; i < N_COINS; i++) {
                uint256 ideal_balance = (D1 * old_balances[i]) / D0;
                uint256 difference;
                if (ideal_balance > new_balances[i]) {
                    difference = ideal_balance - new_balances[i];
                } else {
                    difference = new_balances[i] - ideal_balance;
                }

                fees[i] = (_fee * difference) / FEE_DENOMINATOR;
                balances[i] = new_balances[i] - ((fees[i] * _admin_fee) / FEE_DENOMINATOR);
                new_balances[i] -= fees[i];
            }
            D2 = get_D_mem(new_balances, amp);
        } else {
            balances = new_balances;
        }

        // Calculate, how much pool tokens to mint
        uint256 mint_amount;
        if (token_supply == 0) {
            mint_amount = D1; // Take the dust if there was any
        } else {
            mint_amount = (token_supply * (D2 - D0)) / D0;
        }
        require(mint_amount >= min_mint_amount, "Slippage screwed you");

        // Take coins from the sender
        for (uint256 i = 0; i < N_COINS; i++) {
            uint256 amount = amounts[i];
            address coin = coins[i];
            transfer_in(coin, amount);
        }

        // Mint pool tokens
        token.mint(msg.sender, mint_amount);

        emit AddLiquidity(msg.sender, amounts, fees, D1, token_supply + mint_amount);
    }

    function get_y(
        uint256 i,
        uint256 j,
        uint256 x,
        uint256[N_COINS] memory xp_
    ) internal view returns (uint256) {
        // x in the input is converted to the same price/precision
        require((i != j) && (i < N_COINS) && (j < N_COINS), "Illegal parameter");
        uint256 amp = get_A();
        uint256 D = get_D(xp_, amp);
        uint256 c = D;
        uint256 S_;
        uint256 Ann = amp * N_COINS;

        uint256 _x;
        for (uint256 k = 0; k < N_COINS; k++) {
            if (k == i) {
                _x = x;
            } else if (k != j) {
                _x = xp_[k];
            } else {
                continue;
            }
            S_ += _x;
            c = (c * D) / (_x * N_COINS);
        }
        c = (c * D) / (Ann * N_COINS);
        uint256 b = S_ + D / Ann; // - D
        uint256 y_prev;
        uint256 y = D;

        for (uint256 m = 0; m < 255; m++) {
            y_prev = y;
            y = (y * y + c) / (2 * y + b - D);
            // Equality with the precision of 1
            if (y > y_prev) {
                if (y - y_prev <= 1) {
                    break;
                }
            } else {
                if (y_prev - y <= 1) {
                    break;
                }
            }
        }
        return y;
    }

    function get_dy(
        uint256 i,
        uint256 j,
        uint256 dx
    ) external view returns (uint256) {
        // dx and dy in c-units
        uint256[N_COINS] memory rates = RATES;
        uint256[N_COINS] memory xp = _xp();

        uint256 x = xp[i] + ((dx * rates[i]) / PRECISION);
        uint256 y = get_y(i, j, x, xp);
        uint256 dy = ((xp[j] - y - 1) * PRECISION) / rates[j];
        uint256 _fee = (fee * dy) / FEE_DENOMINATOR;
        return dy - _fee;
    }

    function get_dy_underlying(
        uint256 i,
        uint256 j,
        uint256 dx
    ) external view returns (uint256) {
        // dx and dy in underlying units
        uint256[N_COINS] memory xp = _xp();
        uint256[N_COINS] memory precisions = PRECISION_MUL;

        uint256 x = xp[i] + dx * precisions[i];
        uint256 y = get_y(i, j, x, xp);
        uint256 dy = (xp[j] - y - 1) / precisions[j];
        uint256 _fee = (fee * dy) / FEE_DENOMINATOR;
        return dy - _fee;
    }

    function exchange(
        uint256 i,
        uint256 j,
        uint256 dx,
        uint256 min_dy
    ) external payable nonReentrant {
        require(!is_killed, "Killed");
        if (!support_BNB) {
            require(msg.value == 0, "Inconsistent quantity"); // Avoid sending BNB by mistake.
        }

        uint256[N_COINS] memory old_balances = balances;
        uint256[N_COINS] memory xp = _xp_mem(old_balances);

        uint256 x = xp[i] + (dx * RATES[i]) / PRECISION;
        uint256 y = get_y(i, j, x, xp);

        uint256 dy = xp[j] - y - 1; //  -1 just in case there were some rounding errors
        uint256 dy_fee = (dy * fee) / FEE_DENOMINATOR;

        // Convert all to real units
        dy = ((dy - dy_fee) * PRECISION) / RATES[j];
        require(dy >= min_dy, "Exchange resulted in fewer coins than expected");

        uint256 dy_admin_fee = (dy_fee * admin_fee) / FEE_DENOMINATOR;
        dy_admin_fee = (dy_admin_fee * PRECISION) / RATES[j];

        // Change balances exactly in same way as we change actual ERC20 coin amounts
        balances[i] = old_balances[i] + dx;
        // When rounding errors happen, we undercharge admin fee in favor of LP
        balances[j] = old_balances[j] - dy - dy_admin_fee;

        address iAddress = coins[i];
        if (iAddress == BNB_ADDRESS) {
            require(dx == msg.value, "Inconsistent quantity");
        } else {
            IERC20(iAddress).safeTransferFrom(msg.sender, address(this), dx);
        }
        address jAddress = coins[j];
        transfer_out(jAddress, dy);
        emit TokenExchange(msg.sender, i, dx, j, dy);
    }

    function remove_liquidity(uint256 _amount, uint256[N_COINS] memory min_amounts) external nonReentrant {
        uint256 total_supply = token.totalSupply();
        uint256[N_COINS] memory amounts;
        uint256[N_COINS] memory fees; //Fees are unused but we've got them historically in event

        for (uint256 i = 0; i < N_COINS; i++) {
            uint256 value = (balances[i] * _amount) / total_supply;
            require(value >= min_amounts[i], "Withdrawal resulted in fewer coins than expected");
            balances[i] -= value;
            amounts[i] = value;
            transfer_out(coins[i], value);
        }

        token.burnFrom(msg.sender, _amount); // dev: insufficient funds

        emit RemoveLiquidity(msg.sender, amounts, fees, total_supply - _amount);
    }

    function remove_liquidity_imbalance(uint256[N_COINS] memory amounts, uint256 max_burn_amount)
        external
        nonReentrant
    {
        require(!is_killed, "Killed");

        uint256 token_supply = token.totalSupply();
        require(token_supply > 0, "dev: zero total supply");
        uint256 _fee = (fee * N_COINS) / (4 * (N_COINS - 1));
        uint256 _admin_fee = admin_fee;
        uint256 amp = get_A();

        uint256[N_COINS] memory old_balances = balances;
        uint256[N_COINS] memory new_balances = [old_balances[0], old_balances[1]];
        uint256 D0 = get_D_mem(old_balances, amp);
        for (uint256 i = 0; i < N_COINS; i++) {
            new_balances[i] -= amounts[i];
        }
        uint256 D1 = get_D_mem(new_balances, amp);
        uint256[N_COINS] memory fees;
        for (uint256 i = 0; i < N_COINS; i++) {
            uint256 ideal_balance = (D1 * old_balances[i]) / D0;
            uint256 difference;
            if (ideal_balance > new_balances[i]) {
                difference = ideal_balance - new_balances[i];
            } else {
                difference = new_balances[i] - ideal_balance;
            }
            fees[i] = (_fee * difference) / FEE_DENOMINATOR;
            balances[i] = new_balances[i] - ((fees[i] * _admin_fee) / FEE_DENOMINATOR);
            new_balances[i] -= fees[i];
        }
        uint256 D2 = get_D_mem(new_balances, amp);

        uint256 token_amount = ((D0 - D2) * token_supply) / D0;
        require(token_amount > 0, "token_amount must be greater than 0");
        token_amount += 1; // In case of rounding errors - make it unfavorable for the "attacker"
        require(token_amount <= max_burn_amount, "Slippage screwed you");

        token.burnFrom(msg.sender, token_amount); // dev: insufficient funds

        for (uint256 i = 0; i < N_COINS; i++) {
            if (amounts[i] > 0) {
                transfer_out(coins[i], amounts[i]);
            }
        }
        token_supply -= token_amount;
        emit RemoveLiquidityImbalance(msg.sender, amounts, fees, D1, token_supply);
    }

    function get_y_D(
        uint256 A_,
        uint256 i,
        uint256[N_COINS] memory xp,
        uint256 D
    ) internal pure returns (uint256) {
        /**
        Calculate x[i] if one reduces D from being calculated for xp to D

        Done by solving quadratic equation iteratively.
        x_1**2 + x1 * (sum' - (A*n**n - 1) * D / (A * n**n)) = D ** (n + 1) / (n ** (2 * n) * prod' * A)
        x_1**2 + b*x_1 = c

        x_1 = (x_1**2 + c) / (2*x_1 + b)
        */
        // x in the input is converted to the same price/precision
        require(i < N_COINS, "dev: i above N_COINS");
        uint256 c = D;
        uint256 S_;
        uint256 Ann = A_ * N_COINS;

        uint256 _x;
        for (uint256 k = 0; k < N_COINS; k++) {
            if (k != i) {
                _x = xp[k];
            } else {
                continue;
            }
            S_ += _x;
            c = (c * D) / (_x * N_COINS);
        }
        c = (c * D) / (Ann * N_COINS);
        uint256 b = S_ + D / Ann;
        uint256 y_prev;
        uint256 y = D;

        for (uint256 k = 0; k < 255; k++) {
            y_prev = y;
            y = (y * y + c) / (2 * y + b - D);
            // Equality with the precision of 1
            if (y > y_prev) {
                if (y - y_prev <= 1) {
                    break;
                }
            } else {
                if (y_prev - y <= 1) {
                    break;
                }
            }
        }
        return y;
    }

    function _calc_withdraw_one_coin(uint256 _token_amount, uint256 i) internal view returns (uint256, uint256) {
        // First, need to calculate
        // * Get current D
        // * Solve Eqn against y_i for D - _token_amount
        uint256 amp = get_A();
        uint256 _fee = (fee * N_COINS) / (4 * (N_COINS - 1));
        uint256[N_COINS] memory precisions = PRECISION_MUL;
        uint256 total_supply = token.totalSupply();

        uint256[N_COINS] memory xp = _xp();

        uint256 D0 = get_D(xp, amp);
        uint256 D1 = D0 - (_token_amount * D0) / total_supply;
        uint256[N_COINS] memory xp_reduced = xp;

        uint256 new_y = get_y_D(amp, i, xp, D1);
        uint256 dy_0 = (xp[i] - new_y) / precisions[i]; // w/o fees

        for (uint256 k = 0; k < N_COINS; k++) {
            uint256 dx_expected;
            if (k == i) {
                dx_expected = (xp[k] * D1) / D0 - new_y;
            } else {
                dx_expected = xp[k] - (xp[k] * D1) / D0;
            }
            xp_reduced[k] -= (_fee * dx_expected) / FEE_DENOMINATOR;
        }
        uint256 dy = xp_reduced[i] - get_y_D(amp, i, xp_reduced, D1);
        dy = (dy - 1) / precisions[i]; // Withdraw less to account for rounding errors

        return (dy, dy_0 - dy);
    }

    function calc_withdraw_one_coin(uint256 _token_amount, uint256 i) external view returns (uint256) {
        (uint256 dy, ) = _calc_withdraw_one_coin(_token_amount, i);
        return dy;
    }

    function remove_liquidity_one_coin(
        uint256 _token_amount,
        uint256 i,
        uint256 min_amount
    ) external nonReentrant {
        // Remove _amount of liquidity all in a form of coin i
        require(!is_killed, "Killed");
        (uint256 dy, uint256 dy_fee) = _calc_withdraw_one_coin(_token_amount, i);
        require(dy >= min_amount, "Not enough coins removed");

        balances[i] -= (dy + (dy_fee * admin_fee) / FEE_DENOMINATOR);
        token.burnFrom(msg.sender, _token_amount); // dev: insufficient funds
        transfer_out(coins[i], dy);

        emit RemoveLiquidityOne(msg.sender, i, _token_amount, dy);
    }

    function transfer_out(address coin_address, uint256 value) internal {
        if (coin_address == BNB_ADDRESS) {
            _safeTransferBNB(msg.sender, value);
        } else {
            IERC20(coin_address).safeTransfer(msg.sender, value);
        }
    }

    function transfer_in(address coin_address, uint256 value) internal {
        if (coin_address == BNB_ADDRESS) {
            require(value == msg.value, "Inconsistent quantity");
        } else {
            IERC20(coin_address).safeTransferFrom(msg.sender, address(this), value);
        }
    }

    function _safeTransferBNB(address to, uint256 value) internal {
        (bool success, ) = to.call{gas: bnb_gas, value: value}("");
        require(success, "BNB transfer failed");
    }

    // Admin functions

    function set_bnb_gas(uint256 _bnb_gas) external onlyOwner {
        require(_bnb_gas >= MIN_BNB_GAS && _bnb_gas <= MAX_BNB_GAS, "Illegal gas");
        bnb_gas = _bnb_gas;
        emit SetBNBGas(_bnb_gas);
    }

    function ramp_A(uint256 _future_A, uint256 _future_time) external onlyOwner {
        require(block.timestamp >= initial_A_time + MIN_RAMP_TIME, "dev : too early");
        require(_future_time >= block.timestamp + MIN_RAMP_TIME, "dev: insufficient time");

        uint256 _initial_A = get_A();
        require(_future_A > 0 && _future_A < MAX_A, "_future_A must be between 0 and MAX_A");
        require(
            (_future_A >= _initial_A && _future_A <= _initial_A * MAX_A_CHANGE) ||
                (_future_A < _initial_A && _future_A * MAX_A_CHANGE >= _initial_A),
            "Illegal parameter _future_A"
        );
        initial_A = _initial_A;
        future_A = _future_A;
        initial_A_time = block.timestamp;
        future_A_time = _future_time;

        emit RampA(_initial_A, _future_A, block.timestamp, _future_time);
    }

    function stop_rampget_A() external onlyOwner {
        uint256 current_A = get_A();
        initial_A = current_A;
        future_A = current_A;
        initial_A_time = block.timestamp;
        future_A_time = block.timestamp;
        // now (block.timestamp < t1) is always False, so we return saved A

        emit StopRampA(current_A, block.timestamp);
    }

    function commit_new_fee(uint256 new_fee, uint256 new_admin_fee) external onlyOwner {
        require(admin_actions_deadline == 0, "admin_actions_deadline must be 0"); // dev: active action
        require(new_fee <= MAX_FEE, "dev: fee exceeds maximum");
        require(new_admin_fee <= MAX_ADMIN_FEE, "dev: admin fee exceeds maximum");

        admin_actions_deadline = block.timestamp + ADMIN_ACTIONS_DELAY;
        future_fee = new_fee;
        future_admin_fee = new_admin_fee;

        emit CommitNewFee(admin_actions_deadline, new_fee, new_admin_fee);
    }

    function apply_new_fee() external onlyOwner {
        require(block.timestamp >= admin_actions_deadline, "dev: insufficient time");
        require(admin_actions_deadline != 0, "admin_actions_deadline should not be 0");

        admin_actions_deadline = 0;
        fee = future_fee;
        admin_fee = future_admin_fee;

        emit NewFee(fee, admin_fee);
    }

    function revert_new_parameters() external onlyOwner {
        admin_actions_deadline = 0;
        emit RevertParameters();
    }

    function admin_balances(uint256 i) external view returns (uint256) {
        if (coins[i] == BNB_ADDRESS) {
            return address(this).balance - balances[i];
        } else {
            return IERC20(coins[i]).balanceOf(address(this)) - balances[i];
        }
    }

    function withdraw_admin_fees() external onlyOwner {
        for (uint256 i = 0; i < N_COINS; i++) {
            uint256 value;
            if (coins[i] == BNB_ADDRESS) {
                value = address(this).balance - balances[i];
            } else {
                value = IERC20(coins[i]).balanceOf(address(this)) - balances[i];
            }
            if (value > 0) {
                transfer_out(coins[i], value);
            }
        }
    }

    function donate_admin_fees() external onlyOwner {
        for (uint256 i = 0; i < N_COINS; i++) {
            if (coins[i] == BNB_ADDRESS) {
                balances[i] = address(this).balance;
            } else {
                balances[i] = IERC20(coins[i]).balanceOf(address(this));
            }
        }
        emit DonateAdminFees();
    }

    function kill_me() external onlyOwner {
        require(kill_deadline > block.timestamp, "Exceeded deadline");
        is_killed = true;
        emit Kill();
    }

    function unkill_me() external onlyOwner {
        is_killed = false;
        emit Unkill();
    }
}

File 12 of 29 : IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 *
 * _Available since v4.1._
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

File 13 of 29 : ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant _NOT_ENTERED = 1;
    uint256 private constant _ENTERED = 2;

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        // On the first call to nonReentrant, _notEntered will be true
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // Any calls to nonReentrant after this point will fail
        _status = _ENTERED;

        _;

        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = _NOT_ENTERED;
    }
}

File 14 of 29 : IPancakeStableSwapLP.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;

interface IPancakeStableSwapLP {
    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    function mint(address _to, uint256 _amount) external;

    function burnFrom(address _to, uint256 _amount) external;

    function setMinter(address _newMinter) external;
}

File 15 of 29 : PancakeStableSwapThreePool.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;

import "@openzeppelin-4.5.0/contracts/access/Ownable.sol";
import "@openzeppelin-4.5.0/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin-4.5.0/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "@openzeppelin-4.5.0/contracts/security/ReentrancyGuard.sol";
import "./interfaces/IPancakeStableSwapLP.sol";

contract PancakeStableSwapThreePool is Ownable, ReentrancyGuard {
    using SafeERC20 for IERC20;

    uint256 public constant N_COINS = 3;

    uint256 public constant MAX_DECIMAL = 18;
    uint256 public constant FEE_DENOMINATOR = 1e10;
    uint256 public constant PRECISION = 1e18;
    uint256[N_COINS] public PRECISION_MUL;
    uint256[N_COINS] public RATES;

    uint256 public constant MAX_ADMIN_FEE = 1e10;
    uint256 public constant MAX_FEE = 5e9;
    uint256 public constant MAX_A = 1e6;
    uint256 public constant MAX_A_CHANGE = 10;
    uint256 public constant MIN_BNB_GAS = 2300;
    uint256 public constant MAX_BNB_GAS = 23000;

    uint256 public constant ADMIN_ACTIONS_DELAY = 3 days;
    uint256 public constant MIN_RAMP_TIME = 1 days;

    address[N_COINS] public coins;
    uint256[N_COINS] public balances;
    uint256 public fee; // fee * 1e10.
    uint256 public admin_fee; // admin_fee * 1e10.
    uint256 public bnb_gas = 4029; // transfer bnb gas.

    IPancakeStableSwapLP public token;

    address constant BNB_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;

    bool support_BNB;

    uint256 public initial_A;
    uint256 public future_A;
    uint256 public initial_A_time;
    uint256 public future_A_time;

    uint256 public admin_actions_deadline;
    uint256 public future_fee;
    uint256 public future_admin_fee;

    uint256 public kill_deadline;
    uint256 public constant KILL_DEADLINE_DT = 2 * 30 days;
    bool public is_killed;

    address public immutable STABLESWAP_FACTORY;
    bool public isInitialized;

    event TokenExchange(
        address indexed buyer,
        uint256 sold_id,
        uint256 tokens_sold,
        uint256 bought_id,
        uint256 tokens_bought
    );
    event AddLiquidity(
        address indexed provider,
        uint256[N_COINS] token_amounts,
        uint256[N_COINS] fees,
        uint256 invariant,
        uint256 token_supply
    );
    event RemoveLiquidity(
        address indexed provider,
        uint256[N_COINS] token_amounts,
        uint256[N_COINS] fees,
        uint256 token_supply
    );
    event RemoveLiquidityOne(address indexed provider, uint256 index, uint256 token_amount, uint256 coin_amount);
    event RemoveLiquidityImbalance(
        address indexed provider,
        uint256[N_COINS] token_amounts,
        uint256[N_COINS] fees,
        uint256 invariant,
        uint256 token_supply
    );
    event CommitNewFee(uint256 indexed deadline, uint256 fee, uint256 admin_fee);
    event NewFee(uint256 fee, uint256 admin_fee);
    event RampA(uint256 old_A, uint256 new_A, uint256 initial_time, uint256 future_time);
    event StopRampA(uint256 A, uint256 t);
    event SetBNBGas(uint256 bnb_gas);
    event RevertParameters();
    event DonateAdminFees();
    event Kill();
    event Unkill();

    /**
     * @notice constructor
     */
    constructor() {
        STABLESWAP_FACTORY = msg.sender;
    }

    /**
     * @notice initialize
     * @param _coins: Addresses of ERC20 conracts of coins (c-tokens) involved
     * @param _A: Amplification coefficient multiplied by n * (n - 1)
     * @param _fee: Fee to charge for exchanges
     * @param _admin_fee: Admin fee
     * @param _owner: Owner
     * @param _LP: LP address
     */
    function initialize(
        address[N_COINS] memory _coins,
        uint256 _A,
        uint256 _fee,
        uint256 _admin_fee,
        address _owner,
        address _LP
    ) external {
        require(!isInitialized, "Operations: Already initialized");
        require(msg.sender == STABLESWAP_FACTORY, "Operations: Not factory");
        require(_A <= MAX_A, "_A exceeds maximum");
        require(_fee <= MAX_FEE, "_fee exceeds maximum");
        require(_admin_fee <= MAX_ADMIN_FEE, "_admin_fee exceeds maximum");
        isInitialized = true;
        for (uint256 i = 0; i < N_COINS; i++) {
            require(_coins[i] != address(0), "ZERO Address");
            uint256 coinDecimal;
            if (_coins[i] == BNB_ADDRESS) {
                coinDecimal = 18;
                support_BNB = true;
            } else {
                coinDecimal = IERC20Metadata(_coins[i]).decimals();
            }
            require(coinDecimal <= MAX_DECIMAL, "The maximum decimal cannot exceed 18");
            //set PRECISION_MUL and  RATES
            PRECISION_MUL[i] = 10**(MAX_DECIMAL - coinDecimal);
            RATES[i] = PRECISION * PRECISION_MUL[i];
        }
        coins = _coins;
        initial_A = _A;
        future_A = _A;
        fee = _fee;
        admin_fee = _admin_fee;
        kill_deadline = block.timestamp + KILL_DEADLINE_DT;
        token = IPancakeStableSwapLP(_LP);

        transferOwnership(_owner);
    }

    function get_A() internal view returns (uint256) {
        //Handle ramping A up or down
        uint256 t1 = future_A_time;
        uint256 A1 = future_A;
        if (block.timestamp < t1) {
            uint256 A0 = initial_A;
            uint256 t0 = initial_A_time;
            // Expressions in uint256 cannot have negative numbers, thus "if"
            if (A1 > A0) {
                return A0 + ((A1 - A0) * (block.timestamp - t0)) / (t1 - t0);
            } else {
                return A0 - ((A0 - A1) * (block.timestamp - t0)) / (t1 - t0);
            }
        } else {
            // when t1 == 0 or block.timestamp >= t1
            return A1;
        }
    }

    function A() external view returns (uint256) {
        return get_A();
    }

    function _xp() internal view returns (uint256[N_COINS] memory result) {
        result = RATES;
        for (uint256 i = 0; i < N_COINS; i++) {
            result[i] = (result[i] * balances[i]) / PRECISION;
        }
    }

    function _xp_mem(uint256[N_COINS] memory _balances) internal view returns (uint256[N_COINS] memory result) {
        result = RATES;
        for (uint256 i = 0; i < N_COINS; i++) {
            result[i] = (result[i] * _balances[i]) / PRECISION;
        }
    }

    function get_D(uint256[N_COINS] memory xp, uint256 amp) internal pure returns (uint256) {
        uint256 S;
        for (uint256 i = 0; i < N_COINS; i++) {
            S += xp[i];
        }
        if (S == 0) {
            return 0;
        }

        uint256 Dprev;
        uint256 D = S;
        uint256 Ann = amp * N_COINS;
        for (uint256 j = 0; j < 255; j++) {
            uint256 D_P = D;
            for (uint256 k = 0; k < N_COINS; k++) {
                D_P = (D_P * D) / (xp[k] * N_COINS); // If division by 0, this will be borked: only withdrawal will work. And that is good
            }
            Dprev = D;
            D = ((Ann * S + D_P * N_COINS) * D) / ((Ann - 1) * D + (N_COINS + 1) * D_P);
            // Equality with the precision of 1
            if (D > Dprev) {
                if (D - Dprev <= 1) {
                    break;
                }
            } else {
                if (Dprev - D <= 1) {
                    break;
                }
            }
        }
        return D;
    }

    function get_D_mem(uint256[N_COINS] memory _balances, uint256 amp) internal view returns (uint256) {
        return get_D(_xp_mem(_balances), amp);
    }

    function get_virtual_price() external view returns (uint256) {
        /**
        Returns portfolio virtual price (for calculating profit)
        scaled up by 1e18
        */
        uint256 D = get_D(_xp(), get_A());
        /**
        D is in the units similar to DAI (e.g. converted to precision 1e18)
        When balanced, D = n * x_u - total virtual value of the portfolio
        */
        uint256 token_supply = token.totalSupply();
        return (D * PRECISION) / token_supply;
    }

    function calc_token_amount(uint256[N_COINS] memory amounts, bool deposit) external view returns (uint256) {
        /**
        Simplified method to calculate addition or reduction in token supply at
        deposit or withdrawal without taking fees into account (but looking at
        slippage).
        Needed to prevent front-running, not for precise calculations!
        */
        uint256[N_COINS] memory _balances = balances;
        uint256 amp = get_A();
        uint256 D0 = get_D_mem(_balances, amp);
        for (uint256 i = 0; i < N_COINS; i++) {
            if (deposit) {
                _balances[i] += amounts[i];
            } else {
                _balances[i] -= amounts[i];
            }
        }
        uint256 D1 = get_D_mem(_balances, amp);
        uint256 token_amount = token.totalSupply();
        uint256 difference;
        if (deposit) {
            difference = D1 - D0;
        } else {
            difference = D0 - D1;
        }
        return (difference * token_amount) / D0;
    }

    function add_liquidity(uint256[N_COINS] memory amounts, uint256 min_mint_amount) external payable nonReentrant {
        //Amounts is amounts of c-tokens
        require(!is_killed, "Killed");
        if (!support_BNB) {
            require(msg.value == 0, "Inconsistent quantity"); // Avoid sending BNB by mistake.
        }
        uint256[N_COINS] memory fees;
        uint256 _fee = (fee * N_COINS) / (4 * (N_COINS - 1));
        uint256 _admin_fee = admin_fee;
        uint256 amp = get_A();

        uint256 token_supply = token.totalSupply();
        //Initial invariant
        uint256 D0;
        uint256[N_COINS] memory old_balances = balances;
        if (token_supply > 0) {
            D0 = get_D_mem(old_balances, amp);
        }
        uint256[N_COINS] memory new_balances = [old_balances[0], old_balances[1], old_balances[2]];

        for (uint256 i = 0; i < N_COINS; i++) {
            if (token_supply == 0) {
                require(amounts[i] > 0, "Initial deposit requires all coins");
            }
            // balances store amounts of c-tokens
            new_balances[i] = old_balances[i] + amounts[i];
        }

        // Invariant after change
        uint256 D1 = get_D_mem(new_balances, amp);
        require(D1 > D0, "D1 must be greater than D0");

        // We need to recalculate the invariant accounting for fees
        // to calculate fair user's share
        uint256 D2 = D1;
        if (token_supply > 0) {
            // Only account for fees if we are not the first to deposit
            for (uint256 i = 0; i < N_COINS; i++) {
                uint256 ideal_balance = (D1 * old_balances[i]) / D0;
                uint256 difference;
                if (ideal_balance > new_balances[i]) {
                    difference = ideal_balance - new_balances[i];
                } else {
                    difference = new_balances[i] - ideal_balance;
                }

                fees[i] = (_fee * difference) / FEE_DENOMINATOR;
                balances[i] = new_balances[i] - ((fees[i] * _admin_fee) / FEE_DENOMINATOR);
                new_balances[i] -= fees[i];
            }
            D2 = get_D_mem(new_balances, amp);
        } else {
            balances = new_balances;
        }

        // Calculate, how much pool tokens to mint
        uint256 mint_amount;
        if (token_supply == 0) {
            mint_amount = D1; // Take the dust if there was any
        } else {
            mint_amount = (token_supply * (D2 - D0)) / D0;
        }
        require(mint_amount >= min_mint_amount, "Slippage screwed you");

        // Take coins from the sender
        for (uint256 i = 0; i < N_COINS; i++) {
            uint256 amount = amounts[i];
            address coin = coins[i];
            transfer_in(coin, amount);
        }

        // Mint pool tokens
        token.mint(msg.sender, mint_amount);

        emit AddLiquidity(msg.sender, amounts, fees, D1, token_supply + mint_amount);
    }

    function get_y(
        uint256 i,
        uint256 j,
        uint256 x,
        uint256[N_COINS] memory xp_
    ) internal view returns (uint256) {
        // x in the input is converted to the same price/precision
        require((i != j) && (i < N_COINS) && (j < N_COINS), "Illegal parameter");
        uint256 amp = get_A();
        uint256 D = get_D(xp_, amp);
        uint256 c = D;
        uint256 S_;
        uint256 Ann = amp * N_COINS;

        uint256 _x;
        for (uint256 k = 0; k < N_COINS; k++) {
            if (k == i) {
                _x = x;
            } else if (k != j) {
                _x = xp_[k];
            } else {
                continue;
            }
            S_ += _x;
            c = (c * D) / (_x * N_COINS);
        }
        c = (c * D) / (Ann * N_COINS);
        uint256 b = S_ + D / Ann; // - D
        uint256 y_prev;
        uint256 y = D;

        for (uint256 m = 0; m < 255; m++) {
            y_prev = y;
            y = (y * y + c) / (2 * y + b - D);
            // Equality with the precision of 1
            if (y > y_prev) {
                if (y - y_prev <= 1) {
                    break;
                }
            } else {
                if (y_prev - y <= 1) {
                    break;
                }
            }
        }
        return y;
    }

    function get_dy(
        uint256 i,
        uint256 j,
        uint256 dx
    ) external view returns (uint256) {
        // dx and dy in c-units
        uint256[N_COINS] memory rates = RATES;
        uint256[N_COINS] memory xp = _xp();

        uint256 x = xp[i] + ((dx * rates[i]) / PRECISION);
        uint256 y = get_y(i, j, x, xp);
        uint256 dy = ((xp[j] - y - 1) * PRECISION) / rates[j];
        uint256 _fee = (fee * dy) / FEE_DENOMINATOR;
        return dy - _fee;
    }

    function get_dy_underlying(
        uint256 i,
        uint256 j,
        uint256 dx
    ) external view returns (uint256) {
        // dx and dy in underlying units
        uint256[N_COINS] memory xp = _xp();
        uint256[N_COINS] memory precisions = PRECISION_MUL;

        uint256 x = xp[i] + dx * precisions[i];
        uint256 y = get_y(i, j, x, xp);
        uint256 dy = (xp[j] - y - 1) / precisions[j];
        uint256 _fee = (fee * dy) / FEE_DENOMINATOR;
        return dy - _fee;
    }

    function exchange(
        uint256 i,
        uint256 j,
        uint256 dx,
        uint256 min_dy
    ) external payable nonReentrant {
        require(!is_killed, "Killed");
        if (!support_BNB) {
            require(msg.value == 0, "Inconsistent quantity"); // Avoid sending BNB by mistake.
        }

        uint256[N_COINS] memory old_balances = balances;
        uint256[N_COINS] memory xp = _xp_mem(old_balances);

        uint256 x = xp[i] + (dx * RATES[i]) / PRECISION;
        uint256 y = get_y(i, j, x, xp);

        uint256 dy = xp[j] - y - 1; //  -1 just in case there were some rounding errors
        uint256 dy_fee = (dy * fee) / FEE_DENOMINATOR;

        // Convert all to real units
        dy = ((dy - dy_fee) * PRECISION) / RATES[j];
        require(dy >= min_dy, "Exchange resulted in fewer coins than expected");

        uint256 dy_admin_fee = (dy_fee * admin_fee) / FEE_DENOMINATOR;
        dy_admin_fee = (dy_admin_fee * PRECISION) / RATES[j];

        // Change balances exactly in same way as we change actual ERC20 coin amounts
        balances[i] = old_balances[i] + dx;
        // When rounding errors happen, we undercharge admin fee in favor of LP
        balances[j] = old_balances[j] - dy - dy_admin_fee;

        address iAddress = coins[i];
        if (iAddress == BNB_ADDRESS) {
            require(dx == msg.value, "Inconsistent quantity");
        } else {
            IERC20(iAddress).safeTransferFrom(msg.sender, address(this), dx);
        }
        address jAddress = coins[j];
        transfer_out(jAddress, dy);
        emit TokenExchange(msg.sender, i, dx, j, dy);
    }

    function remove_liquidity(uint256 _amount, uint256[N_COINS] memory min_amounts) external nonReentrant {
        uint256 total_supply = token.totalSupply();
        uint256[N_COINS] memory amounts;
        uint256[N_COINS] memory fees; //Fees are unused but we've got them historically in event

        for (uint256 i = 0; i < N_COINS; i++) {
            uint256 value = (balances[i] * _amount) / total_supply;
            require(value >= min_amounts[i], "Withdrawal resulted in fewer coins than expected");
            balances[i] -= value;
            amounts[i] = value;
            transfer_out(coins[i], value);
        }

        token.burnFrom(msg.sender, _amount); // dev: insufficient funds

        emit RemoveLiquidity(msg.sender, amounts, fees, total_supply - _amount);
    }

    function remove_liquidity_imbalance(uint256[N_COINS] memory amounts, uint256 max_burn_amount)
        external
        nonReentrant
    {
        require(!is_killed, "Killed");

        uint256 token_supply = token.totalSupply();
        require(token_supply > 0, "dev: zero total supply");
        uint256 _fee = (fee * N_COINS) / (4 * (N_COINS - 1));
        uint256 _admin_fee = admin_fee;
        uint256 amp = get_A();

        uint256[N_COINS] memory old_balances = balances;
        uint256[N_COINS] memory new_balances = [old_balances[0], old_balances[1], old_balances[2]];
        uint256 D0 = get_D_mem(old_balances, amp);
        for (uint256 i = 0; i < N_COINS; i++) {
            new_balances[i] -= amounts[i];
        }
        uint256 D1 = get_D_mem(new_balances, amp);
        uint256[N_COINS] memory fees;
        for (uint256 i = 0; i < N_COINS; i++) {
            uint256 ideal_balance = (D1 * old_balances[i]) / D0;
            uint256 difference;
            if (ideal_balance > new_balances[i]) {
                difference = ideal_balance - new_balances[i];
            } else {
                difference = new_balances[i] - ideal_balance;
            }
            fees[i] = (_fee * difference) / FEE_DENOMINATOR;
            balances[i] = new_balances[i] - ((fees[i] * _admin_fee) / FEE_DENOMINATOR);
            new_balances[i] -= fees[i];
        }
        uint256 D2 = get_D_mem(new_balances, amp);

        uint256 token_amount = ((D0 - D2) * token_supply) / D0;
        require(token_amount > 0, "token_amount must be greater than 0");
        token_amount += 1; // In case of rounding errors - make it unfavorable for the "attacker"
        require(token_amount <= max_burn_amount, "Slippage screwed you");

        token.burnFrom(msg.sender, token_amount); // dev: insufficient funds

        for (uint256 i = 0; i < N_COINS; i++) {
            if (amounts[i] > 0) {
                transfer_out(coins[i], amounts[i]);
            }
        }
        token_supply -= token_amount;
        emit RemoveLiquidityImbalance(msg.sender, amounts, fees, D1, token_supply);
    }

    function get_y_D(
        uint256 A_,
        uint256 i,
        uint256[N_COINS] memory xp,
        uint256 D
    ) internal pure returns (uint256) {
        /**
        Calculate x[i] if one reduces D from being calculated for xp to D

        Done by solving quadratic equation iteratively.
        x_1**2 + x1 * (sum' - (A*n**n - 1) * D / (A * n**n)) = D ** (n + 1) / (n ** (2 * n) * prod' * A)
        x_1**2 + b*x_1 = c

        x_1 = (x_1**2 + c) / (2*x_1 + b)
        */
        // x in the input is converted to the same price/precision
        require(i < N_COINS, "dev: i above N_COINS");
        uint256 c = D;
        uint256 S_;
        uint256 Ann = A_ * N_COINS;

        uint256 _x;
        for (uint256 k = 0; k < N_COINS; k++) {
            if (k != i) {
                _x = xp[k];
            } else {
                continue;
            }
            S_ += _x;
            c = (c * D) / (_x * N_COINS);
        }
        c = (c * D) / (Ann * N_COINS);
        uint256 b = S_ + D / Ann;
        uint256 y_prev;
        uint256 y = D;

        for (uint256 k = 0; k < 255; k++) {
            y_prev = y;
            y = (y * y + c) / (2 * y + b - D);
            // Equality with the precision of 1
            if (y > y_prev) {
                if (y - y_prev <= 1) {
                    break;
                }
            } else {
                if (y_prev - y <= 1) {
                    break;
                }
            }
        }
        return y;
    }

    function _calc_withdraw_one_coin(uint256 _token_amount, uint256 i) internal view returns (uint256, uint256) {
        // First, need to calculate
        // * Get current D
        // * Solve Eqn against y_i for D - _token_amount
        uint256 amp = get_A();
        uint256 _fee = (fee * N_COINS) / (4 * (N_COINS - 1));
        uint256[N_COINS] memory precisions = PRECISION_MUL;
        uint256 total_supply = token.totalSupply();

        uint256[N_COINS] memory xp = _xp();

        uint256 D0 = get_D(xp, amp);
        uint256 D1 = D0 - (_token_amount * D0) / total_supply;
        uint256[N_COINS] memory xp_reduced = xp;

        uint256 new_y = get_y_D(amp, i, xp, D1);
        uint256 dy_0 = (xp[i] - new_y) / precisions[i]; // w/o fees

        for (uint256 k = 0; k < N_COINS; k++) {
            uint256 dx_expected;
            if (k == i) {
                dx_expected = (xp[k] * D1) / D0 - new_y;
            } else {
                dx_expected = xp[k] - (xp[k] * D1) / D0;
            }
            xp_reduced[k] -= (_fee * dx_expected) / FEE_DENOMINATOR;
        }
        uint256 dy = xp_reduced[i] - get_y_D(amp, i, xp_reduced, D1);
        dy = (dy - 1) / precisions[i]; // Withdraw less to account for rounding errors

        return (dy, dy_0 - dy);
    }

    function calc_withdraw_one_coin(uint256 _token_amount, uint256 i) external view returns (uint256) {
        (uint256 dy, ) = _calc_withdraw_one_coin(_token_amount, i);
        return dy;
    }

    function remove_liquidity_one_coin(
        uint256 _token_amount,
        uint256 i,
        uint256 min_amount
    ) external nonReentrant {
        // Remove _amount of liquidity all in a form of coin i
        require(!is_killed, "Killed");
        (uint256 dy, uint256 dy_fee) = _calc_withdraw_one_coin(_token_amount, i);
        require(dy >= min_amount, "Not enough coins removed");

        balances[i] -= (dy + (dy_fee * admin_fee) / FEE_DENOMINATOR);
        token.burnFrom(msg.sender, _token_amount); // dev: insufficient funds
        transfer_out(coins[i], dy);

        emit RemoveLiquidityOne(msg.sender, i, _token_amount, dy);
    }

    function transfer_out(address coin_address, uint256 value) internal {
        if (coin_address == BNB_ADDRESS) {
            _safeTransferBNB(msg.sender, value);
        } else {
            IERC20(coin_address).safeTransfer(msg.sender, value);
        }
    }

    function transfer_in(address coin_address, uint256 value) internal {
        if (coin_address == BNB_ADDRESS) {
            require(value == msg.value, "Inconsistent quantity");
        } else {
            IERC20(coin_address).safeTransferFrom(msg.sender, address(this), value);
        }
    }

    function _safeTransferBNB(address to, uint256 value) internal {
        (bool success, ) = to.call{gas: bnb_gas, value: value}("");
        require(success, "BNB transfer failed");
    }

    // Admin functions

    function set_bnb_gas(uint256 _bnb_gas) external onlyOwner {
        require(_bnb_gas >= MIN_BNB_GAS && _bnb_gas <= MAX_BNB_GAS, "Illegal gas");
        bnb_gas = _bnb_gas;
        emit SetBNBGas(_bnb_gas);
    }

    function ramp_A(uint256 _future_A, uint256 _future_time) external onlyOwner {
        require(block.timestamp >= initial_A_time + MIN_RAMP_TIME, "dev : too early");
        require(_future_time >= block.timestamp + MIN_RAMP_TIME, "dev: insufficient time");

        uint256 _initial_A = get_A();
        require(_future_A > 0 && _future_A < MAX_A, "_future_A must be between 0 and MAX_A");
        require(
            (_future_A >= _initial_A && _future_A <= _initial_A * MAX_A_CHANGE) ||
                (_future_A < _initial_A && _future_A * MAX_A_CHANGE >= _initial_A),
            "Illegal parameter _future_A"
        );
        initial_A = _initial_A;
        future_A = _future_A;
        initial_A_time = block.timestamp;
        future_A_time = _future_time;

        emit RampA(_initial_A, _future_A, block.timestamp, _future_time);
    }

    function stop_rampget_A() external onlyOwner {
        uint256 current_A = get_A();
        initial_A = current_A;
        future_A = current_A;
        initial_A_time = block.timestamp;
        future_A_time = block.timestamp;
        // now (block.timestamp < t1) is always False, so we return saved A

        emit StopRampA(current_A, block.timestamp);
    }

    function commit_new_fee(uint256 new_fee, uint256 new_admin_fee) external onlyOwner {
        require(admin_actions_deadline == 0, "admin_actions_deadline must be 0"); // dev: active action
        require(new_fee <= MAX_FEE, "dev: fee exceeds maximum");
        require(new_admin_fee <= MAX_ADMIN_FEE, "dev: admin fee exceeds maximum");

        admin_actions_deadline = block.timestamp + ADMIN_ACTIONS_DELAY;
        future_fee = new_fee;
        future_admin_fee = new_admin_fee;

        emit CommitNewFee(admin_actions_deadline, new_fee, new_admin_fee);
    }

    function apply_new_fee() external onlyOwner {
        require(block.timestamp >= admin_actions_deadline, "dev: insufficient time");
        require(admin_actions_deadline != 0, "admin_actions_deadline should not be 0");

        admin_actions_deadline = 0;
        fee = future_fee;
        admin_fee = future_admin_fee;

        emit NewFee(fee, admin_fee);
    }

    function revert_new_parameters() external onlyOwner {
        admin_actions_deadline = 0;
        emit RevertParameters();
    }

    function admin_balances(uint256 i) external view returns (uint256) {
        if (coins[i] == BNB_ADDRESS) {
            return address(this).balance - balances[i];
        } else {
            return IERC20(coins[i]).balanceOf(address(this)) - balances[i];
        }
    }

    function withdraw_admin_fees() external onlyOwner {
        for (uint256 i = 0; i < N_COINS; i++) {
            uint256 value;
            if (coins[i] == BNB_ADDRESS) {
                value = address(this).balance - balances[i];
            } else {
                value = IERC20(coins[i]).balanceOf(address(this)) - balances[i];
            }
            if (value > 0) {
                transfer_out(coins[i], value);
            }
        }
    }

    function donate_admin_fees() external onlyOwner {
        for (uint256 i = 0; i < N_COINS; i++) {
            if (coins[i] == BNB_ADDRESS) {
                balances[i] = address(this).balance;
            } else {
                balances[i] = IERC20(coins[i]).balanceOf(address(this));
            }
        }
        emit DonateAdminFees();
    }

    function kill_me() external onlyOwner {
        require(kill_deadline > block.timestamp, "Exceeded deadline");
        is_killed = true;
        emit Kill();
    }

    function unkill_me() external onlyOwner {
        is_killed = false;
        emit Unkill();
    }
}

File 16 of 29 : PancakeStableSwapThreePoolDeployer.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;

import "@openzeppelin-4.5.0/contracts/access/Ownable.sol";
import "./PancakeStableSwapThreePool.sol";

contract PancakeStableSwapThreePoolDeployer is Ownable {
    uint256 public constant N_COINS = 3;

    /**
     * @notice constructor
     */
    constructor() {}

    // returns sorted token addresses, used to handle return values from pairs sorted in this order
    function sortTokens(
        address tokenA,
        address tokenB,
        address tokenC
    )
        internal
        pure
        returns (
            address,
            address,
            address
        )
    {
        require(tokenA != tokenB && tokenA != tokenC && tokenB != tokenC, "IDENTICAL_ADDRESSES");
        address tmp;
        if (tokenA > tokenB) {
            tmp = tokenA;
            tokenA = tokenB;
            tokenB = tmp;
        }
        if (tokenB > tokenC) {
            tmp = tokenB;
            tokenB = tokenC;
            tokenC = tmp;
            if (tokenA > tokenB) {
                tmp = tokenA;
                tokenA = tokenB;
                tokenB = tmp;
            }
        }
        return (tokenA, tokenB, tokenC);
    }

    /**
     * @notice createSwapPair
     * @param _tokenA: Addresses of ERC20 conracts .
     * @param _tokenB: Addresses of ERC20 conracts .
     * @param _tokenC: Addresses of ERC20 conracts .
     * @param _A: Amplification coefficient multiplied by n * (n - 1)
     * @param _fee: Fee to charge for exchanges
     * @param _admin_fee: Admin fee
     * @param _admin: Admin
     * @param _LP: LP
     */
    function createSwapPair(
        address _tokenA,
        address _tokenB,
        address _tokenC,
        uint256 _A,
        uint256 _fee,
        uint256 _admin_fee,
        address _admin,
        address _LP
    ) external onlyOwner returns (address) {
        require(_tokenA != address(0) && _tokenB != address(0) && _tokenA != _tokenB, "Illegal token");
        (address t0, address t1, address t2) = sortTokens(_tokenA, _tokenB, _tokenC);
        address[N_COINS] memory coins = [t0, t1, t2];
        // create swap contract
        bytes memory bytecode = type(PancakeStableSwapThreePool).creationCode;
        bytes32 salt = keccak256(abi.encodePacked(t0, t1, t2, msg.sender, block.timestamp, block.chainid));
        address swapContract;
        assembly {
            swapContract := create2(0, add(bytecode, 32), mload(bytecode), salt)
        }
        PancakeStableSwapThreePool(swapContract).initialize(coins, _A, _fee, _admin_fee, _admin, _LP);

        return swapContract;
    }
}

File 17 of 29 : PancakeStableSwapTwoPoolInfo.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
import "@openzeppelin-4.5.0/contracts/token/ERC20/utils/SafeERC20.sol";
import "../interfaces/IPancakeStableSwap.sol";

contract PancakeStableSwapTwoPoolInfo {
    uint256 public constant N_COINS = 2;
    uint256 public constant FEE_DENOMINATOR = 1e10;
    uint256 public constant PRECISION = 1e18;

    function token(address _swap) public view returns (IERC20) {
        return IERC20(IPancakeStableSwap(_swap).token());
    }

    function balances(address _swap) public view returns (uint256[N_COINS] memory swapBalances) {
        for (uint256 i = 0; i < N_COINS; i++) {
            swapBalances[i] = IPancakeStableSwap(_swap).balances(i);
        }
    }

    function RATES(address _swap) public view returns (uint256[N_COINS] memory swapRATES) {
        for (uint256 i = 0; i < N_COINS; i++) {
            swapRATES[i] = IPancakeStableSwap(_swap).RATES(i);
        }
    }

    function PRECISION_MUL(address _swap) public view returns (uint256[N_COINS] memory swapPRECISION_MUL) {
        for (uint256 i = 0; i < N_COINS; i++) {
            swapPRECISION_MUL[i] = IPancakeStableSwap(_swap).PRECISION_MUL(i);
        }
    }

    function calc_coins_amount(address _swap, uint256 _amount) external view returns (uint256[N_COINS] memory) {
        uint256 total_supply = token(_swap).totalSupply();
        uint256[N_COINS] memory amounts;

        for (uint256 i = 0; i < N_COINS; i++) {
            uint256 value = (IPancakeStableSwap(_swap).balances(i) * _amount) / total_supply;
            amounts[i] = value;
        }
        return amounts;
    }

    function get_D_mem(
        address _swap,
        uint256[N_COINS] memory _balances,
        uint256 amp
    ) public view returns (uint256) {
        return get_D(_xp_mem(_swap, _balances), amp);
    }

    function get_add_liquidity_mint_amount(address _swap, uint256[N_COINS] memory amounts)
        external
        view
        returns (uint256)
    {
        IPancakeStableSwap swap = IPancakeStableSwap(_swap);
        uint256[N_COINS] memory fees;
        uint256 _fee = (swap.fee() * N_COINS) / (4 * (N_COINS - 1));
        uint256 amp = swap.A();

        uint256 token_supply = token(_swap).totalSupply();
        //Initial invariant
        uint256 D0;
        uint256[N_COINS] memory old_balances = balances(_swap);
        if (token_supply > 0) {
            D0 = get_D_mem(_swap, old_balances, amp);
        }
        uint256[N_COINS] memory new_balances = [old_balances[0], old_balances[1]];

        for (uint256 i = 0; i < N_COINS; i++) {
            if (token_supply == 0) {
                require(amounts[i] > 0, "Initial deposit requires all coins");
            }
            // balances store amounts of c-tokens
            new_balances[i] = old_balances[i] + amounts[i];
        }

        // Invariant after change
        uint256 D1 = get_D_mem(_swap, new_balances, amp);
        require(D1 > D0, "D1 must be greater than D0");

        // We need to recalculate the invariant accounting for fees
        // to calculate fair user's share
        uint256 D2 = D1;
        if (token_supply > 0) {
            // Only account for fees if we are not the first to deposit
            for (uint256 i = 0; i < N_COINS; i++) {
                uint256 ideal_balance = (D1 * old_balances[i]) / D0;
                uint256 difference;
                if (ideal_balance > new_balances[i]) {
                    difference = ideal_balance - new_balances[i];
                } else {
                    difference = new_balances[i] - ideal_balance;
                }

                fees[i] = (_fee * difference) / FEE_DENOMINATOR;
                new_balances[i] -= fees[i];
            }
            D2 = get_D_mem(_swap, new_balances, amp);
        }

        // Calculate, how much pool tokens to mint
        uint256 mint_amount;
        if (token_supply == 0) {
            mint_amount = D1; // Take the dust if there was any
        } else {
            mint_amount = (token_supply * (D2 - D0)) / D0;
        }
        return mint_amount;
    }

    function get_add_liquidity_fee(address _swap, uint256[N_COINS] memory amounts)
        external
        view
        returns (uint256[N_COINS] memory liquidityFee)
    {
        IPancakeStableSwap swap = IPancakeStableSwap(_swap);
        uint256 _fee = (swap.fee() * N_COINS) / (4 * (N_COINS - 1));
        uint256 _admin_fee = swap.admin_fee();
        uint256 amp = swap.A();

        uint256 token_supply = token(_swap).totalSupply();
        //Initial invariant
        uint256 D0;
        uint256[N_COINS] memory old_balances = balances(_swap);

        if (token_supply > 0) {
            D0 = get_D_mem(_swap, old_balances, amp);
        }
        uint256[N_COINS] memory new_balances = [old_balances[0], old_balances[1]];

        for (uint256 i = 0; i < N_COINS; i++) {
            if (token_supply == 0) {
                require(amounts[i] > 0, "Initial deposit requires all coins");
            }
            new_balances[i] = old_balances[i] + amounts[i];
        }

        // Invariant after change
        uint256 D1 = get_D_mem(_swap, new_balances, amp);
        require(D1 > D0, "D1 must be greater than D0");
        if (token_supply > 0) {
            // Only account for fees if we are not the first to deposit
            for (uint256 i = 0; i < N_COINS; i++) {
                uint256 ideal_balance = (D1 * old_balances[i]) / D0;
                uint256 difference;
                if (ideal_balance > new_balances[i]) {
                    difference = ideal_balance - new_balances[i];
                } else {
                    difference = new_balances[i] - ideal_balance;
                }
                uint256 coinFee;
                coinFee = (_fee * difference) / FEE_DENOMINATOR;
                liquidityFee[i] = ((coinFee * _admin_fee) / FEE_DENOMINATOR);
            }
        }
    }

    function get_remove_liquidity_imbalance_fee(address _swap, uint256[N_COINS] memory amounts)
        external
        view
        returns (uint256[N_COINS] memory liquidityFee)
    {
        IPancakeStableSwap swap = IPancakeStableSwap(_swap);
        uint256 _fee = (swap.fee() * N_COINS) / (4 * (N_COINS - 1));
        uint256 _admin_fee = swap.admin_fee();
        uint256 amp = swap.A();

        uint256[N_COINS] memory old_balances = balances(_swap);
        uint256[N_COINS] memory new_balances = [old_balances[0], old_balances[1]];
        uint256 D0 = get_D_mem(_swap, old_balances, amp);
        for (uint256 i = 0; i < N_COINS; i++) {
            new_balances[i] -= amounts[i];
        }
        uint256 D1 = get_D_mem(_swap, new_balances, amp);
        for (uint256 i = 0; i < N_COINS; i++) {
            uint256 ideal_balance = (D1 * old_balances[i]) / D0;
            uint256 difference;
            if (ideal_balance > new_balances[i]) {
                difference = ideal_balance - new_balances[i];
            } else {
                difference = new_balances[i] - ideal_balance;
            }
            uint256 coinFee;
            coinFee = (_fee * difference) / FEE_DENOMINATOR;
            liquidityFee[i] = ((coinFee * _admin_fee) / FEE_DENOMINATOR);
        }
    }

    function _xp_mem(address _swap, uint256[N_COINS] memory _balances)
        public
        view
        returns (uint256[N_COINS] memory result)
    {
        result = RATES(_swap);
        for (uint256 i = 0; i < N_COINS; i++) {
            result[i] = (result[i] * _balances[i]) / PRECISION;
        }
    }

    function get_D(uint256[N_COINS] memory xp, uint256 amp) internal pure returns (uint256) {
        uint256 S;
        for (uint256 i = 0; i < N_COINS; i++) {
            S += xp[i];
        }
        if (S == 0) {
            return 0;
        }

        uint256 Dprev;
        uint256 D = S;
        uint256 Ann = amp * N_COINS;
        for (uint256 j = 0; j < 255; j++) {
            uint256 D_P = D;
            for (uint256 k = 0; k < N_COINS; k++) {
                D_P = (D_P * D) / (xp[k] * N_COINS); // If division by 0, this will be borked: only withdrawal will work. And that is good
            }
            Dprev = D;
            D = ((Ann * S + D_P * N_COINS) * D) / ((Ann - 1) * D + (N_COINS + 1) * D_P);
            // Equality with the precision of 1
            if (D > Dprev) {
                if (D - Dprev <= 1) {
                    break;
                }
            } else {
                if (Dprev - D <= 1) {
                    break;
                }
            }
        }
        return D;
    }

    function get_y(
        address _swap,
        uint256 i,
        uint256 j,
        uint256 x,
        uint256[N_COINS] memory xp_
    ) internal view returns (uint256) {
        IPancakeStableSwap swap = IPancakeStableSwap(_swap);
        uint256 amp = swap.A();
        uint256 D = get_D(xp_, amp);
        uint256 c = D;
        uint256 S_;
        uint256 Ann = amp * N_COINS;

        uint256 _x;
        for (uint256 k = 0; k < N_COINS; k++) {
            if (k == i) {
                _x = x;
            } else if (k != j) {
                _x = xp_[k];
            } else {
                continue;
            }
            S_ += _x;
            c = (c * D) / (_x * N_COINS);
        }
        c = (c * D) / (Ann * N_COINS);
        uint256 b = S_ + D / Ann; // - D
        uint256 y_prev;
        uint256 y = D;

        for (uint256 m = 0; m < 255; m++) {
            y_prev = y;
            y = (y * y + c) / (2 * y + b - D);
            // Equality with the precision of 1
            if (y > y_prev) {
                if (y - y_prev <= 1) {
                    break;
                }
            } else {
                if (y_prev - y <= 1) {
                    break;
                }
            }
        }
        return y;
    }

    function get_exchange_fee(
        address _swap,
        uint256 i,
        uint256 j,
        uint256 dx
    ) external view returns (uint256 exFee, uint256 exAdminFee) {
        IPancakeStableSwap swap = IPancakeStableSwap(_swap);

        uint256[N_COINS] memory old_balances = balances(_swap);
        uint256[N_COINS] memory xp = _xp_mem(_swap, old_balances);
        uint256[N_COINS] memory rates = RATES(_swap);
        uint256 x = xp[i] + (dx * rates[i]) / PRECISION;
        uint256 y = get_y(_swap, i, j, x, xp);

        uint256 dy = xp[j] - y - 1; //  -1 just in case there were some rounding errors
        uint256 dy_fee = (dy * swap.fee()) / FEE_DENOMINATOR;

        uint256 dy_admin_fee = (dy_fee * swap.admin_fee()) / FEE_DENOMINATOR;
        dy_fee = (dy_fee * PRECISION) / rates[j];
        dy_admin_fee = (dy_admin_fee * PRECISION) / rates[j];
        exFee = dy_fee;
        exAdminFee = dy_admin_fee;
    }

    function _xp(address _swap) internal view returns (uint256[N_COINS] memory result) {
        result = RATES(_swap);
        for (uint256 i = 0; i < N_COINS; i++) {
            result[i] = (result[i] * IPancakeStableSwap(_swap).balances(i)) / PRECISION;
        }
    }

    function get_y_D(
        uint256 A_,
        uint256 i,
        uint256[N_COINS] memory xp,
        uint256 D
    ) internal pure returns (uint256) {
        /**
        Calculate x[i] if one reduces D from being calculated for xp to D

        Done by solving quadratic equation iteratively.
        x_1**2 + x1 * (sum' - (A*n**n - 1) * D / (A * n**n)) = D ** (n + 1) / (n ** (2 * n) * prod' * A)
        x_1**2 + b*x_1 = c

        x_1 = (x_1**2 + c) / (2*x_1 + b)
        */
        // x in the input is converted to the same price/precision
        require(i < N_COINS, "dev: i above N_COINS");
        uint256 c = D;
        uint256 S_;
        uint256 Ann = A_ * N_COINS;

        uint256 _x;
        for (uint256 k = 0; k < N_COINS; k++) {
            if (k != i) {
                _x = xp[k];
            } else {
                continue;
            }
            S_ += _x;
            c = (c * D) / (_x * N_COINS);
        }
        c = (c * D) / (Ann * N_COINS);
        uint256 b = S_ + D / Ann;
        uint256 y_prev;
        uint256 y = D;

        for (uint256 k = 0; k < 255; k++) {
            y_prev = y;
            y = (y * y + c) / (2 * y + b - D);
            // Equality with the precision of 1
            if (y > y_prev) {
                if (y - y_prev <= 1) {
                    break;
                }
            } else {
                if (y_prev - y <= 1) {
                    break;
                }
            }
        }
        return y;
    }

    function _calc_withdraw_one_coin(
        address _swap,
        uint256 _token_amount,
        uint256 i
    ) internal view returns (uint256, uint256) {
        IPancakeStableSwap swap = IPancakeStableSwap(_swap);
        uint256 amp = swap.A();
        uint256 _fee = (swap.fee() * N_COINS) / (4 * (N_COINS - 1));
        uint256[N_COINS] memory precisions = PRECISION_MUL(_swap);

        uint256[N_COINS] memory xp = _xp(_swap);

        uint256 D0 = get_D(xp, amp);
        uint256 D1 = D0 - (_token_amount * D0) / (token(_swap).totalSupply());
        uint256[N_COINS] memory xp_reduced = xp;

        uint256 new_y = get_y_D(amp, i, xp, D1);
        uint256 dy_0 = (xp[i] - new_y) / precisions[i]; // w/o fees

        for (uint256 k = 0; k < N_COINS; k++) {
            uint256 dx_expected;
            if (k == i) {
                dx_expected = (xp[k] * D1) / D0 - new_y;
            } else {
                dx_expected = xp[k] - (xp[k] * D1) / D0;
            }
            xp_reduced[k] -= (_fee * dx_expected) / FEE_DENOMINATOR;
        }
        uint256 dy = xp_reduced[i] - get_y_D(amp, i, xp_reduced, D1);
        dy = (dy - 1) / precisions[i]; // Withdraw less to account for rounding errors

        return (dy, dy_0 - dy);
    }

    function get_remove_liquidity_one_coin_fee(
        address _swap,
        uint256 _token_amount,
        uint256 i
    ) external view returns (uint256 adminFee) {
        IPancakeStableSwap swap = IPancakeStableSwap(_swap);
        (, uint256 dy_fee) = _calc_withdraw_one_coin(_swap, _token_amount, i);
        adminFee = (dy_fee * swap.admin_fee()) / FEE_DENOMINATOR;
    }

    function get_dx(
        address _swap,
        uint256 i,
        uint256 j,
        uint256 dy,
        uint256 max_dx
    ) external view returns (uint256) {
        IPancakeStableSwap swap = IPancakeStableSwap(_swap);
        uint256[N_COINS] memory old_balances = balances(_swap);
        uint256[N_COINS] memory xp = _xp_mem(_swap, old_balances);

        uint256 dy_with_fee = (dy * FEE_DENOMINATOR) / (FEE_DENOMINATOR - swap.fee());
        require(dy_with_fee < old_balances[j], "Excess balance");
        uint256[N_COINS] memory rates = RATES(_swap);
        uint256 y = xp[j] - (dy_with_fee * rates[j]) / PRECISION;
        uint256 x = get_y(_swap, j, i, y, xp);

        uint256 dx = x - xp[i];

        // Convert all to real units
        dx = (dx * PRECISION) / rates[i] + 1; // +1 for round lose.
        require(dx <= max_dx, "Exchange resulted in fewer coins than expected");
        return dx;
    }
}

File 18 of 29 : PancakeStableSwapThreePoolInfo.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
import "@openzeppelin-4.5.0/contracts/token/ERC20/utils/SafeERC20.sol";
import "../interfaces/IPancakeStableSwap.sol";

contract PancakeStableSwapThreePoolInfo {
    uint256 public constant N_COINS = 3;
    uint256 public constant FEE_DENOMINATOR = 1e10;
    uint256 public constant PRECISION = 1e18;

    function token(address _swap) public view returns (IERC20) {
        return IERC20(IPancakeStableSwap(_swap).token());
    }

    function balances(address _swap) public view returns (uint256[N_COINS] memory swapBalances) {
        for (uint256 i = 0; i < N_COINS; i++) {
            swapBalances[i] = IPancakeStableSwap(_swap).balances(i);
        }
    }

    function RATES(address _swap) public view returns (uint256[N_COINS] memory swapRATES) {
        for (uint256 i = 0; i < N_COINS; i++) {
            swapRATES[i] = IPancakeStableSwap(_swap).RATES(i);
        }
    }

    function PRECISION_MUL(address _swap) public view returns (uint256[N_COINS] memory swapPRECISION_MUL) {
        for (uint256 i = 0; i < N_COINS; i++) {
            swapPRECISION_MUL[i] = IPancakeStableSwap(_swap).PRECISION_MUL(i);
        }
    }

    function calc_coins_amount(address _swap, uint256 _amount) external view returns (uint256[N_COINS] memory) {
        uint256 total_supply = token(_swap).totalSupply();
        uint256[N_COINS] memory amounts;

        for (uint256 i = 0; i < N_COINS; i++) {
            uint256 value = (IPancakeStableSwap(_swap).balances(i) * _amount) / total_supply;
            amounts[i] = value;
        }
        return amounts;
    }

    function get_D_mem(
        address _swap,
        uint256[N_COINS] memory _balances,
        uint256 amp
    ) public view returns (uint256) {
        return get_D(_xp_mem(_swap, _balances), amp);
    }

    function get_add_liquidity_mint_amount(address _swap, uint256[N_COINS] memory amounts)
        external
        view
        returns (uint256)
    {
        IPancakeStableSwap swap = IPancakeStableSwap(_swap);
        uint256[N_COINS] memory fees;
        uint256 _fee = (swap.fee() * N_COINS) / (4 * (N_COINS - 1));
        uint256 amp = swap.A();

        uint256 token_supply = token(_swap).totalSupply();
        //Initial invariant
        uint256 D0;
        uint256[N_COINS] memory old_balances = balances(_swap);
        if (token_supply > 0) {
            D0 = get_D_mem(_swap, old_balances, amp);
        }
        uint256[N_COINS] memory new_balances = [old_balances[0], old_balances[1], old_balances[2]];

        for (uint256 i = 0; i < N_COINS; i++) {
            if (token_supply == 0) {
                require(amounts[i] > 0, "Initial deposit requires all coins");
            }
            // balances store amounts of c-tokens
            new_balances[i] = old_balances[i] + amounts[i];
        }

        // Invariant after change
        uint256 D1 = get_D_mem(_swap, new_balances, amp);
        require(D1 > D0, "D1 must be greater than D0");

        // We need to recalculate the invariant accounting for fees
        // to calculate fair user's share
        uint256 D2 = D1;
        if (token_supply > 0) {
            // Only account for fees if we are not the first to deposit
            for (uint256 i = 0; i < N_COINS; i++) {
                uint256 ideal_balance = (D1 * old_balances[i]) / D0;
                uint256 difference;
                if (ideal_balance > new_balances[i]) {
                    difference = ideal_balance - new_balances[i];
                } else {
                    difference = new_balances[i] - ideal_balance;
                }

                fees[i] = (_fee * difference) / FEE_DENOMINATOR;
                new_balances[i] -= fees[i];
            }
            D2 = get_D_mem(_swap, new_balances, amp);
        }

        // Calculate, how much pool tokens to mint
        uint256 mint_amount;
        if (token_supply == 0) {
            mint_amount = D1; // Take the dust if there was any
        } else {
            mint_amount = (token_supply * (D2 - D0)) / D0;
        }
        return mint_amount;
    }

    function get_add_liquidity_fee(address _swap, uint256[N_COINS] memory amounts)
        external
        view
        returns (uint256[N_COINS] memory liquidityFee)
    {
        IPancakeStableSwap swap = IPancakeStableSwap(_swap);
        uint256 _fee = (swap.fee() * N_COINS) / (4 * (N_COINS - 1));
        uint256 _admin_fee = swap.admin_fee();
        uint256 amp = swap.A();

        uint256 token_supply = token(_swap).totalSupply();
        //Initial invariant
        uint256 D0;
        uint256[N_COINS] memory old_balances = balances(_swap);
        if (token_supply > 0) {
            D0 = get_D_mem(_swap, old_balances, amp);
        }
        uint256[N_COINS] memory new_balances = [old_balances[0], old_balances[1], old_balances[2]];

        for (uint256 i = 0; i < N_COINS; i++) {
            if (token_supply == 0) {
                require(amounts[i] > 0, "Initial deposit requires all coins");
            }
            new_balances[i] = old_balances[i] + amounts[i];
        }

        // Invariant after change
        uint256 D1 = get_D_mem(_swap, new_balances, amp);
        require(D1 > D0, "D1 must be greater than D0");
        if (token_supply > 0) {
            // Only account for fees if we are not the first to deposit
            for (uint256 i = 0; i < N_COINS; i++) {
                uint256 ideal_balance = (D1 * old_balances[i]) / D0;
                uint256 difference;
                if (ideal_balance > new_balances[i]) {
                    difference = ideal_balance - new_balances[i];
                } else {
                    difference = new_balances[i] - ideal_balance;
                }
                uint256 coinFee;
                coinFee = (_fee * difference) / FEE_DENOMINATOR;
                liquidityFee[i] = ((coinFee * _admin_fee) / FEE_DENOMINATOR);
            }
        }
    }

    function get_remove_liquidity_imbalance_fee(address _swap, uint256[N_COINS] memory amounts)
        external
        view
        returns (uint256[N_COINS] memory liquidityFee)
    {
        IPancakeStableSwap swap = IPancakeStableSwap(_swap);
        uint256 _fee = (swap.fee() * N_COINS) / (4 * (N_COINS - 1));
        uint256 _admin_fee = swap.admin_fee();
        uint256 amp = swap.A();

        uint256[N_COINS] memory old_balances = balances(_swap);
        uint256[N_COINS] memory new_balances = [old_balances[0], old_balances[1], old_balances[2]];
        uint256 D0 = get_D_mem(_swap, old_balances, amp);
        for (uint256 i = 0; i < N_COINS; i++) {
            new_balances[i] -= amounts[i];
        }
        uint256 D1 = get_D_mem(_swap, new_balances, amp);
        for (uint256 i = 0; i < N_COINS; i++) {
            uint256 ideal_balance = (D1 * old_balances[i]) / D0;
            uint256 difference;
            if (ideal_balance > new_balances[i]) {
                difference = ideal_balance - new_balances[i];
            } else {
                difference = new_balances[i] - ideal_balance;
            }
            uint256 coinFee;
            coinFee = (_fee * difference) / FEE_DENOMINATOR;
            liquidityFee[i] = ((coinFee * _admin_fee) / FEE_DENOMINATOR);
        }
    }

    function _xp_mem(address _swap, uint256[N_COINS] memory _balances)
        public
        view
        returns (uint256[N_COINS] memory result)
    {
        result = RATES(_swap);
        for (uint256 i = 0; i < N_COINS; i++) {
            result[i] = (result[i] * _balances[i]) / PRECISION;
        }
    }

    function get_D(uint256[N_COINS] memory xp, uint256 amp) internal pure returns (uint256) {
        uint256 S;
        for (uint256 i = 0; i < N_COINS; i++) {
            S += xp[i];
        }
        if (S == 0) {
            return 0;
        }

        uint256 Dprev;
        uint256 D = S;
        uint256 Ann = amp * N_COINS;
        for (uint256 j = 0; j < 255; j++) {
            uint256 D_P = D;
            for (uint256 k = 0; k < N_COINS; k++) {
                D_P = (D_P * D) / (xp[k] * N_COINS); // If division by 0, this will be borked: only withdrawal will work. And that is good
            }
            Dprev = D;
            D = ((Ann * S + D_P * N_COINS) * D) / ((Ann - 1) * D + (N_COINS + 1) * D_P);
            // Equality with the precision of 1
            if (D > Dprev) {
                if (D - Dprev <= 1) {
                    break;
                }
            } else {
                if (Dprev - D <= 1) {
                    break;
                }
            }
        }
        return D;
    }

    function get_y(
        address _swap,
        uint256 i,
        uint256 j,
        uint256 x,
        uint256[N_COINS] memory xp_
    ) internal view returns (uint256) {
        IPancakeStableSwap swap = IPancakeStableSwap(_swap);
        uint256 amp = swap.A();
        uint256 D = get_D(xp_, amp);
        uint256 c = D;
        uint256 S_;
        uint256 Ann = amp * N_COINS;

        uint256 _x;
        for (uint256 k = 0; k < N_COINS; k++) {
            if (k == i) {
                _x = x;
            } else if (k != j) {
                _x = xp_[k];
            } else {
                continue;
            }
            S_ += _x;
            c = (c * D) / (_x * N_COINS);
        }
        c = (c * D) / (Ann * N_COINS);
        uint256 b = S_ + D / Ann; // - D
        uint256 y_prev;
        uint256 y = D;

        for (uint256 m = 0; m < 255; m++) {
            y_prev = y;
            y = (y * y + c) / (2 * y + b - D);
            // Equality with the precision of 1
            if (y > y_prev) {
                if (y - y_prev <= 1) {
                    break;
                }
            } else {
                if (y_prev - y <= 1) {
                    break;
                }
            }
        }
        return y;
    }

    function get_exchange_fee(
        address _swap,
        uint256 i,
        uint256 j,
        uint256 dx
    ) external view returns (uint256 exFee, uint256 exAdminFee) {
        IPancakeStableSwap swap = IPancakeStableSwap(_swap);

        uint256[N_COINS] memory old_balances = balances(_swap);
        uint256[N_COINS] memory xp = _xp_mem(_swap, old_balances);
        uint256[N_COINS] memory rates = RATES(_swap);
        uint256 x = xp[i] + (dx * rates[i]) / PRECISION;
        uint256 y = get_y(_swap, i, j, x, xp);

        uint256 dy = xp[j] - y - 1; //  -1 just in case there were some rounding errors
        uint256 dy_fee = (dy * swap.fee()) / FEE_DENOMINATOR;

        uint256 dy_admin_fee = (dy_fee * swap.admin_fee()) / FEE_DENOMINATOR;
        dy_fee = (dy_fee * PRECISION) / rates[j];
        dy_admin_fee = (dy_admin_fee * PRECISION) / rates[j];
        exFee = dy_fee;
        exAdminFee = dy_admin_fee;
    }

    function _xp(address _swap) internal view returns (uint256[N_COINS] memory result) {
        result = RATES(_swap);
        for (uint256 i = 0; i < N_COINS; i++) {
            result[i] = (result[i] * IPancakeStableSwap(_swap).balances(i)) / PRECISION;
        }
    }

    function get_y_D(
        uint256 A_,
        uint256 i,
        uint256[N_COINS] memory xp,
        uint256 D
    ) internal pure returns (uint256) {
        /**
        Calculate x[i] if one reduces D from being calculated for xp to D

        Done by solving quadratic equation iteratively.
        x_1**2 + x1 * (sum' - (A*n**n - 1) * D / (A * n**n)) = D ** (n + 1) / (n ** (2 * n) * prod' * A)
        x_1**2 + b*x_1 = c

        x_1 = (x_1**2 + c) / (2*x_1 + b)
        */
        // x in the input is converted to the same price/precision
        require(i < N_COINS, "dev: i above N_COINS");
        uint256 c = D;
        uint256 S_;
        uint256 Ann = A_ * N_COINS;

        uint256 _x;
        for (uint256 k = 0; k < N_COINS; k++) {
            if (k != i) {
                _x = xp[k];
            } else {
                continue;
            }
            S_ += _x;
            c = (c * D) / (_x * N_COINS);
        }
        c = (c * D) / (Ann * N_COINS);
        uint256 b = S_ + D / Ann;
        uint256 y_prev;
        uint256 y = D;

        for (uint256 k = 0; k < 255; k++) {
            y_prev = y;
            y = (y * y + c) / (2 * y + b - D);
            // Equality with the precision of 1
            if (y > y_prev) {
                if (y - y_prev <= 1) {
                    break;
                }
            } else {
                if (y_prev - y <= 1) {
                    break;
                }
            }
        }
        return y;
    }

    function _calc_withdraw_one_coin(
        address _swap,
        uint256 _token_amount,
        uint256 i
    ) internal view returns (uint256, uint256) {
        IPancakeStableSwap swap = IPancakeStableSwap(_swap);
        uint256 amp = swap.A();
        uint256 _fee = (swap.fee() * N_COINS) / (4 * (N_COINS - 1));
        uint256[N_COINS] memory precisions = PRECISION_MUL(_swap);

        uint256[N_COINS] memory xp = _xp(_swap);

        uint256 D0 = get_D(xp, amp);
        uint256 D1 = D0 - (_token_amount * D0) / (token(_swap).totalSupply());
        uint256[N_COINS] memory xp_reduced = xp;

        uint256 new_y = get_y_D(amp, i, xp, D1);
        uint256 dy_0 = (xp[i] - new_y) / precisions[i]; // w/o fees

        for (uint256 k = 0; k < N_COINS; k++) {
            uint256 dx_expected;
            if (k == i) {
                dx_expected = (xp[k] * D1) / D0 - new_y;
            } else {
                dx_expected = xp[k] - (xp[k] * D1) / D0;
            }
            xp_reduced[k] -= (_fee * dx_expected) / FEE_DENOMINATOR;
        }
        uint256 dy = xp_reduced[i] - get_y_D(amp, i, xp_reduced, D1);
        dy = (dy - 1) / precisions[i]; // Withdraw less to account for rounding errors

        return (dy, dy_0 - dy);
    }

    function get_remove_liquidity_one_coin_fee(
        address _swap,
        uint256 _token_amount,
        uint256 i
    ) external view returns (uint256 adminFee) {
        IPancakeStableSwap swap = IPancakeStableSwap(_swap);
        (, uint256 dy_fee) = _calc_withdraw_one_coin(_swap, _token_amount, i);
        adminFee = (dy_fee * swap.admin_fee()) / FEE_DENOMINATOR;
    }

    function get_dx(
        address _swap,
        uint256 i,
        uint256 j,
        uint256 dy,
        uint256 max_dx
    ) external view returns (uint256) {
        IPancakeStableSwap swap = IPancakeStableSwap(_swap);
        uint256[N_COINS] memory old_balances = balances(_swap);
        uint256[N_COINS] memory xp = _xp_mem(_swap, old_balances);

        uint256 dy_with_fee = (dy * FEE_DENOMINATOR) / (FEE_DENOMINATOR - swap.fee());
        require(dy_with_fee < old_balances[j], "Excess balance");
        uint256[N_COINS] memory rates = RATES(_swap);
        uint256 y = xp[j] - (dy_with_fee * rates[j]) / PRECISION;
        uint256 x = get_y(_swap, j, i, y, xp);

        uint256 dx = x - xp[i];

        // Convert all to real units
        dx = (dx * PRECISION) / rates[i] + 1; // +1 for round lose.
        require(dx <= max_dx, "Exchange resulted in fewer coins than expected");
        return dx;
    }
}

File 19 of 29 : PancakeStableSwapInfo.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
import "@openzeppelin-4.5.0/contracts/token/ERC20/utils/SafeERC20.sol";
import "../interfaces/IPancakeStableSwapInfo.sol";
import "../interfaces/IPancakeStableSwap.sol";

contract PancakeStableSwapInfo {
    IPancakeStableSwapInfo public immutable twoPoolInfo;
    IPancakeStableSwapInfo public immutable threePoolInfo;

    constructor(IPancakeStableSwapInfo _twoPoolInfo, IPancakeStableSwapInfo _threePoolInfo) {
        twoPoolInfo = _twoPoolInfo;
        threePoolInfo = _threePoolInfo;
    }

    function get_dx(
        address _swap,
        uint256 i,
        uint256 j,
        uint256 dy,
        uint256 max_dx
    ) external view returns (uint256 dx) {
        uint256 N_COINS = IPancakeStableSwap(_swap).N_COINS();
        if (N_COINS == 2) {
            dx = twoPoolInfo.get_dx(_swap, i, j, dy, max_dx);
        } else if (N_COINS == 3) {
            dx = threePoolInfo.get_dx(_swap, i, j, dy, max_dx);
        }
    }
}

File 20 of 29 : IPancakeStableSwapInfo.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;

interface IPancakeStableSwapInfo {
    function get_dx(
        address _swap,
        uint256 i,
        uint256 j,
        uint256 dy,
        uint256 max_dx
    ) external view returns (uint256);
}

File 21 of 29 : ERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol)

pragma solidity ^0.8.0;

import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 * For a generic mechanism see {ERC20PresetMinterPauser}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC20
 * applications.
 *
 * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
 * This allows applications to reconstruct the allowance for all accounts just
 * by listening to said events. Other implementations of the EIP may not emit
 * these events, as it isn't required by the specification.
 *
 * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
 * functions have been added to mitigate the well-known issues around setting
 * allowances. See {IERC20-approve}.
 */
contract ERC20 is Context, IERC20, IERC20Metadata {
    mapping(address => uint256) private _balances;

    mapping(address => mapping(address => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * The default value of {decimals} is 18. To select a different value for
     * {decimals} you should overload it.
     *
     * All two of these values are immutable: they can only be set once during
     * construction.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual override returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the value {ERC20} uses, unless this function is
     * overridden;
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual override returns (uint8) {
        return 18;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual override returns (uint256) {
        return _totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual override returns (uint256) {
        return _balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `amount`.
     */
    function transfer(address to, uint256 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, amount);
        return true;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(address owner, address spender) public view virtual override returns (uint256) {
        return _allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
     * `transferFrom`. This is semantically equivalent to an infinite approval.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, amount);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Emits an {Approval} event indicating the updated allowance. This is not
     * required by the EIP. See the note at the beginning of {ERC20}.
     *
     * NOTE: Does not update the allowance if the current allowance
     * is the maximum `uint256`.
     *
     * Requirements:
     *
     * - `from` and `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `amount`.
     */
    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) public virtual override returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, amount);
        _transfer(from, to, amount);
        return true;
    }

    /**
     * @dev 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.
     */
    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, _allowances[owner][spender] + addedValue);
        return true;
    }

    /**
     * @dev 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`.
     */
    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
        address owner = _msgSender();
        uint256 currentAllowance = _allowances[owner][spender];
        require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
        unchecked {
            _approve(owner, spender, currentAllowance - subtractedValue);
        }

        return true;
    }

    /**
     * @dev Moves `amount` of tokens from `sender` to `recipient`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     */
    function _transfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual {
        require(from != address(0), "ERC20: transfer from the zero address");
        require(to != address(0), "ERC20: transfer to the zero address");

        _beforeTokenTransfer(from, to, amount);

        uint256 fromBalance = _balances[from];
        require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
        unchecked {
            _balances[from] = fromBalance - amount;
        }
        _balances[to] += amount;

        emit Transfer(from, to, amount);

        _afterTokenTransfer(from, to, amount);
    }

    /** @dev Creates `amount` tokens and assigns them to `account`, increasing
     * the total supply.
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function _mint(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: mint to the zero address");

        _beforeTokenTransfer(address(0), account, amount);

        _totalSupply += amount;
        _balances[account] += amount;
        emit Transfer(address(0), account, amount);

        _afterTokenTransfer(address(0), account, amount);
    }

    /**
     * @dev Destroys `amount` tokens from `account`, reducing the
     * total supply.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     * - `account` must have at least `amount` tokens.
     */
    function _burn(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: burn from the zero address");

        _beforeTokenTransfer(account, address(0), amount);

        uint256 accountBalance = _balances[account];
        require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
        unchecked {
            _balances[account] = accountBalance - amount;
        }
        _totalSupply -= amount;

        emit Transfer(account, address(0), amount);

        _afterTokenTransfer(account, address(0), amount);
    }

    /**
     * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     */
    function _approve(
        address owner,
        address spender,
        uint256 amount
    ) internal virtual {
        require(owner != address(0), "ERC20: approve from the zero address");
        require(spender != address(0), "ERC20: approve to the zero address");

        _allowances[owner][spender] = amount;
        emit Approval(owner, spender, amount);
    }

    /**
     * @dev Spend `amount` form the allowance of `owner` toward `spender`.
     *
     * Does not update the allowance amount in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Might emit an {Approval} event.
     */
    function _spendAllowance(
        address owner,
        address spender,
        uint256 amount
    ) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance != type(uint256).max) {
            require(currentAllowance >= amount, "ERC20: insufficient allowance");
            unchecked {
                _approve(owner, spender, currentAllowance - amount);
            }
        }
    }

    /**
     * @dev Hook that is called before any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * will be transferred to `to`.
     * - when `from` is zero, `amount` tokens will be minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual {}

    /**
     * @dev Hook that is called after any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * has been transferred to `to`.
     * - when `from` is zero, `amount` tokens have been minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens have been burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _afterTokenTransfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual {}
}

File 22 of 29 : Token.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;

import "@openzeppelin-4.5.0/contracts/token/ERC20/ERC20.sol";

contract Token is ERC20 {
    uint8 private immutable newDecimal;

    constructor(
        string memory _name,
        string memory _symbol,
        uint8 _decimal
    ) ERC20(_name, _symbol) {
        newDecimal = _decimal;
    }

    function decimals() public view override returns (uint8) {
        return newDecimal;
    }

    function mint(address _to, uint256 _amount) external {
        _mint(_to, _amount);
    }

    function burnFrom(address _to, uint256 _amount) external {
        _burn(_to, _amount);
    }
}

File 23 of 29 : PancakeStableSwapLPFactory.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;

import "@openzeppelin-4.5.0/contracts/access/Ownable.sol";
import "./PancakeStableSwapLP.sol";

contract PancakeStableSwapLPFactory is Ownable {
    event NewStableSwapLP(address indexed swapLPContract, address tokenA, address tokenB, address tokenC);

    constructor() {}

    /**
     * @notice createSwapLP
     * @param _tokenA: Addresses of ERC20 conracts .
     * @param _tokenB: Addresses of ERC20 conracts .
     * @param _tokenC: Addresses of ERC20 conracts .
     * @param _minter: Minter address
     */
    function createSwapLP(
        address _tokenA,
        address _tokenB,
        address _tokenC,
        address _minter
    ) external onlyOwner returns (address) {
        // create LP token
        bytes memory bytecode = type(PancakeStableSwapLP).creationCode;
        bytes32 salt = keccak256(
            abi.encodePacked(_tokenA, _tokenB, _tokenC, msg.sender, block.timestamp, block.chainid)
        );
        address lpToken;
        assembly {
            lpToken := create2(0, add(bytecode, 32), mload(bytecode), salt)
        }
        PancakeStableSwapLP(lpToken).setMinter(_minter);
        emit NewStableSwapLP(lpToken, _tokenA, _tokenB, _tokenC);
        return lpToken;
    }
}

File 24 of 29 : MockToken.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;

import "@openzeppelin-4.5.0/contracts/token/ERC20/ERC20.sol";

contract MockToken is ERC20 {
    constructor() ERC20("Binance USD", "BUSD") {
        // _mint(msg.sender, 100000 ether);
    }

    function decimals() public pure override returns (uint8) {
        return 18;
    }

    function mint(address _to, uint256 _amount) external {
        _mint(_to, _amount);
    }

    function burnFrom(address _to, uint256 _amount) external {
        _burn(_to, _amount);
    }
}

File 25 of 29 : PancakeStableSwapFactory.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;

import "@openzeppelin-4.5.0/contracts/access/Ownable.sol";
import "./interfaces/IPancakeStableSwap.sol";
import "./interfaces/IPancakeStableSwapLP.sol";
import "./interfaces/IPancakeStableSwapDeployer.sol";
import "./interfaces/IPancakeStableSwapLPFactory.sol";

contract PancakeStableSwapFactory is Ownable {
    struct StableSwapPairInfo {
        address swapContract;
        address token0;
        address token1;
        address LPContract;
    }
    struct StableSwapThreePoolPairInfo {
        address swapContract;
        address token0;
        address token1;
        address token2;
        address LPContract;
    }

    mapping(address => mapping(address => mapping(address => StableSwapThreePoolPairInfo))) public stableSwapPairInfo;
    // Query three pool pair infomation by two tokens.
    mapping(address => mapping(address => StableSwapThreePoolPairInfo)) threePoolInfo;
    mapping(uint256 => address) public swapPairContract;

    IPancakeStableSwapLPFactory public immutable LPFactory;
    IPancakeStableSwapDeployer public immutable SwapTwoPoolDeployer;
    IPancakeStableSwapDeployer public immutable SwapThreePoolDeployer;

    address constant ZEROADDRESS = address(0);

    uint256 public pairLength;

    event NewStableSwapPair(address indexed swapContract, address tokenA, address tokenB, address tokenC, address LP);

    /**
     * @notice constructor
     * _LPFactory: LP factory
     * _SwapTwoPoolDeployer: Swap two pool deployer
     * _SwapThreePoolDeployer: Swap three pool deployer
     */
    constructor(
        IPancakeStableSwapLPFactory _LPFactory,
        IPancakeStableSwapDeployer _SwapTwoPoolDeployer,
        IPancakeStableSwapDeployer _SwapThreePoolDeployer
    ) {
        LPFactory = _LPFactory;
        SwapTwoPoolDeployer = _SwapTwoPoolDeployer;
        SwapThreePoolDeployer = _SwapThreePoolDeployer;
    }

    // returns sorted token addresses, used to handle return values from pairs sorted in this order
    function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
        require(tokenA != tokenB, "IDENTICAL_ADDRESSES");
        (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
    }

    function sortTokens(
        address tokenA,
        address tokenB,
        address tokenC
    )
        internal
        pure
        returns (
            address,
            address,
            address
        )
    {
        require(tokenA != tokenB && tokenA != tokenC && tokenB != tokenC, "IDENTICAL_ADDRESSES");
        address tmp;
        if (tokenA > tokenB) {
            tmp = tokenA;
            tokenA = tokenB;
            tokenB = tmp;
        }
        if (tokenB > tokenC) {
            tmp = tokenB;
            tokenB = tokenC;
            tokenC = tmp;
            if (tokenA > tokenB) {
                tmp = tokenA;
                tokenA = tokenB;
                tokenB = tmp;
            }
        }
        return (tokenA, tokenB, tokenC);
    }

    /**
     * @notice createSwapPair
     * @param _tokenA: Addresses of ERC20 conracts .
     * @param _tokenB: Addresses of ERC20 conracts .
     * @param _A: Amplification coefficient multiplied by n * (n - 1)
     * @param _fee: Fee to charge for exchanges
     * @param _admin_fee: Admin fee
     */
    function createSwapPair(
        address _tokenA,
        address _tokenB,
        uint256 _A,
        uint256 _fee,
        uint256 _admin_fee
    ) external onlyOwner {
        require(_tokenA != ZEROADDRESS && _tokenB != ZEROADDRESS && _tokenA != _tokenB, "Illegal token");
        (address t0, address t1) = sortTokens(_tokenA, _tokenB);
        address LP = LPFactory.createSwapLP(t0, t1, ZEROADDRESS, address(this));
        address swapContract = SwapTwoPoolDeployer.createSwapPair(t0, t1, _A, _fee, _admin_fee, msg.sender, LP);
        IPancakeStableSwapLP(LP).setMinter(swapContract);
        addPairInfoInternal(swapContract, t0, t1, ZEROADDRESS, LP);
    }

    /**
     * @notice createThreePoolPair
     * @param _tokenA: Addresses of ERC20 conracts .
     * @param _tokenB: Addresses of ERC20 conracts .
     * @param _tokenC: Addresses of ERC20 conracts .
     * @param _A: Amplification coefficient multiplied by n * (n - 1)
     * @param _fee: Fee to charge for exchanges
     * @param _admin_fee: Admin fee
     */
    function createThreePoolPair(
        address _tokenA,
        address _tokenB,
        address _tokenC,
        uint256 _A,
        uint256 _fee,
        uint256 _admin_fee
    ) external onlyOwner {
        require(
            _tokenA != ZEROADDRESS &&
                _tokenB != ZEROADDRESS &&
                _tokenC != ZEROADDRESS &&
                _tokenA != _tokenB &&
                _tokenA != _tokenC &&
                _tokenB != _tokenC,
            "Illegal token"
        );
        (address t0, address t1, address t2) = sortTokens(_tokenA, _tokenB, _tokenC);
        address LP = LPFactory.createSwapLP(t0, t1, t2, address(this));
        address swapContract = SwapThreePoolDeployer.createSwapPair(t0, t1, t2, _A, _fee, _admin_fee, msg.sender, LP);
        IPancakeStableSwapLP(LP).setMinter(swapContract);
        addPairInfoInternal(swapContract, t0, t1, t2, LP);
    }

    function addPairInfoInternal(
        address _swapContract,
        address _t0,
        address _t1,
        address _t2,
        address _LP
    ) internal {
        StableSwapThreePoolPairInfo storage info = stableSwapPairInfo[_t0][_t1][_t2];
        info.swapContract = _swapContract;
        info.token0 = _t0;
        info.token1 = _t1;
        info.token2 = _t2;
        info.LPContract = _LP;
        swapPairContract[pairLength] = _swapContract;
        pairLength += 1;
        if (_t2 != ZEROADDRESS) {
            addThreePoolPairInfo(_t0, _t1, _t2, info);
        }

        emit NewStableSwapPair(_swapContract, _t0, _t1, _t2, _LP);
    }

    function addThreePoolPairInfo(
        address _t0,
        address _t1,
        address _t2,
        StableSwapThreePoolPairInfo memory info
    ) internal {
        threePoolInfo[_t0][_t1] = info;
        threePoolInfo[_t0][_t2] = info;
        threePoolInfo[_t1][_t2] = info;
    }

    function addPairInfo(address _swapContract) external onlyOwner {
        IPancakeStableSwap swap = IPancakeStableSwap(_swapContract);
        uint256 N_COINS = swap.N_COINS();
        if (N_COINS == 2) {
            addPairInfoInternal(_swapContract, swap.coins(0), swap.coins(1), ZEROADDRESS, swap.token());
        } else if (N_COINS == 3) {
            addPairInfoInternal(_swapContract, swap.coins(0), swap.coins(1), swap.coins(2), swap.token());
        }
    }

    function getPairInfo(address _tokenA, address _tokenB) external view returns (StableSwapPairInfo memory info) {
        (address t0, address t1) = sortTokens(_tokenA, _tokenB);
        StableSwapThreePoolPairInfo memory pairInfo = stableSwapPairInfo[t0][t1][ZEROADDRESS];
        info.swapContract = pairInfo.swapContract;
        info.token0 = pairInfo.token0;
        info.token1 = pairInfo.token1;
        info.LPContract = pairInfo.LPContract;
    }

    function getThreePoolPairInfo(address _tokenA, address _tokenB)
        external
        view
        returns (StableSwapThreePoolPairInfo memory info)
    {
        (address t0, address t1) = sortTokens(_tokenA, _tokenB);
        info = threePoolInfo[t0][t1];
    }
}

File 26 of 29 : IPancakeStableSwapDeployer.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;

interface IPancakeStableSwapDeployer {
    function createSwapPair(
        address _tokenA,
        address _tokenB,
        uint256 _A,
        uint256 _fee,
        uint256 _admin_fee,
        address _admin,
        address _LP
    ) external returns (address);

    function createSwapPair(
        address _tokenA,
        address _tokenB,
        address _tokenC,
        uint256 _A,
        uint256 _fee,
        uint256 _admin_fee,
        address _admin,
        address _LP
    ) external returns (address);
}

File 27 of 29 : IPancakeStableSwapLPFactory.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;

interface IPancakeStableSwapLPFactory {
    function createSwapLP(
        address _tokenA,
        address _tokenB,
        address _tokenC,
        address _minter
    ) external returns (address);
}

File 28 of 29 : PancakeStableSwapFactoryOwner.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;

import "@openzeppelin-4.5.0/contracts/access/Ownable.sol";
import "./interfaces/IPancakeStableSwapFactory.sol";
import "./interfaces/IPancakeStableSwap.sol";

contract PancakeStableSwapFactoryOwner is Ownable {
    IPancakeStableSwapFactory public immutable PancakeStableSwapFactory;

    // user can deploy new stable swap pair with permission.
    mapping(address => bool) public deployPermission;

    event UpdatePermission(address indexed user, bool permission);
    event NewStableSwapPair(address indexed user, address swapContract, address lpContract);

    error ZeroAddress();
    error NoPermission();
    error PairAlreadyExist(address swapContract);

    modifier onlyPermission() {
        if (!deployPermission[msg.sender]) {
            revert NoPermission();
        }
        _;
    }

    /**
     * @notice constructor
     * _factory : PancakeStableSwapFactory
     */
    constructor(IPancakeStableSwapFactory _factory) {
        PancakeStableSwapFactory = _factory;
    }

    struct PermissionConfig {
        address user;
        bool permission;
    }

    /**
     * @notice setPermission
     * @param _permissions : PermissionConfig array.
     */
    function setPermission(PermissionConfig[] calldata _permissions) external onlyOwner {
        for (uint256 i = 0; i < _permissions.length; i++) {
            PermissionConfig memory currentPermissionConfig = _permissions[i];
            if (currentPermissionConfig.user == address(0)) {
                revert ZeroAddress();
            }

            deployPermission[currentPermissionConfig.user] = currentPermissionConfig.permission;
            emit UpdatePermission(currentPermissionConfig.user, currentPermissionConfig.permission);
        }
    }

    /**
     * @notice createSwapPairWithPermission
     * @dev Create a new stable swap pair with permission.
     * @dev Can only create pair which does not exist.
     * @param _tokenA : Addresses of ERC20 conracts .
     * @param _tokenB : Addresses of ERC20 conracts .
     * @param _A : Amplification coefficient multiplied by n * (n - 1)
     * @param _fee : Fee to charge for exchanges
     * @param _admin_fee : Admin fee
     */
    function createSwapPairWithPermission(
        address _tokenA,
        address _tokenB,
        uint256 _A,
        uint256 _fee,
        uint256 _admin_fee
    ) external onlyPermission {
        _checkExistPair(_tokenA, _tokenB);
        _createSwapPair(_tokenA, _tokenB, _A, _fee, _admin_fee);
    }

    /**
     * @notice createSwapPair
     * @dev Create a new stable swap pair by owner.
     * @dev Can create pair which exists.
     * @dev It will update the stableSwapPairInfo in PancakeStableSwapFactory when deploying existing pair, and there is no effect on existing pairs.
     * @param _tokenA : Addresses of ERC20 conracts .
     * @param _tokenB : Addresses of ERC20 conracts .
     * @param _A : Amplification coefficient multiplied by n * (n - 1)
     * @param _fee : Fee to charge for exchanges
     * @param _admin_fee : Admin fee
     */
    function createSwapPair(
        address _tokenA,
        address _tokenB,
        uint256 _A,
        uint256 _fee,
        uint256 _admin_fee
    ) external onlyOwner {
        _createSwapPair(_tokenA, _tokenB, _A, _fee, _admin_fee);
    }

    /**
     * @notice setFactoryOwner
     * @dev Transfer ownership of PancakeStableSwapFactory.
     * @param _newOwner : New owner.
     */
    function setFactoryOwner(address _newOwner) external onlyOwner {
        PancakeStableSwapFactory.transferOwnership(_newOwner);
    }

    /**
     * @notice addPairInfo
     * @dev Add pair info to PancakeStableSwapFactory when we deploy a new factory.
     * @dev It will update the stableSwapPairInfo in PancakeStableSwapFactory, and there is no effect on existing pairs.
     * @param _swapContract : Swap contract.
     */
    function addPairInfo(address _swapContract) external onlyOwner {
        PancakeStableSwapFactory.addPairInfo(_swapContract);
    }

    function _createSwapPair(
        address _tokenA,
        address _tokenB,
        uint256 _A,
        uint256 _fee,
        uint256 _admin_fee
    ) internal {
        PancakeStableSwapFactory.createSwapPair(_tokenA, _tokenB, _A, _fee, _admin_fee);
        (address swapContract, , , address LPContract) = PancakeStableSwapFactory.getPairInfo(_tokenA, _tokenB);
        // transfer stable swap pool ownership to owner
        IPancakeStableSwap(swapContract).transferOwnership(owner());
        emit NewStableSwapPair(msg.sender, swapContract, LPContract);
    }

    function _checkExistPair(address _tokenA, address _tokenB) internal view {
        (address swapContract, , , ) = PancakeStableSwapFactory.getPairInfo(_tokenA, _tokenB);
        if (swapContract != address(0)) {
            revert PairAlreadyExist(swapContract);
        }
    }
}

File 29 of 29 : IPancakeStableSwapFactory.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;

interface IPancakeStableSwapFactory {
    function stableSwapPairInfo(
        address,
        address,
        address
    )
        external
        view
        returns (
            address swapContract,
            address token0,
            address token1,
            address LPContract
        );

    /**
     * @notice createSwapPair
     * @param _tokenA: Addresses of ERC20 conracts .
     * @param _tokenB: Addresses of ERC20 conracts .
     * @param _A: Amplification coefficient multiplied by n * (n - 1)
     * @param _fee: Fee to charge for exchanges
     * @param _admin_fee: Admin fee
     */
    function createSwapPair(
        address _tokenA,
        address _tokenB,
        uint256 _A,
        uint256 _fee,
        uint256 _admin_fee
    ) external;

    /**
     * @notice createThreePoolPair
     * @param _tokenA: Addresses of ERC20 conracts .
     * @param _tokenB: Addresses of ERC20 conracts .
     * @param _tokenC: Addresses of ERC20 conracts .
     * @param _A: Amplification coefficient multiplied by n * (n - 1)
     * @param _fee: Fee to charge for exchanges
     * @param _admin_fee: Admin fee
     */
    function createThreePoolPair(
        address _tokenA,
        address _tokenB,
        address _tokenC,
        uint256 _A,
        uint256 _fee,
        uint256 _admin_fee
    ) external;

    function addPairInfo(address _swapContract) external;

    function transferOwnership(address _newOwner) external;

    function getPairInfo(address _tokenA, address _tokenB)
        external
        view
        returns (
            address,
            address,
            address,
            address
        );
}

Settings
{
  "optimizer": {
    "enabled": true,
    "runs": 100
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "abi"
      ]
    }
  }
}

Contract Security Audit

Contract ABI

[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_to","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"burnFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"subtractedValue","type":"uint256"}],"name":"decreaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"addedValue","type":"uint256"}],"name":"increaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_to","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"mint","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"minter","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_newMinter","type":"address"}],"name":"setMinter","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"}]

60806040523480156200001157600080fd5b50604080518082018252601681527f50616e63616b6520537461626c6553776170204c5073000000000000000000006020808301918252835180850190945260098452680537461626c652d4c560bc1b9084015281519192916200007891600391620000a9565b5080516200008e906004906020840190620000a9565b5050600580546001600160a01b03191633179055506200018c565b828054620000b7906200014f565b90600052602060002090601f016020900481019282620000db576000855562000126565b82601f10620000f657805160ff191683800117855562000126565b8280016001018555821562000126579182015b828111156200012657825182559160200191906001019062000109565b506200013492915062000138565b5090565b5b8082111562000134576000815560010162000139565b600181811c908216806200016457607f821691505b602082108114156200018657634e487b7160e01b600052602260045260246000fd5b50919050565b610c5c806200019c6000396000f3fe608060405234801561001057600080fd5b50600436106100d55760003560e01c806340c10f191161008757806340c10f191461018d57806370a08231146101a257806379cc6790146101cb57806395d89b41146101de578063a457c2d7146101e6578063a9059cbb146101f9578063dd62ed3e1461020c578063fca3b5aa1461021f57600080fd5b806306fdde03146100da57806307546172146100f8578063095ea7b31461012357806318160ddd1461014657806323b872dd14610158578063313ce5671461016b578063395093511461017a575b600080fd5b6100e2610232565b6040516100ef9190610a36565b60405180910390f35b60055461010b906001600160a01b031681565b6040516001600160a01b0390911681526020016100ef565b610136610131366004610aa7565b6102c4565b60405190151581526020016100ef565b6002545b6040519081526020016100ef565b610136610166366004610ad1565b6102dc565b604051601281526020016100ef565b610136610188366004610aa7565b610300565b6101a061019b366004610aa7565b61033f565b005b61014a6101b0366004610b0d565b6001600160a01b031660009081526020819052604090205490565b6101a06101d9366004610aa7565b610380565b6100e26103b4565b6101366101f4366004610aa7565b6103c3565b610136610207366004610aa7565b610455565b61014a61021a366004610b2f565b610463565b6101a061022d366004610b0d565b61048e565b60606003805461024190610b62565b80601f016020809104026020016040519081016040528092919081815260200182805461026d90610b62565b80156102ba5780601f1061028f576101008083540402835291602001916102ba565b820191906000526020600020905b81548152906001019060200180831161029d57829003601f168201915b5050505050905090565b6000336102d28185856104da565b5060019392505050565b6000336102ea8582856105ff565b6102f5858585610679565b506001949350505050565b3360008181526001602090815260408083206001600160a01b03871684529091528120549091906102d2908290869061033a908790610bb3565b6104da565b6005546001600160a01b031633146103725760405162461bcd60e51b815260040161036990610bcb565b60405180910390fd5b61037c8282610835565b5050565b6005546001600160a01b031633146103aa5760405162461bcd60e51b815260040161036990610bcb565b61037c8282610902565b60606004805461024190610b62565b3360008181526001602090815260408083206001600160a01b0387168452909152812054909190838110156104485760405162461bcd60e51b815260206004820152602560248201527f45524332303a2064656372656173656420616c6c6f77616e63652062656c6f77604482015264207a65726f60d81b6064820152608401610369565b6102f582868684036104da565b6000336102d2818585610679565b6001600160a01b03918216600090815260016020908152604080832093909416825291909152205490565b6005546001600160a01b031633146104b85760405162461bcd60e51b815260040161036990610bcb565b600580546001600160a01b0319166001600160a01b0392909216919091179055565b6001600160a01b03831661053c5760405162461bcd60e51b8152602060048201526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f206164646044820152637265737360e01b6064820152608401610369565b6001600160a01b03821661059d5760405162461bcd60e51b815260206004820152602260248201527f45524332303a20617070726f766520746f20746865207a65726f206164647265604482015261737360f01b6064820152608401610369565b6001600160a01b0383811660008181526001602090815260408083209487168084529482529182902085905590518481527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92591015b60405180910390a3505050565b600061060b8484610463565b9050600019811461067357818110156106665760405162461bcd60e51b815260206004820152601d60248201527f45524332303a20696e73756666696369656e7420616c6c6f77616e63650000006044820152606401610369565b61067384848484036104da565b50505050565b6001600160a01b0383166106dd5760405162461bcd60e51b815260206004820152602560248201527f45524332303a207472616e736665722066726f6d20746865207a65726f206164604482015264647265737360d81b6064820152608401610369565b6001600160a01b03821661073f5760405162461bcd60e51b815260206004820152602360248201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260448201526265737360e81b6064820152608401610369565b6001600160a01b038316600090815260208190526040902054818110156107b75760405162461bcd60e51b815260206004820152602660248201527f45524332303a207472616e7366657220616d6f756e7420657863656564732062604482015265616c616e636560d01b6064820152608401610369565b6001600160a01b038085166000908152602081905260408082208585039055918516815290812080548492906107ee908490610bb3565b92505081905550826001600160a01b0316846001600160a01b0316600080516020610c078339815191528460405161082891815260200190565b60405180910390a3610673565b6001600160a01b03821661088b5760405162461bcd60e51b815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f2061646472657373006044820152606401610369565b806002600082825461089d9190610bb3565b90915550506001600160a01b038216600090815260208190526040812080548392906108ca908490610bb3565b90915550506040518181526001600160a01b03831690600090600080516020610c078339815191529060200160405180910390a35050565b6001600160a01b0382166109625760405162461bcd60e51b815260206004820152602160248201527f45524332303a206275726e2066726f6d20746865207a65726f206164647265736044820152607360f81b6064820152608401610369565b6001600160a01b038216600090815260208190526040902054818110156109d65760405162461bcd60e51b815260206004820152602260248201527f45524332303a206275726e20616d6f756e7420657863656564732062616c616e604482015261636560f01b6064820152608401610369565b6001600160a01b0383166000908152602081905260408120838303905560028054849290610a05908490610bef565b90915550506040518281526000906001600160a01b03851690600080516020610c07833981519152906020016105f2565b600060208083528351808285015260005b81811015610a6357858101830151858201604001528201610a47565b81811115610a75576000604083870101525b50601f01601f1916929092016040019392505050565b80356001600160a01b0381168114610aa257600080fd5b919050565b60008060408385031215610aba57600080fd5b610ac383610a8b565b946020939093013593505050565b600080600060608486031215610ae657600080fd5b610aef84610a8b565b9250610afd60208501610a8b565b9150604084013590509250925092565b600060208284031215610b1f57600080fd5b610b2882610a8b565b9392505050565b60008060408385031215610b4257600080fd5b610b4b83610a8b565b9150610b5960208401610a8b565b90509250929050565b600181811c90821680610b7657607f821691505b60208210811415610b9757634e487b7160e01b600052602260045260246000fd5b50919050565b634e487b7160e01b600052601160045260246000fd5b60008219821115610bc657610bc6610b9d565b500190565b6020808252600a90820152692737ba1036b4b73a32b960b11b604082015260600190565b600082821015610c0157610c01610b9d565b50039056feddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3efa2646970667358221220fe49ceebabb439405bb5c511fc7e03bcdf6be5c40e736c4af2b62ded3bb7891d64736f6c634300080a0033

Deployed Bytecode

0x608060405234801561001057600080fd5b50600436106100d55760003560e01c806340c10f191161008757806340c10f191461018d57806370a08231146101a257806379cc6790146101cb57806395d89b41146101de578063a457c2d7146101e6578063a9059cbb146101f9578063dd62ed3e1461020c578063fca3b5aa1461021f57600080fd5b806306fdde03146100da57806307546172146100f8578063095ea7b31461012357806318160ddd1461014657806323b872dd14610158578063313ce5671461016b578063395093511461017a575b600080fd5b6100e2610232565b6040516100ef9190610a36565b60405180910390f35b60055461010b906001600160a01b031681565b6040516001600160a01b0390911681526020016100ef565b610136610131366004610aa7565b6102c4565b60405190151581526020016100ef565b6002545b6040519081526020016100ef565b610136610166366004610ad1565b6102dc565b604051601281526020016100ef565b610136610188366004610aa7565b610300565b6101a061019b366004610aa7565b61033f565b005b61014a6101b0366004610b0d565b6001600160a01b031660009081526020819052604090205490565b6101a06101d9366004610aa7565b610380565b6100e26103b4565b6101366101f4366004610aa7565b6103c3565b610136610207366004610aa7565b610455565b61014a61021a366004610b2f565b610463565b6101a061022d366004610b0d565b61048e565b60606003805461024190610b62565b80601f016020809104026020016040519081016040528092919081815260200182805461026d90610b62565b80156102ba5780601f1061028f576101008083540402835291602001916102ba565b820191906000526020600020905b81548152906001019060200180831161029d57829003601f168201915b5050505050905090565b6000336102d28185856104da565b5060019392505050565b6000336102ea8582856105ff565b6102f5858585610679565b506001949350505050565b3360008181526001602090815260408083206001600160a01b03871684529091528120549091906102d2908290869061033a908790610bb3565b6104da565b6005546001600160a01b031633146103725760405162461bcd60e51b815260040161036990610bcb565b60405180910390fd5b61037c8282610835565b5050565b6005546001600160a01b031633146103aa5760405162461bcd60e51b815260040161036990610bcb565b61037c8282610902565b60606004805461024190610b62565b3360008181526001602090815260408083206001600160a01b0387168452909152812054909190838110156104485760405162461bcd60e51b815260206004820152602560248201527f45524332303a2064656372656173656420616c6c6f77616e63652062656c6f77604482015264207a65726f60d81b6064820152608401610369565b6102f582868684036104da565b6000336102d2818585610679565b6001600160a01b03918216600090815260016020908152604080832093909416825291909152205490565b6005546001600160a01b031633146104b85760405162461bcd60e51b815260040161036990610bcb565b600580546001600160a01b0319166001600160a01b0392909216919091179055565b6001600160a01b03831661053c5760405162461bcd60e51b8152602060048201526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f206164646044820152637265737360e01b6064820152608401610369565b6001600160a01b03821661059d5760405162461bcd60e51b815260206004820152602260248201527f45524332303a20617070726f766520746f20746865207a65726f206164647265604482015261737360f01b6064820152608401610369565b6001600160a01b0383811660008181526001602090815260408083209487168084529482529182902085905590518481527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92591015b60405180910390a3505050565b600061060b8484610463565b9050600019811461067357818110156106665760405162461bcd60e51b815260206004820152601d60248201527f45524332303a20696e73756666696369656e7420616c6c6f77616e63650000006044820152606401610369565b61067384848484036104da565b50505050565b6001600160a01b0383166106dd5760405162461bcd60e51b815260206004820152602560248201527f45524332303a207472616e736665722066726f6d20746865207a65726f206164604482015264647265737360d81b6064820152608401610369565b6001600160a01b03821661073f5760405162461bcd60e51b815260206004820152602360248201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260448201526265737360e81b6064820152608401610369565b6001600160a01b038316600090815260208190526040902054818110156107b75760405162461bcd60e51b815260206004820152602660248201527f45524332303a207472616e7366657220616d6f756e7420657863656564732062604482015265616c616e636560d01b6064820152608401610369565b6001600160a01b038085166000908152602081905260408082208585039055918516815290812080548492906107ee908490610bb3565b92505081905550826001600160a01b0316846001600160a01b0316600080516020610c078339815191528460405161082891815260200190565b60405180910390a3610673565b6001600160a01b03821661088b5760405162461bcd60e51b815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f2061646472657373006044820152606401610369565b806002600082825461089d9190610bb3565b90915550506001600160a01b038216600090815260208190526040812080548392906108ca908490610bb3565b90915550506040518181526001600160a01b03831690600090600080516020610c078339815191529060200160405180910390a35050565b6001600160a01b0382166109625760405162461bcd60e51b815260206004820152602160248201527f45524332303a206275726e2066726f6d20746865207a65726f206164647265736044820152607360f81b6064820152608401610369565b6001600160a01b038216600090815260208190526040902054818110156109d65760405162461bcd60e51b815260206004820152602260248201527f45524332303a206275726e20616d6f756e7420657863656564732062616c616e604482015261636560f01b6064820152608401610369565b6001600160a01b0383166000908152602081905260408120838303905560028054849290610a05908490610bef565b90915550506040518281526000906001600160a01b03851690600080516020610c07833981519152906020016105f2565b600060208083528351808285015260005b81811015610a6357858101830151858201604001528201610a47565b81811115610a75576000604083870101525b50601f01601f1916929092016040019392505050565b80356001600160a01b0381168114610aa257600080fd5b919050565b60008060408385031215610aba57600080fd5b610ac383610a8b565b946020939093013593505050565b600080600060608486031215610ae657600080fd5b610aef84610a8b565b9250610afd60208501610a8b565b9150604084013590509250925092565b600060208284031215610b1f57600080fd5b610b2882610a8b565b9392505050565b60008060408385031215610b4257600080fd5b610b4b83610a8b565b9150610b5960208401610a8b565b90509250929050565b600181811c90821680610b7657607f821691505b60208210811415610b9757634e487b7160e01b600052602260045260246000fd5b50919050565b634e487b7160e01b600052601160045260246000fd5b60008219821115610bc657610bc6610b9d565b500190565b6020808252600a90820152692737ba1036b4b73a32b960b11b604082015260600190565b600082821015610c0157610c01610b9d565b50039056feddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3efa2646970667358221220fe49ceebabb439405bb5c511fc7e03bcdf6be5c40e736c4af2b62ded3bb7891d64736f6c634300080a0033

Deployed Bytecode Sourcemap

121:664:10:-:0;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2156:98:2;;;:::i;:::-;;;;;;;:::i;:::-;;;;;;;;165:21:10;;;;;-1:-1:-1;;;;;165:21:10;;;;;;-1:-1:-1;;;;;780:32:29;;;762:51;;750:2;735:18;165:21:10;616:203:29;4433:197:2;;;;;;:::i;:::-;;:::i;:::-;;;1426:14:29;;1419:22;1401:41;;1389:2;1374:18;4433:197:2;1261:187:29;3244:106:2;3331:12;;3244:106;;;1599:25:29;;;1587:2;1572:18;3244:106:2;1453:177:29;5192:286:2;;;;;;:::i;:::-;;:::i;3093:91::-;;;3175:2;2110:36:29;;2098:2;2083:18;3093:91:2;1968:184:29;5873:236:2;;;;;;:::i;:::-;;:::i;573:100:10:-;;;;;;:::i;:::-;;:::i;:::-;;3408:125:2;;;;;;:::i;:::-;-1:-1:-1;;;;;3508:18:2;3482:7;3508:18;;;;;;;;;;;;3408:125;679:104:10;;;;;;:::i;:::-;;:::i;2367:102:2:-;;;:::i;6596:429::-;;;;;;:::i;:::-;;:::i;3729:189::-;;;;;;:::i;:::-;;:::i;3976:149::-;;;;;;:::i;:::-;;:::i;472:95:10:-;;;;;;:::i;:::-;;:::i;2156:98:2:-;2210:13;2242:5;2235:12;;;;;:::i;:::-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2156:98;:::o;4433:197::-;4516:4;719:10:7;4570:32:2;719:10:7;4586:7:2;4595:6;4570:8;:32::i;:::-;-1:-1:-1;4619:4:2;;4433:197;-1:-1:-1;;;4433:197:2:o;5192:286::-;5319:4;719:10:7;5375:38:2;5391:4;719:10:7;5406:6:2;5375:15;:38::i;:::-;5423:27;5433:4;5439:2;5443:6;5423:9;:27::i;:::-;-1:-1:-1;5467:4:2;;5192:286;-1:-1:-1;;;;5192:286:2:o;5873:236::-;719:10:7;5961:4:2;6040:18;;;:11;:18;;;;;;;;-1:-1:-1;;;;;6040:27:2;;;;;;;;;;5961:4;;719:10:7;6015:66:2;;719:10:7;;6040:27:2;;:40;;6070:10;;6040:40;:::i;:::-;6015:8;:66::i;573:100:10:-;427:6;;-1:-1:-1;;;;;427:6:10;413:10;:20;405:43;;;;-1:-1:-1;;;405:43:10;;;;;;;:::i;:::-;;;;;;;;;647:19:::1;653:3;658:7;647:5;:19::i;:::-;573:100:::0;;:::o;679:104::-;427:6;;-1:-1:-1;;;;;427:6:10;413:10;:20;405:43;;;;-1:-1:-1;;;405:43:10;;;;;;;:::i;:::-;757:19:::1;763:3;768:7;757:5;:19::i;2367:102:2:-:0;2423:13;2455:7;2448:14;;;;;:::i;6596:429::-;719:10:7;6689:4:2;6770:18;;;:11;:18;;;;;;;;-1:-1:-1;;;;;6770:27:2;;;;;;;;;;6689:4;;719:10:7;6815:35:2;;;;6807:85;;;;-1:-1:-1;;;6807:85:2;;3804:2:29;6807:85:2;;;3786:21:29;3843:2;3823:18;;;3816:30;3882:34;3862:18;;;3855:62;-1:-1:-1;;;3933:18:29;;;3926:35;3978:19;;6807:85:2;3602:401:29;6807:85:2;6926:60;6935:5;6942:7;6970:15;6951:16;:34;6926:8;:60::i;3729:189::-;3808:4;719:10:7;3862:28:2;719:10:7;3879:2:2;3883:6;3862:9;:28::i;3976:149::-;-1:-1:-1;;;;;4091:18:2;;;4065:7;4091:18;;;:11;:18;;;;;;;;:27;;;;;;;;;;;;;3976:149::o;472:95:10:-;427:6;;-1:-1:-1;;;;;427:6:10;413:10;:20;405:43;;;;-1:-1:-1;;;405:43:10;;;;;;;:::i;:::-;541:6:::1;:19:::0;;-1:-1:-1;;;;;;541:19:10::1;-1:-1:-1::0;;;;;541:19:10;;;::::1;::::0;;;::::1;::::0;;472:95::o;10123:370:2:-;-1:-1:-1;;;;;10254:19:2;;10246:68;;;;-1:-1:-1;;;10246:68:2;;4210:2:29;10246:68:2;;;4192:21:29;4249:2;4229:18;;;4222:30;4288:34;4268:18;;;4261:62;-1:-1:-1;;;4339:18:29;;;4332:34;4383:19;;10246:68:2;4008:400:29;10246:68:2;-1:-1:-1;;;;;10332:21:2;;10324:68;;;;-1:-1:-1;;;10324:68:2;;4615:2:29;10324:68:2;;;4597:21:29;4654:2;4634:18;;;4627:30;4693:34;4673:18;;;4666:62;-1:-1:-1;;;4744:18:29;;;4737:32;4786:19;;10324:68:2;4413:398:29;10324:68:2;-1:-1:-1;;;;;10403:18:2;;;;;;;:11;:18;;;;;;;;:27;;;;;;;;;;;;;:36;;;10454:32;;1599:25:29;;;10454:32:2;;1572:18:29;10454:32:2;;;;;;;;10123:370;;;:::o;10770:441::-;10900:24;10927:25;10937:5;10944:7;10927:9;:25::i;:::-;10900:52;;-1:-1:-1;;10966:16:2;:37;10962:243;;11047:6;11027:16;:26;;11019:68;;;;-1:-1:-1;;;11019:68:2;;5018:2:29;11019:68:2;;;5000:21:29;5057:2;5037:18;;;5030:30;5096:31;5076:18;;;5069:59;5145:18;;11019:68:2;4816:353:29;11019:68:2;11129:51;11138:5;11145:7;11173:6;11154:16;:25;11129:8;:51::i;:::-;10890:321;10770:441;;;:::o;7488:651::-;-1:-1:-1;;;;;7614:18:2;;7606:68;;;;-1:-1:-1;;;7606:68:2;;5376:2:29;7606:68:2;;;5358:21:29;5415:2;5395:18;;;5388:30;5454:34;5434:18;;;5427:62;-1:-1:-1;;;5505:18:29;;;5498:35;5550:19;;7606:68:2;5174:401:29;7606:68:2;-1:-1:-1;;;;;7692:16:2;;7684:64;;;;-1:-1:-1;;;7684:64:2;;5782:2:29;7684:64:2;;;5764:21:29;5821:2;5801:18;;;5794:30;5860:34;5840:18;;;5833:62;-1:-1:-1;;;5911:18:29;;;5904:33;5954:19;;7684:64:2;5580:399:29;7684:64:2;-1:-1:-1;;;;;7830:15:2;;7808:19;7830:15;;;;;;;;;;;7863:21;;;;7855:72;;;;-1:-1:-1;;;7855:72:2;;6186:2:29;7855:72:2;;;6168:21:29;6225:2;6205:18;;;6198:30;6264:34;6244:18;;;6237:62;-1:-1:-1;;;6315:18:29;;;6308:36;6361:19;;7855:72:2;5984:402:29;7855:72:2;-1:-1:-1;;;;;7961:15:2;;;:9;:15;;;;;;;;;;;7979:20;;;7961:38;;8019:13;;;;;;;;:23;;7993:6;;7961:9;8019:23;;7993:6;;8019:23;:::i;:::-;;;;;;;;8073:2;-1:-1:-1;;;;;8058:26:2;8067:4;-1:-1:-1;;;;;8058:26:2;-1:-1:-1;;;;;;;;;;;8077:6:2;8058:26;;;;1599:25:29;;1587:2;1572:18;;1453:177;8058:26:2;;;;;;;;8095:37;9124:576;8415:389;-1:-1:-1;;;;;8498:21:2;;8490:65;;;;-1:-1:-1;;;8490:65:2;;6593:2:29;8490:65:2;;;6575:21:29;6632:2;6612:18;;;6605:30;6671:33;6651:18;;;6644:61;6722:18;;8490:65:2;6391:355:29;8490:65:2;8642:6;8626:12;;:22;;;;;;;:::i;:::-;;;;-1:-1:-1;;;;;;;8658:18:2;;:9;:18;;;;;;;;;;:28;;8680:6;;8658:9;:28;;8680:6;;8658:28;:::i;:::-;;;;-1:-1:-1;;8701:37:2;;1599:25:29;;;-1:-1:-1;;;;;8701:37:2;;;8718:1;;-1:-1:-1;;;;;;;;;;;8701:37:2;1587:2:29;1572:18;8701:37:2;;;;;;;573:100:10;;:::o;9124:576:2:-;-1:-1:-1;;;;;9207:21:2;;9199:67;;;;-1:-1:-1;;;9199:67:2;;6953:2:29;9199:67:2;;;6935:21:29;6992:2;6972:18;;;6965:30;7031:34;7011:18;;;7004:62;-1:-1:-1;;;7082:18:29;;;7075:31;7123:19;;9199:67:2;6751:397:29;9199:67:2;-1:-1:-1;;;;;9362:18:2;;9337:22;9362:18;;;;;;;;;;;9398:24;;;;9390:71;;;;-1:-1:-1;;;9390:71:2;;7355:2:29;9390:71:2;;;7337:21:29;7394:2;7374:18;;;7367:30;7433:34;7413:18;;;7406:62;-1:-1:-1;;;7484:18:29;;;7477:32;7526:19;;9390:71:2;7153:398:29;9390:71:2;-1:-1:-1;;;;;9495:18:2;;:9;:18;;;;;;;;;;9516:23;;;9495:44;;9559:12;:22;;9533:6;;9495:9;9559:22;;9533:6;;9559:22;:::i;:::-;;;;-1:-1:-1;;9597:37:2;;1599:25:29;;;9623:1:2;;-1:-1:-1;;;;;9597:37:2;;;-1:-1:-1;;;;;;;;;;;9597:37:2;1587:2:29;1572:18;9597:37:2;1453:177:29;14:597;126:4;155:2;184;173:9;166:21;216:6;210:13;259:6;254:2;243:9;239:18;232:34;284:1;294:140;308:6;305:1;302:13;294:140;;;403:14;;;399:23;;393:30;369:17;;;388:2;365:26;358:66;323:10;;294:140;;;452:6;449:1;446:13;443:91;;;522:1;517:2;508:6;497:9;493:22;489:31;482:42;443:91;-1:-1:-1;595:2:29;574:15;-1:-1:-1;;570:29:29;555:45;;;;602:2;551:54;;14:597;-1:-1:-1;;;14:597:29:o;824:173::-;892:20;;-1:-1:-1;;;;;941:31:29;;931:42;;921:70;;987:1;984;977:12;921:70;824:173;;;:::o;1002:254::-;1070:6;1078;1131:2;1119:9;1110:7;1106:23;1102:32;1099:52;;;1147:1;1144;1137:12;1099:52;1170:29;1189:9;1170:29;:::i;:::-;1160:39;1246:2;1231:18;;;;1218:32;;-1:-1:-1;;;1002:254:29:o;1635:328::-;1712:6;1720;1728;1781:2;1769:9;1760:7;1756:23;1752:32;1749:52;;;1797:1;1794;1787:12;1749:52;1820:29;1839:9;1820:29;:::i;:::-;1810:39;;1868:38;1902:2;1891:9;1887:18;1868:38;:::i;:::-;1858:48;;1953:2;1942:9;1938:18;1925:32;1915:42;;1635:328;;;;;:::o;2157:186::-;2216:6;2269:2;2257:9;2248:7;2244:23;2240:32;2237:52;;;2285:1;2282;2275:12;2237:52;2308:29;2327:9;2308:29;:::i;:::-;2298:39;2157:186;-1:-1:-1;;;2157:186:29:o;2348:260::-;2416:6;2424;2477:2;2465:9;2456:7;2452:23;2448:32;2445:52;;;2493:1;2490;2483:12;2445:52;2516:29;2535:9;2516:29;:::i;:::-;2506:39;;2564:38;2598:2;2587:9;2583:18;2564:38;:::i;:::-;2554:48;;2348:260;;;;;:::o;2613:380::-;2692:1;2688:12;;;;2735;;;2756:61;;2810:4;2802:6;2798:17;2788:27;;2756:61;2863:2;2855:6;2852:14;2832:18;2829:38;2826:161;;;2909:10;2904:3;2900:20;2897:1;2890:31;2944:4;2941:1;2934:15;2972:4;2969:1;2962:15;2826:161;;2613:380;;;:::o;2998:127::-;3059:10;3054:3;3050:20;3047:1;3040:31;3090:4;3087:1;3080:15;3114:4;3111:1;3104:15;3130:128;3170:3;3201:1;3197:6;3194:1;3191:13;3188:39;;;3207:18;;:::i;:::-;-1:-1:-1;3243:9:29;;3130:128::o;3263:334::-;3465:2;3447:21;;;3504:2;3484:18;;;3477:30;-1:-1:-1;;;3538:2:29;3523:18;;3516:40;3588:2;3573:18;;3263:334::o;7556:125::-;7596:4;7624:1;7621;7618:8;7615:34;;;7629:18;;:::i;:::-;-1:-1:-1;7666:9:29;;7556:125::o

Swarm Source

ipfs://fe49ceebabb439405bb5c511fc7e03bcdf6be5c40e736c4af2b62ded3bb7891d

Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

Block Uncle Number Difficulty Gas Used Reward
View All Uncles
Loading...
Loading
Loading...
Loading

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
Loading...
Loading
[ Download: CSV Export  ]
[ Download: CSV Export  ]

A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.