MNT Price: $0.86 (+1.97%)

Contract

0xeC0Ad37432b489C40ED6da003B2C2F033928599E
 

Overview

MNT Balance

Mantle Mainnet Network LogoMantle Mainnet Network LogoMantle Mainnet Network Logo0 MNT

MNT Value

$0.00

More Info

Private Name Tags

Multichain Info

No addresses found
Transaction Hash
Block
From
To
Create Vault And...734139532024-12-23 12:50:18398 days ago1734958218IN
0xeC0Ad374...33928599E
0 MNT0.08405590.02
Create Vault729222772024-12-12 3:41:06410 days ago1733974866IN
0xeC0Ad374...33928599E
0 MNT0.079416260.03
Create Vault And...728839312024-12-11 6:22:54411 days ago1733898174IN
0xeC0Ad374...33928599E
0 MNT0.09471690.02
Create Vault And...727616812024-12-08 10:27:54413 days ago1733653674IN
0xeC0Ad374...33928599E
0 MNT0.100130740.0202
Create Vault And...727275352024-12-07 15:29:42414 days ago1733585382IN
0xeC0Ad374...33928599E
0 MNT0.1540010.03
Create Vault And...726391232024-12-05 14:22:38416 days ago1733408558IN
0xeC0Ad374...33928599E
0 MNT0.163384170.03
Create Vault And...726358582024-12-05 12:33:48416 days ago1733402028IN
0xeC0Ad374...33928599E
0 MNT0.109609210.02
Create Vault And...726128102024-12-04 23:45:32417 days ago1733355932IN
0xeC0Ad374...33928599E
0 MNT0.110686890.02
Create Vault And...726098182024-12-04 22:05:48417 days ago1733349948IN
0xeC0Ad374...33928599E
0 MNT0.104991530.02
Create Vault And...726064062024-12-04 20:12:04417 days ago1733343124IN
0xeC0Ad374...33928599E
0 MNT0.153465970.03
Create Vault And...726051832024-12-04 19:31:18417 days ago1733340678IN
0xeC0Ad374...33928599E
0 MNT0.105315210.02
Create Vault And...726038942024-12-04 18:48:20417 days ago1733338100IN
0xeC0Ad374...33928599E
0 MNT0.106884650.02
Create Vault And...725442932024-12-03 9:41:38418 days ago1733218898IN
0xeC0Ad374...33928599E
0 MNT0.116432920.02
Create Vault And...725011772024-12-02 9:44:26419 days ago1733132666IN
0xeC0Ad374...33928599E
0 MNT0.119106830.02
Create Vault And...723591902024-11-29 2:51:32423 days ago1732848692IN
0xeC0Ad374...33928599E
0 MNT0.185362560.03
Create Vault722811752024-11-27 7:31:02425 days ago1732692662IN
0xeC0Ad374...33928599E
0 MNT0.070463360.02
Create Vault And...721043042024-11-23 5:15:20429 days ago1732338920IN
0xeC0Ad374...33928599E
0 MNT0.116483630.02
Create Vault718663032024-11-17 17:01:58434 days ago1731862918IN
0xeC0Ad374...33928599E
0 MNT0.078861690.02
Create Vault And...716056982024-11-11 16:15:08440 days ago1731341708IN
0xeC0Ad374...33928599E
0 MNT0.127936570.02
Create Vault And...712065102024-11-02 10:28:52449 days ago1730543332IN
0xeC0Ad374...33928599E
0 MNT0.251424240.04
Create Vault And...707688012024-10-23 7:18:34460 days ago1729667914IN
0xeC0Ad374...33928599E
0 MNT0.124372880.02
Create Vault And...707374752024-10-22 13:54:22460 days ago1729605262IN
0xeC0Ad374...33928599E
0 MNT0.19515660.03
Create Vault And...705629702024-10-18 12:57:32464 days ago1729256252IN
0xeC0Ad374...33928599E
0 MNT0.125031770.02
Create Vault704850232024-10-16 17:39:18466 days ago1729100358IN
0xeC0Ad374...33928599E
0 MNT0.112534150.03
Create Vault702604612024-10-11 12:53:54471 days ago1728651234IN
0xeC0Ad374...33928599E
0 MNT0.075928110.02
View all transactions

Latest 25 internal transactions (View All)

Advanced mode:
Parent Transaction Hash Block From To
734139532024-12-23 12:50:18398 days ago1734958218
0xeC0Ad374...33928599E
 Contract Creation0 MNT
729222772024-12-12 3:41:06410 days ago1733974866
0xeC0Ad374...33928599E
 Contract Creation0 MNT
728839312024-12-11 6:22:54411 days ago1733898174
0xeC0Ad374...33928599E
 Contract Creation0 MNT
727616812024-12-08 10:27:54413 days ago1733653674
0xeC0Ad374...33928599E
 Contract Creation0 MNT
727275352024-12-07 15:29:42414 days ago1733585382
0xeC0Ad374...33928599E
 Contract Creation0 MNT
726391232024-12-05 14:22:38416 days ago1733408558
0xeC0Ad374...33928599E
 Contract Creation0 MNT
726358582024-12-05 12:33:48416 days ago1733402028
0xeC0Ad374...33928599E
 Contract Creation0 MNT
726128102024-12-04 23:45:32417 days ago1733355932
0xeC0Ad374...33928599E
 Contract Creation0 MNT
726098182024-12-04 22:05:48417 days ago1733349948
0xeC0Ad374...33928599E
 Contract Creation0 MNT
726064062024-12-04 20:12:04417 days ago1733343124
0xeC0Ad374...33928599E
 Contract Creation0 MNT
726051832024-12-04 19:31:18417 days ago1733340678
0xeC0Ad374...33928599E
 Contract Creation0 MNT
726038942024-12-04 18:48:20417 days ago1733338100
0xeC0Ad374...33928599E
 Contract Creation0 MNT
725442932024-12-03 9:41:38418 days ago1733218898
0xeC0Ad374...33928599E
 Contract Creation0 MNT
725011772024-12-02 9:44:26419 days ago1733132666
0xeC0Ad374...33928599E
 Contract Creation0 MNT
723591902024-11-29 2:51:32423 days ago1732848692
0xeC0Ad374...33928599E
 Contract Creation0 MNT
722811752024-11-27 7:31:02425 days ago1732692662
0xeC0Ad374...33928599E
 Contract Creation0 MNT
721043042024-11-23 5:15:20429 days ago1732338920
0xeC0Ad374...33928599E
 Contract Creation0 MNT
718663032024-11-17 17:01:58434 days ago1731862918
0xeC0Ad374...33928599E
 Contract Creation0 MNT
716056982024-11-11 16:15:08440 days ago1731341708
0xeC0Ad374...33928599E
 Contract Creation0 MNT
712065102024-11-02 10:28:52449 days ago1730543332
0xeC0Ad374...33928599E
 Contract Creation0 MNT
707688012024-10-23 7:18:34460 days ago1729667914
0xeC0Ad374...33928599E
 Contract Creation0 MNT
707374752024-10-22 13:54:22460 days ago1729605262
0xeC0Ad374...33928599E
 Contract Creation0 MNT
705629702024-10-18 12:57:32464 days ago1729256252
0xeC0Ad374...33928599E
 Contract Creation0 MNT
704850232024-10-16 17:39:18466 days ago1729100358
0xeC0Ad374...33928599E
 Contract Creation0 MNT
702604612024-10-11 12:53:54471 days ago1728651234
0xeC0Ad374...33928599E
 Contract Creation0 MNT
View All Internal Transactions

Cross-Chain Transactions
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
PendlePtIsolationModeVaultFactory

Compiler Version
v0.8.9+commit.e5eed63a

Optimization Enabled:
Yes with 200 runs

Other Settings:
default evmVersion
// SPDX-License-Identifier: GPL-3.0-or-later
/*

    Copyright 2023 Dolomite

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

pragma solidity ^0.8.9;

import { IsolationModeVaultFactory } from "@dolomite-exchange/modules-base/contracts/isolation-mode/abstract/IsolationModeVaultFactory.sol"; // solhint-disable-line max-line-length
import { IPendlePtIsolationModeVaultFactory } from "./interfaces/IPendlePtIsolationModeVaultFactory.sol";
import { IPendleRegistry } from "./interfaces/IPendleRegistry.sol";


/**
 * @title   PendlePtIsolationModeVaultFactory
 * @author  Dolomite
 *
 * @notice  The wrapper around the PT token that is used to create user vaults and manage the entry points that a
 *          user can use to interact with DolomiteMargin from the vault.
 */
contract PendlePtIsolationModeVaultFactory is
    IPendlePtIsolationModeVaultFactory,
    IsolationModeVaultFactory
{
    // ============ Constants ============

    bytes32 private constant _FILE = "PendlePtVaultFactory"; // needed to be shortened to fit into 32 bytes

    // ============ Field Variables ============

    IPendleRegistry public override pendleRegistry;

    // ============ Constructor ============

    constructor(
        address _pendleRegistry,
        address _ptToken, // this serves as the underlying token
        address _borrowPositionProxy,
        address _userVaultImplementation,
        address _dolomiteMargin
    )
    IsolationModeVaultFactory(
        _ptToken,
        _borrowPositionProxy,
        _userVaultImplementation,
        address(IPendleRegistry(_pendleRegistry).dolomiteRegistry()),
        _dolomiteMargin
    ) {
        pendleRegistry = IPendleRegistry(_pendleRegistry);
    }

    // ============ External Functions ============

    function ownerSetPendleRegistry(
        address _pendleRegistry
    )
    external
    override
    onlyDolomiteMarginOwner(msg.sender) {
        pendleRegistry = IPendleRegistry(_pendleRegistry);
        emit PendleRegistrySet(_pendleRegistry);
    }

    function allowableDebtMarketIds() external pure returns (uint256[] memory) {
        // allow all markets
        return new uint256[](0);
    }

    function allowableCollateralMarketIds() external pure returns (uint256[] memory) {
        // allow all markets
        return new uint256[](0);
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/ERC20.sol)

pragma solidity ^0.8.9;

import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";


/**
 * @title   MinimalERC20
 * @author  OpenZeppelin
 *
 * @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.openzeppelin.com/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 MinimalERC20 is IERC20, IERC20Metadata {

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

    uint256 private _totalSupply;
    string private _name;
    string private _symbol;
    uint8 private _decimals;

    /**
     * @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_, uint8 decimals_) {
        _initializeTokenInfo(name_, symbol_, decimals_);
    }

    /**
     * @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 = msg.sender;
        _transfer(owner, to, amount);
        return true;
    }

    /**
     * @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 = msg.sender;
        _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 = msg.sender;
        _spendAllowance(from, spender, amount);
        _transfer(from, to, amount);
        return true;
    }

    /**
     * @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 _decimals;
    }

    /**
     * @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-allowance}.
     */
    function allowance(address owner, address spender) public view virtual override returns (uint256) {
        return _allowances[owner][spender];
    }

    function _initializeTokenInfo(string memory name_, string memory symbol_, uint8 decimals_) internal {
        _name = name_;
        _symbol = symbol_;
        _decimals = decimals_;
    }

    /**
     * @dev Moves `amount` of tokens from `from` to `to`.
     *
     * 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"
        );

        uint256 fromBalance = _balances[from];
        require(
            fromBalance >= amount,
            "ERC20: Transfer amount exceeds balance"
        );
        unchecked {
            _balances[from] = fromBalance - amount;
            // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
            // decrementing then incrementing.
            _balances[to] += amount;
        }

        emit Transfer(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"
        );

        _totalSupply += amount;
        unchecked {
            // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
            _balances[account] += amount;
        }
        emit Transfer(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"
        );

        uint256 accountBalance = _balances[account];
        require(
            accountBalance >= amount,
            "ERC20: Burn amount exceeds balance"
        );
        unchecked {
            _balances[account] = accountBalance - amount;
            // Overflow not possible: amount <= accountBalance <= totalSupply.
            _totalSupply -= amount;
        }

        emit Transfer(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 Updates `owner` s allowance for `spender` based on spent `amount`.
     *
     * 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);
        require(
            currentAllowance >= amount,
            "ERC20: Insufficient allowance"
        );
        unchecked {
            _approve(owner, spender, currentAllowance - amount);
        }
    }
}

File 3 of 51 : OnlyDolomiteMargin.sol
// SPDX-License-Identifier: GPL-3.0-or-later
/*

    Copyright 2023 Dolomite

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

pragma solidity ^0.8.9;

import { OnlyDolomiteMarginForUpgradeable } from "./OnlyDolomiteMarginForUpgradeable.sol";
import { IDolomiteMargin } from "../protocol/interfaces/IDolomiteMargin.sol";


/**
 * @title   OnlyDolomiteMargin
 * @author  Dolomite
 *
 * @notice  Inheritable contract that restricts the calling of certain functions to `DolomiteMargin`, the owner of
 *          `DolomiteMargin` or a `DolomiteMargin` global operator
 */
abstract contract OnlyDolomiteMargin is OnlyDolomiteMarginForUpgradeable {

    // ============ Constants ============

    bytes32 private constant _FILE = "OnlyDolomiteMargin";

    // ============ Storage ============

    IDolomiteMargin private immutable _DOLOMITE_MARGIN; // solhint-disable-line var-name-mixedcase

    // ============ Constructor ============

    constructor (address _dolomiteMargin) {
        _DOLOMITE_MARGIN = IDolomiteMargin(_dolomiteMargin);
    }

    // ============ Functions ============

    function DOLOMITE_MARGIN() public override view returns (IDolomiteMargin) {
        return _DOLOMITE_MARGIN;
    }
}

// SPDX-License-Identifier: GPL-3.0-or-later
/*

    Copyright 2023 Dolomite

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

pragma solidity ^0.8.9;

import { ProxyContractHelpers } from "./ProxyContractHelpers.sol";
import { IOnlyDolomiteMargin } from "../interfaces/IOnlyDolomiteMargin.sol";
import { IDolomiteMargin } from "../protocol/interfaces/IDolomiteMargin.sol";
import { Require } from "../protocol/lib/Require.sol";


/**
 * @title   OnlyDolomiteMarginForUpgradeable
 * @author  Dolomite
 *
 * @notice  Inheritable contract that restricts the calling of certain functions to `DolomiteMargin`, the owner of
 *          `DolomiteMargin` or a `DolomiteMargin` global operator
 */
abstract contract OnlyDolomiteMarginForUpgradeable is IOnlyDolomiteMargin, ProxyContractHelpers {

    // ============ Constants ============

    bytes32 private constant _FILE = "OnlyDolomiteMargin";
    bytes32 private constant _DOLOMITE_MARGIN_SLOT = bytes32(uint256(keccak256("eip1967.proxy.dolomiteMargin")) - 1);

    // ============ Modifiers ============

    modifier onlyDolomiteMargin(address _from) {
        Require.that(
            _from == address(DOLOMITE_MARGIN()),
            _FILE,
            "Only Dolomite can call function",
            _from
        );
        _;
    }

    modifier onlyDolomiteMarginOwner(address _from) {
        Require.that(
            _from == DOLOMITE_MARGIN_OWNER(),
            _FILE,
            "Caller is not owner of Dolomite",
            _from
        );
        _;
    }

    modifier onlyDolomiteMarginGlobalOperator(address _from) {
        Require.that(
            DOLOMITE_MARGIN().getIsGlobalOperator(_from),
            _FILE,
            "Caller is not a global operator",
            _from
        );
        _;
    }

    // ============ Functions ============

    function DOLOMITE_MARGIN() public virtual view returns (IDolomiteMargin) {
        return IDolomiteMargin(_getAddress(_DOLOMITE_MARGIN_SLOT));
    }

    function DOLOMITE_MARGIN_OWNER() public view returns (address) {
        return DOLOMITE_MARGIN().owner();
    }

    function _setDolomiteMarginViaSlot(address _dolomiteMargin) internal {
        _setAddress(_DOLOMITE_MARGIN_SLOT, _dolomiteMargin);
    }
}

// SPDX-License-Identifier: GPL-3.0-or-later
/*

    Copyright 2023 Dolomite

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

pragma solidity ^0.8.9;


/**
 * @title   ProxyContractHelpers
 * @author  Dolomite
 *
 * @notice  Helper functions for upgradeable proxy contracts to use
 */
abstract contract ProxyContractHelpers {

    // ================ Internal Functions ==================

    function _callImplementation(address _implementation) internal {
        // solhint-disable-next-line no-inline-assembly
        assembly {
            // Copy msg.data. We take full control of memory in this inline assembly
            // block because it will not return to Solidity code. We overwrite the
            // Solidity scratch pad at memory position 0.
            calldatacopy(0, 0, calldatasize())

            // Call the implementation.
            // out and outsize are 0 because we don't know the size yet.
            let result := delegatecall(gas(), _implementation, 0, calldatasize(), 0, 0)

            // Copy the returned data.
            returndatacopy(0, 0, returndatasize())

            switch result
            // delegatecall returns 0 on error.
            case 0 {
                revert(0, returndatasize())
            }
            default {
                return(0, returndatasize())
            }
        }
    }

    function _setAddress(bytes32 slot, address _value) internal {
        // solhint-disable-next-line no-inline-assembly
        assembly {
            sstore(slot, _value)
        }
    }

    function _setUint256(bytes32 slot, uint256 _value) internal {
        // solhint-disable-next-line no-inline-assembly
        assembly {
            sstore(slot, _value)
        }
    }

    function _setUint256InMap(bytes32 slot, address key, uint256 _value) internal {
        // solhint-disable-next-line no-inline-assembly
        bytes32 mappingSlot = keccak256(abi.encode(key, slot));
        assembly {
            sstore(mappingSlot, _value)
        }
    }

    function _setUint256InNestedMap(bytes32 slot, address key1, address key2, uint256 _value) internal {
        bytes32 mappingSlot = keccak256(abi.encode(key2, keccak256(abi.encode(key1, slot))));
        assembly {
            sstore(mappingSlot, _value)
        }
    }

    function _getAddress(bytes32 slot) internal view returns (address value) {
        // solhint-disable-next-line no-inline-assembly
        assembly {
            value := sload(slot)
        }
    }

    function _getUint256(bytes32 slot) internal view returns (uint256 value) {
        // solhint-disable-next-line no-inline-assembly
        assembly {
            value := sload(slot)
        }
    }

    function _getUint256FromMap(bytes32 slot, address key) internal view returns (uint256 value) {
        // solhint-disable-next-line no-inline-assembly
        bytes32 mappingSlot = keccak256(abi.encode(key, slot));
        assembly {
            value := sload(mappingSlot)
        }
    }

    function _getUint256InNestedMap(bytes32 slot, address key1, address key2) internal view returns (uint256 value) {
        bytes32 mappingSlot = keccak256(abi.encode(key2, keccak256(abi.encode(key1, slot))));
        assembly {
            value := sload(mappingSlot)
        }
    }
}

// SPDX-License-Identifier: GPL-3.0-or-later
/*

    Copyright 2023 Dolomite

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

pragma solidity ^0.8.9;


/**
 * @title   IAuthorizationBase
 * @author  Dolomite
 *
 * @notice  Interface for allowing only trusted callers to invoke functions that use the `requireIsCallerAuthorized`
 *          modifier.
 */
interface IAuthorizationBase {

    function setIsCallerAuthorized(address _caller, bool _isAuthorized) external;

    function isCallerAuthorized(address _caller) external view returns (bool);
}

// SPDX-License-Identifier: GPL-3.0-or-later
/*

    Copyright 2023 Dolomite

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

pragma solidity ^0.8.9;

import { IDolomiteRegistry } from "./IDolomiteRegistry.sol";


/**
 * @title   IBaseRegistry
 * @author  Dolomite
 *
 * @notice  Interface for base storage variables that should be in all registry contracts
 */
interface IBaseRegistry {

    // ========================================================
    // ======================== Events ========================
    // ========================================================

    event DolomiteRegistrySet(address indexed _dolomiteRegistry);

    // ========================================================
    // =================== Admin Functions ====================
    // ========================================================

    function ownerSetDolomiteRegistry(address _dolomiteRegistry) external;

    // ========================================================
    // =================== Getter Functions ===================
    // ========================================================

    function dolomiteRegistry() external view returns (IDolomiteRegistry);
}

// SPDX-License-Identifier: GPL-3.0-or-later
/*

    Copyright 2023 Dolomite

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

pragma solidity ^0.8.9;

import { AccountBalanceLib } from "../lib/AccountBalanceLib.sol";


/**
 * @title   IBorrowPositionProxyV1
 * @author  Dolomite
 *
 * @notice  Interface for allowing the transfer of assets between account numbers. Emits an event to allow for easy
 *          indexing of a subgraph for getting active borrow positions.
 */
interface IBorrowPositionProxyV1 {

    // ========================= Events =========================

    event BorrowPositionOpen(address indexed _borrower, uint256 indexed _borrowAccountNumber);

    // ========================= Functions =========================

    /**
     *
     * @param  _fromAccountNumber   The index from which `msg.sender` will be sourcing the deposit
     * @param  _toAccountNumber     The index into which `msg.sender` will be depositing
     * @param  _collateralMarketId  The ID of the market being deposited
     * @param  _amountWei           The amount, in Wei, to deposit
     * @param  _balanceCheckFlag    Flag used to check if `_fromAccountNumber`, `_toAccountNumber`, or both accounts can
     *                              go negative after the transfer settles. Setting the flag to
     *                              `AccountBalanceLib.BalanceCheckFlag.None=3` results in neither account being
     *                              checked.
     */
    function openBorrowPosition(
        uint256 _fromAccountNumber,
        uint256 _toAccountNumber,
        uint256 _collateralMarketId,
        uint256 _amountWei,
        AccountBalanceLib.BalanceCheckFlag _balanceCheckFlag
    ) external;

    /**
     * @notice  This method can only be called once the user's debt has been reduced to zero. Sends all
     *          `_collateralMarketIds` from `_borrowAccountNumber` to `_toAccountNumber`.
     *
     * @param  _borrowAccountNumber The index from which `msg.sender` collateral will be withdrawn
     * @param  _toAccountNumber     The index into which `msg.sender` will be depositing leftover collateral
     * @param  _collateralMarketIds The IDs of the markets being withdrawn, to close the position
     */
    function closeBorrowPosition(
        uint256 _borrowAccountNumber,
        uint256 _toAccountNumber,
        uint256[] calldata _collateralMarketIds
    ) external;

    /**
     *
     * @param  _fromAccountNumber   The index from which `msg.sender` will be withdrawing assets
     * @param  _toAccountNumber     The index into which `msg.sender` will be depositing assets
     * @param  _marketId            The ID of the market being transferred
     * @param  _amountWei           The amount, in Wei, to transfer
     * @param  _balanceCheckFlag    Flag used to check if `_fromAccountNumber`, `_toAccountNumber`, or both accounts can
     *                              go negative after the transfer settles. Setting the flag to
     *                              `AccountBalanceLib.BalanceCheckFlag.None=3` results in neither account being
     *                              checked.
     */
    function transferBetweenAccounts(
        uint256 _fromAccountNumber,
        uint256 _toAccountNumber,
        uint256 _marketId,
        uint256 _amountWei,
        AccountBalanceLib.BalanceCheckFlag _balanceCheckFlag
    ) external;

    /**
     *
     * @param  _fromAccountNumber   The index from which `msg.sender` will be depositing assets
     * @param  _borrowAccountNumber The index of the borrow position for that will receive the deposited assets
     * @param  _marketId            The ID of the market being transferred
     * @param  _balanceCheckFlag    Flag used to check if `_fromAccountNumber`, `_borrowAccountNumber`, or both accounts
     *                              can go negative after the transfer settles. Setting the flag to
     *                              `AccountBalanceLib.BalanceCheckFlag.None=3` results in neither account being
     *                              checked.
     */
    function repayAllForBorrowPosition(
        uint256 _fromAccountNumber,
        uint256 _borrowAccountNumber,
        uint256 _marketId,
        AccountBalanceLib.BalanceCheckFlag _balanceCheckFlag
    ) external;
}

// SPDX-License-Identifier: GPL-3.0-or-later
/*

    Copyright 2023 Dolomite

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

pragma solidity ^0.8.9;

import { IAuthorizationBase } from "./IAuthorizationBase.sol";
import { IBorrowPositionProxyV1 } from "./IBorrowPositionProxyV1.sol";
import { AccountBalanceLib } from "../lib/AccountBalanceLib.sol";


/**
 * @title   IBorrowPositionProxyV2
 * @author  Dolomite
 *
 * @notice  Interface for allowing only trusted callers to invoke borrow related functions for transferring funds
 *          between account owners.
 */
interface IBorrowPositionProxyV2 is IAuthorizationBase, IBorrowPositionProxyV1 {

    // ========================= Functions =========================

    /**
     *
     * @param  _fromAccountOwner    The account from which the user will be sourcing the deposit
     * @param  _fromAccountNumber   The index from which `_toAccountOwner` will be sourcing the deposit
     * @param  _toAccountOwner      The account into which `_fromAccountOwner` will be depositing
     * @param  _toAccountNumber     The index into which `_fromAccountOwner` will be depositing
     * @param  _collateralMarketId  The ID of the market being deposited
     * @param  _amountWei           The amount, in Wei, to deposit
     * @param  _balanceCheckFlag    Flag used to check if `_fromAccountNumber`, `_toAccountNumber`, or both accounts can
     *                              go negative after the transfer settles. Setting the flag to
     *                              `AccountBalanceLib.BalanceCheckFlag.None=3` results in neither account being
     *                              checked.
     */
    function openBorrowPositionWithDifferentAccounts(
        address _fromAccountOwner,
        uint256 _fromAccountNumber,
        address _toAccountOwner,
        uint256 _toAccountNumber,
        uint256 _collateralMarketId,
        uint256 _amountWei,
        AccountBalanceLib.BalanceCheckFlag _balanceCheckFlag
    ) external;

    /**
     * @notice  This method can only be called once the user's debt has been reduced to zero. Sends all
     *          `_collateralMarketIds` from `_borrowAccountNumber` to `_toAccountNumber`.
     *
     * @param  _borrowAccountOwner  The account from which collateral will be withdrawn
     * @param  _borrowAccountNumber The index from which `msg.sender` collateral will be withdrawn
     * @param  _toAccountOwner      The account into which `_borrowAccountOwner` will be depositing leftover collateral
     * @param  _toAccountNumber     The index into which `_borrowAccountOwner` will be depositing leftover collateral
     * @param  _collateralMarketIds The IDs of the markets being withdrawn, to close the position
     */
    function closeBorrowPositionWithDifferentAccounts(
        address _borrowAccountOwner,
        uint256 _borrowAccountNumber,
        address _toAccountOwner,
        uint256 _toAccountNumber,
        uint256[] calldata _collateralMarketIds
    ) external;

    /**
     *
     * @param  _fromAccountOwner    The account from which assets will be withdrawn
     * @param  _fromAccountNumber   The index from which `msg.sender` will be withdrawing assets
     * @param  _toAccountOwner      The account to which assets will be deposited
     * @param  _toAccountNumber     The index into which `msg.sender` will be depositing assets
     * @param  _marketId            The ID of the market being transferred
     * @param  _amountWei           The amount, in Wei, to transfer
     * @param  _balanceCheckFlag    Flag used to check if `_fromAccountNumber`, `_toAccountNumber`, or both accounts can
     *                              go negative after the transfer settles. Setting the flag to
     *                              `AccountBalanceLib.BalanceCheckFlag.None=3` results in neither account being
     *                              checked.
     */
    function transferBetweenAccountsWithDifferentAccounts(
        address _fromAccountOwner,
        uint256 _fromAccountNumber,
        address _toAccountOwner,
        uint256 _toAccountNumber,
        uint256 _marketId,
        uint256 _amountWei,
        AccountBalanceLib.BalanceCheckFlag _balanceCheckFlag
    ) external;

    /**
     *
     * @param  _fromAccountOwner    The account from which assets will be withdrawn for repayment
     * @param  _fromAccountNumber   The index from which `msg.sender` will be depositing assets
     * @param  _borrowAccountOwner  The account of the borrow position that will receive the deposited assets
     * @param  _borrowAccountNumber The index of the borrow position for that will receive the deposited assets
     * @param  _marketId            The ID of the market being transferred
     * @param  _balanceCheckFlag    Flag used to check if `_fromAccountNumber`, `_borrowAccountNumber`, or both accounts
     *                              can go negative after the transfer settles. Setting the flag to
     *                              `AccountBalanceLib.BalanceCheckFlag.None=3` results in neither account being
     *                              checked.
     */
    function repayAllForBorrowPositionWithDifferentAccounts(
        address _fromAccountOwner,
        uint256 _fromAccountNumber,
        address _borrowAccountOwner,
        uint256 _borrowAccountNumber,
        uint256 _marketId,
        AccountBalanceLib.BalanceCheckFlag _balanceCheckFlag
    ) external;
}

// SPDX-License-Identifier: GPL-3.0-or-later
/*

    Copyright 2023 Dolomite

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

pragma solidity ^0.8.9;

import { EnumerableSet } from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";


/**
 * @title   IDolomiteAccountRegistry
 * @author  Dolomite
 *
 * @notice  A registry contract for storing restricted Dolomite ERC20 accounts
 */
interface IDolomiteAccountRegistry {

    struct AccountInformation {
        mapping(address => bool) restrictedAccounts;
        mapping(address => EnumerableSet.AddressSet) accountToVaults;
        mapping(address => address) vaultToAccount;
        address[] factories;
    }

    // ================================================
    // ==================== Events ====================
    // ================================================

    event RestrictedAccountSet(address _account, bool _isRestricted);
    event VaultAddedToAccount(address _account, address _vault);

    // ===================================================
    // ==================== Functions ====================
    // ===================================================

    function registerVault(
        address _account,
        address _vault
    ) external;

    function ownerSetRestrictedAccount(
        address _account,
        bool _isRestricted
    ) external;

    function isIsolationModeVault(address _vault) external view returns (bool);

    function isRestrictedAccount(address _account) external view returns (bool);

    /**
     * @notice  Future-proof function for checking inclusivity for an address to be in the registry. This is mainly
     *          useful for general-purpose contracts like dERC20 tokens that don't want to send assets to accounts that
     *          don't want to be receivable
     *
     * @param  _account The account to check if it's in this registry as a restricted account or isolation mode vault
     * @return          True if this account is an isolation mode vault or restricted
     */
    function isAccountInRegistry(address _account) external view returns (bool);

    function getAccountByVault(address _vault) external view returns (address);

    function getVaultsByAccount(address _account) external view returns (address[] memory);

    function getFactories() external view returns (address[] memory);

    function isMarketIdIsolationMode(uint256 _marketId) external view returns (bool);

    function isTokenIsolationMode(address _token) external view returns (bool);
}

// SPDX-License-Identifier: GPL-3.0-or-later
/*

    Copyright 2023 Dolomite

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

pragma solidity ^0.8.9;

import { IDolomiteStructs } from "../protocol/interfaces/IDolomiteStructs.sol";


/**
 * @title   IDolomiteMigrator
 * @author  Dolomite
 *
 * Interface for a migrator contract, which can migrate funds out of users isolation mode vaults
 */
interface IDolomiteMigrator {

    // ================================================
    // ==================== Structs ===================
    // ================================================

    struct Transformer {
        address transformer;
        bool soloAllowable;
    }

    // ================================================
    // ==================== Events ====================
    // ================================================

    event MigrationComplete(
        address indexed _accountOwner,
        uint256 _accountNumber,
        uint256 _fromMarketId,
        uint256 _toMarketId
    );

    event TransformerSet(uint256 _fromMarketId, uint256 _toMarketId, address _transformer);

    event HandlerSet(address _handler);

    // ================================================
    // ================== Functions ===================
    // ================================================

    function migrate(
        IDolomiteStructs.AccountInfo[] calldata _accounts,
        uint256 _fromMarketId,
        uint256 _toMarketId,
        bytes calldata _extraData
    ) external;

    function selfMigrate(
        uint256 _accountNumber,
        uint256 _fromMarketId,
        uint256 _toMarketId,
        bytes calldata _extraData
    ) external;

    function ownerSetTransformer(
        uint256 _fromMarketId,
        uint256 _toMarketId,
        address _transformer,
        bool _soloAllowable
    ) external;

    function ownerSetHandler(address _handler) external;

    function getTransformerByMarketIds(
        uint256 _fromMarketId,
        uint256 _toMarketId
    ) external view returns (Transformer memory);
}

// SPDX-License-Identifier: GPL-3.0-or-later
/*

    Copyright 2023 Dolomite

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

pragma solidity ^0.8.9;

import { IDolomiteAccountRegistry } from "./IDolomiteAccountRegistry.sol";
import { IDolomiteMigrator } from "./IDolomiteMigrator.sol";
import { IEventEmitterRegistry } from "./IEventEmitterRegistry.sol";
import { IExpiry } from "./IExpiry.sol";
import { IGenericTraderProxyV1 } from "./IGenericTraderProxyV1.sol";
import { ILiquidatorAssetRegistry } from "./ILiquidatorAssetRegistry.sol";
import { IDolomitePriceOracle } from "../protocol/interfaces/IDolomitePriceOracle.sol";


/**
 * @title   IDolomiteRegistry
 * @author  Dolomite
 *
 * @notice  A registry contract for storing all of the addresses that can interact with Umami's Delta Neutral vaults
 */
interface IDolomiteRegistry {

    // ========================================================
    // ======================== Events ========================
    // ========================================================

    event GenericTraderProxySet(address indexed _genericTraderProxy);
    event ExpirySet(address indexed _expiry);
    event SlippageToleranceForPauseSentinelSet(uint256 _slippageTolerance);
    event LiquidatorAssetRegistrySet(address indexed _liquidatorAssetRegistry);
    event EventEmitterSet(address indexed _eventEmitter);
    event ChainlinkPriceOracleSet(address indexed _chainlinkPriceOracle);
    event DolomiteMigratorSet(address indexed _dolomiteMigrator);
    event RedstonePriceOracleSet(address indexed _redstonePriceOracle);
    event OracleAggregatorSet(address indexed _oracleAggregator);
    event DolomiteAccountRegistrySet(address indexed _dolomiteAccountRegistry);

    // ========================================================
    // =================== Write Functions ====================
    // ========================================================

    function lazyInitialize(address _dolomiteMigrator, address _oracleAggregator) external;

    /**
     *
     * @param  _genericTraderProxy  The new address of the generic trader proxy
     */
    function ownerSetGenericTraderProxy(address _genericTraderProxy) external;

    /**
     *
     * @param  _expiry  The new address of the expiry contract
     */
    function ownerSetExpiry(address _expiry) external;

    /**
     *
     * @param  _slippageToleranceForPauseSentinel   The slippage tolerance (using 1e18 as the base) for zaps when pauses
     *                                              are enabled
     */
    function ownerSetSlippageToleranceForPauseSentinel(uint256 _slippageToleranceForPauseSentinel) external;

    /**
     *
     * @param  _liquidatorRegistry  The new address of the liquidator registry
     */
    function ownerSetLiquidatorAssetRegistry(address _liquidatorRegistry) external;

    /**
     *
     * @param  _eventEmitter  The new address of the event emitter
     */
    function ownerSetEventEmitter(address _eventEmitter) external;

    /**
     *
     * @param  _chainlinkPriceOracle    The new address of the Chainlink price oracle that's compatible with
     *                                  DolomiteMargin.
     */
    function ownerSetChainlinkPriceOracle(address _chainlinkPriceOracle) external;

    function ownerSetDolomiteMigrator(address _dolomiteMigrator) external;

    /**
     *
     * @param  _redstonePriceOracle    The new address of the Redstone price oracle that's compatible with
     *                                  DolomiteMargin.
     */
    function ownerSetRedstonePriceOracle(address _redstonePriceOracle) external;

    /**
     *
     * @param  _oracleAggregator    The new address of the oracle aggregator that's compatible with
     *                              DolomiteMargin.
     */
    function ownerSetOracleAggregator(address _oracleAggregator) external;

    /**
     *
     * @param  _dolomiteAccountRegistry    The new address of the Dolomite address registry
     */
    function ownerSetDolomiteAccountRegistry(address _dolomiteAccountRegistry) external;

    // ========================================================
    // =================== Getter Functions ===================
    // ========================================================

    /**
     * @return  The address of the generic trader proxy for making zaps
     */
    function genericTraderProxy() external view returns (IGenericTraderProxyV1);

    /**
     * @return  The address of the expiry contract
     */
    function expiry() external view returns (IExpiry);

    /**
     * @return  The slippage tolerance (using 1e18 as the base) for zaps when pauses are enabled
     */
    function slippageToleranceForPauseSentinel() external view returns (uint256);

    /**
     * @return  The address of the liquidator asset registry contract
     */
    function liquidatorAssetRegistry() external view returns (ILiquidatorAssetRegistry);

    /**
     * @return The address of the emitter contract that can emit certain events for indexing
     */
    function eventEmitter() external view returns (IEventEmitterRegistry);

    /**
     * @return The address of the Chainlink price oracle that's compatible with DolomiteMargin
     */
    function chainlinkPriceOracle() external view returns (IDolomitePriceOracle);

    /**
     * @return The address of the migrator contract
     */
    function dolomiteMigrator() external view returns (IDolomiteMigrator);

    /**
     * @return The address of the Redstone price oracle that's compatible with DolomiteMargin
     */
    function redstonePriceOracle() external view returns (IDolomitePriceOracle);

    /**
     * @return The address of the oracle aggregator that's compatible with DolomiteMargin
     */
    function oracleAggregator() external view returns (IDolomitePriceOracle);

    /**
     * @return The address of the Dolomite address registry
     */
    function dolomiteAccountRegistry() external view returns (IDolomiteAccountRegistry);

    /**
     * @return The base (denominator) for the slippage tolerance variable. Always 1e18.
     */
    function slippageToleranceForPauseSentinelBase() external pure returns (uint256);
}

// SPDX-License-Identifier: GPL-3.0-or-later
/*

    Copyright 2023 Dolomite

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

pragma solidity ^0.8.9;

import { IGenericTraderBase } from "./IGenericTraderBase.sol";
import { IUpgradeableAsyncIsolationModeUnwrapperTrader } from "../isolation-mode/interfaces/IUpgradeableAsyncIsolationModeUnwrapperTrader.sol"; // solhint-disable-line max-line-length
import { IUpgradeableAsyncIsolationModeWrapperTrader } from "../isolation-mode/interfaces/IUpgradeableAsyncIsolationModeWrapperTrader.sol"; // solhint-disable-line max-line-length
import { IDolomiteStructs } from "../protocol/interfaces/IDolomiteStructs.sol";


/**
 * @title   IEventEmitterRegistry
 * @author  Dolomite
 *
 * Interface for a a singleton event emission contract, which makes tracking events easier for the Subgraph.
 */
interface IEventEmitterRegistry {

    // ================================================
    // ==================== Structs ===================
    // ================================================

    struct BalanceUpdate {
        IDolomiteStructs.Wei deltaWei;
        IDolomiteStructs.Par newPar;
    }

    // ================================================
    // ==================== Events ====================
    // ================================================

    /**
     * @notice This is emitted when a zap is executed
     *
     * @param  accountOwner     The address of the account that executed the zap
     * @param  accountNumber    The sub account of the address that executed the zap
     * @param  marketIdsPath    The path of market IDs that was executed
     * @param  tradersPath      The path of traders that was executed
     */
    event ZapExecuted(
        address indexed accountOwner,
        uint256 accountNumber,
        uint256[] marketIdsPath,
        IGenericTraderBase.TraderParam[] tradersPath
    );

    /**
     * @notice This is emitted when a borrow position is initially opened
     *
     * @param  borrower             The address of the account that opened the position
     * @param  borrowAccountNumber  The account number of the account that opened the position
     */
    event BorrowPositionOpen(
        address indexed borrower,
        uint256 indexed borrowAccountNumber
    );

    /**
     * @notice This is emitted when a margin position is initially opened
     *
     * @param  accountOwner         The address of the account that opened the position
     * @param  accountNumber        The account number of the account that opened the position
     * @param  inputToken           The token that was sold to purchase the collateral. This should be the owed token
     * @param  outputToken          The token that was purchased with the debt. This should be the held token
     * @param  depositToken         The token that was deposited as collateral. This should be the held token
     * @param  inputBalanceUpdate   The amount of inputToken that was sold to purchase the outputToken
     * @param  outputBalanceUpdate  The amount of outputToken that was purchased with the inputToken
     * @param  marginDepositUpdate  The amount of depositToken that was deposited as collateral
     */
    event MarginPositionOpen(
        address indexed accountOwner,
        uint256 indexed accountNumber,
        address inputToken,
        address outputToken,
        address depositToken,
        BalanceUpdate inputBalanceUpdate,
        BalanceUpdate outputBalanceUpdate,
        BalanceUpdate marginDepositUpdate
    );

    /**
     * @notice This is emitted when a margin position is (partially) closed
     *
     * @param  accountOwner             The address of the account that opened the position
     * @param  accountNumber            The account number of the account that opened the position
     * @param  inputToken               The token that was sold to purchase the debt. This should be the held token
     * @param  outputToken              The token that was purchased with the collateral. This should be the owed token
     * @param  withdrawalToken          The token that was withdrawn as collateral. This should be the held token
     * @param  inputBalanceUpdate       The amount of inputToken that was sold to purchase the outputToken
     * @param  outputBalanceUpdate      The amount of outputToken that was purchased with the inputToken
     * @param  marginWithdrawalUpdate   The amount of withdrawalToken that was deposited as collateral
     */
    event MarginPositionClose(
        address indexed accountOwner,
        uint256 indexed accountNumber,
        address inputToken,
        address outputToken,
        address withdrawalToken,
        BalanceUpdate inputBalanceUpdate,
        BalanceUpdate outputBalanceUpdate,
        BalanceUpdate marginWithdrawalUpdate
    );

    event AsyncDepositCreated(
        bytes32 indexed key,
        address indexed token,
        IUpgradeableAsyncIsolationModeWrapperTrader.DepositInfo deposit
    );

    event AsyncDepositOutputAmountUpdated(
        bytes32 indexed key,
        address indexed token,
        uint256 outputAmount
    );

    event AsyncDepositExecuted(bytes32 indexed key, address indexed token);

    event AsyncDepositFailed(bytes32 indexed key, address indexed token, string reason);

    event AsyncDepositCancelled(bytes32 indexed key, address indexed token);

    event AsyncDepositCancelledFailed(bytes32 indexed key, address indexed token, string reason);

    event AsyncWithdrawalCreated(
        bytes32 indexed key,
        address indexed token,
        IUpgradeableAsyncIsolationModeUnwrapperTrader.WithdrawalInfo withdrawal
    );

    event AsyncWithdrawalOutputAmountUpdated(
        bytes32 indexed key,
        address indexed token,
        uint256 outputAmount
    );

    event AsyncWithdrawalExecuted(bytes32 indexed key, address indexed token);

    event AsyncWithdrawalFailed(bytes32 indexed key, address indexed token, string reason);

    event AsyncWithdrawalCancelled(bytes32 indexed key, address indexed token);

    event DistributorRegistered(
        address oTokenAddress,
        address pairToken,
        address paymentToken
    );

    event RewardClaimed(
        address indexed distributor,
        address indexed user,
        uint256 epoch,
        uint256 amount
    );

    // ================================================
    // ================== Functions ===================
    // ================================================

    /**
     * @notice Emits a ZapExecuted event
     *
     * @param  _accountOwner    The address of the account that executed the zap
     * @param  _accountNumber   The sub account of the address that executed the zap
     * @param  _marketIdsPath   The path of market IDs that was executed
     * @param  _tradersPath     The path of traders that was executed
     */
    function emitZapExecuted(
        address _accountOwner,
        uint256 _accountNumber,
        uint256[] calldata _marketIdsPath,
        IGenericTraderBase.TraderParam[] calldata _tradersPath
    )
    external;

    /**
     * @notice Emits a MarginPositionOpen event
     *
     * @param  _accountOwner         The address of the account that opened the position
     * @param  _accountNumber        The account number of the account that opened the position
     */
    function emitBorrowPositionOpen(
        address _accountOwner,
        uint256 _accountNumber
    )
    external;

    /**
     * @notice Emits a MarginPositionOpen event
     *
     * @param  _accountOwner         The address of the account that opened the position
     * @param  _accountNumber        The account number of the account that opened the position
     * @param  _inputToken           The token that was sold to purchase the collateral. This should be the owed token
     * @param  _outputToken          The token that was purchased with the debt. This should be the held token
     * @param  _depositToken         The token that was deposited as collateral. This should be the held token
     * @param  _inputBalanceUpdate   The amount of inputToken that was sold to purchase the outputToken
     * @param  _outputBalanceUpdate  The amount of outputToken that was purchased with the inputToken
     * @param  _marginDepositUpdate  The amount of depositToken that was deposited as collateral
     */
    function emitMarginPositionOpen(
        address _accountOwner,
        uint256 _accountNumber,
        address _inputToken,
        address _outputToken,
        address _depositToken,
        BalanceUpdate calldata _inputBalanceUpdate,
        BalanceUpdate calldata _outputBalanceUpdate,
        BalanceUpdate calldata _marginDepositUpdate
    )
    external;

    /**
     * @notice Emits a MarginPositionClose event
     *
     * @param  _accountOwner            The address of the account that opened the position
     * @param  _accountNumber           The account number of the account that opened the position
     * @param  _inputToken              The token that was sold to purchase the debt. This should be the held token
     * @param  _outputToken             The token that was purchased with the collateral. This should be the owed token
     * @param  _withdrawalToken         The token that was withdrawn as collateral. This should be the held token
     * @param  _inputBalanceUpdate      The amount of inputToken that was sold to purchase the outputToken
     * @param  _outputBalanceUpdate     The amount of outputToken that was purchased with the inputToken
     * @param  _marginWithdrawalUpdate  The amount of withdrawalToken that was deposited as collateral
     */
    function emitMarginPositionClose(
        address _accountOwner,
        uint256 _accountNumber,
        address _inputToken,
        address _outputToken,
        address _withdrawalToken,
        BalanceUpdate calldata _inputBalanceUpdate,
        BalanceUpdate calldata _outputBalanceUpdate,
        BalanceUpdate calldata _marginWithdrawalUpdate
    )
    external;

    function emitAsyncDepositCreated(
        bytes32 _key,
        address _token,
        IUpgradeableAsyncIsolationModeWrapperTrader.DepositInfo calldata _deposit
    ) external;

    function emitAsyncDepositOutputAmountUpdated(
        bytes32 _key,
        address _token,
        uint256 _outputAmount
    ) external;

    function emitAsyncDepositExecuted(bytes32 _key, address _token) external;

    function emitAsyncDepositFailed(bytes32 _key, address _token, string calldata _reason) external;

    function emitAsyncDepositCancelled(bytes32 _key, address _token) external;

    function emitAsyncDepositCancelledFailed(bytes32 _key, address _token, string calldata _reason) external;

    function emitAsyncWithdrawalCreated(
        bytes32 _key,
        address _token,
        IUpgradeableAsyncIsolationModeUnwrapperTrader.WithdrawalInfo calldata _withdrawal
    ) external;

    function emitAsyncWithdrawalOutputAmountUpdated(
        bytes32 _key,
        address _token,
        uint256 _outputAmount
    ) external;

    function emitAsyncWithdrawalExecuted(bytes32 _key, address _token) external;

    function emitAsyncWithdrawalFailed(bytes32 _key, address _token, string calldata _reason) external;

    function emitAsyncWithdrawalCancelled(bytes32 _key, address _token) external;

    function emitDistributorRegistered(address _oTokenAddress, address _pairToken, address _paymentToken) external;

    function emitRewardClaimed(address _user, uint256 _epoch, uint256 _amount) external;
}

// SPDX-License-Identifier: GPL-3.0-or-later
/*

    Copyright 2023 Dolomite

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

pragma solidity ^0.8.9;

import { IDolomiteMargin } from "../protocol/interfaces/IDolomiteMargin.sol";


/**
 * @title   IExpiry
 * @author  Dolomite
 *
 * @notice  Interface for getting, setting, and executing the expiry of a position.
 */
interface IExpiry {

    // ============ Enums ============

    enum CallFunctionType {
        SetExpiry,
        SetApproval
    }

    // ============ Structs ============

    struct SetExpiryArg {
        IDolomiteMargin.AccountInfo account;
        uint256 marketId;
        uint32 timeDelta;
        bool forceUpdate;
    }

    struct SetApprovalArg {
        address sender;
        uint32 minTimeDelta;
    }

    function getSpreadAdjustedPrices(
        uint256 heldMarketId,
        uint256 owedMarketId,
        uint32 expiry
    )
    external
    view
    returns (IDolomiteMargin.MonetaryPrice memory heldPrice, IDolomiteMargin.MonetaryPrice memory owedPriceAdj);

    function getExpiry(
        IDolomiteMargin.AccountInfo calldata account,
        uint256 marketId
    )
    external
    view
    returns (uint32);

    function g_expiryRampTime() external view returns (uint256);
}

File 15 of 51 : IGenericTraderBase.sol
// SPDX-License-Identifier: GPL-3.0-or-later
/*

    Copyright 2023 Dolomite

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

pragma solidity ^0.8.9;

import { IDolomiteMargin } from "../protocol/interfaces/IDolomiteMargin.sol";


/**
 * @title   IGenericTraderBase
 * @author  Dolomite
 *
 * @notice  Base contract structs/params for a generic trader contract.
 */
interface IGenericTraderBase {

    // ============ Enums ============

    enum TraderType {
        /// @dev    The trade will be conducted using external liquidity, using an `ActionType.Sell` or `ActionType.Buy`
        ///         action.
        ExternalLiquidity,
        /// @dev    The trade will be conducted using internal liquidity, using an `ActionType.Trade` action.
        InternalLiquidity,
        /// @dev    The trade will be conducted using external liquidity using an `ActionType.Sell` or `ActionType.Buy`
        ///         action. If this TradeType is used, the trader must be validated using
        ///         the `IIsolationModeToken#isTokenConverterTrusted` function on the IsolationMode token.
        IsolationModeUnwrapper,
        /// @dev    The trade will be conducted using external liquidity using an `ActionType.Sell` or `ActionType.Buy`
        ///         action. If this TradeType is used, the trader must be validated using
        ///         the `IIsolationModeToken#isTokenConverterTrusted` function on the IsolationMode token.
        IsolationModeWrapper
    }

    // ============ Structs ============

    struct TraderParam {
        /// @dev The type of trade to conduct
        TraderType traderType;
        /// @dev    The index into the `_makerAccounts` array of the maker account to trade with. Should be set to 0 if
        ///         the traderType is not `TraderType.InternalLiquidity`.
        uint256 makerAccountIndex;
        /// @dev The address of IAutoTrader or IExchangeWrapper that will be used to conduct the trade.
        address trader;
        /// @dev The data that will be passed through to the trader contract.
        bytes tradeData;
    }

    struct GenericTraderProxyCache {
        IDolomiteMargin dolomiteMargin;
        /// @dev    True if the user is making a margin deposit, false if they are withdrawing. False if the variable is
        ///         unused too.
        bool isMarginDeposit;
        /// @dev    The other account number that is not `_traderAccountNumber`. Only used for TransferCollateralParams.
        uint256 otherAccountNumber;
        /// @dev    The index into the account array at which traders start.
        uint256 traderAccountStartIndex;
        /// @dev    The cursor for the looping through the operation's actions.
        uint256 actionsCursor;
        /// @dev    The balance of `inputMarket` that the trader has before the call to `dolomiteMargin.operate`
        IDolomiteMargin.Wei inputBalanceWeiBeforeOperate;
        /// @dev    The balance of `outputMarket` that the trader has before the call to `dolomiteMargin.operate`
        IDolomiteMargin.Wei outputBalanceWeiBeforeOperate;
        /// @dev    The balance of `transferMarket` that the trader has before the call to `dolomiteMargin.operate`
        IDolomiteMargin.Wei transferBalanceWeiBeforeOperate;
    }
}

// SPDX-License-Identifier: GPL-3.0-or-later
/*

    Copyright 2023 Dolomite.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

*/

pragma solidity ^0.8.9;

import { IGenericTraderBase } from "./IGenericTraderBase.sol";
import { AccountBalanceLib } from "../lib/AccountBalanceLib.sol";
import { IDolomiteMargin } from "../protocol/interfaces/IDolomiteMargin.sol";



/**
 * @title   IGenericTraderProxyV1
 * @author  Dolomite
 *
 * Trader proxy interface for trading assets using any trader from msg.sender
 */
interface IGenericTraderProxyV1 is IGenericTraderBase {

    // ============ Structs ============

    enum EventEmissionType {
        None,
        BorrowPosition,
        MarginPosition
    }

    struct TransferAmount {
        /// @dev The market ID to transfer
        uint256 marketId;
        /// @dev Note, setting to uint(-1) will transfer all of the user's balance.
        uint256 amountWei;
    }

    struct TransferCollateralParam {
        /// @dev The account number from which collateral will be transferred.
        uint256 fromAccountNumber;
        /// @dev The account number to which collateral will be transferred.
        uint256 toAccountNumber;
        /// @dev The transfers to execute after all of the trades.
        TransferAmount[] transferAmounts;
    }

    struct ExpiryParam {
        /// @dev The market ID whose expiry will be updated.
        uint256 marketId;
        /// @dev The new expiry time delta for the market. Setting this to `0` will reset the expiration.
        uint32 expiryTimeDelta;
    }

    struct UserConfig {
        /// @dev The timestamp at which the zap request fails
        uint256 deadline;
        /// @dev    Setting this to `BalanceCheckFlag.Both` or `BalanceCheckFlag.From` will check the
        ///         `_tradeAccountNumber` is not negative after the trade for the input market (_marketIdsPath[0]).
        ///         Setting this to `BalanceCheckFlag.Both` or `BalanceCheckFlag.To` will check the
        ///         `_transferAccountNumber` is not negative after the trade for any of the transfers in
        ///         `TransferCollateralParam.transferAmounts`.
        AccountBalanceLib.BalanceCheckFlag balanceCheckFlag;
        EventEmissionType eventType;
    }

    // ============ Functions ============

    /**
     * @dev     Swaps an exact amount of input for a minimum amount of output.
     *
     * @param  _tradeAccountNumber          The account number to use for msg.sender's trade
     * @param  _marketIdsPath               The path of market IDs to use for each trade action. Length should be equal
     *                                      to `_tradersPath.length + 1`.
     * @param  _inputAmountWei              The input amount (in wei) to use for the initial trade action. Setting this
     *                                      value to `uint(-1)` will use the user's full balance.
     * @param  _minOutputAmountWei          The minimum output amount expected to be received by the user.
     * @param  _tradersPath                 The path of traders to use for each trade action. Length should be equal to
     *                                      `_marketIdsPath.length - 1`.
     * @param  _makerAccounts               The accounts that will be used for the maker side of the trades involving
     *                                      `TraderType.InternalLiquidity`.
     * @param  _userConfig                  The user configuration for the trade. Setting the `balanceCheckFlag` to
     *                                      `BalanceCheckFlag.From` will check that the user's `_tradeAccountNumber`
     *                                      is non-negative after the trade. Setting the `balanceCheckFlag` to
     *                                      `BalanceCheckFlag.To` has no effect.
     */
    function swapExactInputForOutput(
        uint256 _tradeAccountNumber,
        uint256[] calldata _marketIdsPath,
        uint256 _inputAmountWei,
        uint256 _minOutputAmountWei,
        IGenericTraderBase.TraderParam[] calldata _tradersPath,
        IDolomiteMargin.AccountInfo[] calldata _makerAccounts,
        UserConfig calldata _userConfig
    )
    external;

    /**
     * @dev     The same function as `swapExactInputForOutput`, but allows the caller to transfer collateral and modify
     *          the position's expiration in the same transaction.
     *
     * @param  _tradeAccountNumber          The account number to use for msg.sender's trade
     * @param  _marketIdsPath               The path of market IDs to use for each trade action. Length should be equal
     *                                      to `_tradersPath.length + 1`.
     * @param  _inputAmountWei              The input amount (in wei) to use for the initial trade action. Setting this
     *                                      value to `uint(-1)` will use the user's full balance.
     * @param  _minOutputAmountWei          The minimum output amount expected to be received by the user.
     * @param  _tradersPath                 The path of traders to use for each trade action. Length should be equal to
     *                                      `_marketIdsPath.length - 1`.
     * @param  _makerAccounts               The accounts that will be used for the maker side of the trades involving
                                            `TraderType.InternalLiquidity`.
     * @param  _transferCollateralParams    The parameters for transferring collateral in/out of the
     *                                      `_tradeAccountNumber` once the trades settle. One of
     *                                      `_params.fromAccountNumber` or `_params.toAccountNumber` must be equal to
     *                                      `_tradeAccountNumber`.
     * @param  _expiryParams                The parameters for modifying the expiration of the debt in the position.
     * @param  _userConfig                  The user configuration for the trade. Setting the `balanceCheckFlag` to
     *                                      `BalanceCheckFlag.From` will check that the user's balance for inputMarket
     *                                      for `_tradeAccountNumber` is non-negative after the trade. Setting the
     *                                      `balanceCheckFlag` to `BalanceCheckFlag.To` will check that the user's
     *                                      balance for each `transferMarket` for `transferAccountNumber` is
     *                                      non-negative after.
     */
    function swapExactInputForOutputAndModifyPosition(
        uint256 _tradeAccountNumber,
        uint256[] calldata _marketIdsPath,
        uint256 _inputAmountWei,
        uint256 _minOutputAmountWei,
        IGenericTraderBase.TraderParam[] calldata _tradersPath,
        IDolomiteMargin.AccountInfo[] calldata _makerAccounts,
        TransferCollateralParam calldata _transferCollateralParams,
        ExpiryParam calldata _expiryParams,
        UserConfig calldata _userConfig
    )
    external;

    function ownerSetEventEmitterRegistry(
        address _eventEmitterRegistry
    ) external;

    function EVENT_EMITTER_REGISTRY() external view returns (address);

    function EXPIRY() external view returns (address);
}

// SPDX-License-Identifier: GPL-3.0-or-later
/*

    Copyright 2023 Dolomite

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

pragma solidity ^0.8.9;

/**
 * @title   ILiquidatorAssetRegistry
 * @author  Dolomite
 *
 * Interface for a registry that tracks which assets can be liquidated and by each contract
 */
interface ILiquidatorAssetRegistry {

    /**
     *
     * @param  _marketId    The market ID of the asset
     * @param  _liquidator  The address of the liquidator to add
     */
    function ownerAddLiquidatorToAssetWhitelist(
        uint256 _marketId,
        address _liquidator
    )
    external;

    /**
     *
     * @param  _marketId    The market ID of the asset
     * @param  _liquidator  The address of the liquidator to remove
     */
    function ownerRemoveLiquidatorFromAssetWhitelist(
        uint256 _marketId,
        address _liquidator
    )
    external;

    /**
     *
     * @param  _marketId    The market ID of the asset to check
     * @return              An array of whitelisted liquidators for the asset. An empty array is returned if any
     *                      liquidator can be used for this asset
     */
    function getLiquidatorsForAsset(
        uint256 _marketId
    )
    external view returns (address[] memory);

    /**
     *
     * @param  _marketId    The market ID of the asset to check
     * @param  _liquidator  The address of the liquidator to check
     * @return              True if the liquidator is whitelisted for the asset, false otherwise. Returns true if there
     *                      are no whitelisted liquidators for the asset. Should ALWAYS have at least ONE whitelisted
     *                      liquidator for IsolationMode assets.
     */
    function isAssetWhitelistedForLiquidation(
        uint256 _marketId,
        address _liquidator
    )
    external view returns (bool);
}

File 18 of 51 : IOnlyDolomiteMargin.sol
// SPDX-License-Identifier: GPL-3.0-or-later
/*

    Copyright 2023 Dolomite

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

pragma solidity ^0.8.9;

import { IDolomiteMargin } from "../protocol/interfaces/IDolomiteMargin.sol";


/**
 * @title   IOnlyDolomiteMargin
 * @author  Dolomite
 *
 * @notice  This interface is for contracts that need to add modifiers for only DolomiteMargin / Owner caller.
 */
interface IOnlyDolomiteMargin {

    function DOLOMITE_MARGIN() external view returns (IDolomiteMargin);
}

// SPDX-License-Identifier: GPL-3.0-or-later
/*

    Copyright 2023 Dolomite

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

pragma solidity ^0.8.9;

import { Create2 } from "@openzeppelin/contracts/utils/Create2.sol";
import { IsolationModeUpgradeableProxy } from "../IsolationModeUpgradeableProxy.sol";
import { MinimalERC20 } from "../../general/MinimalERC20.sol";
import { OnlyDolomiteMargin } from "../../helpers/OnlyDolomiteMargin.sol";
import { IBorrowPositionProxyV2 } from "../../interfaces/IBorrowPositionProxyV2.sol";
import { IDolomiteRegistry } from "../../interfaces/IDolomiteRegistry.sol";
import { AccountActionLib } from "../../lib/AccountActionLib.sol";
import { AccountBalanceLib } from "../../lib/AccountBalanceLib.sol";
import { IDolomiteStructs } from "../../protocol/interfaces/IDolomiteStructs.sol";
import { Require } from "../../protocol/lib/Require.sol";
import { IIsolationModeTokenVaultV1 } from "../interfaces/IIsolationModeTokenVaultV1.sol";
import { IIsolationModeUpgradeableProxy } from "../interfaces/IIsolationModeUpgradeableProxy.sol";
import { IIsolationModeVaultFactory } from "../interfaces/IIsolationModeVaultFactory.sol";


/**
 * @title   IsolationModeVaultFactory
 * @author  Dolomite
 *
 * @notice  Abstract contract for wrapping tokens via a per-user vault that credits a user's balance within
 *          DolomiteMargin
 */
abstract contract IsolationModeVaultFactory is
    IIsolationModeVaultFactory,
    OnlyDolomiteMargin,
    MinimalERC20
{

    // ===================================================
    // ==================== Constants ====================
    // ===================================================

    bytes32 private constant _FILE = "IsolationModeVaultFactory";
    address private constant _DEAD_VAULT = 0x000000000000000000000000000000000000dEaD;

    // ==================================================
    // ================ Immutable Fields ================
    // ==================================================

    address public immutable override UNDERLYING_TOKEN; // solhint-disable-line var-name-mixedcase
    IBorrowPositionProxyV2 public immutable override BORROW_POSITION_PROXY; // solhint-disable-line var-name-mixedcase
    IDolomiteRegistry public immutable DOLOMITE_REGISTRY;

    // ================================================
    // ==================== Fields ====================
    // ================================================

    address public override userVaultImplementation;
    bool public isInitialized;
    uint256 public override marketId; // can't be immutable because it's set in the call to #initialize
    uint256 public transferCursor;

    mapping(uint256 => QueuedTransfer) internal _cursorToQueuedTransferMap;
    mapping(address => address) internal _vaultToUserMap;
    mapping(address => address) internal _userToVaultMap;
    mapping(address => bool) internal _tokenConverterToIsTrustedMap;

    // ===================================================
    // ==================== Modifiers ====================
    // ===================================================

    modifier requireIsInitialized {
        Require.that(
            isInitialized,
            _FILE,
            "Not initialized"
        );
        _;
    }

    modifier requireIsVault(address _vault) {
        Require.that(
            address(_vaultToUserMap[_vault]) != address(0),
            _FILE,
            "Invalid vault",
            _vault
        );
        _;
    }

    modifier requireIsTokenConverter(address _tokenConverter) {
        Require.that(
            _tokenConverterToIsTrustedMap[_tokenConverter],
            _FILE,
            "Caller is not a token converter",
            _tokenConverter
        );
        _;
    }

    modifier requireIsTokenConverterOrVault(address _tokenConverterOrVault) {
        Require.that(
            _tokenConverterToIsTrustedMap[_tokenConverterOrVault]
                || _vaultToUserMap[_tokenConverterOrVault] != address(0),
            _FILE,
            "Caller is not a authorized",
            _tokenConverterOrVault
        );
        _;
    }

    constructor(
        address _underlyingToken,
        address _borrowPositionProxyV2,
        address _userVaultImplementation,
        address _dolomiteRegistry,
        address _dolomiteMargin
    )
    MinimalERC20(
        /* name_ = */ string(abi.encodePacked("Dolomite Isolation: ", MinimalERC20(_underlyingToken).name())),
        /* symbol_ = */ string(abi.encodePacked("d", MinimalERC20(_underlyingToken).symbol())),
        /* decimals_ = */ MinimalERC20(_underlyingToken).decimals()
    )
    OnlyDolomiteMargin(_dolomiteMargin)
    {
        DOLOMITE_REGISTRY = IDolomiteRegistry(_dolomiteRegistry);
        UNDERLYING_TOKEN = _underlyingToken;
        BORROW_POSITION_PROXY = IBorrowPositionProxyV2(_borrowPositionProxyV2);
        userVaultImplementation = _userVaultImplementation;

        _createVault(_DEAD_VAULT);
    }

    // =================================================
    // ================ Write Functions ================
    // =================================================

    function ownerInitialize(
        address[] calldata _tokenConverters
    )
    external
    override
    onlyDolomiteMarginOwner(msg.sender) {
        Require.that(
            !isInitialized,
            _FILE,
            "Already initialized"
        );
        marketId = DOLOMITE_MARGIN().getMarketIdByTokenAddress(address(this));
        Require.that(
            DOLOMITE_MARGIN().getMarketIsClosing(marketId),
            _FILE,
            "Market cannot allow borrowing"
        );

        _initializeVault(_DEAD_VAULT, _userToVaultMap[_DEAD_VAULT]);

        for (uint256 i = 0; i < _tokenConverters.length; i++) {
            _ownerSetIsTokenConverterTrusted(_tokenConverters[i], true);
        }

        isInitialized = true;
        emit Initialized();

        _afterInitialize();
    }

    function createVault(
        address _account
    )
    external
    override
    requireIsInitialized
    returns (address) {
        return _createVault(_account);
    }

    function createVaultAndDepositIntoDolomiteMargin(
        uint256 _toAccountNumber,
        uint256 _amountWei
    )
    external
    override
    requireIsInitialized
    returns (address) {
        address vault = _createVault(msg.sender);
        IIsolationModeTokenVaultV1(vault).depositIntoVaultForDolomiteMargin(_toAccountNumber, _amountWei);
        return vault;
    }

    function ownerSetUserVaultImplementation(
        address _userVaultImplementation
    )
    external
    override
    requireIsInitialized
    onlyDolomiteMarginOwner(msg.sender) {
        Require.that(
            _userVaultImplementation != address(0),
            _FILE,
            "Invalid user implementation"
        );
        address _oldUserVaultImplementation = userVaultImplementation;
        userVaultImplementation = _userVaultImplementation;
        emit UserVaultImplementationSet(_oldUserVaultImplementation, _userVaultImplementation);
    }

    function ownerSetIsTokenConverterTrusted(
        address _tokenConverter,
        bool _isTrusted
    )
    external
    override
    requireIsInitialized
    onlyDolomiteMarginOwner(msg.sender) {
        _ownerSetIsTokenConverterTrusted(_tokenConverter, _isTrusted);
    }

    function depositOtherTokenIntoDolomiteMarginForVaultOwner(
        uint256 _toAccountNumber,
        uint256 _otherMarketId,
        uint256 _amountWei
    )
    external
    override
    requireIsVault(msg.sender) {
        Require.that(
            _otherMarketId != marketId,
            _FILE,
            "Invalid market",
            _otherMarketId
        );

        // we have to deposit into the vault first and then transfer to vault.owner, because the deposit is not
        // coming from the factory address or the vault owner.
        IDolomiteStructs.AccountInfo[] memory accounts = new IDolomiteStructs.AccountInfo[](2);
        accounts[0] = IDolomiteStructs.AccountInfo({
            owner: msg.sender,
            number: 0
        });
        accounts[1] = IDolomiteStructs.AccountInfo({
            owner: _vaultToUserMap[msg.sender],
            number: _toAccountNumber
        });

        IDolomiteStructs.ActionArgs[] memory actions = new IDolomiteStructs.ActionArgs[](2);
        actions[0] = AccountActionLib.encodeDepositAction(
            /* _accountId = */ 0,
            _otherMarketId,
            IDolomiteStructs.AssetAmount({
                sign: true,
                denomination: IDolomiteStructs.AssetDenomination.Wei,
                ref: IDolomiteStructs.AssetReference.Delta,
                value: _amountWei
            }),
            /* _fromAccount = */ msg.sender
        );
        actions[1] = AccountActionLib.encodeTransferAction(
            /* _fromAccountId = */ 0,
            /* _toAccountId = */ 1,
            _otherMarketId,
            IDolomiteStructs.AssetDenomination.Wei,
            AccountActionLib.all()
        );

        DOLOMITE_MARGIN().operate(accounts, actions);
    }

    function enqueueTransferIntoDolomiteMargin(
        address _vault,
        uint256 _amountWei
    )
    external
    override
    requireIsTokenConverter(msg.sender)
    requireIsVault(_vault) {
        _enqueueTransfer(msg.sender, address(DOLOMITE_MARGIN()), _amountWei, _vault);
    }

    function enqueueTransferFromDolomiteMargin(
        address _vault,
        uint256 _amountWei
    )
    external
    override
    requireIsTokenConverter(msg.sender)
    requireIsVault(_vault) {
        _enqueueTransfer(address(DOLOMITE_MARGIN()), msg.sender, _amountWei, _vault);
    }

    function depositIntoDolomiteMargin(
        uint256 _toAccountNumber,
        uint256 _amountWei
    )
    external
    override
    requireIsVault(msg.sender) {
        address vault = msg.sender;
        _enqueueTransfer(
            vault,
            address(DOLOMITE_MARGIN()),
            _amountWei,
            vault
        );
        AccountActionLib.deposit(
            DOLOMITE_MARGIN(),
            /* _accountOwner = */ vault,
            /* _fromAccount = */ vault,
            _toAccountNumber,
            marketId,
            IDolomiteStructs.AssetAmount({
                sign: true,
                denomination: IDolomiteStructs.AssetDenomination.Wei,
                ref: IDolomiteStructs.AssetReference.Delta,
                value: _amountWei
            })
        );
    }

    function withdrawFromDolomiteMargin(
        uint256 _fromAccountNumber,
        uint256 _amountWei
    )
    external
    override
    requireIsVault(msg.sender) {
        address vault = msg.sender;
        _enqueueTransfer(
            address(DOLOMITE_MARGIN()),
            vault,
            _amountWei,
            vault
        );
        AccountActionLib.withdraw(
            DOLOMITE_MARGIN(),
            /* _accountOwner = */ vault,
            _fromAccountNumber,
            /* _toAccount = */ vault,
            marketId,
            IDolomiteStructs.AssetAmount({
                sign: false,
                denomination: IDolomiteStructs.AssetDenomination.Wei,
                ref: IDolomiteStructs.AssetReference.Delta,
                value: _amountWei
            }),
            AccountBalanceLib.BalanceCheckFlag.From
        );
    }

    // ================================================
    // ================ Read Functions ================
    // ================================================

    function getQueuedTransferByCursor(uint256 _transferCursor) external view returns (QueuedTransfer memory) {
        Require.that(
            _transferCursor <= transferCursor,
            _FILE,
            "Invalid transfer cursor"
        );
        return _cursorToQueuedTransferMap[_transferCursor];
    }

    function isTokenConverterTrusted(address _tokenConverter) external view override returns (bool) {
        return _tokenConverterToIsTrustedMap[_tokenConverter];
    }

    function getVaultByAccount(address _account) external view override returns (address _vault) {
        _vault = _userToVaultMap[_account];
    }

    function calculateVaultByAccount(address _account) external view override returns (address _vault) {
        _vault = Create2.computeAddress(
            keccak256(abi.encodePacked(_account)),
            getProxyVaultInitCodeHash()
        );
    }

    function getAccountByVault(address _vault) external view override returns (address _account) {
        _account = _vaultToUserMap[_vault];
    }

    function isIsolationAsset() external pure returns (bool) {
        return true;
    }

    // ====================================================
    // ================= Public Functions =================
    // ====================================================

    function getProxyVaultInitCodeHash() public pure override returns (bytes32) {
        return keccak256(type(IsolationModeUpgradeableProxy).creationCode);
    }

    // ====================================================
    // ================ Internal Functions ================
    // ====================================================

    function _afterInitialize() internal virtual {
        // solhint-disable-previous-line no-empty-blocks
    }

    function _ownerSetIsTokenConverterTrusted(address _tokenConverter, bool _isTrusted) internal {
        Require.that(
            _tokenConverter != address(0),
            _FILE,
            "Invalid token converter"
        );
        _tokenConverterToIsTrustedMap[_tokenConverter] = _isTrusted;
        emit TokenConverterSet(_tokenConverter, _isTrusted);
    }

    function _createVault(address _account) internal virtual returns (address) {
        Require.that(
            _account != address(0),
            _FILE,
            "Invalid account"
        );
        Require.that(
            _userToVaultMap[_account] == address(0),
            _FILE,
            "Vault already exists"
        );
        address vault = Create2.deploy(
            /* amount = */ 0,
            keccak256(abi.encodePacked(_account)),
            type(IsolationModeUpgradeableProxy).creationCode
        );
        assert(vault != address(0));
        emit VaultCreated(_account, vault);
        _vaultToUserMap[vault] = _account;
        _userToVaultMap[_account] = vault;

        if (_account != _DEAD_VAULT) {
            _initializeVault(_account, vault);
        }

        return vault;
    }

    function _initializeVault(address _account, address _vault) internal {
        assert(_account != address(0) && _vault != address(0));
        IIsolationModeUpgradeableProxy(_vault).initialize(_account);
        BORROW_POSITION_PROXY.setIsCallerAuthorized(_vault, true);
        DOLOMITE_REGISTRY.dolomiteAccountRegistry().registerVault(_account, _vault);
    }

    function _enqueueTransfer(
        address _from,
        address _to,
        uint256 _amount,
        address _vault
    ) internal {
        QueuedTransfer memory oldTransfer = _cursorToQueuedTransferMap[transferCursor];
        if (!oldTransfer.isExecuted && oldTransfer.to == address(DOLOMITE_MARGIN())) {
            // remove the approval if the previous transfer was not executed and was to DolomiteMargin
            _approve(oldTransfer.vault, oldTransfer.to, 0);
        }

        if (_from == _vault && _to == address(DOLOMITE_MARGIN())) {
            // Approve the queued transfer amount from the vault contract into DolomiteMargin from this contract
            _approve(_vault, _to, _amount);
        }
        // add 1 to the cursor for any enqueue, allowing anyone to overwrite stale enqueues in case a developer
        // doesn't integrate with this contract properly
        transferCursor += 1;
        _cursorToQueuedTransferMap[transferCursor] = QueuedTransfer({
            from: _from,
            to: _to,
            amount: _amount,
            vault: _vault,
            isExecuted: false
        });
        emit TransferQueued(transferCursor, _from, _to, _amount, _vault);
    }

    function _transfer(
        address _from,
        address _to,
        uint256 _amount
    )
    internal
    override
    onlyDolomiteMargin(msg.sender) {
        Require.that(
            _from != address(0),
            _FILE,
            "Transfer from the zero address"
        );
        Require.that(
            _to != address(0),
            _FILE,
            "Transfer to the zero address"
        );

        // Since this must be called from DolomiteMargin via Exchange#transferIn/Exchange#transferOut, we can assume
        // that it's non-reentrant
        address dolomiteMargin = address(DOLOMITE_MARGIN());
        Require.that(
            _from == dolomiteMargin || _to == dolomiteMargin,
            _FILE,
            "from/to must eq DolomiteMargin"
        );

        uint256 _transferCursor = transferCursor;
        QueuedTransfer memory queuedTransfer = _cursorToQueuedTransferMap[_transferCursor];
        Require.that(
            queuedTransfer.from == _from
                && queuedTransfer.to == _to
                && queuedTransfer.amount == _amount
                && _vaultToUserMap[queuedTransfer.vault] != address(0),
            _FILE,
            "Invalid queued transfer"
        );
        Require.that(
            !queuedTransfer.isExecuted,
            _FILE,
            "Transfer already executed",
            _transferCursor
        );
        _cursorToQueuedTransferMap[_transferCursor].isExecuted = true;

        if (_to == dolomiteMargin) {
            // transfers TO DolomiteMargin must be made FROM a vault or a tokenConverter
            address vaultOwner = _vaultToUserMap[_from];
            Require.that(
                (vaultOwner != address(0) && _from == queuedTransfer.vault) || _tokenConverterToIsTrustedMap[_from],
                _FILE,
                "Invalid from"
            );
            IIsolationModeTokenVaultV1(queuedTransfer.vault).executeDepositIntoVault(
                vaultOwner != address(0) ? vaultOwner : _from,
                _amount
            );
            _mint(_to, _amount);
        } else {
            assert(_from == dolomiteMargin);

            // transfers FROM DolomiteMargin must be made TO a vault OR to a tokenConverter
            address vaultOwner = _vaultToUserMap[_to];
            Require.that(
                vaultOwner != address(0) || _tokenConverterToIsTrustedMap[_to],
                _FILE,
                "Invalid to"
            );

            IIsolationModeTokenVaultV1(queuedTransfer.vault).executeWithdrawalFromVault(
                vaultOwner != address(0) ? vaultOwner : _to,
                _amount
            );
            _burn(_from, _amount);
        }
    }
}

// SPDX-License-Identifier: GPL-3.0-or-later
/*

    Copyright 2023 Dolomite

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

pragma solidity ^0.8.9;

import { IBorrowPositionProxyV2 } from "../../interfaces/IBorrowPositionProxyV2.sol";
import { IDolomiteRegistry } from "../../interfaces/IDolomiteRegistry.sol";
import { IGenericTraderBase } from "../../interfaces/IGenericTraderBase.sol";
import { IGenericTraderProxyV1 } from "../../interfaces/IGenericTraderProxyV1.sol";
import { AccountBalanceLib } from "../../lib/AccountBalanceLib.sol";
import { IDolomiteMargin } from "../../protocol/interfaces/IDolomiteMargin.sol";
import { IDolomiteStructs } from "../../protocol/interfaces/IDolomiteStructs.sol";


/**
 * @title   IIsolationModeTokenVaultV1
 * @author  Dolomite
 *
 * @notice Interface for the implementation contract used by proxy user vault contracts.
 */
interface IIsolationModeTokenVaultV1 {

    struct SwapExactInputForOutputParams {
        uint256 tradeAccountNumber;
        uint256[] marketIdsPath;
        uint256 inputAmountWei;
        uint256 minOutputAmountWei;
        IGenericTraderProxyV1.TraderParam[] tradersPath;
        IDolomiteStructs.AccountInfo[] makerAccounts;
        IGenericTraderProxyV1.UserConfig userConfig;
    }

    // ===========================================================
    // ======================== Functions ========================
    // ===========================================================

    /**
     * @notice  Initializes the vault contract. Should only be executable once by the proxy.
     */
    function initialize() external;

    /**
     * @notice  End-user function for depositing the vault factory's underlying token into DolomiteMargin. Should only
     *          be executable by the vault owner OR the vault factory.
     */
    function depositIntoVaultForDolomiteMargin(uint256 _toAccountNumber, uint256 _amountWei) external;

    /**
     * @notice  End-user function for withdrawing the vault factory's underlying token from DolomiteMargin. Should only
     *          be executable by the vault owner.
     */
    function withdrawFromVaultForDolomiteMargin(uint256 _fromAccountNumber, uint256 _amountWei) external;

    /**
     * @notice  End-user function for opening a borrow position involving the vault factory's underlying token. Should
     *          only be executable by the vault owner. Reverts if `_fromAccountNumber` is not 0 or if `_toAccountNumber`
     *          is 0.
     */
    function openBorrowPosition(
        uint256 _fromAccountNumber,
        uint256 _toAccountNumber,
        uint256 _amountWei
    ) external payable;

    /**
     * @notice  End-user function for closing a borrow position involving the vault factory's underlying token. Should
     *          only be executable by the vault owner. Reverts if `_borrowAccountNumber` is 0 or if `_toAccountNumber`
     *          is not 0.
     */
    function closeBorrowPositionWithUnderlyingVaultToken(
        uint256 _borrowAccountNumber,
        uint256 _toAccountNumber
    ) external;

    /**
     * @notice  End-user function for closing a borrow position involving anything BUT the vault factory's underlying
     *          token. Should only be executable by the vault owner. Throws if any of the `collateralMarketIds` is set
     *          to the vault factory's underlying token. Reverts if `_borrowAccountNumber` is 0.
     */
    function closeBorrowPositionWithOtherTokens(
        uint256 _borrowAccountNumber,
        uint256 _toAccountNumber,
        uint256[] calldata collateralMarketIds
    ) external;

    /**
     * @notice  End-user function for transferring collateral into a position using the vault factory's underlying
     *          token. Should only be executable by the vault owner. Reverts if `_fromAccountNumber` is not 0 or if
     *          `_borrowAccountNumber` is 0.
     */
    function transferIntoPositionWithUnderlyingToken(
        uint256 _fromAccountNumber,
        uint256 _borrowAccountNumber,
        uint256 _amountWei
    ) external;

    /**
     * @notice  End-user function for transferring collateral into a position using anything BUT the vault factory's
     *          underlying token. Should only be executable by the vault owner. Throws if the `_marketId` is set to the
     *          vault factory's underlying token. Reverts if `_borrowAccountNumber` is 0.
     */
    function transferIntoPositionWithOtherToken(
        uint256 _fromAccountNumber,
        uint256 _borrowAccountNumber,
        uint256 _marketId,
        uint256 _amountWei,
        AccountBalanceLib.BalanceCheckFlag _balanceCheckFlag
    ) external;

    /**
     * @notice  End-user function for transferring collateral from a position using the vault factory's underlying
     *          token. Should only be executable by the vault owner. Reverts if `_borrowAccountNumber` is 0 or if
     *          `_toAccountNumber` is not 0.
     */
    function transferFromPositionWithUnderlyingToken(
        uint256 _borrowAccountNumber,
        uint256 _toAccountNumber,
        uint256 _amountWei
    ) external;

    /**
     * @notice  End-user function for transferring collateral from a position using anything BUT the vault factory's
     *          underlying token. Should only be executable by the vault owner. Throws if the `_marketId` is set to the
     *          vault factory's underlying token. Reverts if `_borrowAccountNumber` is 0.
     */
    function transferFromPositionWithOtherToken(
        uint256 _borrowAccountNumber,
        uint256 _toAccountNumber,
        uint256 _marketId,
        uint256 _amountWei,
        AccountBalanceLib.BalanceCheckFlag _balanceCheckFlag
    ) external;

    /**
     * @notice  End-user function for transferring collateral involving anything BUT the vault factory's underlying
     *          token. Should only be executable by the vault owner. Throws if the `_marketId` is set to the vault
     *          factory's underlying token. Reverts if `_borrowAccountNumber` is 0.
     */
    function repayAllForBorrowPosition(
        uint256 _fromAccountNumber,
        uint256 _borrowAccountNumber,
        uint256 _marketId,
        AccountBalanceLib.BalanceCheckFlag _balanceCheckFlag
    ) external;

    /**
     * @dev     End-user function for adding collateral from the vault (in the case where `_marketIdsPath[0]` is the
     *          underlying marketId) or the vault owner (in the case where `_marketIdsPath[0]` is not the underlying
     *          marketId), then trading an exact amount of input for a minimum amount of output. Reverts if
     *          `_borrowAccountNumber` is 0 or if `_fromAccountNumber` is not 0 (and the `_marketIdsPath[0]` is the
     *          underlying). Reverts if the user has a negative balance for `_marketIdsPath[0]`.
     *
     * @param  _fromAccountNumber           The account number to use for the source of the transfer.
     * @param  _borrowAccountNumber         The account number to use for the vault's trade. Cannot be 0.
     * @param  _marketIdsPath               The path of market IDs to use for each trade action. Length should be equal
     *                                      to `_tradersPath.length + 1`.
     * @param  _inputAmountWei              The input amount (in wei) to use for the initial trade action. Setting this
     *                                      value to `uint(-1)` will use the user's full balance.
     * @param  _minOutputAmountWei          The minimum output amount expected to be received by the user.
     * @param  _tradersPath                 The path of traders to use for each trade action. Length should be equal to
     *                                      `_marketIdsPath.length - 1`.
     * @param  _makerAccounts               The accounts that will be used for the maker side of the trades involving
     *                                      `TraderType.InternalLiquidity`.
     * @param  _userConfig                  The user configuration for the trade. Setting the `balanceCheckFlag` to
     *                                      `BalanceCheckFlag.From` will check that the user's `_borrowAccountNumber`
     *                                      and `_fromAccountNumber` is non-negative after the trade.
     */
    function addCollateralAndSwapExactInputForOutput(
        uint256 _fromAccountNumber,
        uint256 _borrowAccountNumber,
        uint256[] calldata _marketIdsPath,
        uint256 _inputAmountWei,
        uint256 _minOutputAmountWei,
        IGenericTraderBase.TraderParam[] calldata _tradersPath,
        IDolomiteStructs.AccountInfo[] calldata _makerAccounts,
        IGenericTraderProxyV1.UserConfig calldata _userConfig
    )
    external payable;

    /**
     * @dev     End-user function for removing collateral from the vault (in the case where `_marketIdsPath[last]` is
     *          the underlying marketId) or the vault owner (in the case where `_marketIdsPath[last]` is not the
     *          underlying marketId). Reverts if `_borrowAccountNumber` is 0 or if `_toAccountNumber` is not 0 (and
     *          the `_marketIdsPath[0]` is the underlying). Reverts if the user has a negative balance before the swap
     *          for `_marketIdsPath[last]`.
     *
     * @param  _toAccountNumber             The account number to receive the collateral transfer after the trade.
     * @param  _borrowAccountNumber         The account number to use for the vault's trade.
     * @param  _marketIdsPath               The path of market IDs to use for each trade action. Length should be equal
     *                                      to `_tradersPath.length + 1`.
     * @param  _inputAmountWei              The input amount (in wei) to use for the initial trade action. Setting this
     *                                      value to `uint(-1)` will use the user's full balance.
     * @param  _minOutputAmountWei          The minimum output amount expected to be received by the user.
     * @param  _tradersPath                 The path of traders to use for each trade action. Length should be equal to
     *                                      `_marketIdsPath.length - 1`.
     * @param  _makerAccounts               The accounts that will be used for the maker side of the trades involving
     *                                      `TraderType.InternalLiquidity`.
     * @param  _userConfig                  The user configuration for the trade. Setting the `balanceCheckFlag` to
     *                                      `BalanceCheckFlag.From` will check that the user's `_tradeAccountNumber`
     *                                      is non-negative after the trade. Setting the `balanceCheckFlag` to
     *                                      `BalanceCheckFlag.To` has no effect.
     */
    function swapExactInputForOutputAndRemoveCollateral(
        uint256 _toAccountNumber,
        uint256 _borrowAccountNumber,
        uint256[] calldata _marketIdsPath,
        uint256 _inputAmountWei,
        uint256 _minOutputAmountWei,
        IGenericTraderBase.TraderParam[] calldata _tradersPath,
        IDolomiteStructs.AccountInfo[] calldata _makerAccounts,
        IGenericTraderProxyV1.UserConfig calldata _userConfig
    )
    external payable;

    /**
     * @dev     End-user function for swapping an exact amount of input for a minimum amount of output. Reverts if
     *          `_tradeAccountNumber` is 0.
     *
     * @param  _tradeAccountNumber          The account number to use for the vault's trade. Cannot be 0.
     * @param  _marketIdsPath               The path of market IDs to use for each trade action. Length should be equal
     *                                      to `_tradersPath.length + 1`.
     * @param  _inputAmountWei              The input amount (in wei) to use for the initial trade action. Setting this
     *                                      value to `uint(-1)` will use the user's full balance.
     * @param  _minOutputAmountWei          The minimum output amount expected to be received by the user.
     * @param  _tradersPath                 The path of traders to use for each trade action. Length should be equal to
     *                                      `_marketIdsPath.length - 1`.
     * @param  _makerAccounts               The accounts that will be used for the maker side of the trades involving
     *                                      `TraderType.InternalLiquidity`.
     * @param  _userConfig                  The user configuration for the trade. Setting the `balanceCheckFlag` to
     *                                      `BalanceCheckFlag.From` will check that the user's `_tradeAccountNumber`
     *                                      is non-negative after the trade. Setting the `balanceCheckFlag` to
     *                                      `BalanceCheckFlag.To` has no effect.
     */
    function swapExactInputForOutput(
        uint256 _tradeAccountNumber,
        uint256[] calldata _marketIdsPath,
        uint256 _inputAmountWei,
        uint256 _minOutputAmountWei,
        IGenericTraderBase.TraderParam[] calldata _tradersPath,
        IDolomiteStructs.AccountInfo[] calldata _makerAccounts,
        IGenericTraderProxyV1.UserConfig calldata _userConfig
    )
    external payable;

    // ==================== Does not modify balances ====================

    /**
     * @notice  Attempts to deposit assets into this vault from the vault's owner. Reverts if the caller is not the
     *          Vault Factory.
     *
     * @param  _from    The sender of the tokens into this vault.
     * @param  _amount  The amount of the vault's underlying token to transfer.
     */
    function executeDepositIntoVault(address _from, uint256 _amount) external;

    /**
     * @notice  Attempts to withdraw assets from this vault to the recipient. Reverts if the caller is not the
     *          Vault Factory.
     *
     * @param  _recipient   The address to receive the withdrawal.
     * @param  _amount      The amount of the vault's underlying token to transfer out.
     */
    function executeWithdrawalFromVault(address _recipient, uint256 _amount) external;

    /**
     * @return The amount of `UNDERLYING_TOKEN` that are currently in this vault.
     */
    function underlyingBalanceOf() external view returns (uint256);

    /**
     * @return The registry used to discover important addresses for Dolomite
     */
    function dolomiteRegistry() external view returns (IDolomiteRegistry);

    function marketId() external view returns (uint256);

    function BORROW_POSITION_PROXY() external view returns (IBorrowPositionProxyV2);

    function DOLOMITE_MARGIN() external view returns (IDolomiteMargin);

    function VAULT_FACTORY() external view returns (address);

    function OWNER() external view returns (address);
}

// SPDX-License-Identifier: GPL-3.0-or-later
/*

    Copyright 2023 Dolomite

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

pragma solidity ^0.8.9;

import { IDolomiteMargin } from "../../protocol/interfaces/IDolomiteMargin.sol";
import { IDolomiteMarginExchangeWrapper } from "../../protocol/interfaces/IDolomiteMarginExchangeWrapper.sol";


/**
 * @title   IIsolationModeUnwrapperTraderV2
 * @author  Dolomite
 *
 * V2 Interface for a contract that can convert an isolation mode token into an underlying component token.
 */
interface IIsolationModeUnwrapperTraderV2 is IDolomiteMarginExchangeWrapper {

    struct CreateActionsForUnwrappingParams {
        /// @dev    The index of the account (according the Accounts[] array) that is performing the sell.
        uint256 primaryAccountId;
        /// @dev    The index of the account (according the Accounts[] array) that is being liquidated. This is set to
        ///         `_primaryAccountId` if a liquidation is not occurring.
        uint256 otherAccountId;
        /// @dev    The address of the owner of the account that is performing the sell.
        address primaryAccountOwner;
        /// @dev    The account number of the owner of the account that is performing the sell.
        uint256 primaryAccountNumber;
        /// @dev    The address of the owner of the account that is being liquidated. This is set to
        ///         `_primaryAccountOwner` if a liquidation is not occurring.
        address otherAccountOwner;
        /// @dev    The account number of the owner of the account that is being liquidated. This is set to
        ///         `_primaryAccountNumber` if a liquidation is not occurring.
        uint256 otherAccountNumber;
        /// @dev    The market that is being outputted by the unwrapping.
        uint256 outputMarket;
        /// @dev    The market that is being unwrapped, should be equal to `token()`.
        uint256 inputMarket;
        /// @dev    The min amount of `_outputMarket` that must be outputted by the unwrapping.
        uint256 minOutputAmount;
        /// @dev    The amount of the `_inputMarket` that the _primaryAccountId must sell.
        uint256 inputAmount;
        /// @dev    The calldata to pass through to any external sales that occur.
        bytes orderData;
    }

    /**
     * @return The isolation mode token that this contract can unwrap (the input token).
     */
    function token() external view returns (address);

    /**
     * @return True if the `_outputToken` is a valid output token for this contract, to be unwrapped by `token()`.
     */
    function isValidOutputToken(address _outputToken) external view returns (bool);

    /**
     * @notice  Creates the necessary actions for selling the `_inputMarket` into `_outputMarket`. Note, the
     *          `_inputMarket` should be equal to `token()` and `_outputMarket` should be validated to be a correct
     *           market that can be transformed into `token()`.
     *
     * @param  _params  The parameters for creating the actions for unwrapping.
     * @return          The actions that will be executed to unwrap the `_inputMarket` into `_outputMarket`.
     */
    function createActionsForUnwrapping(
        CreateActionsForUnwrappingParams calldata _params
    )
        external
        view
        returns (IDolomiteMargin.ActionArgs[] memory);

    /**
     * @return  The number of actions used to unwrap the isolation mode token.
     */
    function actionsLength() external view returns (uint256);
}

// SPDX-License-Identifier: GPL-3.0-or-later
/*

    Copyright 2023 Dolomite

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

pragma solidity ^0.8.9;


/**
 * @title   IIsolationModeUpgradeableProxy
 * @author  Dolomite
 *
 * @notice  The interface for the upgradeable proxy contract that holds each user's tokens that are wrapped by the
 *          IsolationModeVaultFactory.
 */
interface IIsolationModeUpgradeableProxy {

    /**
     *
     * @param  _account The owner of this vault contract
     */
    function initialize(address _account) external;

    function isInitialized() external view returns (bool);

    function implementation() external view returns (address);

    function vaultFactory() external view returns (address);

    function owner() external view returns (address);
}

// SPDX-License-Identifier: GPL-3.0-or-later
/*

    Copyright 2023 Dolomite

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

pragma solidity ^0.8.9;

import { IBorrowPositionProxyV2 } from "../../interfaces/IBorrowPositionProxyV2.sol";
import { IOnlyDolomiteMargin } from "../../interfaces/IOnlyDolomiteMargin.sol";


/**
 * @title   IIsolationModeVaultFactory
 * @author  Dolomite
 *
 * @notice A wrapper contract around a certain token to offer isolation mode features for DolomiteMargin.
 */
interface IIsolationModeVaultFactory is IOnlyDolomiteMargin {

    // =================================================
    // ==================== Structs ====================
    // =================================================

    struct QueuedTransfer {
        address from;
        address to;
        uint256 amount;
        address vault;
        bool isExecuted;
    }

    // ================================================
    // ==================== Events ====================
    // ================================================

    event UserVaultImplementationSet(
        address indexed previousUserVaultImplementation,
        address indexed newUserVaultImplementation
    );

    event TokenConverterSet(address indexed tokenConverter, bool isTrusted);

    event VaultCreated(address indexed account, address vault);

    event Initialized();

    event TransferQueued(
        uint256 indexed transferCursor,
        address from,
        address to,
        uint256 amountWei,
        address vault
    );

    // ======================================================
    // ================== Admin Functions ===================
    // ======================================================

    /**
     * @notice  Initializes this contract's variables that are dependent on this token being added to DolomiteMargin.
     */
    function ownerInitialize(address[] calldata _tokenConverters) external;

    /**
     *
     * @param  _userVaultImplementation  The address of the new vault implementation contract
     */
    function ownerSetUserVaultImplementation(address _userVaultImplementation) external;

    /**
     * @notice  A token converter is used to convert this underlying token into a Dolomite-compatible one for deposit
     *          or withdrawal
     *
     * @param  _tokenConverter   The address of the token converter contract to set whether or not it's trusted for
     *                          executing transfers to/from vaults
     * @param  _isTrusted        True if the token converter is trusted, false otherwise
     */
    function ownerSetIsTokenConverterTrusted(address _tokenConverter, bool _isTrusted) external;

    // ======================================================
    // ================== User Functions ===================
    // ======================================================

    /**
     * @notice  Creates the vault for `_account`
     *
     * @param  _account  The account owner to create the vault for
     */
    function createVault(address _account) external returns (address);

    /**
     * @notice  Creates the vault for `msg.sender`
     *
     * @param  _toAccountNumber  The account number of the account to which the tokens will be deposited
     * @param  _amountWei        The amount of tokens to deposit
     */
    function createVaultAndDepositIntoDolomiteMargin(
        uint256 _toAccountNumber,
        uint256 _amountWei
    ) external returns (address);

    /**
     * @notice  Deposits a token into the vault owner's account at `_toAccountNumber`. This function can only be called
     *          by a user's vault contract. Reverts if `_marketId` is set to the market ID of this vault.
     *
     * @param  _toAccountNumber  The account number of the account to which the tokens will be deposited
     * @param  _marketId         The market ID of the token to deposit
     * @param  _amountWei        The amount of tokens to deposit
     */
    function depositOtherTokenIntoDolomiteMarginForVaultOwner(
        uint256 _toAccountNumber,
        uint256 _marketId,
        uint256 _amountWei
    )
    external;

    /**
     * @notice  Enqueues a transfer into Dolomite Margin from the vault. Assumes msg.sender is a trusted token
     *          converter, else reverts. Reverts if `_vault` is not a valid vault contract.
     *
     * @param  _vault        The address of the vault that the token converter is interacting with
     * @param  _amountWei    The amount of tokens to transfer into Dolomite Margin
     */
    function enqueueTransferIntoDolomiteMargin(
        address _vault,
        uint256 _amountWei
    )
    external;

    /**
     * @notice  Enqueues a transfer from Dolomite Margin to the token converter. Assumes msg.sender is a trusted token
     *          converter, else reverts. Reverts if `_vault` is not a valid vault contract.
     *
     * @param  _vault        The address of the vault that the token converter is interacting with
     * @param  _amountWei    The amount of tokens to transfer from Dolomite Margin to the token converter
     */
    function enqueueTransferFromDolomiteMargin(
        address _vault,
        uint256 _amountWei
    )
    external;

    /**
     * @notice  This function should only be called by a user's vault contract
     *
     * @param  _toAccountNumber  The account number of the account to which the tokens will be deposited
     * @param  _amountWei        The amount of tokens to deposit
     */
    function depositIntoDolomiteMargin(
        uint256 _toAccountNumber,
        uint256 _amountWei
    )
    external;

    /**
     * @notice  This function should only be called by a user's vault contract
     *
     * @param  _fromAccountNumber    The account number of the account from which the tokens will be withdrawn
     * @param  _amountWei            The amount of tokens to withdraw
     */
    function withdrawFromDolomiteMargin(
        uint256 _fromAccountNumber,
        uint256 _amountWei
    )
    external;

    // ============================================
    // ================= Constants ================
    // ============================================

    /**
     * @return The address of the token that this vault wraps around
     */
    function UNDERLYING_TOKEN() external view returns (address);

    /**
     * @return  The address of the BorrowPositionProxyV2 contract
     */
    function BORROW_POSITION_PROXY() external view returns (IBorrowPositionProxyV2);

    // =================================================
    // ================= View Functions ================
    // =================================================

    /**
     * @return  The market ID of this token contract according to DolomiteMargin. This value is initializes in the
     *          #initialize function
     */
    function marketId() external view returns (uint256);

    /**
     * @return  This function should always return `true`. It's used by The Graph to index this contract as a Wrapper.
     */
    function isIsolationAsset() external view returns (bool);

    /**
     * @return  Returns the current transfer cursor
     */
    function transferCursor() external view returns (uint256);

    /**
     *
     * @param  _transferCursor   The cursor used to key into the mapping of queued transfers
     * @return The transfer enqueued in the mapping at the cursor's position
     */
    function getQueuedTransferByCursor(uint256 _transferCursor) external view returns (QueuedTransfer memory);

    /**
     * @return  The market IDs of the assets that can be borrowed in a position with this wrapped asset. An empty array
     *          indicates that any non-isolation mode asset can be borrowed against it.
     */
    function allowableDebtMarketIds() external view returns (uint256[] memory);

    /**
     * @return  The market IDs of the assets that can be used as collateral in a position with this wrapped asset. An
     *          empty array indicates that any non-isolation mode asset can be borrowed against it. To indicate that no
     *          assets can be used as collateral, return an array with a single element containing #marketId().
     */
    function allowableCollateralMarketIds() external view returns (uint256[] memory);

    /**
     * @return  The address of the current vault implementation contract
     */
    function userVaultImplementation() external view returns (address);

    /**
     *
     * @param  _account  The account owner to get the vault for
     * @return  _vault   The address of the vault created for `_account`. Returns address(0) if no vault has been
     *                   created yet for this account.
     */
    function getVaultByAccount(address _account) external view returns (address _vault);

    /**
     * @notice  Same as `getVaultByAccount`, but always returns the user's non-zero vault address.
     */
    function calculateVaultByAccount(address _account) external view returns (address _vault);

    /**
     *
     * @param  _vault    The vault that's used by an account for depositing/withdrawing
     * @return  _account The address of the account that owns the `_vault`
     */
    function getAccountByVault(address _vault) external view returns (address _account);

    /**
     * @notice  A token converter is used to convert this underlying token into a Dolomite-compatible one for deposit
     *          or withdrawal
     * @return  True if the token converter is currently in-use by this contract.
     */
    function isTokenConverterTrusted(address _tokenConverter) external view returns (bool);

    function getProxyVaultInitCodeHash() external pure returns (bytes32);
}

// SPDX-License-Identifier: GPL-3.0-or-later
/*

    Copyright 2023 Dolomite

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

pragma solidity ^0.8.9;

import { IDolomiteMargin } from "../../protocol/interfaces/IDolomiteMargin.sol";
import { IDolomiteMarginExchangeWrapper } from "../../protocol/interfaces/IDolomiteMarginExchangeWrapper.sol";


/**
 * @title   IIsolationModeWrapperTraderV2
 * @author  Dolomite
 *
 * Interface for a contract that can convert a token into an isolation mode token.
 */
interface IIsolationModeWrapperTraderV2 is IDolomiteMarginExchangeWrapper {

    struct CreateActionsForWrappingParams {
        /// @dev    The index of the account (according the Accounts[] array) that is performing the sell.
        uint256 primaryAccountId;
        /// @dev    The index of the account (according the Accounts[] array) that is being liquidated. This is set to
        ///         `_primaryAccountId` if a liquidation is not occurring.
        uint256 otherAccountId;
        /// @dev    The address of the owner of the account that is performing the sell.
        address primaryAccountOwner;
        /// @dev    The account number of the owner of the account that is performing the sell.
        uint256 primaryAccountNumber;
        /// @dev    The address of the owner of the account that is being liquidated. This is set to
        ///         `_primaryAccountOwner` if a liquidation is not occurring.
        address otherAccountOwner;
        /// @dev    The account number of the owner of the account that is being liquidated. This is set to
        ///         `_primaryAccountNumber` if a liquidation is not occurring.
        uint256 otherAccountNumber;
        /// @dev    The market that is being outputted by the wrapping, should be equal to `token().
        uint256 outputMarket;
        /// @dev    The market that is being used to wrap into `token()`.
        uint256 inputMarket;
        /// @dev    The min amount of `_outputMarket` that must be outputted by the wrapping.
        uint256 minOutputAmount;
        /// @dev    The amount of the `_inputMarket` that the _primaryAccountId must sell.
        uint256 inputAmount;
        /// @dev    The calldata to pass through to any external sales that occur.
        bytes orderData;
    }

    /**
     * @return The isolation mode token that this contract can wrap (the output token)
     */
    function token() external view returns (address);

    /**
     * @return True if the `_inputToken` is a valid input token for this contract, to be wrapped into `token()`
     */
    function isValidInputToken(address _inputToken) external view returns (bool);

    /**
     * @notice  Creates the necessary actions for selling the `_inputMarket` into `_outputMarket`. Note, the
     *          `_outputMarket` should be equal to `token()` and `_inputMarket` should be validated to be a correct
     *           market that can be transformed into `token()`.
     *
     * @param  _params  The parameters for creating the actions for wrapping.
     * @return          The actions that will be executed to unwrap the `_inputMarket` into `_outputMarket`.
     */
    function createActionsForWrapping(
        CreateActionsForWrappingParams calldata _params
    )
        external
        view
        returns (IDolomiteMargin.ActionArgs[] memory);

    /**
     * @return  The number of Actions used to wrap a valid input token into the this wrapper's Isolation Mode token.
     */
    function actionsLength() external pure returns (uint256);
}

// SPDX-License-Identifier: GPL-3.0-or-later
/*

    Copyright 2023 Dolomite

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

pragma solidity ^0.8.9;

import { IIsolationModeUnwrapperTraderV2 } from "./IIsolationModeUnwrapperTraderV2.sol";
import { IIsolationModeVaultFactory } from "./IIsolationModeVaultFactory.sol";
import { IOnlyDolomiteMargin } from "../../interfaces/IOnlyDolomiteMargin.sol";


/**
 * @title   IUpgradeableAsyncIsolationModeUnwrapperTrader
 * @author  Dolomite
 *
 * Interface for an upgradeable contract that can convert an isolation mode token into another token.
 */
interface IUpgradeableAsyncIsolationModeUnwrapperTrader is IIsolationModeUnwrapperTraderV2, IOnlyDolomiteMargin {

    // ================================================
    // ==================== Structs ===================
    // ================================================

    struct WithdrawalInfo {
        bytes32 key;
        address vault;
        uint256 accountNumber;
        /// @dev The amount of FACTORY tokens that is being sold
        uint256 inputAmount;
        address outputToken;
        /// @dev initially 0 until the withdrawal is executed
        uint256 outputAmount;
        bool isRetryable;
        bool isLiquidation;
        bytes extraData;
    }

    struct State {
        uint256 actionsLength;
        uint256 reentrancyGuard;
        address vaultFactory;
        address handlerRegistry;
        mapping(bytes32 => WithdrawalInfo) withdrawalInfo;
    }

    // ================================================
    // ===================== Enums ====================
    // ================================================

    enum TradeType {
        FromWithdrawal,
        FromDeposit,
        NoOp
    }

    // ===================================================
    // ==================== Functions ====================
    // ===================================================

    function executeWithdrawalForRetry(bytes32 _key) external;

    function executeWithdrawalCancellation(bytes32 _key) external;

    function emitWithdrawalExecuted(bytes32 _key) external;

    /**
     * Notifies the unwrapper that it'll be entered for a trade from the unwrapper. This allows it to modify the action
     * length
     */
    function handleCallbackFromWrapperBefore() external;

    /**
     * Reverts any changes made in `handleCallbackFromWrapperBefore`. Can only be called by a corresponding Wrapper
     * trader.
     */
    function handleCallbackFromWrapperAfter() external;

    /**
     * Transfers underlying tokens from the vault (msg.sender) to this contract to initiate a redemption.
     */
    function vaultInitiateUnwrapping(
        uint256 _tradeAccountNumber,
        uint256 _inputAmount,
        address _outputToken,
        uint256 _minOutputAmount,
        bool _isLiquidation,
        bytes calldata _extraData
    ) external payable;

    /**
     *
     * @param  _key The key of the withdrawal that should be cancelled
     */
    function initiateCancelWithdrawal(bytes32 _key) external;

    function getWithdrawalInfo(bytes32 _key) external view returns (WithdrawalInfo memory);

    function VAULT_FACTORY() external view returns (IIsolationModeVaultFactory);
}

// SPDX-License-Identifier: GPL-3.0-or-later
/*

    Copyright 2023 Dolomite

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

pragma solidity ^0.8.9;

import { IIsolationModeVaultFactory } from "./IIsolationModeVaultFactory.sol";
import { IIsolationModeWrapperTraderV2 } from "./IIsolationModeWrapperTraderV2.sol";
import { IOnlyDolomiteMargin } from "../../interfaces/IOnlyDolomiteMargin.sol";


/**
 * @title   IUpgradeableAsyncIsolationModeWrapperTrader
 * @author  Dolomite
 *
 * Interface for an upgradeable contract that can convert a token into an isolation mode token.
 */
interface IUpgradeableAsyncIsolationModeWrapperTrader is IIsolationModeWrapperTraderV2, IOnlyDolomiteMargin {

    // ================================================
    // ==================== Structs ===================
    // ================================================

    struct State {
        mapping(bytes32 => DepositInfo) depositInfo;
        address vaultFactory;
        address handlerRegistry;
    }

    struct DepositInfo {
        bytes32 key;
        address vault;
        uint256 accountNumber;
        address inputToken;
        uint256 inputAmount;
        uint256 outputAmount;
        bool isRetryable;
    }

    // ===================================================
    // ==================== Functions ====================
    // ===================================================

    /**
     * This should be called by the vault to initiate a cancellation for a deposit.
     *
     * @param  _key The key of the deposit that should be cancelled
     */
    function initiateCancelDeposit(bytes32 _key) external;

    function setDepositInfoAndReducePendingAmountFromUnwrapper(
        bytes32 _key,
        uint256 _outputAmountDeltaWei,
        DepositInfo calldata _depositInfo
    ) external;

    function emitDepositCancelled(bytes32 _key) external;

    function getDepositInfo(bytes32 _key) external view returns (DepositInfo memory);

    function VAULT_FACTORY() external view returns (IIsolationModeVaultFactory);
}

// SPDX-License-Identifier: GPL-3.0-or-later
/*

    Copyright 2023 Dolomite

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

pragma solidity ^0.8.9;

import { ProxyContractHelpers } from "../helpers/ProxyContractHelpers.sol";
import { Require } from "../protocol/lib/Require.sol";
import { IIsolationModeTokenVaultV1 } from "./interfaces/IIsolationModeTokenVaultV1.sol";
import { IIsolationModeUpgradeableProxy } from "./interfaces/IIsolationModeUpgradeableProxy.sol";
import { IIsolationModeVaultFactory } from "./interfaces/IIsolationModeVaultFactory.sol";


/**
 * @title   IsolationModeUpgradeableProxy
 * @author  Dolomite
 *
 * @notice  Abstract "implementation" (for an upgradeable proxy) contract for wrapping tokens via a per-user vault that
 *          can be used with DolomiteMargin
 */
contract IsolationModeUpgradeableProxy is
    IIsolationModeUpgradeableProxy,
    ProxyContractHelpers
{

    // ============ Constants ============

    bytes32 private constant _FILE = "IsolationModeUpgradeableProxy";
    bytes32 private constant _IS_INITIALIZED_SLOT = bytes32(uint256(keccak256("eip1967.proxy.isInitialized")) - 1);
    bytes32 private constant _VAULT_FACTORY_SLOT = bytes32(uint256(keccak256("eip1967.proxy.vaultFactory")) - 1);
    bytes32 private constant _OWNER_SLOT = bytes32(uint256(keccak256("eip1967.proxy.owner")) - 1);

    // ======== Modifiers =========

    modifier requireIsInitialized() {
        Require.that(
            isInitialized(),
            _FILE,
            "Not initialized"
        );
        _;
    }

    // ============ Constructor ============

    constructor() {
        _setAddress(_VAULT_FACTORY_SLOT, msg.sender);
    }

    // ============ Functions ============

    receive() external payable {} // solhint-disable-line no-empty-blocks

    // solhint-disable-next-line payable-fallback
    fallback() external payable requireIsInitialized {
        _callImplementation(implementation());
    }

    function initialize(
        address _account
    ) external {
        Require.that(
            !isInitialized(),
            _FILE,
            "Already initialized"
        );
        Require.that(
            IIsolationModeVaultFactory(vaultFactory()).getVaultByAccount(_account) == address(this),
            _FILE,
            "Invalid account",
            _account
        );
        _setAddress(_OWNER_SLOT, _account);
        _safeDelegateCall(implementation(), abi.encodePacked(IIsolationModeTokenVaultV1.initialize.selector));
        _setUint256(_IS_INITIALIZED_SLOT, 1);
    }

    function implementation() public override view returns (address) {
        return IIsolationModeVaultFactory(vaultFactory()).userVaultImplementation();
    }

    function isInitialized() public override view returns (bool) {
        return _getUint256(_IS_INITIALIZED_SLOT) == 1;
    }

    function vaultFactory() public override view returns (address) {
        return _getAddress(_VAULT_FACTORY_SLOT);
    }

    function owner() public override view returns (address) {
        return _getAddress(_OWNER_SLOT);
    }

    function _safeDelegateCall(address _target, bytes memory _calldata) internal returns (bytes memory) {
        // solhint-disable-next-line avoid-low-level-calls
        (bool isSuccessful, bytes memory result) = _target.delegatecall(_calldata);
        assert(isSuccessful);

        return result;
    }
}

// SPDX-License-Identifier: GPL-3.0-or-later
/*

    Copyright 2023 Dolomite

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

pragma solidity ^0.8.9;

import { AccountBalanceLib } from "./AccountBalanceLib.sol";
import { ChainHelperLib } from "./ChainHelperLib.sol";
import { IExpiry } from "../interfaces/IExpiry.sol";
import { IDolomiteMargin } from "../protocol/interfaces/IDolomiteMargin.sol";
import { IDolomiteStructs } from "../protocol/interfaces/IDolomiteStructs.sol";
import { Require } from "../protocol/lib/Require.sol";


/**
 * @title   AccountActionLib
 * @author  Dolomite
 *
 * @notice  Library contract that makes specific actions easy to call
 */
library AccountActionLib {

    // ============ Constants ============

    bytes32 private constant _FILE = "AccountActionLib";

    uint256 private constant _ALL = type(uint256).max;

    // ===================================================================
    // ========================= Write Functions =========================
    // ===================================================================

    function deposit(
        IDolomiteMargin _dolomiteMargin,
        address _accountOwner,
        address _fromAccount,
        uint256 _toAccountNumber,
        uint256 _marketId,
        IDolomiteMargin.AssetAmount memory _amount
    ) internal {
        IDolomiteStructs.AccountInfo[] memory accounts = new IDolomiteStructs.AccountInfo[](1);
        accounts[0] = IDolomiteStructs.AccountInfo({
            owner: _accountOwner,
            number: _toAccountNumber
        });

        IDolomiteStructs.ActionArgs[] memory actions = new IDolomiteStructs.ActionArgs[](1);
        actions[0] = encodeDepositAction(
            /* _accountId = */ 0,
            _marketId,
            _amount,
            _fromAccount
        );

        _dolomiteMargin.operate(accounts, actions);
    }

    /**
     *  Withdraws `_marketId` from `_fromAccount` to `_toAccount`
     */
    function withdraw(
        IDolomiteMargin _dolomiteMargin,
        address _accountOwner,
        uint256 _fromAccountNumber,
        address _toAccount,
        uint256 _marketId,
        IDolomiteStructs.AssetAmount memory _amount,
        AccountBalanceLib.BalanceCheckFlag _balanceCheckFlag
    ) internal {
        IDolomiteStructs.AccountInfo[] memory accounts = new IDolomiteStructs.AccountInfo[](1);
        accounts[0] = IDolomiteStructs.AccountInfo({
            owner: _accountOwner,
            number: _fromAccountNumber
        });

        IDolomiteStructs.ActionArgs[] memory actions = new IDolomiteStructs.ActionArgs[](1);
        actions[0] = encodeWithdrawalAction(
            /* _accountId = */ 0,
            _marketId,
            _amount,
            _toAccount
        );

        _dolomiteMargin.operate(accounts, actions);

        if (
            _balanceCheckFlag == AccountBalanceLib.BalanceCheckFlag.Both
            || _balanceCheckFlag == AccountBalanceLib.BalanceCheckFlag.From
        ) {
            AccountBalanceLib.verifyBalanceIsNonNegative(
                _dolomiteMargin,
                accounts[0].owner,
                _fromAccountNumber,
                _marketId
            );
        }
    }

    /**
     * Transfers `_marketId` from `_fromAccount` to `_toAccount`
     */
    function transfer(
        IDolomiteMargin _dolomiteMargin,
        address _fromAccountOwner,
        uint256 _fromAccountNumber,
        address _toAccountOwner,
        uint256 _toAccountNumber,
        uint256 _marketId,
        IDolomiteStructs.AssetDenomination _amountDenomination,
        uint256 _amount,
        AccountBalanceLib.BalanceCheckFlag _balanceCheckFlag
    ) internal {
        IDolomiteStructs.AccountInfo[] memory accounts = new IDolomiteStructs.AccountInfo[](2);
        accounts[0] = IDolomiteStructs.AccountInfo({
            owner: _fromAccountOwner,
            number: _fromAccountNumber
        });
        accounts[1] = IDolomiteStructs.AccountInfo({
            owner: _toAccountOwner,
            number: _toAccountNumber
        });

        IDolomiteStructs.ActionArgs[] memory actions = new IDolomiteStructs.ActionArgs[](1);
        actions[0] = encodeTransferAction(
            /* _fromAccountId = */ 0,
            /* _toAccountId = */ 1,
            _marketId,
            _amountDenomination,
            _amount
        );

        _dolomiteMargin.operate(accounts, actions);

        if (
            _balanceCheckFlag == AccountBalanceLib.BalanceCheckFlag.Both
            || _balanceCheckFlag == AccountBalanceLib.BalanceCheckFlag.From
        ) {
            AccountBalanceLib.verifyBalanceIsNonNegative(
                _dolomiteMargin,
                _fromAccountOwner,
                _fromAccountNumber,
                _marketId
            );
        }

        if (
            _balanceCheckFlag == AccountBalanceLib.BalanceCheckFlag.Both
            || _balanceCheckFlag == AccountBalanceLib.BalanceCheckFlag.To
        ) {
            AccountBalanceLib.verifyBalanceIsNonNegative(
                _dolomiteMargin,
                _toAccountOwner,
                _toAccountNumber,
                _marketId
            );
        }
    }

    // ===============================================================
    // ========================= Pure Functions ======================
    // ===============================================================

    function all() internal pure returns (uint256) {
        return _ALL;
    }

    function encodeCallAction(
        uint256 _accountId,
        address _callee,
        bytes memory _callData
    ) internal pure returns (IDolomiteStructs.ActionArgs memory) {
        return IDolomiteStructs.ActionArgs({
            actionType : IDolomiteStructs.ActionType.Call,
            accountId : _accountId,
            amount : IDolomiteStructs.AssetAmount({
                sign: false,
                denomination: IDolomiteStructs.AssetDenomination.Wei,
                ref: IDolomiteStructs.AssetReference.Delta,
                value: 0
            }),
            primaryMarketId : 0,
            secondaryMarketId : 0,
            otherAddress : _callee,
            otherAccountId : 0,
            data : _callData
        });
    }

    function encodeDepositAction(
        uint256 _accountId,
        uint256 _marketId,
        IDolomiteStructs.AssetAmount memory _amount,
        address _fromAccount
    ) internal pure returns (IDolomiteStructs.ActionArgs memory) {
        return IDolomiteStructs.ActionArgs({
            actionType: IDolomiteStructs.ActionType.Deposit,
            accountId: _accountId,
            amount: _amount,
            primaryMarketId: _marketId,
            secondaryMarketId: 0,
            otherAddress: _fromAccount,
            otherAccountId: 0,
            data: bytes("")
        });
    }

    function encodeExpirationAction(
        IDolomiteStructs.AccountInfo memory _account,
        uint256 _accountId,
        uint256 _owedMarketId,
        address _expiry,
        uint256 _expiryTimeDelta
    ) internal pure returns (IDolomiteStructs.ActionArgs memory) {
        Require.that(
            _expiryTimeDelta == uint32(_expiryTimeDelta),
            _FILE,
            "Invalid expiry time delta"
        );

        IExpiry.SetExpiryArg[] memory expiryArgs = new IExpiry.SetExpiryArg[](1);
        expiryArgs[0] = IExpiry.SetExpiryArg({
            account : _account,
            marketId : _owedMarketId,
            timeDelta : uint32(_expiryTimeDelta),
            forceUpdate : true
        });

        return encodeCallAction(
            _accountId,
            _expiry,
            abi.encode(IExpiry.CallFunctionType.SetExpiry, expiryArgs)
        );
    }

    function encodeExpiryLiquidateAction(
        uint256 _solidAccountId,
        uint256 _liquidAccountId,
        uint256 _owedMarketId,
        uint256 _heldMarketId,
        address _expiryProxy,
        uint32 _expiry,
        bool _flipMarkets
    ) internal pure returns (IDolomiteStructs.ActionArgs memory) {
        return IDolomiteStructs.ActionArgs({
            actionType: IDolomiteStructs.ActionType.Trade,
            accountId: _solidAccountId,
            amount: IDolomiteStructs.AssetAmount({
                sign: false,
                denomination: IDolomiteStructs.AssetDenomination.Wei,
                ref: IDolomiteStructs.AssetReference.Target,
                value: 0
            }),
            primaryMarketId: !_flipMarkets ? _owedMarketId : _heldMarketId,
            secondaryMarketId: !_flipMarkets ? _heldMarketId : _owedMarketId,
            otherAddress: _expiryProxy,
            otherAccountId: _liquidAccountId,
            data: abi.encode(_owedMarketId, _expiry)
        });
    }

    function encodeLiquidateAction(
        uint256 _solidAccountId,
        uint256 _liquidAccountId,
        uint256 _owedMarketId,
        uint256 _heldMarketId,
        uint256 _owedWeiToLiquidate
    ) internal pure returns (IDolomiteStructs.ActionArgs memory) {
        return IDolomiteStructs.ActionArgs({
            actionType: IDolomiteStructs.ActionType.Liquidate,
            accountId: _solidAccountId,
            amount: IDolomiteStructs.AssetAmount({
                sign: true,
                denomination: IDolomiteStructs.AssetDenomination.Wei,
                ref: IDolomiteStructs.AssetReference.Delta,
                value: _owedWeiToLiquidate
            }),
            primaryMarketId: _owedMarketId,
            secondaryMarketId: _heldMarketId,
            otherAddress: address(0),
            otherAccountId: _liquidAccountId,
            data: new bytes(0)
        });
    }

    function encodeExternalSellActionWithTarget(
        uint256 _fromAccountId,
        uint256 _primaryMarketId,
        uint256 _secondaryMarketId,
        address _trader,
        uint256 _targetAmountWei,
        uint256 _amountOutMinWei,
        bytes memory _orderData
    ) internal pure returns (IDolomiteStructs.ActionArgs memory) {
    IDolomiteStructs.AssetAmount memory assetAmount;
        assetAmount = IDolomiteStructs.AssetAmount({
            sign: true,
            denomination: IDolomiteStructs.AssetDenomination.Wei,
            ref: IDolomiteStructs.AssetReference.Target,
            value: _targetAmountWei
        });

        return IDolomiteStructs.ActionArgs({
            actionType : IDolomiteStructs.ActionType.Sell,
            accountId : _fromAccountId,
            amount : assetAmount,
            primaryMarketId : _primaryMarketId,
            secondaryMarketId : _secondaryMarketId,
            otherAddress : _trader,
            otherAccountId : 0,
            data : abi.encode(_amountOutMinWei, _orderData)
        });
    }

    function encodeExternalSellAction(
        uint256 _fromAccountId,
        uint256 _primaryMarketId,
        uint256 _secondaryMarketId,
        address _trader,
        uint256 _amountInWei,
        uint256 _amountOutMinWei,
        bytes memory _orderData
    ) internal pure returns (IDolomiteStructs.ActionArgs memory) {
        IDolomiteStructs.AssetAmount memory assetAmount;
        if (_amountInWei == _ALL) {
            assetAmount = IDolomiteStructs.AssetAmount({
                sign: false,
                denomination: IDolomiteStructs.AssetDenomination.Wei,
                ref: IDolomiteStructs.AssetReference.Target,
                value: 0
            });
        } else {
            assetAmount = IDolomiteStructs.AssetAmount({
                sign: false,
                denomination: IDolomiteStructs.AssetDenomination.Wei,
                ref: IDolomiteStructs.AssetReference.Delta,
                value: _amountInWei
            });
        }

        return IDolomiteStructs.ActionArgs({
            actionType : IDolomiteStructs.ActionType.Sell,
            accountId : _fromAccountId,
            amount : assetAmount,
            primaryMarketId : _primaryMarketId,
            secondaryMarketId : _secondaryMarketId,
            otherAddress : _trader,
            otherAccountId : 0,
            data : abi.encode(_amountOutMinWei, _orderData)
        });
    }

    function encodeInternalTradeAction(
        uint256 _fromAccountId,
        uint256 _toAccountId,
        uint256 _primaryMarketId,
        uint256 _secondaryMarketId,
        address _traderAddress,
        uint256 _amountInWei,
        uint256 _chainId,
        bool _calculateAmountWithMakerAccount,
        bytes memory _orderData
    ) internal pure returns (IDolomiteStructs.ActionArgs memory) {
        return IDolomiteStructs.ActionArgs({
            actionType: IDolomiteStructs.ActionType.Trade,
            accountId: _fromAccountId,
            amount: IDolomiteStructs.AssetAmount({
                sign: true,
                denomination: IDolomiteStructs.AssetDenomination.Wei,
                ref: IDolomiteStructs.AssetReference.Delta,
                value: _amountInWei
            }),
            primaryMarketId: _primaryMarketId,
            secondaryMarketId: _secondaryMarketId,
            otherAddress: _traderAddress,
            otherAccountId: _toAccountId,
            data: ChainHelperLib.isArbitrum(_chainId)
                ? _orderData
                : abi.encode(_calculateAmountWithMakerAccount, _orderData)
        });
    }

    function encodeTransferAction(
        uint256 _fromAccountId,
        uint256 _toAccountId,
        uint256 _marketId,
        IDolomiteStructs.AssetDenomination _amountDenomination,
        uint256 _amount
    ) internal pure returns (IDolomiteStructs.ActionArgs memory) {
        IDolomiteStructs.AssetAmount memory assetAmount;
        if (_amount == _ALL) {
            assetAmount = IDolomiteStructs.AssetAmount({
                sign: false,
                denomination: _amountDenomination,
                ref: IDolomiteStructs.AssetReference.Target,
                value: 0
            });
        } else {
            assetAmount = IDolomiteStructs.AssetAmount({
                sign: false,
                denomination: _amountDenomination,
                ref: IDolomiteStructs.AssetReference.Delta,
                value: _amount
            });
        }
        return IDolomiteStructs.ActionArgs({
            actionType : IDolomiteStructs.ActionType.Transfer,
            accountId : _fromAccountId,
            amount : assetAmount,
            primaryMarketId : _marketId,
            secondaryMarketId : 0,
            otherAddress : address(0),
            otherAccountId : _toAccountId,
            data : bytes("")
        });
    }

    function encodeWithdrawalAction(
        uint256 _accountId,
        uint256 _marketId,
        IDolomiteStructs.AssetAmount memory _amount,
        address _toAccount
    ) internal pure returns (IDolomiteStructs.ActionArgs memory) {
        return IDolomiteStructs.ActionArgs({
            actionType: IDolomiteStructs.ActionType.Withdraw,
            accountId: _accountId,
            amount: _amount,
            primaryMarketId: _marketId,
            secondaryMarketId: 0,
            otherAddress: _toAccount,
            otherAccountId: 0,
            data: bytes("")
        });
    }
}

// SPDX-License-Identifier: GPL-3.0-or-later
/*

    Copyright 2023 Dolomite

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

pragma solidity ^0.8.9;

import { IDolomiteMargin } from "../protocol/interfaces/IDolomiteMargin.sol";
import { IDolomiteStructs } from "../protocol/interfaces/IDolomiteStructs.sol";

import { Require } from "../protocol/lib/Require.sol";
import { TypesLib } from "../protocol/lib/TypesLib.sol";


/**
 * @title   AccountBalanceLib
 * @author  Dolomite
 *
 * @notice  Library contract that checks a user's balance after transaction to be non-negative
 */
library AccountBalanceLib {
    using TypesLib for IDolomiteStructs.Par;

    // ============ Types ============

    /// Checks that either BOTH, FROM, or TO accounts all have non-negative balances
    enum BalanceCheckFlag {
        Both,
        From,
        To,
        None
    }

    // ============ Constants ============

    bytes32 private constant _FILE = "AccountBalanceLib";

    // ============ Functions ============

    /**
     *  Checks that the account's balance is non-negative. Reverts if the check fails
     */
    function verifyBalanceIsNonNegative(
        IDolomiteMargin dolomiteMargin,
        address _accountOwner,
        uint256 _accountNumber,
        uint256 _marketId
    ) internal view {
        IDolomiteStructs.AccountInfo memory account = IDolomiteStructs.AccountInfo({
            owner: _accountOwner,
            number: _accountNumber
        });
        IDolomiteStructs.Par memory par = dolomiteMargin.getAccountPar(account, _marketId);
        Require.that(
            par.isPositive() || par.isZero(),
            _FILE,
            "account cannot go negative",
            _accountOwner,
            _accountNumber,
            _marketId
        );
    }
}

// SPDX-License-Identifier: GPL-3.0-or-later
/*

    Copyright 2023 Dolomite

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

pragma solidity ^0.8.9;


/**
 * @title   ChainHelperLib
 * @author  Dolomite
 *
 * @notice  Library contract that discovers which chain we're on
 */
library ChainHelperLib {

    // ============ Constants ============

    bytes32 private constant _FILE = "ChainHelperLib";
    uint256 private constant _ARBITRUM_ONE = 42161;
    uint256 private constant _ARBITRUM_SEPOLIA = 421614;

    // ============ Functions ============

    function isArbitrum(uint256 chainId) internal pure returns (bool) {
        return chainId == _ARBITRUM_ONE || chainId == _ARBITRUM_SEPOLIA;
    }
}

File 31 of 51 : IDolomiteAccountRiskOverrideSetter.sol
// SPDX-License-Identifier: GPL-3.0-or-later
/*

    Copyright 2023 Dolomite.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

*/

pragma solidity ^0.8.9;

import { IDolomiteStructs } from "./IDolomiteStructs.sol";


/**
 * @title   IDolomiteAccountRiskOverrideSetter
 * @author  Dolomite
 *
 * @notice  Interface that can be implemented by any contract that needs to implement risk overrides for an account.
 */
interface IDolomiteAccountRiskOverrideSetter {

    /**
     * @notice  Gets the risk overrides for a given account owner.
     *
     * @param  _accountOwner               The owner of the account whose risk override should be retrieved.
     * @return  marginRatioOverride         The margin ratio override for this account.
     * @return  liquidationSpreadOverride   The liquidation spread override for this account.
     */
    function getAccountRiskOverride(
        address _accountOwner
    )
    external
    view
    returns
    (
        IDolomiteStructs.Decimal memory marginRatioOverride,
        IDolomiteStructs.Decimal memory liquidationSpreadOverride
    );
}

// SPDX-License-Identifier: GPL-3.0-or-later
/*

    Copyright 2023 Dolomite

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

pragma solidity ^0.8.9;


/**
 * @title   IDolomiteInterestSetter
 * @author  Dolomite
 *
 * @notice  This interface defines the functions that for an interest setter that can be used to determine the interest
 *          rate of a market.
 */
interface IDolomiteInterestSetter {

    // ============ Enum ============

    enum InterestSetterType {
        None,
        Linear,
        DoubleExponential,
        Other
    }

    // ============ Structs ============

    struct InterestRate {
        uint256 value;
    }

    // ============ Functions ============

    /**
     * Get the interest rate of a token given some borrowed and supplied amounts
     *
     * @param  token        The address of the ERC20 token for the market
     * @param  borrowWei    The total borrowed token amount for the market
     * @param  supplyWei    The total supplied token amount for the market
     * @return              The interest rate per second
     */
    function getInterestRate(
        address token,
        uint256 borrowWei,
        uint256 supplyWei
    )
    external
    view
    returns (InterestRate memory);

    function interestSetterType() external pure returns (InterestSetterType);
}

File 33 of 51 : IDolomiteMargin.sol
// SPDX-License-Identifier: GPL-3.0-or-later
/*

    Copyright 2023 Dolomite

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

pragma solidity ^0.8.9;

import { IDolomiteInterestSetter } from "./IDolomiteInterestSetter.sol";
import { IDolomiteMarginAdmin } from "./IDolomiteMarginAdmin.sol";
import { IDolomitePriceOracle } from "./IDolomitePriceOracle.sol";


/**
 * @title   IDolomiteMargin
 * @author  Dolomite
 *
 * @notice  The interface for interacting with the main entry-point to DolomiteMargin
 */
interface IDolomiteMargin is IDolomiteMarginAdmin {

    // ==================================================
    // ================= Write Functions ================
    // ==================================================

    /**
     * The main entry-point to DolomiteMargin that allows users and contracts to manage accounts.
     * Take one or more actions on one or more accounts. The msg.sender must be the owner or
     * operator of all accounts except for those being liquidated, vaporized, or traded with.
     * One call to operate() is considered a singular "operation". Account collateralization is
     * ensured only after the completion of the entire operation.
     *
     * @param  accounts  A list of all accounts that will be used in this operation. Cannot contain
     *                   duplicates. In each action, the relevant account will be referred-to by its
     *                   index in the list.
     * @param  actions   An ordered list of all actions that will be taken in this operation. The
     *                   actions will be processed in order.
     */
    function operate(
        AccountInfo[] calldata accounts,
        ActionArgs[] calldata actions
    ) external;

    /**
     * Approves/disapproves any number of operators. An operator is an external address that has the
     * same permissions to manipulate an account as the owner of the account. Operators are simply
     * addresses and therefore may either be externally-owned Ethereum accounts OR smart contracts.
     *
     * Operators are also able to act as AutoTrader contracts on behalf of the account owner if the
     * operator is a smart contract and implements the IAutoTrader interface.
     *
     * @param  args  A list of OperatorArgs which have an address and a boolean. The boolean value
     *               denotes whether to approve (true) or revoke approval (false) for that address.
     */
    function setOperators(
        OperatorArg[] calldata args
    ) external;

    // ==================================================
    // ================= Read Functions ================
    // ==================================================

    // ============ Getters for Markets ============

    /**
     * Get the ERC20 token address for a market.
     *
     * @param  token    The token to query
     * @return          The token's marketId if the token is valid
     */
    function getMarketIdByTokenAddress(
        address token
    ) external view returns (uint256);

    /**
     * Get the ERC20 token address for a market.
     *
     * @param  marketId  The market to query
     * @return           The token address
     */
    function getMarketTokenAddress(
        uint256 marketId
    ) external view returns (address);

    /**
     * Return the maximum amount of the market that can be supplied on Dolomite. Always 0 or positive.
     *
     * @param  marketId  The market to query
     * @return           The max amount of the market that can be supplied
     */
    function getMarketMaxWei(
        uint256 marketId
    ) external view returns (Wei memory);

    /**
     * Return true if a particular market is in closing mode. Additional borrows cannot be taken
     * from a market that is closing.
     *
     * @param  marketId  The market to query
     * @return           True if the market is closing
     */
    function getMarketIsClosing(
        uint256 marketId
    )
    external
    view
    returns (bool);

    /**
     * Get the price of the token for a market.
     *
     * @param  marketId  The market to query
     * @return           The price of each atomic unit of the token
     */
    function getMarketPrice(
        uint256 marketId
    ) external view returns (MonetaryPrice memory);

    /**
     * Get the total number of markets.
     *
     * @return  The number of markets
     */
    function getNumMarkets() external view returns (uint256);

    /**
     * Get the total principal amounts (borrowed and supplied) for a market.
     *
     * @param  marketId  The market to query
     * @return           The total principal amounts
     */
    function getMarketTotalPar(
        uint256 marketId
    ) external view returns (TotalPar memory);

    /**
     * Get the most recently cached interest index for a market.
     *
     * @param  marketId  The market to query
     * @return           The most recent index
     */
    function getMarketCachedIndex(
        uint256 marketId
    ) external view returns (InterestIndex memory);

    /**
     * Get the interest index for a market if it were to be updated right now.
     *
     * @param  marketId  The market to query
     * @return           The estimated current index
     */
    function getMarketCurrentIndex(
        uint256 marketId
    ) external view returns (InterestIndex memory);

    /**
     * Get the price oracle address for a market.
     *
     * @param  marketId  The market to query
     * @return           The price oracle address
     */
    function getMarketPriceOracle(
        uint256 marketId
    ) external view returns (IDolomitePriceOracle);

    /**
     * Get the interest-setter address for a market.
     *
     * @param  marketId  The market to query
     * @return           The interest-setter address
     */
    function getMarketInterestSetter(
        uint256 marketId
    ) external view returns (IDolomiteInterestSetter);

    /**
     * Get the margin premium for a market. A margin premium makes it so that any positions that
     * include the market require a higher collateralization to avoid being liquidated.
     *
     * @param  marketId  The market to query
     * @return           The market's margin premium
     */
    function getMarketMarginPremium(
        uint256 marketId
    ) external view returns (Decimal memory);

    /**
     * Get the spread premium for a market. A spread premium makes it so that any liquidations
     * that include the market have a higher spread than the global default.
     *
     * @param  marketId  The market to query
     * @return           The market's spread premium
     */
    function getMarketSpreadPremium(
        uint256 marketId
    ) external view returns (Decimal memory);

    /**
     * Return true if this market can be removed and its ID can be recycled and reused
     *
     * @param  marketId  The market to query
     * @return           True if the market is recyclable
     */
    function getMarketIsRecyclable(
        uint256 marketId
    ) external view returns (bool);

    /**
     * Gets the recyclable markets, up to `n` length. If `n` is greater than the length of the list, 0's are returned
     * for the empty slots.
     *
     * @param  n    The number of markets to get, bounded by the linked list being smaller than `n`
     * @return      The list of recyclable markets, in the same order held by the linked list
     */
    function getRecyclableMarkets(
        uint256 n
    ) external view returns (uint[] memory);

    /**
     * Get the current borrower interest rate for a market.
     *
     * @param  marketId  The market to query
     * @return           The current interest rate
     */
    function getMarketInterestRate(
        uint256 marketId
    ) external view returns (IDolomiteInterestSetter.InterestRate memory);

    /**
     * Get basic information about a particular market.
     *
     * @param  marketId  The market to query
     * @return           A Market struct with the current state of the market
     */
    function getMarket(
        uint256 marketId
    ) external view returns (Market memory);

    /**
     * Get comprehensive information about a particular market.
     *
     * @param  marketId  The market to query
     * @return           A tuple containing the values:
     *                    - A Market struct with the current state of the market
     *                    - The current estimated interest index
     *                    - The current token price
     *                    - The current market interest rate
     */
    function getMarketWithInfo(
        uint256 marketId
    )
    external
    view
    returns (
        Market memory,
        InterestIndex memory,
        MonetaryPrice memory,
        IDolomiteInterestSetter.InterestRate memory
    );

    /**
     * Get the number of excess tokens for a market. The number of excess tokens is calculated by taking the current
     * number of tokens held in DolomiteMargin, adding the number of tokens owed to DolomiteMargin by borrowers, and
     * subtracting the number of tokens owed to suppliers by DolomiteMargin.
     *
     * @param  marketId  The market to query
     * @return           The number of excess tokens
     */
    function getNumExcessTokens(
        uint256 marketId
    ) external view returns (Wei memory);

    // ============ Getters for Accounts ============

    /**
     * Get the principal value for a particular account and market.
     *
     * @param  account   The account to query
     * @param  marketId  The market to query
     * @return           The principal value
     */
    function getAccountPar(
        AccountInfo calldata account,
        uint256 marketId
    ) external view returns (Par memory);

    /**
     * Get the principal value for a particular account and market, with no check the market is valid. Meaning, markets
     * that don't exist return 0.
     *
     * @param  account   The account to query
     * @param  marketId  The market to query
     * @return           The principal value
     */
    function getAccountParNoMarketCheck(
        AccountInfo calldata account,
        uint256 marketId
    ) external view returns (Par memory);

    /**
     * Get the token balance for a particular account and market.
     *
     * @param  account   The account to query
     * @param  marketId  The market to query
     * @return           The token amount
     */
    function getAccountWei(
        AccountInfo calldata account,
        uint256 marketId
    ) external view returns (Wei memory);

    /**
     * Get the status of an account (Normal, Liquidating, or Vaporizing).
     *
     * @param  account  The account to query
     * @return          The account's status
     */
    function getAccountStatus(
        AccountInfo calldata account
    ) external view returns (AccountStatus);

    /**
     * Get a list of markets that have a non-zero balance for an account
     *
     * @param  account  The account to query
     * @return          The non-sorted marketIds with non-zero balance for the account.
     */
    function getAccountMarketsWithBalances(
        AccountInfo calldata account
    ) external view returns (uint256[] memory);

    /**
     * Get the number of markets that have a non-zero balance for an account
     *
     * @param  account  The account to query
     * @return          The non-sorted marketIds with non-zero balance for the account.
     */
    function getAccountNumberOfMarketsWithBalances(
        AccountInfo calldata account
    ) external view returns (uint256);

    /**
     * Get the marketId for an account's market with a non-zero balance at the given index
     *
     * @param  account  The account to query
     * @return          The non-sorted marketIds with non-zero balance for the account.
     */
    function getAccountMarketWithBalanceAtIndex(
        AccountInfo calldata account,
        uint256 index
    ) external view returns (uint256);

    /**
     * Get the number of markets with which an account has a negative balance.
     *
     * @param  account  The account to query
     * @return          The non-sorted marketIds with non-zero balance for the account.
     */
    function getAccountNumberOfMarketsWithDebt(
        AccountInfo calldata account
    ) external view returns (uint256);

    /**
     * Get the total supplied and total borrowed value of an account.
     *
     * @param  account  The account to query
     * @return          The following values:
     *                   - The supplied value of the account
     *                   - The borrowed value of the account
     */
    function getAccountValues(
        AccountInfo calldata account
    ) external view returns (MonetaryValue memory, MonetaryValue memory);

    /**
     * Get the total supplied and total borrowed values of an account adjusted by the marginPremium
     * of each market. Supplied values are divided by (1 + marginPremium) for each market and
     * borrowed values are multiplied by (1 + marginPremium) for each market. Comparing these
     * adjusted values gives the margin-ratio of the account which will be compared to the global
     * margin-ratio when determining if the account can be liquidated.
     *
     * @param  account  The account to query
     * @return          The following values:
     *                   - The supplied value of the account (adjusted for marginPremium)
     *                   - The borrowed value of the account (adjusted for marginPremium)
     */
    function getAdjustedAccountValues(
        AccountInfo calldata account
    ) external view returns (MonetaryValue memory, MonetaryValue memory);

    /**
     * Get an account's summary for each market.
     *
     * @param  account  The account to query
     * @return          The following values:
     *                   - The market IDs for each market
     *                   - The ERC20 token address for each market
     *                   - The account's principal value for each market
     *                   - The account's (supplied or borrowed) number of tokens for each market
     */
    function getAccountBalances(
        AccountInfo calldata account
    ) external view returns (uint[] memory, address[] memory, Par[] memory, Wei[] memory);

    // ============ Getters for Account Permissions ============

    /**
     * Return true if a particular address is approved as an operator for an owner's accounts.
     * Approved operators can act on the accounts of the owner as if it were the operator's own.
     *
     * @param  owner     The owner of the accounts
     * @param  operator  The possible operator
     * @return           True if operator is approved for owner's accounts
     */
    function getIsLocalOperator(
        address owner,
        address operator
    ) external view returns (bool);

    /**
     * Return true if a particular address is approved as a global operator. Such an address can
     * act on any account as if it were the operator's own.
     *
     * @param  operator  The address to query
     * @return           True if operator is a global operator
     */
    function getIsGlobalOperator(
        address operator
    ) external view returns (bool);

    /**
     * Checks if the autoTrader can only be called invoked by a global operator
     *
     * @param  autoTrader    The trader that should be checked for special call privileges.
     */
    function getIsAutoTraderSpecial(address autoTrader) external view returns (bool);

    /**
     * @return The address that owns the DolomiteMargin protocol
     */
    function owner() external view returns (address);

    // ============ Getters for Risk Params ============

    /**
     * Get the global minimum margin-ratio that every position must maintain to prevent being
     * liquidated.
     *
     * @return  The global margin-ratio
     */
    function getMarginRatio() external view returns (Decimal memory);

    /**
     * Get the global liquidation spread. This is the spread between oracle prices that incentivizes
     * the liquidation of risky positions.
     *
     * @return  The global liquidation spread
     */
    function getLiquidationSpread() external view returns (Decimal memory);

    /**
     * Get the adjusted liquidation spread for some market pair. This is equal to the global
     * liquidation spread multiplied by (1 + spreadPremium) for each of the two markets.
     *
     * @param  heldMarketId  The market for which the account has collateral
     * @param  owedMarketId  The market for which the account has borrowed tokens
     * @return               The adjusted liquidation spread
     */
    function getLiquidationSpreadForPair(
        uint256 heldMarketId,
        uint256 owedMarketId
    ) external view returns (Decimal memory);

    /**
     * Get the global earnings-rate variable that determines what percentage of the interest paid
     * by borrowers gets passed-on to suppliers.
     *
     * @return  The global earnings rate
     */
    function getEarningsRate() external view returns (Decimal memory);

    /**
     * Get the global minimum-borrow value which is the minimum value of any new borrow on DolomiteMargin.
     *
     * @return  The global minimum borrow value
     */
    function getMinBorrowedValue() external view returns (MonetaryValue memory);

    /**
     * Get all risk parameters in a single struct.
     *
     * @return  All global risk parameters
     */
    function getRiskParams() external view returns (RiskParams memory);

    /**
     * Get all risk parameter limits in a single struct. These are the maximum limits at which the
     * risk parameters can be set by the admin of DolomiteMargin.
     *
     * @return  All global risk parameter limits
     */
    function getRiskLimits() external view returns (RiskLimits memory);
}

// SPDX-License-Identifier: GPL-3.0-or-later
/*

    Copyright 2023 Dolomite

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

pragma solidity ^0.8.9;

import { IDolomiteInterestSetter } from "./IDolomiteInterestSetter.sol";
import { IDolomitePriceOracle } from "./IDolomitePriceOracle.sol";
import { IDolomiteStructs } from "./IDolomiteStructs.sol";


/**
 * @title   IDolomiteMarginAdmin
 * @author  Dolomite
 *
 * @notice  This interface defines the functions that can be called by the owner of DolomiteMargin.
 */
interface IDolomiteMarginAdmin is IDolomiteStructs {

    // ============ Token Functions ============

    /**
     * Withdraw an ERC20 token for which there is an associated market. Only excess tokens can be withdrawn. The number
     * of excess tokens is calculated by taking the current number of tokens held in DolomiteMargin, adding the number
     * of tokens owed to DolomiteMargin by borrowers, and subtracting the number of tokens owed to suppliers by
     * DolomiteMargin.
     */
    function ownerWithdrawExcessTokens(
        uint256 marketId,
        address recipient
    )
    external
    returns (uint256);

    /**
     * Withdraw an ERC20 token for which there is no associated market.
     */
    function ownerWithdrawUnsupportedTokens(
        address token,
        address recipient
    )
    external
    returns (uint256);

    // ============ Market Functions ============

    /**
     * Sets the number of non-zero balances an account may have within the same `accountIndex`. This ensures a user
     * cannot DOS the system by filling their account with non-zero balances (which linearly increases gas costs when
     * checking collateralization) and disallowing themselves to close the position, because the number of gas units
     * needed to process their transaction exceed the block's gas limit. In turn, this would  prevent the user from also
     * being liquidated, causing the all of the capital to be "stuck" in the position.
     *
     * Lowering this number does not "freeze" user accounts that have more than the new limit of balances, because this
     * variable is enforced by checking the users number of non-zero balances against the max or if it sizes down before
     * each transaction finishes.
     */
    function ownerSetAccountMaxNumberOfMarketsWithBalances(
        uint256 accountMaxNumberOfMarketsWithBalances
    )
    external;

    /**
     * Add a new market to DolomiteMargin. Must be for a previously-unsupported ERC20 token.
     */
    function ownerAddMarket(
        address token,
        IDolomitePriceOracle priceOracle,
        IDolomiteInterestSetter interestSetter,
        Decimal calldata marginPremium,
        Decimal calldata spreadPremium,
        uint256 maxWei,
        bool isClosing,
        bool isRecyclable
    )
    external;

    /**
     * Removes a market from DolomiteMargin, sends any remaining tokens in this contract to `salvager` and invokes the
     * recyclable callback
     */
    function ownerRemoveMarkets(
        uint[] calldata marketIds,
        address salvager
    )
    external;

    /**
     * Set (or unset) the status of a market to "closing". The borrowedValue of a market cannot increase while its
     * status is "closing".
     */
    function ownerSetIsClosing(
        uint256 marketId,
        bool isClosing
    )
    external;

    /**
     * Set the price oracle for a market.
     */
    function ownerSetPriceOracle(
        uint256 marketId,
        IDolomitePriceOracle priceOracle
    )
    external;

    /**
     * Set the interest-setter for a market.
     */
    function ownerSetInterestSetter(
        uint256 marketId,
        IDolomiteInterestSetter interestSetter
    )
    external;

    /**
     * Set a premium on the minimum margin-ratio for a market. This makes it so that any positions that include this
     * market require a higher collateralization to avoid being liquidated.
     */
    function ownerSetMarginPremium(
        uint256 marketId,
        Decimal calldata marginPremium
    )
    external;

    function ownerSetMaxWei(
        uint256 marketId,
        uint256 maxWei
    )
    external;

    /**
     * Set a premium on the liquidation spread for a market. This makes it so that any liquidations that include this
     * market have a higher spread than the global default.
     */
    function ownerSetSpreadPremium(
        uint256 marketId,
        Decimal calldata spreadPremium
    )
    external;

    // ============ Risk Functions ============

    /**
     * Set the global minimum margin-ratio that every position must maintain to prevent being liquidated.
     */
    function ownerSetMarginRatio(
        Decimal calldata ratio
    )
    external;

    /**
     * Set the global liquidation spread. This is the spread between oracle prices that incentivizes the liquidation of
     * risky positions.
     */
    function ownerSetLiquidationSpread(
        Decimal calldata spread
    )
    external;

    /**
     * Set the global earnings-rate variable that determines what percentage of the interest paid by borrowers gets
     * passed-on to suppliers.
     */
    function ownerSetEarningsRate(
        Decimal calldata earningsRate
    )
    external;

    /**
     * Set the global minimum-borrow value which is the minimum value of any new borrow on DolomiteMargin.
     */
    function ownerSetMinBorrowedValue(
        MonetaryValue calldata minBorrowedValue
    )
    external;

    // ============ Global Operator Functions ============

    /**
     * Approve (or disapprove) an address that is permissioned to be an operator for all accounts in DolomiteMargin.
     * Intended only to approve smart-contracts.
     */
    function ownerSetGlobalOperator(
        address operator,
        bool approved
    )
    external;

    /**
     * Approve (or disapprove) an auto trader that can only be called by a global operator. IE for expirations
     */
    function ownerSetAutoTraderSpecial(
        address autoTrader,
        bool special
    )
    external;
}

// SPDX-License-Identifier: Apache-2.0
/*

    Copyright 2019 dYdX Trading Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

*/

pragma solidity ^0.8.9;


/**
 * @title   IDolomiteMarginExchangeWrapper
 * @author  dYdX
 *
 * @notice  Interface that Exchange Wrappers for DolomiteMargin must implement in order to trade ERC20 tokens with
 *          external protocols.
 */
interface IDolomiteMarginExchangeWrapper {

    // ============ Public Functions ============

    /**
     * Exchange some amount of inputToken for outputToken.
     *
     * @param  _tradeOriginator Address of the initiator of the trade (however, this value cannot always be trusted as
     *                          it is set at the discretion of the msg.sender)
     * @param  _receiver        Address to set allowance on once the trade has completed
     * @param  _outputToken     The token to receive (target asset; IE path[path.length - 1])
     * @param  _inputToken      The token to pay (originator asset; IE path[0])
     * @param  _inputAmount     Amount of `inputToken` being paid to this wrapper
     * @param  _orderData       Arbitrary bytes data for any information to pass to the exchange
     * @return                  The amount of outputToken to be received by DolomiteMargin
     */
    function exchange(
        address _tradeOriginator,
        address _receiver,
        address _outputToken,
        address _inputToken,
        uint256 _inputAmount,
        bytes calldata _orderData
    )
    external
    returns (uint256);

    /**
     * Get amount of `inputToken` required to buy a certain amount of `outputToken` for a given trade.
     * Should match the `inputToken` amount used in exchangeForAmount. If the order cannot provide
     * exactly `_desiredOutputToken`, then it must return the price to buy the minimum amount greater
     * than `_desiredOutputToken`
     *
     * @param  _inputToken          The token to pay to this contract (originator asset; IE path[0])
     * @param  _outputToken         The token to receive by DolomiteMargin (target asset; IE path[path.length - 1])
     * @param  _desiredInputAmount  Amount of `_inputToken` requested
     * @param  _orderData           Arbitrary bytes data for any information to pass to the exchange
     * @return                      Amount of `_inputToken` the needed to complete the exchange
     */
    function getExchangeCost(
        address _inputToken,
        address _outputToken,
        uint256 _desiredInputAmount,
        bytes calldata _orderData
    )
    external
    view
    returns (uint256);
}

// SPDX-License-Identifier: GPL-3.0-or-later
/*

    Copyright 2023 Dolomite

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

*/

pragma solidity ^0.8.9;


/**
 * @title   IDolomiteOracleSentinel
 * @author  Dolomite
 *
 * Interface that Dolomite pings to check if the Blockchain or L2 is alive, if liquidations should be processed, and if
 * markets should are in size-down only mode.
 */
interface IDolomiteOracleSentinel {

    // ============ Events ============

    event GracePeriodSet(
        uint256 gracePeriod
    );

    // ============ Functions ============

    /**
     * @dev Allows the owner to set the grace period duration, which specifies how long the system will disallow
     *      liquidations after sequencer is back online. Only callable by the owner.
     *
     * @param  _gracePeriod  The new duration of the grace period
     */
    function ownerSetGracePeriod(
        uint256 _gracePeriod
    )
    external;

    /**
     * @return True if new borrows should be allowed, false otherwise
     */
    function isBorrowAllowed() external view returns (bool);

    /**
     * @return True if liquidations should be allowed, false otherwise
     */
    function isLiquidationAllowed() external view returns (bool);

    /**
     * @return  The duration between when the feed comes back online and when the system will allow liquidations to be
     *          processed normally
     */
    function gracePeriod() external view returns (uint256);
}

File 37 of 51 : IDolomitePriceOracle.sol
// SPDX-License-Identifier: GPL-3.0-or-later
/*

    Copyright 2023 Dolomite

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

pragma solidity ^0.8.9;

import { IDolomiteStructs } from "./IDolomiteStructs.sol";


/**
 * @title   IDolomitePriceOracle
 * @author  Dolomite
 *
 * @notice  Interface that Price Oracles for DolomiteMargin must implement in order to report prices.
 */
interface IDolomitePriceOracle {

    // ============ Public Functions ============

    /**
     * Get the price of a token
     *
     * @param  token  The ERC20 token address of the market
     * @return        The USD price of a base unit of the token, then multiplied by 10^(36 - decimals).
     *                So a USD-stable coin with 6 decimal places would return `price * 10^30`.
     *                This is the price of the base unit rather than the price of a "human-readable"
     *                token amount. Every ERC20 may have a different number of decimals.
     */
    function getPrice(
        address token
    )
    external
    view
    returns (IDolomiteStructs.MonetaryPrice memory);
}

File 38 of 51 : IDolomiteStructs.sol
// SPDX-License-Identifier: GPL-3.0-or-later
/*

    Copyright 2023 Dolomite

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

pragma solidity ^0.8.9;

import { IDolomiteAccountRiskOverrideSetter } from "./IDolomiteAccountRiskOverrideSetter.sol";
import { IDolomiteInterestSetter } from "./IDolomiteInterestSetter.sol";
import { IDolomiteOracleSentinel } from "./IDolomiteOracleSentinel.sol";
import { IDolomitePriceOracle } from "./IDolomitePriceOracle.sol";


/**
 * @title   IDolomiteStructs
 * @author  Dolomite
 *
 * @notice  This interface defines the structs used by DolomiteMargin
 */
interface IDolomiteStructs {

    // ========================= Enums =========================

    enum ActionType {
        Deposit,   // supply tokens
        Withdraw,  // borrow tokens
        Transfer,  // transfer balance between accounts
        Buy,       // buy an amount of some token (externally)
        Sell,      // sell an amount of some token (externally)
        Trade,     // trade tokens against another account
        Liquidate, // liquidate an undercollateralized or expiring account
        Vaporize,  // use excess tokens to zero-out a completely negative account
        Call       // send arbitrary data to an address
    }

    enum AssetDenomination {
        Wei, // the amount is denominated in wei
        Par  // the amount is denominated in par
    }

    enum AssetReference {
        Delta, // the amount is given as a delta from the current value
        Target // the amount is given as an exact number to end up at
    }

    // ========================= Structs =========================

    struct AccountInfo {
        address owner;  // The address that owns the account
        uint256 number; // A nonce that allows a single address to control many accounts
    }

    /**
     * Most-recently-cached account status.
     *
     * Normal: Can only be liquidated if the account values are violating the global margin-ratio.
     * Liquid: Can be liquidated no matter the account values.
     *         Can be vaporized if there are no more positive account values.
     * Vapor:  Has only negative (or zeroed) account values. Can be vaporized.
     *
     */
    enum AccountStatus {
        Normal,
        Liquid,
        Vapor
    }

    /*
     * Arguments that are passed to DolomiteMargin in an ordered list as part of a single operation.
     * Each ActionArgs has an actionType which specifies which action struct that this data will be
     * parsed into before being processed.
     */
    struct ActionArgs {
        ActionType actionType;
        uint256 accountId;
        AssetAmount amount;
        uint256 primaryMarketId;
        uint256 secondaryMarketId;
        address otherAddress;
        uint256 otherAccountId;
        bytes data;
    }

    struct AssetAmount {
        bool sign; // true if positive
        AssetDenomination denomination;
        AssetReference ref;
        uint256 value;
    }

    struct Decimal {
        uint256 value;
    }

    struct InterestIndex {
        uint96 borrow;
        uint96 supply;
        uint32 lastUpdate;
    }

    struct Market {
        address token;

        // Whether additional borrows are allowed for this market
        bool isClosing;

        // Whether this market can be removed and its ID can be recycled and reused
        bool isRecyclable;

        // Total aggregated supply and borrow amount of the entire market
        TotalPar totalPar;

        // Interest index of the market
        InterestIndex index;

        // Contract address of the price oracle for this market
        IDolomitePriceOracle priceOracle;

        // Contract address of the interest setter for this market
        IDolomiteInterestSetter interestSetter;

        // Multiplier on the marginRatio for this market, IE 5% (0.05 * 1e18). This number increases the market's
        // required collateralization by: reducing the user's supplied value (in terms of dollars) for this market and
        // increasing its borrowed value. This is done through the following operation:
        // `suppliedWei = suppliedWei + (assetValueForThisMarket / (1 + marginPremium))`
        // This number increases the user's borrowed wei by multiplying it by:
        // `borrowedWei = borrowedWei + (assetValueForThisMarket * (1 + marginPremium))`
        Decimal marginPremium;

        // Multiplier on the liquidationSpread for this market, IE 20% (0.2 * 1e18). This number increases the
        // `liquidationSpread` using the following formula:
        // `liquidationSpread = liquidationSpread * (1 + spreadPremium)`
        // NOTE: This formula is applied up to two times - one for each market whose spreadPremium is greater than 0
        // (when performing a liquidation between two markets)
        Decimal spreadPremium;

        // The maximum amount that can be held by the external. This allows the external to cap any additional risk
        // that is inferred by allowing borrowing against low-cap or assets with increased volatility. Setting this
        // value to 0 is analogous to having no limit. This value can never be below 0.
        Wei maxWei;
    }

    struct MarketV2 {
        // Contract address of the associated ERC20 token
        address token;

        // Whether additional borrows are allowed for this market
        bool isClosing;

        // Total aggregated supply and borrow amount of the entire market
        TotalPar totalPar;

        // Interest index of the market
        InterestIndex index;

        // Contract address of the price oracle for this market
        IDolomitePriceOracle priceOracle;

        // Contract address of the interest setter for this market
        IDolomiteInterestSetter interestSetter;

        // Multiplier on the marginRatio for this market, IE 5% (0.05 * 1e18). This number increases the market's
        // required collateralization by: reducing the user's supplied value (in terms of dollars) for this market and
        // increasing its borrowed value. This is done through the following operation:
        // `suppliedWei = suppliedWei + (assetValueForThisMarket / (1 + marginPremium))`
        // This number increases the user's borrowed wei by multiplying it by:
        // `borrowedWei = borrowedWei + (assetValueForThisMarket * (1 + marginPremium))`
        Decimal marginPremium;

        // Multiplier on the liquidationSpread for this market, IE 20% (0.2 * 1e18). This number increases the
        // `liquidationSpread` using the following formula:
        // `liquidationSpread = liquidationSpread * (1 + spreadPremium)`
        // NOTE: This formula is applied up to two times - one for each market whose spreadPremium is greater than 0
        // (when performing a liquidation between two markets)
        Decimal liquidationSpreadPremium;

        // The maximum amount that can be held by the protocol. This allows the protocol to cap any additional risk
        // that is inferred by allowing borrowing against low-cap or assets with increased volatility. Setting this
        // value to 0 is analogous to having no limit. This value can never be below 0.
        Wei maxSupplyWei;

        // The maximum amount that can be borrowed by the protocol. This allows the protocol to cap any additional risk
        // that is inferred by allowing borrowing against low-cap or assets with increased volatility. Setting this
        // value to 0 is analogous to having no limit. This value can never be greater than 0.
        Wei maxBorrowWei;

        // The percentage of interest paid that is passed along from borrowers to suppliers. Setting this to 0 will
        // default to RiskParams.earningsRate.
        Decimal earningsRateOverride;
    }

    /*
     * The price of a base-unit of an asset. Has `36 - token.decimals` decimals
     */
    struct MonetaryPrice {
        uint256 value;
    }

    struct MonetaryValue {
        uint256 value;
    }

    struct OperatorArg {
        address operator;
        bool trusted;
    }

    struct Par {
        bool sign;
        uint128 value;
    }

    struct RiskLimits {
        // The highest that the ratio can be for liquidating under-water accounts
        uint64 marginRatioMax;
        // The highest that the liquidation rewards can be when a liquidator liquidates an account
        uint64 liquidationSpreadMax;
        // The highest that the supply APR can be for a market, as a proportion of the borrow rate. Meaning, a rate of
        // 100% (1e18) would give suppliers all of the interest that borrowers are paying. A rate of 90% would give
        // suppliers 90% of the interest that borrowers pay.
        uint64 earningsRateMax;
        // The highest min margin ratio premium that can be applied to a particular market. Meaning, a value of 100%
        // (1e18) would require borrowers to maintain an extra 100% collateral to maintain a healthy margin ratio. This
        // value works by increasing the debt owed and decreasing the supply held for the particular market by this
        // amount, plus 1e18 (since a value of 10% needs to be applied as `decimal.plusOne`)
        uint64 marginPremiumMax;
        // The highest liquidation reward that can be applied to a particular market. This percentage is applied
        // in addition to the liquidation spread in `RiskParams`. Meaning a value of 1e18 is 100%. It is calculated as:
        // `liquidationSpread * Decimal.onePlus(spreadPremium)`
        uint64 spreadPremiumMax;
        uint128 minBorrowedValueMax;
    }

    struct RiskLimitsV2 {
        // The highest that the ratio can be for liquidating under-water accounts
        uint64 marginRatioMax;
        // The highest that the liquidation rewards can be when a liquidator liquidates an account
        uint64 liquidationSpreadMax;
        // The highest that the supply APR can be for a market, as a proportion of the borrow rate. Meaning, a rate of
        // 100% (1e18) would give suppliers all of the interest that borrowers are paying. A rate of 90% would give
        // suppliers 90% of the interest that borrowers pay.
        uint64 earningsRateMax;
        // The highest min margin ratio premium that can be applied to a particular market. Meaning, a value of 100%
        // (1e18) would require borrowers to maintain an extra 100% collateral to maintain a healthy margin ratio. This
        // value works by increasing the debt owed and decreasing the supply held for the particular market by this
        // amount, plus 1e18 (since a value of 10% needs to be applied as `decimal.plusOne`)
        uint64 marginPremiumMax;
        // The highest liquidation reward that can be applied to a particular market. This percentage is applied
        // in addition to the liquidation spread in `RiskParams`. Meaning a value of 1e18 is 100%. It is calculated as:
        // `liquidationSpread * Decimal.onePlus(spreadPremium)`
        uint64 liquidationSpreadPremiumMax;
        // The highest that the borrow interest rate can ever be. If the rate returned is ever higher, the rate is
        // capped at this value instead of reverting. The goal is to keep Dolomite operational under all circumstances
        // instead of inadvertently DOS'ing the protocol.
        uint96 interestRateMax;
        // The highest that the minBorrowedValue can be. This is the minimum amount of value that must be borrowed.
        // Typically a value of $100 (100 * 1e18) is more than sufficient.
        uint128 minBorrowedValueMax;
    }

    struct RiskParams {
        // Required ratio of over-collateralization
        Decimal marginRatio;

        // Percentage penalty incurred by liquidated accounts
        Decimal liquidationSpread;

        // Percentage of the borrower's interest fee that gets passed to the suppliers
        Decimal earningsRate;

        // The minimum absolute borrow value of an account
        // There must be sufficient incentivize to liquidate undercollateralized accounts
        MonetaryValue minBorrowedValue;

        // The maximum number of markets a user can have a non-zero balance for a given account.
        uint256 accountMaxNumberOfMarketsWithBalances;
    }

    // The global risk parameters that govern the health and security of the system
    struct RiskParamsV2 {
        // Required ratio of over-collateralization
        Decimal marginRatio;

        // Percentage penalty incurred by liquidated accounts
        Decimal liquidationSpread;

        // Percentage of the borrower's interest fee that gets passed to the suppliers
        Decimal earningsRate;

        // The minimum absolute borrow value of an account
        // There must be sufficient incentivize to liquidate undercollateralized accounts
        MonetaryValue minBorrowedValue;

        // The maximum number of markets a user can have a non-zero balance for a given account.
        uint256 accountMaxNumberOfMarketsWithBalances;

        // The oracle sentinel used to disable borrowing/liquidations if the sequencer goes down
        IDolomiteOracleSentinel oracleSentinel;

        // The gas limit used for making callbacks via `IExternalCallback::onInternalBalanceChange` to smart contract
        // wallets. Setting to 0 will effectively disable callbacks; setting it super large is not desired since it
        // could lead to DOS attacks on the protocol; however, hard coding a max value isn't preferred since some chains
        // can calculate gas usage differently (like ArbGas before Arbitrum rolled out nitro)
        uint256 callbackGasLimit;

        // Certain addresses are allowed to borrow with different LTV requirements. When an account's risk is overrode,
        // the global risk parameters are ignored and the account's risk parameters are used instead.
        mapping(address => IDolomiteAccountRiskOverrideSetter) accountRiskOverrideSetterMap;
    }

    struct TotalPar {
        uint128 borrow;
        uint128 supply;
    }

    struct TotalWei {
        uint128 borrow;
        uint128 supply;
    }

    struct Wei {
        bool sign;
        uint256 value;
    }
}

// SPDX-License-Identifier: GPL-3.0-or-later
/*

    Copyright 2023 Dolomite

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

pragma solidity ^0.8.9;

import { Require } from "./Require.sol";


/**
 * @title   DolomiteMarginMath
 * @author  dYdX
 *
 * @notice  Library for non-standard Math functions
 */
library DolomiteMarginMath {

    // ============ Constants ============

    bytes32 internal constant _FILE = "DolomiteMarginMath";

    // ============ Library Functions ============

    /*
     * Return target * (numerator / denominator).
     */
    function getPartial(
        uint256 target,
        uint256 numerator,
        uint256 denominator
    )
    internal
    pure
    returns (uint256)
    {
        return target * numerator / denominator;
    }

    /*
     * Return target * (numerator / denominator), but rounded half-up. Meaning, a result of 101.1 rounds to 102
     * instead of 101.
     */
    function getPartialRoundUp(
        uint256 target,
        uint256 numerator,
        uint256 denominator
    )
    internal
    pure
    returns (uint256)
    {
        if (target == 0 || numerator == 0) {
            return 0;
        }
        return (((target * numerator) - 1) / denominator) + 1;
    }

    /*
     * Return target * (numerator / denominator), but rounded half-up. Meaning, a result of 101.5 rounds to 102
     * instead of 101.
     */
    function getPartialRoundHalfUp(
        uint256 target,
        uint256 numerator,
        uint256 denominator
    )
    internal
    pure
    returns (uint256)
    {
        if (target == 0 || numerator == 0) {
            return 0;
        }
        return (((target * numerator) + (denominator / 2)) / denominator);
    }

    function to128(
        uint256 number
    )
    internal
    pure
    returns (uint128)
    {
        uint128 result = uint128(number);
        Require.that(
            result == number,
            _FILE,
            "Unsafe cast to uint128",
            number
        );
        return result;
    }

    function to96(
        uint256 number
    )
    internal
    pure
    returns (uint96)
    {
        uint96 result = uint96(number);
        Require.that(
            result == number,
            _FILE,
            "Unsafe cast to uint96",
            number
        );
        return result;
    }

    function to32(
        uint256 number
    )
    internal
    pure
    returns (uint32)
    {
        uint32 result = uint32(number);
        Require.that(
            result == number,
            _FILE,
            "Unsafe cast to uint32",
            number
        );
        return result;
    }
}

// SPDX-License-Identifier: Apache-2.0
/*

    Copyright 2019 dYdX Trading Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

*/

pragma solidity ^0.8.9;


/**
 * @title   Require
 * @author  dYdX
 *
 * @notice  Stringifies parameters to pretty-print revert messages. Costs more gas than regular require()
 */
library Require {

    // ============ Constants ============

    uint256 private constant _ASCII_ZERO = 48; // '0'
    uint256 private constant _ASCII_RELATIVE_ZERO = 87; // 'a' - 10
    uint256 private constant _ASCII_LOWER_EX = 120; // 'x'
    bytes2 private constant _COLON = 0x3a20; // ': '
    bytes2 private constant _COMMA = 0x2c20; // ', '
    bytes2 private constant _LPAREN = 0x203c; // ' <'
    bytes1 private constant _RPAREN = 0x3e; // '>'
    uint256 private constant _FOUR_BIT_MASK = 0xf;

    // ============ Library Functions ============

    function that(
        bool must,
        bytes32 file,
        bytes32 reason
    )
    internal
    pure
    {
        if (!must) {
            revert(
            string(
                abi.encodePacked(
                    stringifyTruncated(file),
                    _COLON,
                    stringifyTruncated(reason)
                )
            )
            );
        }
    }

    function that(
        bool must,
        bytes32 file,
        bytes32 reason,
        uint256 payloadA
    )
    internal
    pure
    {
        if (!must) {
            revert(
            string(
                abi.encodePacked(
                    stringifyTruncated(file),
                    _COLON,
                    stringifyTruncated(reason),
                    _LPAREN,
                    _stringify(payloadA),
                    _RPAREN
                )
            )
            );
        }
    }

    function that(
        bool must,
        bytes32 file,
        bytes32 reason,
        uint256 payloadA,
        uint256 payloadB
    )
    internal
    pure
    {
        if (!must) {
            revert(
            string(
                abi.encodePacked(
                    stringifyTruncated(file),
                    _COLON,
                    stringifyTruncated(reason),
                    _LPAREN,
                    _stringify(payloadA),
                    _COMMA,
                    _stringify(payloadB),
                    _RPAREN
                )
            )
            );
        }
    }

    function that(
        bool must,
        bytes32 file,
        bytes32 reason,
        address payloadA
    )
    internal
    pure
    {
        if (!must) {
            revert(
            string(
                abi.encodePacked(
                    stringifyTruncated(file),
                    _COLON,
                    stringifyTruncated(reason),
                    _LPAREN,
                    _stringify(payloadA),
                    _RPAREN
                )
            )
            );
        }
    }

    function that(
        bool must,
        bytes32 file,
        bytes32 reason,
        address payloadA,
        uint256 payloadB
    )
    internal
    pure
    {
        if (!must) {
            revert(
            string(
                abi.encodePacked(
                    stringifyTruncated(file),
                    _COLON,
                    stringifyTruncated(reason),
                    _LPAREN,
                    _stringify(payloadA),
                    _COMMA,
                    _stringify(payloadB),
                    _RPAREN
                )
            )
            );
        }
    }

    function that(
        bool must,
        bytes32 file,
        bytes32 reason,
        address payloadA,
        uint256 payloadB,
        uint256 payloadC
    )
    internal
    pure
    {
        if (!must) {
            revert(
            string(
                abi.encodePacked(
                    stringifyTruncated(file),
                    _COLON,
                    stringifyTruncated(reason),
                    _LPAREN,
                    _stringify(payloadA),
                    _COMMA,
                    _stringify(payloadB),
                    _COMMA,
                    _stringify(payloadC),
                    _RPAREN
                )
            )
            );
        }
    }

    function that(
        bool must,
        bytes32 file,
        bytes32 reason,
        bytes32 payloadA
    )
    internal
    pure
    {
        if (!must) {
            revert(
            string(
                abi.encodePacked(
                    stringifyTruncated(file),
                    _COLON,
                    stringifyTruncated(reason),
                    _LPAREN,
                    _stringify(payloadA),
                    _RPAREN
                )
            )
            );
        }
    }

    function that(
        bool must,
        bytes32 file,
        bytes32 reason,
        bytes32 payloadA,
        uint256 payloadB,
        uint256 payloadC
    )
    internal
    pure
    {
        if (!must) {
            revert(
            string(
                abi.encodePacked(
                    stringifyTruncated(file),
                    _COLON,
                    stringifyTruncated(reason),
                    _LPAREN,
                    _stringify(payloadA),
                    _COMMA,
                    _stringify(payloadB),
                    _COMMA,
                    _stringify(payloadC),
                    _RPAREN
                )
            )
            );
        }
    }

    // ============ Private Functions ============

    function stringifyTruncated(
        bytes32 input
    )
    internal
    pure
    returns (bytes memory)
    {
        // put the input bytes into the result
        bytes memory result = abi.encodePacked(input);

        // determine the length of the input by finding the location of the last non-zero byte
        for (uint256 i = 32; i > 0; ) {
            // reverse-for-loops with unsigned integer
            i--;

            // find the last non-zero byte in order to determine the length
            if (result[i] != 0) {
                uint256 length = i + 1;

                /* solhint-disable-next-line no-inline-assembly */
                assembly {
                    mstore(result, length) // r.length = length;
                }

                return result;
            }
        }

        // all bytes are zero
        return new bytes(0);
    }

    function stringifyFunctionSelector(
        bytes4 input
    )
    internal
    pure
    returns (bytes memory)
    {
        uint256 z = uint256(bytes32(input) >> 224);

        // bytes4 are "0x" followed by 4 bytes of data which take up 2 characters each
        bytes memory result = new bytes(10);

        // populate the result with "0x"
        result[0] = bytes1(uint8(_ASCII_ZERO));
        result[1] = bytes1(uint8(_ASCII_LOWER_EX));

        // for each byte (starting from the lowest byte), populate the result with two characters
        for (uint256 i = 0; i < 4; i++) {
            // each byte takes two characters
            uint256 shift = i * 2;

            // populate the least-significant character
            result[9 - shift] = _char(z & _FOUR_BIT_MASK);
            z = z >> 4;

            // populate the most-significant character
            result[8 - shift] = _char(z & _FOUR_BIT_MASK);
            z = z >> 4;
        }

        return result;
    }

    function _stringify(
        uint256 input
    )
    private
    pure
    returns (bytes memory)
    {
        if (input == 0) {
            return "0";
        }

        // get the final string length
        uint256 j = input;
        uint256 length;
        while (j != 0) {
            length++;
            j /= 10;
        }

        // allocate the string
        bytes memory bstr = new bytes(length);

        // populate the string starting with the least-significant character
        j = input;
        for (uint256 i = length; i > 0; ) {
            // reverse-for-loops with unsigned integer
            i--;

            // take last decimal digit
            bstr[i] = bytes1(uint8(_ASCII_ZERO + (j % 10)));

            // remove the last decimal digit
            j /= 10;
        }

        return bstr;
    }

    function _stringify(
        address input
    )
    private
    pure
    returns (bytes memory)
    {
        uint256 z = uint256(uint160(input));

        // addresses are "0x" followed by 20 bytes of data which take up 2 characters each
        bytes memory result = new bytes(42);

        // populate the result with "0x"
        result[0] = bytes1(uint8(_ASCII_ZERO));
        result[1] = bytes1(uint8(_ASCII_LOWER_EX));

        // for each byte (starting from the lowest byte), populate the result with two characters
        for (uint256 i = 0; i < 20; i++) {
            // each byte takes two characters
            uint256 shift = i * 2;

            // populate the least-significant character
            result[41 - shift] = _char(z & _FOUR_BIT_MASK);
            z = z >> 4;

            // populate the most-significant character
            result[40 - shift] = _char(z & _FOUR_BIT_MASK);
            z = z >> 4;
        }

        return result;
    }

    function _stringify(
        bytes32 input
    )
    private
    pure
    returns (bytes memory)
    {
        uint256 z = uint256(input);

        // bytes32 are "0x" followed by 32 bytes of data which take up 2 characters each
        bytes memory result = new bytes(66);

        // populate the result with "0x"
        result[0] = bytes1(uint8(_ASCII_ZERO));
        result[1] = bytes1(uint8(_ASCII_LOWER_EX));

        // for each byte (starting from the lowest byte), populate the result with two characters
        for (uint256 i = 0; i < 32; i++) {
            // each byte takes two characters
            uint256 shift = i * 2;

            // populate the least-significant character
            result[65 - shift] = _char(z & _FOUR_BIT_MASK);
            z = z >> 4;

            // populate the most-significant character
            result[64 - shift] = _char(z & _FOUR_BIT_MASK);
            z = z >> 4;
        }

        return result;
    }

    function _char(
        uint256 input
    )
    private
    pure
    returns (bytes1)
    {
        // return ASCII digit (0-9)
        if (input < 10) {
            return bytes1(uint8(input + _ASCII_ZERO));
        }

        // return ASCII letter (a-f)
        return bytes1(uint8(input + _ASCII_RELATIVE_ZERO));
    }
}

// SPDX-License-Identifier: Apache-2.0
/*

    Copyright 2019 dYdX Trading Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

*/

pragma solidity ^0.8.9;

import { DolomiteMarginMath } from "./DolomiteMarginMath.sol";
import { IDolomiteStructs } from "../interfaces/IDolomiteStructs.sol";


/**
 * @title   TypesLib
 * @author  dYdX
 *
 * @notice  Library for interacting with the basic structs used in DolomiteMargin
 */
library TypesLib {
    using DolomiteMarginMath for uint256;

    // ============ Par (Principal Amount) ============

    function zeroPar()
    internal
    pure
    returns (IDolomiteStructs.Par memory)
    {
        return IDolomiteStructs.Par({
            sign: false,
            value: 0
        });
    }

    function sub(
        IDolomiteStructs.Par memory a,
        IDolomiteStructs.Par memory b
    )
    internal
    pure
    returns (IDolomiteStructs.Par memory)
    {
        return add(a, negative(b));
    }

    function add(
        IDolomiteStructs.Par memory a,
        IDolomiteStructs.Par memory b
    )
    internal
    pure
    returns (IDolomiteStructs.Par memory)
    {
        IDolomiteStructs.Par memory result;
        if (a.sign == b.sign) {
            result.sign = a.sign;
            result.value = a.value + b.value;
        } else {
            if (a.value >= b.value) {
                result.sign = a.sign;
                result.value = a.value - b.value;
            } else {
                result.sign = b.sign;
                result.value = b.value - a.value;
            }
        }
        return result;
    }

    function equals(
        IDolomiteStructs.Par memory a,
        IDolomiteStructs.Par memory b
    )
    internal
    pure
    returns (bool)
    {
        if (a.value == b.value) {
            if (a.value == 0) {
                return true;
            }
            return a.sign == b.sign;
        }
        return false;
    }

    function negative(
        IDolomiteStructs.Par memory a
    )
    internal
    pure
    returns (IDolomiteStructs.Par memory)
    {
        return IDolomiteStructs.Par({
            sign: !a.sign,
            value: a.value
        });
    }

    function isNegative(
        IDolomiteStructs.Par memory a
    )
    internal
    pure
    returns (bool)
    {
        return !a.sign && a.value > 0;
    }

    function isPositive(
        IDolomiteStructs.Par memory a
    )
    internal
    pure
    returns (bool)
    {
        return a.sign && a.value > 0;
    }

    function isZero(
        IDolomiteStructs.Par memory a
    )
    internal
    pure
    returns (bool)
    {
        return a.value == 0;
    }

    function isLessThanZero(
        IDolomiteStructs.Par memory a
    )
    internal
    pure
    returns (bool)
    {
        return a.value > 0 && !a.sign;
    }

    function isGreaterThanOrEqualToZero(
        IDolomiteStructs.Par memory a
    )
    internal
    pure
    returns (bool)
    {
        return isZero(a) || a.sign;
    }

    // ============ Wei (Token Amount) ============

    function zeroWei()
    internal
    pure
    returns (IDolomiteStructs.Wei memory)
    {
        return IDolomiteStructs.Wei({
            sign: false,
            value: 0
        });
    }

    function sub(
        IDolomiteStructs.Wei memory a,
        IDolomiteStructs.Wei memory b
    )
    internal
    pure
    returns (IDolomiteStructs.Wei memory)
    {
        return add(a, negative(b));
    }

    function add(
        IDolomiteStructs.Wei memory a,
        IDolomiteStructs.Wei memory b
    )
    internal
    pure
    returns (IDolomiteStructs.Wei memory)
    {
        IDolomiteStructs.Wei memory result;
        if (a.sign == b.sign) {
            result.sign = a.sign;
            result.value = a.value + b.value;
        } else {
            if (a.value >= b.value) {
                result.sign = a.sign;
                result.value = a.value - b.value;
            } else {
                result.sign = b.sign;
                result.value = b.value - a.value;
            }
        }
        return result;
    }

    function equals(
        IDolomiteStructs.Wei memory a,
        IDolomiteStructs.Wei memory b
    )
    internal
    pure
    returns (bool)
    {
        if (a.value == b.value) {
            if (a.value == 0) {
                return true;
            }
            return a.sign == b.sign;
        }
        return false;
    }

    function negative(
        IDolomiteStructs.Wei memory a
    )
    internal
    pure
    returns (IDolomiteStructs.Wei memory)
    {
        return IDolomiteStructs.Wei({
            sign: !a.sign,
            value: a.value
        });
    }

    function isNegative(
        IDolomiteStructs.Wei memory a
    )
    internal
    pure
    returns (bool)
    {
        return !a.sign && a.value > 0;
    }

    function isPositive(
        IDolomiteStructs.Wei memory a
    )
    internal
    pure
    returns (bool)
    {
        return a.sign && a.value > 0;
    }

    function isZero(
        IDolomiteStructs.Wei memory a
    )
    internal
    pure
    returns (bool)
    {
        return a.value == 0;
    }
}

// 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);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @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);

    /**
     * @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);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Create2.sol)

pragma solidity ^0.8.0;

/**
 * @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer.
 * `CREATE2` can be used to compute in advance the address where a smart
 * contract will be deployed, which allows for interesting new mechanisms known
 * as 'counterfactual interactions'.
 *
 * See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more
 * information.
 */
library Create2 {
    /**
     * @dev Deploys a contract using `CREATE2`. The address where the contract
     * will be deployed can be known in advance via {computeAddress}.
     *
     * The bytecode for a contract can be obtained from Solidity with
     * `type(contractName).creationCode`.
     *
     * Requirements:
     *
     * - `bytecode` must not be empty.
     * - `salt` must have not been used for `bytecode` already.
     * - the factory must have a balance of at least `amount`.
     * - if `amount` is non-zero, `bytecode` must have a `payable` constructor.
     */
    function deploy(uint256 amount, bytes32 salt, bytes memory bytecode) internal returns (address addr) {
        require(address(this).balance >= amount, "Create2: insufficient balance");
        require(bytecode.length != 0, "Create2: bytecode length is zero");
        /// @solidity memory-safe-assembly
        assembly {
            addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt)
        }
        require(addr != address(0), "Create2: Failed on deploy");
    }

    /**
     * @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the
     * `bytecodeHash` or `salt` will result in a new destination address.
     */
    function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address) {
        return computeAddress(salt, bytecodeHash, address(this));
    }

    /**
     * @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at
     * `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}.
     */
    function computeAddress(bytes32 salt, bytes32 bytecodeHash, address deployer) internal pure returns (address addr) {
        /// @solidity memory-safe-assembly
        assembly {
            let ptr := mload(0x40) // Get free memory pointer

            // |                   | ↓ ptr ...  ↓ ptr + 0x0B (start) ...  ↓ ptr + 0x20 ...  ↓ ptr + 0x40 ...   |
            // |-------------------|---------------------------------------------------------------------------|
            // | bytecodeHash      |                                                        CCCCCCCCCCCCC...CC |
            // | salt              |                                      BBBBBBBBBBBBB...BB                   |
            // | deployer          | 000000...0000AAAAAAAAAAAAAAAAAAA...AA                                     |
            // | 0xFF              |            FF                                                             |
            // |-------------------|---------------------------------------------------------------------------|
            // | memory            | 000000...00FFAAAAAAAAAAAAAAAAAAA...AABBBBBBBBBBBBB...BBCCCCCCCCCCCCC...CC |
            // | keccak(start, 85) |            ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ |

            mstore(add(ptr, 0x40), bytecodeHash)
            mstore(add(ptr, 0x20), salt)
            mstore(ptr, deployer) // Right-aligned with 12 preceding garbage bytes
            let start := add(ptr, 0x0b) // The hashed data starts at the final garbage byte which we will set to 0xff
            mstore8(start, 0xff)
            addr := keccak256(start, 85)
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.

pragma solidity ^0.8.0;

/**
 * @dev Library for managing
 * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
 * types.
 *
 * Sets have the following properties:
 *
 * - Elements are added, removed, and checked for existence in constant time
 * (O(1)).
 * - Elements are enumerated in O(n). No guarantees are made on the ordering.
 *
 * ```solidity
 * contract Example {
 *     // Add the library methods
 *     using EnumerableSet for EnumerableSet.AddressSet;
 *
 *     // Declare a set state variable
 *     EnumerableSet.AddressSet private mySet;
 * }
 * ```
 *
 * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
 * and `uint256` (`UintSet`) are supported.
 *
 * [WARNING]
 * ====
 * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
 * unusable.
 * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
 *
 * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
 * array of EnumerableSet.
 * ====
 */
library EnumerableSet {
    // To implement this library for multiple types with as little code
    // repetition as possible, we write it in terms of a generic Set type with
    // bytes32 values.
    // The Set implementation uses private functions, and user-facing
    // implementations (such as AddressSet) are just wrappers around the
    // underlying Set.
    // This means that we can only create new EnumerableSets for types that fit
    // in bytes32.

    struct Set {
        // Storage of set values
        bytes32[] _values;
        // Position of the value in the `values` array, plus 1 because index 0
        // means a value is not in the set.
        mapping(bytes32 => uint256) _indexes;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function _add(Set storage set, bytes32 value) private returns (bool) {
        if (!_contains(set, value)) {
            set._values.push(value);
            // The value is stored at length-1, but we add 1 to all indexes
            // and use 0 as a sentinel value
            set._indexes[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function _remove(Set storage set, bytes32 value) private returns (bool) {
        // We read and store the value's index to prevent multiple reads from the same storage slot
        uint256 valueIndex = set._indexes[value];

        if (valueIndex != 0) {
            // Equivalent to contains(set, value)
            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
            // the array, and then remove the last element (sometimes called as 'swap and pop').
            // This modifies the order of the array, as noted in {at}.

            uint256 toDeleteIndex = valueIndex - 1;
            uint256 lastIndex = set._values.length - 1;

            if (lastIndex != toDeleteIndex) {
                bytes32 lastValue = set._values[lastIndex];

                // Move the last value to the index where the value to delete is
                set._values[toDeleteIndex] = lastValue;
                // Update the index for the moved value
                set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex
            }

            // Delete the slot where the moved value was stored
            set._values.pop();

            // Delete the index for the deleted slot
            delete set._indexes[value];

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function _contains(Set storage set, bytes32 value) private view returns (bool) {
        return set._indexes[value] != 0;
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function _length(Set storage set) private view returns (uint256) {
        return set._values.length;
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function _at(Set storage set, uint256 index) private view returns (bytes32) {
        return set._values[index];
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function _values(Set storage set) private view returns (bytes32[] memory) {
        return set._values;
    }

    // Bytes32Set

    struct Bytes32Set {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _add(set._inner, value);
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _remove(set._inner, value);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
        return _contains(set._inner, value);
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(Bytes32Set storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
        return _at(set._inner, index);
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
        bytes32[] memory store = _values(set._inner);
        bytes32[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(AddressSet storage set, address value) internal returns (bool) {
        return _add(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(AddressSet storage set, address value) internal returns (bool) {
        return _remove(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(AddressSet storage set, address value) internal view returns (bool) {
        return _contains(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(AddressSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(AddressSet storage set, uint256 index) internal view returns (address) {
        return address(uint160(uint256(_at(set._inner, index))));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(AddressSet storage set) internal view returns (address[] memory) {
        bytes32[] memory store = _values(set._inner);
        address[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }

    // UintSet

    struct UintSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(UintSet storage set, uint256 value) internal returns (bool) {
        return _add(set._inner, bytes32(value));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(UintSet storage set, uint256 value) internal returns (bool) {
        return _remove(set._inner, bytes32(value));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(UintSet storage set, uint256 value) internal view returns (bool) {
        return _contains(set._inner, bytes32(value));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(UintSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(UintSet storage set, uint256 index) internal view returns (uint256) {
        return uint256(_at(set._inner, index));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(UintSet storage set) internal view returns (uint256[] memory) {
        bytes32[] memory store = _values(set._inner);
        uint256[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }
}

// SPDX-License-Identifier: GPL-3.0-or-later
/*

    Copyright 2023 Dolomite

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

pragma solidity ^0.8.9;

import { IIsolationModeVaultFactory } from "@dolomite-exchange/modules-base/contracts/isolation-mode/interfaces/IIsolationModeVaultFactory.sol"; // solhint-disable-line max-line-length
import { IPendleRegistry } from "./IPendleRegistry.sol";


/**
 * @title   IPendlePtIsolationModeVaultFactory
 * @author  Dolomite
 *
 * @notice  Interface for a subclass of IsolationModeVaultFactory that creates vaults for PT tokens.
 */
interface IPendlePtIsolationModeVaultFactory is IIsolationModeVaultFactory {

    // ================================================
    // ==================== Events ====================
    // ================================================

    event PendleRegistrySet(address _pendleRETHRegistry);

    // ===================================================
    // ==================== Functions ====================
    // ===================================================

    function ownerSetPendleRegistry(address _pendleRegistry) external;

    function pendleRegistry() external view returns (IPendleRegistry);
}

// SPDX-License-Identifier: GPL-3.0-or-later
/*

    Copyright 2023 Dolomite

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

pragma solidity ^0.8.9;

import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";


/**
 * @title   IPendlePtMarket
 * @author  Dolomite
 *
 * @notice  Interface for interacting with Pendle's AMM LP tokens.
 */
interface IPendlePtMarket is IERC20 {

    function isExpired() external view returns (bool);

    function readTokens() external view returns (address sy, address pt, address yt);
}

// SPDX-License-Identifier: GPL-3.0-or-later
/*

    Copyright 2023 Dolomite

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

pragma solidity ^0.8.9;


/**
 * @title   IPendlePtOracle
 * @author  Dolomite
 *
 * @notice  The vault contract used by GMX for holding the assets that back GLP.
 */
interface IPendlePtOracle {

    /**
     * Gets the TWAP rate of PT/Asset for the given market and duration
     *
     * @param  _market   The market to get the rate from
     * @param  _duration The TWAP duration (in seconds)
     * @return the TWAP rate PT/Asset on market (uses 18 decimals of precision)
     */
    function getPtToAssetRate(
        address _market,
        uint32 _duration
    ) external view returns (uint256);

    /**
     * Gets the state of the oracle (whether or not it can be validly accessed now for the given market and duration)
     *
     * @param  _market   The market to check that oracle state for
     * @param  _duration The TWAP duration (in seconds)
     */
    function getOracleState(
        address _market,
        uint32 _duration
    )
        external
        view
        returns (bool increaseCardinalityRequired, uint16 cardinalityRequired, bool oldestObservationSatisfied);
}

// SPDX-License-Identifier: GPL-3.0-or-later
/*

    Copyright 2023 Dolomite

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

pragma solidity ^0.8.9;

import { IBaseRegistry } from "@dolomite-exchange/modules-base/contracts/interfaces/IBaseRegistry.sol";
import { IPendlePtMarket } from "./IPendlePtMarket.sol";
import { IPendlePtOracle } from "./IPendlePtOracle.sol";
import { IPendleRouter } from "./IPendleRouter.sol";
import { IPendleSyToken } from "./IPendleSyToken.sol";


/**
 * @title   IPendleRegistry
 * @author  Dolomite
 *
 * @notice  A registry contract for storing all of the addresses that can interact with the Pendle ecosystem for a PT
 *          asset.
 */
interface IPendleRegistry is IBaseRegistry {

    // ========================================================
    // ======================== Events ========================
    // ========================================================

    event PendleRouterSet(address indexed _pendleRouter);
    event PtMarketSet(address indexed _ptMarket);
    event PtOracleSet(address indexed _ptOracle);
    event SyTokenSet(address indexed _syToken);

    // ========================================================
    // =================== Admin Functions ====================
    // ========================================================

    function ownerSetPendleRouter(address _pendleRouter) external;

    function ownerSetPtMarket(address _ptMarket) external;

    function ownerSetPtOracle(address _ptOracle) external;

    function ownerSetSyToken(address _syToken) external;

    // ========================================================
    // =================== Getter Functions ===================
    // ========================================================

    function pendleRouter() external view returns (IPendleRouter);

    function ptMarket() external view returns (IPendlePtMarket);

    function ptOracle() external view returns (IPendlePtOracle);

    function syToken() external view returns (IPendleSyToken);
}

// SPDX-License-Identifier: GPL-3.0-or-later
/*

    Copyright 2023 Dolomite

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

pragma solidity ^0.8.9;


/**
 * @title   IPendleRouter
 * @author  Dolomite
 *
 * @notice  Router contract for selling ptTokens for underlying assets
 */
interface IPendleRouter {

    struct ApproxParams {
        uint256 guessMin;
        uint256 guessMax;
        /// pass 0 in to skip this variable
        uint256 guessOffchain;
        /// every iteration, the diff between guessMin and guessMax will be divided by 2
        uint256 maxIteration;
        /// the max eps between the returned result & the correct result, base 1e18. Normally this number will be set
        uint256 eps;
        // to 1e15 (1e18/1000 = 0.1%)

        /// Further explanation of the eps. Take swapExactSyForPt for example. To calc the corresponding amount of Pt to
        /// swap out, it's necessary to run an approximation algorithm, because by default there only exists the Pt to
        /// Sy formula
        /// To approx, the 5 values above will have to be provided, and the approx process will run as follows:
        /// mid = (guessMin + guessMax) / 2 // mid here is the current guess of the amount of Pt out
        /// netSyNeed = calcSwapSyForExactPt(mid)
        /// if (netSyNeed > exactSyIn) guessMax = mid - 1 // since the maximum Sy in can't exceed the exactSyIn
        /// else guessMin = mid (1)
        /// For the (1), since netSyNeed <= exactSyIn, the result might be usable. If the netSyNeed is within eps of
        /// exactSyIn (ex eps=0.1% => we have used 99.9% the amount of Sy specified), mid will be chosen as the final
        /// guess result

        /// for guessOffchain, this is to provide a shortcut to guessing. The offchain SDK can precalculate the exact
        /// result before the tx is sent. When the tx reaches the contract, the guessOffchain will be checked first, and
        /// if it satisfies the approximation, it will be used (and save all the guessing). It's expected that this
        /// shortcut will be used in most cases except in cases that there is a trade in the same market right before
        /// the tx
    }

    struct SwapData {
        SwapType swapType;
        address extRouter;
        bytes extCalldata;
        bool needScale;
    }

    enum SwapType {
        NONE,
        KYBERSWAP,
        ONE_INCH,
        // ETH_WETH not used in Aggregator
        ETH_WETH
    }

    struct TokenInput {
        // Token/Sy data
        address tokenIn;
        uint256 netTokenIn;
        address tokenMintSy;
        address bulk;
        // aggregator data
        address pendleSwap;
        SwapData swapData;
    }

    struct TokenOutput {
        // Token/Sy data
        address tokenOut;
        uint256 minTokenOut;
        address tokenRedeemSy;
        address bulk;
        // aggregator data
        address pendleSwap;
        SwapData swapData;
    }

    /**
     * @notice swap (through Kyberswap) from any input token for SY-mintable tokens, then mints SY
     * and swaps said SY for PT
     *
     * @param  input  data for input token, see {`./kyberswap/KyberSwapHelper.sol`}
     * @dev is a combination of `_mintSyFromToken()` and `_swapExactSyForPt()`
     */
    function swapExactTokenForPt(
        address receiver,
        address market,
        uint256 minPtOut,
        ApproxParams calldata guessPtOut,
        TokenInput calldata input
    ) external payable returns (uint256 netPtOut, uint256 netSyFee);

    /**
     * @notice swap from exact amount of PT to SY, then redeem SY for assets, finally swaps
     * resulting assets through Kyberswap to get desired output token
     *
     * @param  receiver      The address to receive output token
     * @param  exactPtIn     There will always consume this much PT for as much SY as possible
     * @param  output        The data for desired output token, see {`./kyberswap/KyberSwapHelper.sol`}
     * @dev This is a combination of `_swapExactPtForSy()` and `_redeemSyToToken()`
     */
    function swapExactPtForToken(
        address receiver,
        address market,
        uint256 exactPtIn,
        TokenOutput calldata output
    ) external returns (uint256 netTokenOut, uint256 netSyFee);

    function swapExactYtForToken(
        address receiver,
        address market,
        uint256 netYtIn,
        TokenOutput calldata output
    ) external returns (uint256 netTokenOut, uint256 netSyFee);

    function swapExactTokenForYt(
        address receiver,
        address market,
        uint256 minYtOut,
        ApproxParams calldata guessYtOut,
        TokenInput calldata input
    ) external payable returns (uint256 netYtOut, uint256 netSyFee);

    function mintPyFromSy(
        address receiver,
        address YT, // solhint-disable-line var-name-mixedcase
        uint256 netSyIn,
        uint256 minPyOut
    ) external returns (uint256 netPyOut);

    function redeemPyToToken(
        address receiver,
        address YT,
        uint256 netPyIn,
        TokenOutput calldata output
    ) external returns (uint256 netTokenOut);
}

// SPDX-License-Identifier: GPL-3.0-or-later
/*

    Copyright 2023 Dolomite

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

pragma solidity ^0.8.9;

import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";


/**
 * @title   IPendleSyToken
 * @author  Dolomite
 *
 * @notice  Interface for interacting with Pendle's standard yield tokens (SYs).
 */
interface IPendleSyToken is IERC20 {

    function pause() external;

    function transferOwnership(
        address newOwner,
        bool direct,
        bool renounce
    ) external;

    function deposit(
        address receiver,
        address tokenIn,
        uint256 amountTokenToDeposit,
        uint256 minSharesOut
    ) external payable returns (uint256 amountSharesOut);

    function paused() external view returns (bool);

    function owner() external view returns (address);

    function getTokensIn() external view returns (address[] memory);
}

Settings
{
  "optimizer": {
    "enabled": true,
    "runs": 200,
    "details": {
      "yul": false
    }
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "libraries": {}
}

Contract Security Audit

Contract ABI

API
[{"inputs":[{"internalType":"address","name":"_pendleRegistry","type":"address"},{"internalType":"address","name":"_ptToken","type":"address"},{"internalType":"address","name":"_borrowPositionProxy","type":"address"},{"internalType":"address","name":"_userVaultImplementation","type":"address"},{"internalType":"address","name":"_dolomiteMargin","type":"address"}],"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":[],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"_pendleRETHRegistry","type":"address"}],"name":"PendleRegistrySet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"tokenConverter","type":"address"},{"indexed":false,"internalType":"bool","name":"isTrusted","type":"bool"}],"name":"TokenConverterSet","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"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"transferCursor","type":"uint256"},{"indexed":false,"internalType":"address","name":"from","type":"address"},{"indexed":false,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"amountWei","type":"uint256"},{"indexed":false,"internalType":"address","name":"vault","type":"address"}],"name":"TransferQueued","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousUserVaultImplementation","type":"address"},{"indexed":true,"internalType":"address","name":"newUserVaultImplementation","type":"address"}],"name":"UserVaultImplementationSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"address","name":"vault","type":"address"}],"name":"VaultCreated","type":"event"},{"inputs":[],"name":"BORROW_POSITION_PROXY","outputs":[{"internalType":"contract IBorrowPositionProxyV2","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"DOLOMITE_MARGIN","outputs":[{"internalType":"contract IDolomiteMargin","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"DOLOMITE_MARGIN_OWNER","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"DOLOMITE_REGISTRY","outputs":[{"internalType":"contract IDolomiteRegistry","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"UNDERLYING_TOKEN","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"allowableCollateralMarketIds","outputs":[{"internalType":"uint256[]","name":"","type":"uint256[]"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"allowableDebtMarketIds","outputs":[{"internalType":"uint256[]","name":"","type":"uint256[]"}],"stateMutability":"pure","type":"function"},{"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":"_account","type":"address"}],"name":"calculateVaultByAccount","outputs":[{"internalType":"address","name":"_vault","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_account","type":"address"}],"name":"createVault","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_toAccountNumber","type":"uint256"},{"internalType":"uint256","name":"_amountWei","type":"uint256"}],"name":"createVaultAndDepositIntoDolomiteMargin","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_toAccountNumber","type":"uint256"},{"internalType":"uint256","name":"_amountWei","type":"uint256"}],"name":"depositIntoDolomiteMargin","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_toAccountNumber","type":"uint256"},{"internalType":"uint256","name":"_otherMarketId","type":"uint256"},{"internalType":"uint256","name":"_amountWei","type":"uint256"}],"name":"depositOtherTokenIntoDolomiteMarginForVaultOwner","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_vault","type":"address"},{"internalType":"uint256","name":"_amountWei","type":"uint256"}],"name":"enqueueTransferFromDolomiteMargin","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_vault","type":"address"},{"internalType":"uint256","name":"_amountWei","type":"uint256"}],"name":"enqueueTransferIntoDolomiteMargin","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_vault","type":"address"}],"name":"getAccountByVault","outputs":[{"internalType":"address","name":"_account","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getProxyVaultInitCodeHash","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"uint256","name":"_transferCursor","type":"uint256"}],"name":"getQueuedTransferByCursor","outputs":[{"components":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"address","name":"vault","type":"address"},{"internalType":"bool","name":"isExecuted","type":"bool"}],"internalType":"struct IIsolationModeVaultFactory.QueuedTransfer","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_account","type":"address"}],"name":"getVaultByAccount","outputs":[{"internalType":"address","name":"_vault","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"isInitialized","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"isIsolationAsset","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"address","name":"_tokenConverter","type":"address"}],"name":"isTokenConverterTrusted","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"marketId","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address[]","name":"_tokenConverters","type":"address[]"}],"name":"ownerInitialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_tokenConverter","type":"address"},{"internalType":"bool","name":"_isTrusted","type":"bool"}],"name":"ownerSetIsTokenConverterTrusted","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_pendleRegistry","type":"address"}],"name":"ownerSetPendleRegistry","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_userVaultImplementation","type":"address"}],"name":"ownerSetUserVaultImplementation","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"pendleRegistry","outputs":[{"internalType":"contract IPendleRegistry","name":"","type":"address"}],"stateMutability":"view","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":[],"name":"transferCursor","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","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"},{"inputs":[],"name":"userVaultImplementation","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_fromAccountNumber","type":"uint256"},{"internalType":"uint256","name":"_amountWei","type":"uint256"}],"name":"withdrawFromDolomiteMargin","outputs":[],"stateMutability":"nonpayable","type":"function"}]

6101006040523480156200001257600080fd5b5060405162006641380380620066418339810160408190526200003591620009a2565b838383876001600160a01b031663bd12584f6040518163ffffffff1660e01b815260040160206040518083038186803b1580156200007257600080fd5b505afa15801562000087573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620000ad919062000a4b565b84846001600160a01b03166306fdde036040518163ffffffff1660e01b815260040160006040518083038186803b158015620000e857600080fd5b505afa158015620000fd573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405262000127919081019062000ba5565b60405160200162000139919062000c0a565b604051602081830303815290604052856001600160a01b03166395d89b416040518163ffffffff1660e01b815260040160006040518083038186803b1580156200018257600080fd5b505afa15801562000197573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052620001c1919081019062000ba5565b604051602001620001d3919062000c42565b604051602081830303815290604052866001600160a01b031663313ce5676040518163ffffffff1660e01b815260040160206040518083038186803b1580156200021c57600080fd5b505afa15801562000231573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062000257919062000c6c565b6001600160a01b03841660805262000271838383620002eb565b5050506001600160a01b0380831660e05285811660a05284811660c0526005805491851661010002610100600160a81b0319909216919091179055620002b961dead6200032f565b5050600c80546001600160a01b0319166001600160a01b039a909a16999099179098555062000f809650505050505050565b825162000300906003906020860190620008b5565b50815162000316906004906020850190620008b5565b506005805460ff191660ff929092169190911790555050565b60006200039160006001600160a01b0316836001600160a01b031614157f49736f6c6174696f6e4d6f64655661756c74466163746f7279000000000000006e125b9d985b1a59081858d8dbdd5b9d608a1b6200053260201b6200152d1760201c565b6001600160a01b038281166000908152600a602090815260409091205462000409921615907f49736f6c6174696f6e4d6f64655661756c74466163746f727900000000000000907f5661756c7420616c726561647920657869737473000000000000000000000000906200152d62000532821b17901c565b60006200047160008460405160200162000424919062000cc6565b60405160208183030381529060405280519060200120604051806020016200044c9062000944565b6020820181038252601f19601f820116604052506200059e60201b620015941760201c565b90506001600160a01b0381166200048c576200048c62000cdd565b826001600160a01b03167f5d9c31ffa0fecffd7cf379989a3c7af252f0335e0d2a1320b55245912c781f5382604051620004c7919062000cfe565b60405180910390a26001600160a01b03808216600081815260096020908152604080832080549589166001600160a01b03199687168117909155808452600a909252909120805490931690911790915561dead146200052c576200052c83826200061f565b92915050565b8262000599576200054382620007f6565b6101d160f51b6200055483620007f6565b604051602001620005689392919062000d1f565b60408051601f198184030181529082905262461bcd60e51b8252620005909160040162000d8b565b60405180910390fd5b505050565b600083471015620005c35760405162461bcd60e51b8152600401620005909062000dd5565b8151620005e45760405162461bcd60e51b8152600401620005909062000e1a565b8282516020840186f590506001600160a01b038116620006185760405162461bcd60e51b8152600401620005909062000e61565b9392505050565b6001600160a01b038216158015906200064057506001600160a01b03811615155b6200064f576200064f62000cdd565b60405163189acdbd60e31b81526001600160a01b0382169063c4d66de8906200067d90859060040162000cfe565b600060405180830381600087803b1580156200069857600080fd5b505af1158015620006ad573d6000803e3d6000fd5b5050505060c0516001600160a01b031663f697ae998260016040518363ffffffff1660e01b8152600401620006e492919062000e7c565b600060405180830381600087803b158015620006ff57600080fd5b505af115801562000714573d6000803e3d6000fd5b5050505060e0516001600160a01b031663f68ebbbd6040518163ffffffff1660e01b815260040160206040518083038186803b1580156200075457600080fd5b505afa15801562000769573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906200078f919062000a4b565b6001600160a01b03166305c4fdf983836040518363ffffffff1660e01b8152600401620007be92919062000e9b565b600060405180830381600087803b158015620007d957600080fd5b505af1158015620007ee573d6000803e3d6000fd5b505050505050565b60606000826040516020016200080d919062000ec1565b60408051601f19818403018152919052905060205b80156200089a5780620008358162000eee565b9150508181815181106200084d576200084d62000f08565b01602001517fff000000000000000000000000000000000000000000000000000000000000001615620008945760006200088982600162000f1e565b835250909392505050565b62000822565b5060408051600080825260208201909252905b509392505050565b828054620008c39062000f4f565b90600052602060002090601f016020900481019282620008e7576000855562000932565b82601f106200090257805160ff191683800117855562000932565b8280016001018555821562000932579182015b828111156200093257825182559160200191906001019062000915565b506200094092915062000952565b5090565b610b2e8062005b1383390190565b5b8082111562000940576000815560010162000953565b60006001600160a01b0382166200052c565b620009868162000969565b81146200099257600080fd5b50565b80516200052c816200097b565b600080600080600060a08688031215620009bf57620009bf600080fd5b6000620009cd888862000995565b9550506020620009e08882890162000995565b9450506040620009f38882890162000995565b935050606062000a068882890162000995565b925050608062000a198882890162000995565b9150509295509295909350565b60006200052c8262000969565b620009868162000a26565b80516200052c8162000a33565b60006020828403121562000a625762000a62600080fd5b600062000a70848462000a3e565b949350505050565b634e487b7160e01b600052604160045260246000fd5b601f19601f83011681018181106001600160401b038211171562000ab65762000ab662000a78565b6040525050565b600062000ac960405190565b905062000ad7828262000a8e565b919050565b60006001600160401b0382111562000af85762000af862000a78565b601f19601f83011660200192915050565b60005b8381101562000b2657818101518382015260200162000b0c565b8381111562000b36576000848401525b50505050565b600062000b5362000b4d8462000adc565b62000abd565b90508281526020810184848401111562000b705762000b70600080fd5b620008ad84828562000b09565b600082601f83011262000b935762000b93600080fd5b815162000a7084826020860162000b3c565b60006020828403121562000bbc5762000bbc600080fd5b81516001600160401b0381111562000bd75762000bd7600080fd5b62000a708482850162000b7d565b600062000bf0825190565b62000c0081856020860162000b09565b9290920192915050565b7f446f6c6f6d6974652049736f6c6174696f6e3a2000000000000000000000000081526000601482015b915062000618828462000be5565b601960fa1b815260006001820162000c34565b60ff811662000986565b80516200052c8162000c55565b60006020828403121562000c835762000c83600080fd5b600062000a70848462000c5f565b60006200052c8260601b90565b60006200052c8262000c91565b62000cc062000cba8262000969565b62000c9e565b82525050565b600062000cd4828462000cab565b50601401919050565b634e487b7160e01b600052600160045260246000fd5b62000cc08162000969565b602081016200052c828462000cf3565b6001600160f01b0319811662000cc0565b600062000d2d828662000be5565b915062000d3b828562000d0e565b60028201915062000d4d828462000be5565b95945050505050565b600062000d61825190565b80845260208401935062000d7a81856020860162000b09565b601f01601f19169290920192915050565b6020808252810162000618818462000d56565b601d81526000602082017f437265617465323a20696e73756666696369656e742062616c616e6365000000815291505b5060200190565b602080825281016200052c8162000d9e565b60208082527f437265617465323a2062797465636f6465206c656e677468206973207a65726f9101908152600062000dce565b602080825281016200052c8162000de7565b601981526000602082017f437265617465323a204661696c6564206f6e206465706c6f79000000000000008152915062000dce565b602080825281016200052c8162000e2c565b80151562000cc0565b6040810162000e8c828562000cf3565b62000618602083018462000e73565b6040810162000eab828562000cf3565b62000618602083018462000cf3565b8062000cc0565b600062000ecf828462000eba565b50602001919050565b634e487b7160e01b600052601160045260246000fd5b60008162000f005762000f0062000ed8565b506000190190565b634e487b7160e01b600052603260045260246000fd5b6000821982111562000f345762000f3462000ed8565b500190565b634e487b7160e01b600052602260045260246000fd5b60028104600182168062000f6457607f821691505b6020821081141562000f7a5762000f7a62000f39565b50919050565b60805160a05160c05160e051614ae96200102a6000396000818161060c01526118410152600081816103fa01526117cf015260006103d201526000818161032d0152818161083d015281816108e901528181610d8d01528181610e6a01528181610e9701528181610fa30152818161106e015281816112a0015281816112ce0152818161146101528181611a4b01528181611b3b015281816121ca015261223d0152614ae96000f3fe60806040523480156200001157600080fd5b50600436106200026d5760003560e01c80635b7490541162000155578063b01f61e111620000c7578063cbffd9211162000086578063cbffd921146200062e578063d143d5911462000638578063d3f5f0621462000642578063dd62ed3e146200064c578063ed4e3a35146200068857600080fd5b8063b01f61e1146200057a578063b4bd6f4614620005a9578063bc08373214620005c0578063c1090d5a14620005ef578063c6d20c85146200060657600080fd5b806389c32efb116200011457806389c32efb146200027257806395b5b196146200052957806395d89b411462000540578063a6e7d83f146200054a578063a9059cbb146200056357600080fd5b80635b749054146200049f5780636ed71ede14620004b657806370a0823114620004c057806372dcf67914620004ec578063816bbc2e146200050357600080fd5b806323b872dd11620001ef578063392e53cd11620001ae578063392e53cd14620004315780633c939dc11462000446578063516885be146200045d57806353769bbf146200047457806354441311146200048857600080fd5b806323b872dd146200039e578063260fa1a114620003b557806329db1be614620003cc5780632ee3d92f14620003f4578063313ce567146200041c57600080fd5b80630a3ee461116200023c5780630a3ee46114620002fb5780630d97c9fa146200031457806315c14a4a146200032b57806316774ba0146200035c57806318160ddd146200038b57600080fd5b8063037ec8c8146200027257806306fdde031462000296578063095ea7b314620002af57806309da2c5414620002d5575b600080fd5b604080516000815260208101918290526200028d9162002fd1565b60405180910390f35b620002a062000690565b6040516200028d919062003048565b620002c6620002c0366004620030a8565b6200072a565b6040516200028d9190620030f4565b620002ec620002e636600462003104565b62000746565b6040516200028d91906200313c565b620003126200030c366004620031a4565b62000785565b005b620003126200032536600462003208565b62000a89565b7f00000000000000000000000000000000000000000000000000000000000000005b6040516200028d919062003266565b620002c66200036d36600462003104565b6001600160a01b03166000908152600b602052604090205460ff1690565b6002545b6040516200028d919062003276565b620002c6620003af36600462003286565b62000adf565b62000312620003c636600462003104565b62000b09565b620002ec7f000000000000000000000000000000000000000000000000000000000000000081565b6200034d7f000000000000000000000000000000000000000000000000000000000000000081565b60055460ff166040516200028d9190620032e8565b600554620002c690600160a81b900460ff1681565b6200031262000457366004620032f8565b62000b71565b620003126200046e36600462003333565b62000e1a565b600c546200034d906001600160a01b031681565b6200031262000499366004620030a8565b62000f01565b62000312620004b0366004620030a8565b62000fcb565b6200038f60065481565b6200038f620004d136600462003104565b6001600160a01b031660009081526020819052604090205490565b62000312620004fd36600462003104565b62001095565b6200051a6200051436600462003359565b62001181565b6040516200028d9190620033e5565b620003126200053a36600462003333565b62001251565b620002a062001334565b600554620002ec9061010090046001600160a01b031681565b620002c662000574366004620030a8565b62001345565b620002ec6200058b36600462003104565b6001600160a01b039081166000908152600a60205260409020541690565b620002ec620005ba36600462003104565b62001355565b620002ec620005d136600462003104565b6001600160a01b039081166000908152600960205260409020541690565b620002ec6200060036600462003333565b620013a3565b6200034d7f000000000000000000000000000000000000000000000000000000000000000081565b620002ec6200145d565b6200038f60075481565b6200038f620014f9565b6200038f6200065d366004620033f5565b6001600160a01b03918216600090815260016020908152604080832093909416825291909152205490565b6001620002c6565b606060038054620006a1906200345a565b80601f0160208091040260200160405190810160405280929190818152602001828054620006cf906200345a565b8015620007205780601f10620006f45761010080835404028352916020019162000720565b820191906000526020600020905b8154815290600101906020018083116200070257829003601f168201915b5050505050905090565b6000336200073a8185856200160e565b60019150505b92915050565b600062000740826040516020016200075f9190620034ba565b604051602081830303815290604052805190602001206200077f620014f9565b620016ca565b33620007e6620007946200145d565b6001600160a01b0316826001600160a01b0316147127b7363ca237b637b6b4ba32a6b0b933b4b760711b7f43616c6c6572206973206e6f74206f776e6572206f6620446f6c6f6d6974650084620016d9565b6005546200082690600160a81b900460ff161560008051602062004a9483398151915272105b1c9958591e481a5b9a5d1a585b1a5e9959606a1b6200152d565b604051638fae3be160e01b81526001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001690638fae3be190620008749030906004016200313c565b60206040518083038186803b1580156200088d57600080fd5b505afa158015620008a2573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620008c89190620034de565b60068190556040516316b1f45f60e21b8152620009a9916001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001691635ac7d17c916200091e9160040162003276565b60206040518083038186803b1580156200093757600080fd5b505afa1580156200094c573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062000972919062003510565b60008051602062004a948339815191527f4d61726b65742063616e6e6f7420616c6c6f7720626f72726f77696e670000006200152d565b61dead6000819052600a6020527f20677881080440a9b3c87e826370bb5d9c2f74efd4dede686d52d77a6a09f8bb54620009ed91906001600160a01b031662001728565b60005b8281101562000a465762000a3184848381811062000a125762000a1262003535565b905060200201602081019062000a29919062003104565b60016200193b565b8062000a3d8162003561565b915050620009f0565b506005805460ff60a81b1916600160a81b1790556040517f5daa87a0e9463431830481fd4b6e3403442dfb9a12b9c07597e9f61d50b633c890600090a15b505050565b60055462000ac490600160a81b900460ff1660008051602062004a948339815191526e139bdd081a5b9a5d1a585b1a5e9959608a1b6200152d565b3362000ad3620007946200145d565b62000a8483836200193b565b60003362000aef858285620019e4565b62000afc85858562001a3c565b60019150505b9392505050565b3362000b18620007946200145d565b600c80546001600160a01b0319166001600160a01b0384161790556040517fe06bb3aa40c10f71cf0e0dc17d6f449f6efbc87668e14dc51db81ea21827655b9062000b659084906200313c565b60405180910390a15050565b3360008181526009602052604090205462000bb9906001600160a01b0316151560008051602062004a948339815191526c125b9d985b1a59081d985d5b1d609a1b84620016d9565b62000bec60065484141560008051602062004a948339815191526d125b9d985b1a59081b585c9ad95d60921b8662001f9c565b60408051600280825260608201909252600091816020015b604080518082019091526000808252602082015281526020019060019003908162000c045790505090506040518060400160405280336001600160a01b0316815260200160008152508160008151811062000c635762000c6362003535565b6020908102919091018101919091526040805180820182523360009081526009845291909120546001600160a01b0316815290810186905281518290600190811062000cb35762000cb362003535565b602090810291909101015260408051600280825260608201909252600091816020015b62000ce062002ee0565b81526020019060019003908162000cd657505060408051608081019091526001815290915062000d2a90600090879060208101838152602001600081526020018890523362001fcf565b8160008151811062000d405762000d4062003535565b602002602001018190525062000d666000600187600062000d6060001990565b6200203a565b8160018151811062000d7c5762000d7c62003535565b602002602001018190525062000daf7f000000000000000000000000000000000000000000000000000000000000000090565b6001600160a01b031663a67a6a4583836040518363ffffffff1660e01b815260040162000dde92919062003802565b600060405180830381600087803b15801562000df957600080fd5b505af115801562000e0e573d6000803e3d6000fd5b50505050505050505050565b3360008181526009602052604090205462000e62906001600160a01b0316151560008051602062004a948339815191526c125b9d985b1a59081d985d5b1d609a1b84620016d9565b3362000e91817f000000000000000000000000000000000000000000000000000000000000000085846200215c565b62000efb7f000000000000000000000000000000000000000000000000000000000000000082838760065460405180608001604052806001151581526020016000600181111562000ee65762000ee66200357f565b8152602001600081526020018a905262002388565b50505050565b336000818152600b602052604090205462000f519060ff1660008051602062004a948339815191527f43616c6c6572206973206e6f74206120746f6b656e20636f6e7665727465720084620016d9565b6001600160a01b03808416600090815260096020526040902054849162000f9d9116151560008051602062004a948339815191526c125b9d985b1a59081d985d5b1d609a1b84620016d9565b62000efb7f00000000000000000000000000000000000000000000000000000000000000003385876200215c565b336000818152600b60205260409020546200101b9060ff1660008051602062004a948339815191527f43616c6c6572206973206e6f74206120746f6b656e20636f6e7665727465720084620016d9565b6001600160a01b038084166000908152600960205260409020548491620010679116151560008051602062004a948339815191526c125b9d985b1a59081d985d5b1d609a1b84620016d9565b62000efb337f000000000000000000000000000000000000000000000000000000000000000085876200215c565b600554620010d090600160a81b900460ff1660008051602062004a948339815191526e139bdd081a5b9a5d1a585b1a5e9959608a1b6200152d565b33620010df620007946200145d565b620011266001600160a01b038316151560008051602062004a948339815191527f496e76616c6964207573657220696d706c656d656e746174696f6e00000000006200152d565b600580546001600160a01b03848116610100818102610100600160a81b031985161790945560405193909204169182907fdc5a954098cef71f25bbe48bbd58cd5866495daacabf32492424363af66dd01890600090a3505050565b6040805160a081018252600080825260208201819052918101829052606081018290526080810191909152620011ed60075483111560008051602062004a948339815191527f496e76616c6964207472616e7366657220637572736f720000000000000000006200152d565b50600090815260086020908152604091829020825160a08101845281546001600160a01b0390811682526001830154811693820193909352600282015493810193909352600301549081166060830152600160a01b900460ff161515608082015290565b3360008181526009602052604090205462001299906001600160a01b0316151560008051602062004a948339815191526c125b9d985b1a59081d985d5b1d609a1b84620016d9565b33620012c87f00000000000000000000000000000000000000000000000000000000000000008285846200215c565b62000efb7f00000000000000000000000000000000000000000000000000000000000000008286846006546040518060800160405280600015158152602001600060018111156200131d576200131d6200357f565b8152602001600081526020018a90526001620024dd565b606060048054620006a1906200345a565b6000336200073a81858562001a3c565b6005546000906200139390600160a81b900460ff1660008051602062004a948339815191526e139bdd081a5b9a5d1a585b1a5e9959608a1b6200152d565b6200074082620026a8565b919050565b600554600090620013e190600160a81b900460ff1660008051602062004a948339815191526e139bdd081a5b9a5d1a585b1a5e9959608a1b6200152d565b6000620013ee33620026a8565b604051637d49eb4d60e11b81529091506001600160a01b0382169063fa93d69a906200142190879087906004016200382b565b600060405180830381600087803b1580156200143c57600080fd5b505af115801562001451573d6000803e3d6000fd5b50929695505050505050565b60007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316638da5cb5b6040518163ffffffff1660e01b815260040160206040518083038186803b158015620014b957600080fd5b505afa158015620014ce573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620014f4919062003857565b905090565b6000604051806020016200150d9062002f57565b6020820181038252601f19601f8201166040525080519060200120905090565b8262000a84576200153e8262002849565b6101d160f51b6200154f8362002849565b6040516020016200156393929190620038b2565b60408051601f198184030181529082905262461bcd60e51b82526200158b9160040162003048565b60405180910390fd5b600083471015620015b95760405162461bcd60e51b81526004016200158b9062003917565b8151620015da5760405162461bcd60e51b81526004016200158b906200395c565b8282516020840186f590506001600160a01b03811662000b025760405162461bcd60e51b81526004016200158b90620039a3565b6001600160a01b038316620016375760405162461bcd60e51b81526004016200158b90620039f9565b6001600160a01b038216620016605760405162461bcd60e51b81526004016200158b9062003a4b565b6001600160a01b0380841660008181526001602090815260408083209487168084529490915290819020849055517f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92590620016bd90859062003276565b60405180910390a3505050565b600062000b02838330620028f0565b8362000efb57620016ea8362002849565b6101d160f51b620016fb8462002849565b61080f60f21b6200170c8562002919565b60405162001563959493929190601f60f91b9060200162003a6e565b6001600160a01b038216158015906200174957506001600160a01b03811615155b62001758576200175862003ad8565b60405163189acdbd60e31b81526001600160a01b0382169063c4d66de890620017869085906004016200313c565b600060405180830381600087803b158015620017a157600080fd5b505af1158015620017b6573d6000803e3d6000fd5b505060405163f697ae9960e01b81526001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016925063f697ae9991506200180b90849060019060040162003aee565b600060405180830381600087803b1580156200182657600080fd5b505af11580156200183b573d6000803e3d6000fd5b505050507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663f68ebbbd6040518163ffffffff1660e01b815260040160206040518083038186803b1580156200189957600080fd5b505afa158015620018ae573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620018d4919062003b25565b6001600160a01b03166305c4fdf983836040518363ffffffff1660e01b81526004016200190392919062003b4a565b600060405180830381600087803b1580156200191e57600080fd5b505af115801562001933573d6000803e3d6000fd5b505050505050565b620019826001600160a01b038316151560008051602062004a948339815191527f496e76616c696420746f6b656e20636f6e7665727465720000000000000000006200152d565b6001600160a01b0382166000818152600b602052604090819020805460ff1916841515179055517f1a2aaf8fb443c30344ac3e041f678060eb802aa3e68057d31682b9909d5693a490620019d8908490620030f4565b60405180910390a25050565b6001600160a01b038381166000908152600160209081526040808320938616835292905220548181101562001a2d5760405162461bcd60e51b81526004016200158b9062003b9e565b62000efb84848484036200160e565b3362001aab6001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001682147127b7363ca237b637b6b4ba32a6b0b933b4b760711b7f4f6e6c7920446f6c6f6d6974652063616e2063616c6c2066756e6374696f6e0084620016d9565b62001af26001600160a01b038516151560008051602062004a948339815191527f5472616e736665722066726f6d20746865207a65726f206164647265737300006200152d565b62001b396001600160a01b038416151560008051602062004a948339815191527f5472616e7366657220746f20746865207a65726f2061646472657373000000006200152d565b7f000000000000000000000000000000000000000000000000000000000000000062001bc16001600160a01b03868116908316148062001b8a5750816001600160a01b0316856001600160a01b0316145b60008051602062004a948339815191527f66726f6d2f746f206d75737420657120446f6c6f6d6974654d617267696e00006200152d565b600754600081815260086020908152604091829020825160a08101845281546001600160a01b0390811680835260018401548216948301949094526002830154948201949094526003909101548084166060830152600160a01b900460ff16151560808201529162001cc59190891614801562001c535750866001600160a01b031682602001516001600160a01b0316145b801562001c635750858260400151145b801562001c8e575060608201516001600160a01b039081166000908152600960205260409020541615155b60008051602062004a948339815191527f496e76616c696420717565756564207472616e736665720000000000000000006200152d565b62001d0781608001511560008051602062004a948339815191527f5472616e7366657220616c7265616479206578656375746564000000000000008562001f9c565b6000828152600860205260409020600301805460ff60a01b1916600160a01b1790556001600160a01b03868116908416141562001e6b576001600160a01b038088166000908152600960205260409020541662001dcc811580159062001d82575082606001516001600160a01b0316896001600160a01b0316145b8062001da657506001600160a01b0389166000908152600b602052604090205460ff165b60008051602062004a948339815191526b496e76616c69642066726f6d60a01b6200152d565b81606001516001600160a01b0316638ddab4e560006001600160a01b0316836001600160a01b0316141562001e02578962001e04565b825b886040518363ffffffff1660e01b815260040162001e2492919062003bb0565b600060405180830381600087803b15801562001e3f57600080fd5b505af115801562001e54573d6000803e3d6000fd5b5050505062001e64878762002a79565b5062001f93565b826001600160a01b0316876001600160a01b03161462001e8f5762001e8f62003ad8565b6001600160a01b038087166000908152600960205260409020541662001ef98115158062001ed557506001600160a01b0388166000908152600b602052604090205460ff165b60008051602062004a9483398151915269496e76616c696420746f60b01b6200152d565b81606001516001600160a01b031663797b512560006001600160a01b0316836001600160a01b0316141562001f2f578862001f31565b825b886040518363ffffffff1660e01b815260040162001f5192919062003bb0565b600060405180830381600087803b15801562001f6c57600080fd5b505af115801562001f81573d6000803e3d6000fd5b5050505062001f91888762002b16565b505b50505050505050565b8362000efb5762001fad8362002849565b6101d160f51b62001fbe8462002849565b61080f60f21b6200170c8562002bd5565b62001fd962002ee0565b6040805161010081019091528060005b815260200186815260200184815260200185815260200160008152602001836001600160a01b0316815260200160008152602001604051806020016040528060008152508152509050949350505050565b6200204462002ee0565b62002071604080516080810190915260008082526020820190815260200160008152602001600081525090565b600019831415620020be576040518060800160405280600015158152602001856001811115620020a557620020a56200357f565b81526020016001815260200160008152509050620020f9565b6040518060800160405280600015158152602001856001811115620020e757620020e76200357f565b81526020016000815260200184905290505b60408051610100810190915280600281526020018881526020018281526020018681526020016000815260200160006001600160a01b03168152602001878152602001604051806020016040528060008152508152509150505b95945050505050565b600754600090815260086020908152604091829020825160a08101845281546001600160a01b0390811682526001830154811693820193909352600282015493810193909352600301549081166060830152600160a01b900460ff16158015608083018190526200220257507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031681602001516001600160a01b0316145b156200221e576200221e8160600151826020015160006200160e565b816001600160a01b0316856001600160a01b03161480156200227157507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316846001600160a01b0316145b156200228457620022848285856200160e565b60016007600082825462002299919062003bc0565b90915550506040805160a0810182526001600160a01b038088168252868116602080840191825283850188815287841660608601908152600060808701818152600780548352600890955290889020965187549087166001600160a01b03199182161788559451600188018054918816919096161790945590516002860155516003909401805492511515600160a01b026001600160a81b031990931694909316939093171790555490517f41f436ede2f45a36c2a15333e202b31f7040c914a78d7eb62d6f7caa6414a756906200237990889088908890889062003bdb565b60405180910390a25050505050565b604080516001808252818301909252600091816020015b60408051808201909152600080825260208201528152602001906001900390816200239f5790505090506040518060400160405280876001600160a01b031681526020018581525081600081518110620023fd57620023fd62003535565b6020908102919091010152604080516001808252818301909252600091816020015b6200242962002ee0565b8152602001906001900390816200241f5790505090506200244e600085858962001fcf565b8160008151811062002464576200246462003535565b602090810291909101015260405163a67a6a4560e01b81526001600160a01b0389169063a67a6a45906200249f908590859060040162003802565b600060405180830381600087803b158015620024ba57600080fd5b505af1158015620024cf573d6000803e3d6000fd5b505050505050505050505050565b604080516001808252818301909252600091816020015b6040805180820190915260008082526020820152815260200190600190039081620024f45790505090506040518060400160405280886001600160a01b03168152602001878152508160008151811062002552576200255262003535565b6020908102919091010152604080516001808252818301909252600091816020015b6200257e62002ee0565b81526020019060019003908162002574579050509050620025a3600086868962002cf9565b81600081518110620025b957620025b962003535565b602090810291909101015260405163a67a6a4560e01b81526001600160a01b038a169063a67a6a4590620025f4908590859060040162003802565b600060405180830381600087803b1580156200260f57600080fd5b505af115801562002624573d6000803e3d6000fd5b506000925062002632915050565b8360038111156200264757620026476200357f565b148062002668575060018360038111156200266657620026666200357f565b145b156200269d576200269d898360008151811062002689576200268962003535565b602002602001015160000151898862002d18565b505050505050505050565b6000620026e36001600160a01b038316151560008051602062004a948339815191526e125b9d985b1a59081858d8dbdd5b9d608a1b6200152d565b6001600160a01b038281166000908152600a60205260409020546200273291161560008051602062004a94833981519152735661756c7420616c72656164792065786973747360601b6200152d565b60006200278e6000846040516020016200274d9190620034ba565b6040516020818303038152906040528051906020012060405180602001620027759062002f57565b601f1982820381018352601f9091011660405262001594565b90506001600160a01b038116620027a957620027a962003ad8565b826001600160a01b03167f5d9c31ffa0fecffd7cf379989a3c7af252f0335e0d2a1320b55245912c781f5382604051620027e491906200313c565b60405180910390a26001600160a01b03808216600081815260096020908152604080832080549589166001600160a01b03199687168117909155808452600a909252909120805490931690911790915561dead14620007405762000740838262001728565b606060008260405160200162002860919062003c1f565b60408051601f19818403018152919052905060205b8015620028d55780620028888162003c36565b915050818181518110620028a057620028a062003535565b01602001516001600160f81b03191615620028cf576000620028c482600162003bc0565b835250909392505050565b62002875565b5060408051600080825260208201909252905b509392505050565b6000604051836040820152846020820152828152600b810160ff81536055902095945050505050565b60408051602a80825260608281019093526001600160a01b03841691600091602082018180368337019050509050603060f81b8160008151811062002962576200296262003535565b60200101906001600160f81b031916908160001a905350607860f81b8160018151811062002994576200299462003535565b60200101906001600160f81b031916908160001a90535060005b6014811015620028e8576000620029c782600262003c50565b9050620029d7600f851662002e1c565b83620029e583602962003c72565b81518110620029f857620029f862003535565b60200101906001600160f81b031916908160001a905350600484901c935062002a24600f851662002e1c565b8362002a3283602862003c72565b8151811062002a455762002a4562003535565b60200101906001600160f81b031916908160001a9053505060049290921c918062002a708162003561565b915050620029ae565b6001600160a01b03821662002aa25760405162461bcd60e51b81526004016200158b9062003cc1565b806002600082825462002ab6919062003bc0565b90915550506001600160a01b038216600081815260208190526040808220805485019055517fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9062002b0a90859062003276565b60405180910390a35050565b6001600160a01b03821662002b3f5760405162461bcd60e51b81526004016200158b9062003d12565b6001600160a01b0382166000908152602081905260409020548181101562002b7b5760405162461bcd60e51b81526004016200158b9062003d64565b6001600160a01b0383166000818152602081905260408082208585039055600280548690039055519091907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef90620016bd90869062003276565b60608162002bfa5750506040805180820190915260018152600360fc1b602082015290565b8160005b811562002c2a578062002c118162003561565b915062002c229050600a8362003d8c565b915062002bfe565b60008167ffffffffffffffff81111562002c485762002c486200342e565b6040519080825280601f01601f19166020018201604052801562002c73576020820181803683370190505b508593509050815b801562002cf0578062002c8e8162003c36565b915062002c9f9050600a8562003da3565b62002cac90603062003bc0565b60f81b82828151811062002cc45762002cc462003535565b60200101906001600160f81b031916908160001a90535062002ce8600a8562003d8c565b935062002c7b565b50949350505050565b62002d0362002ee0565b60408051610100810190915280600162001fe9565b6040805180820182526001600160a01b0380861682526020820185905291516311f46d4f60e21b81529091600091908716906347d1b53c9062002d62908590879060040162003dba565b604080518083038186803b15801562002d7a57600080fd5b505afa15801562002d8f573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062002db5919062003e92565b90506200193362002dc68262002e4b565b8062002ddd575060208201516001600160801b0316155b7020b1b1b7bab73a2130b630b731b2a634b160791b7f6163636f756e742063616e6e6f7420676f206e6567617469766500000000000088888862002e6b565b6000600a82101562002e3e5762002e3560308362003bc0565b60f81b92915050565b62002e3560578362003bc0565b8051600090801562000740575050602001516001600160801b0316151590565b85620019335762002e7c8562002849565b6101d160f51b62002e8d8662002849565b61080f60f21b62002e9e8762002919565b61016160f51b62002eaf8862002bd5565b61016160f51b62002ec08962002bd5565b6040516200156399989796959493929190601f60f91b9060200162003eb7565b60408051610100810182526000808252602082015290810162002f25604080516080810190915260008082526020820190815260200160008152602001600081525090565b8152602001600081526020016000815260200160006001600160a01b0316815260200160008152602001606081525090565b610b2e8062003f6683390190565b805b82525050565b600062002f7b838362002f65565b505060200190565b600062002f8e825190565b80845260209384019383018060005b8381101562002fc657815162002fb4888262002f6d565b97506020830192505060010162002f9d565b509495945050505050565b6020808252810162000b02818462002f83565b60005b838110156200300157818101518382015260200162002fe7565b8381111562000efb5750506000910152565b60006200301e825190565b8084526020840193506200303781856020860162002fe4565b601f01601f19169290920192915050565b6020808252810162000b02818462003013565b60006001600160a01b03821662000740565b62003078816200305b565b81146200308457600080fd5b50565b803562000740816200306d565b8062003078565b8035620007408162003094565b60008060408385031215620030c057620030c0600080fd5b6000620030ce858562003087565b9250506020620030e1858286016200309b565b9150509250929050565b80151562002f67565b60208101620007408284620030eb565b6000602082840312156200311b576200311b600080fd5b600062003129848462003087565b949350505050565b62002f67816200305b565b6020810162000740828462003131565b60008083601f840112620031635762003163600080fd5b50813567ffffffffffffffff811115620031805762003180600080fd5b6020830191508360208202830111156200319d576200319d600080fd5b9250929050565b60008060208385031215620031bc57620031bc600080fd5b823567ffffffffffffffff811115620031d857620031d8600080fd5b620031e6858286016200314c565b92509250509250929050565b80151562003078565b80356200074081620031f2565b60008060408385031215620032205762003220600080fd5b60006200322e858562003087565b9250506020620030e185828601620031fb565b600062000740826200305b565b6000620007408262003241565b62002f67816200324e565b602081016200074082846200325b565b6020810162000740828462002f65565b600080600060608486031215620032a057620032a0600080fd5b6000620032ae868662003087565b9350506020620032c18682870162003087565b9250506040620032d4868287016200309b565b9150509250925092565b60ff811662002f67565b60208101620007408284620032de565b600080600060608486031215620033125762003312600080fd5b60006200332086866200309b565b9350506020620032c1868287016200309b565b600080604083850312156200334b576200334b600080fd5b6000620030ce85856200309b565b600060208284031215620033705762003370600080fd5b60006200312984846200309b565b805160a083019062003391848262003131565b506020820151620033a6602085018262003131565b506040820151620033bb604085018262002f65565b506060820151620033d0606085018262003131565b50608082015162000efb6080850182620030eb565b60a081016200074082846200337e565b600080604083850312156200340d576200340d600080fd5b60006200341b858562003087565b9250506020620030e18582860162003087565b634e487b7160e01b600052604160045260246000fd5b634e487b7160e01b600052602260045260246000fd5b6002810460018216806200346f57607f821691505b6020821081141562003485576200348562003444565b50919050565b6000620007408260601b90565b600062000740826200348b565b62002f67620034b4826200305b565b62003498565b6000620034c88284620034a5565b50601401919050565b8051620007408162003094565b600060208284031215620034f557620034f5600080fd5b6000620031298484620034d1565b80516200074081620031f2565b600060208284031215620035275762003527600080fd5b600062003129848462003503565b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052601160045260246000fd5b60006000198214156200357857620035786200354b565b5060010190565b634e487b7160e01b600052602160045260246000fd5b80516040830190620035a8848262003131565b50602082015162000efb602085018262002f65565b6000620035cb838362003595565b505060400190565b6000620035de825190565b80845260209384019383018060005b8381101562002fc6578151620036048882620035bd565b975060208301925050600101620035ed565b600981106200308457620030846200357f565b806200139e8162003616565b6000620007408262003629565b62002f678162003635565b600281106200308457620030846200357f565b806200139e816200364d565b6000620007408262003660565b62002f67816200366c565b80516080830190620036978482620030eb565b506020820151620036ac602085018262003679565b506040820151620036c1604085018262003679565b50606082015162000efb606085018262002f65565b8051600090610160840190620036ed858262003642565b50602083015162003702602086018262002f65565b50604083015162003717604086018262003684565b5060608301516200372c60c086018262002f65565b5060808301516200374160e086018262002f65565b5060a08301516200375761010086018262003131565b5060c08301516200376d61012086018262002f65565b5060e083015184820361014086015262002153828262003013565b600062000b028383620036d6565b6000620037a1825190565b80845260208401935083602082028501620037bc8560200190565b8060005b85811015620037f55784840389528151620037dc858262003788565b94506020830160209a909a0199925050600101620037c0565b5091979650505050505050565b60408082528101620038158185620035d3565b9050818103602083015262003129818462003796565b604081016200383b828562002f65565b62000b02602083018462002f65565b805162000740816200306d565b6000602082840312156200386e576200386e600080fd5b60006200312984846200384a565b600062003887825190565b6200389781856020860162002fe4565b9290920192915050565b6001600160f01b0319811662002f67565b6000620038c082866200387c565b9150620038ce8285620038a1565b6002820191506200215382846200387c565b601d81526000602082017f437265617465323a20696e73756666696369656e742062616c616e6365000000815291505b5060200190565b602080825281016200074081620038e0565b60208082527f437265617465323a2062797465636f6465206c656e677468206973207a65726f9101908152600062003910565b60208082528101620007408162003929565b601981526000602082017f437265617465323a204661696c6564206f6e206465706c6f79000000000000008152915062003910565b6020808252810162000740816200396e565b602481526000602082017f45524332303a20417070726f76652066726f6d20746865207a65726f206164648152637265737360e01b602082015291505b5060400190565b602080825281016200074081620039b5565b602281526000602082017f45524332303a20417070726f766520746f20746865207a65726f206164647265815261737360f01b60208201529150620039f2565b60208082528101620007408162003a0b565b6001600160f81b0319811662002f67565b600062003a7c82896200387c565b915062003a8a8288620038a1565b60028201915062003a9c82876200387c565b915062003aaa8286620038a1565b60028201915062003abc82856200387c565b915062003aca828462003a5d565b506001019695505050505050565b634e487b7160e01b600052600160045260246000fd5b6040810162003afe828562003131565b62000b026020830184620030eb565b620030788162003241565b8051620007408162003b0d565b60006020828403121562003b3c5762003b3c600080fd5b600062003129848462003b18565b6040810162003b5a828562003131565b62000b02602083018462003131565b601d81526000602082017f45524332303a20496e73756666696369656e7420616c6c6f77616e63650000008152915062003910565b60208082528101620007408162003b69565b604081016200383b828562003131565b6000821982111562003bd65762003bd66200354b565b500190565b6080810162003beb828762003131565b62003bfa602083018662003131565b62003c09604083018562002f65565b62002153606083018462003131565b8062002f67565b600062003c2d828462003c18565b50602001919050565b60008162003c485762003c486200354b565b506000190190565b600081600019048311821515161562003c6d5762003c6d6200354b565b500290565b60008282101562003c875762003c876200354b565b500390565b601f81526000602082017f45524332303a204d696e7420746f20746865207a65726f2061646472657373008152915062003910565b60208082528101620007408162003c8c565b602181526000602082017f45524332303a204275726e2066726f6d20746865207a65726f206164647265738152607360f81b60208201529150620039f2565b60208082528101620007408162003cd3565b602281526000602082017f45524332303a204275726e20616d6f756e7420657863656564732062616c616e815261636560f01b60208201529150620039f2565b60208082528101620007408162003d24565b634e487b7160e01b600052601260045260246000fd5b60008262003d9e5762003d9e62003d76565b500490565b60008262003db55762003db562003d76565b500690565b6060810162003dca828562003595565b62000b02604083018462002f65565b601f19601f830116810181811067ffffffffffffffff8211171562003e025762003e026200342e565b6040525050565b600062003e1560405190565b90506200139e828262003dd9565b6001600160801b03811662003078565b8051620007408162003e23565b60006040828403121562003e575762003e57600080fd5b62003e63604062003e09565b9050600062003e73848462003503565b825250602062003e868484830162003e33565b60208301525092915050565b60006040828403121562003ea95762003ea9600080fd5b600062003129848462003e40565b600062003ec5828d6200387c565b915062003ed3828c620038a1565b60028201915062003ee5828b6200387c565b915062003ef3828a620038a1565b60028201915062003f0582896200387c565b915062003f138288620038a1565b60028201915062003f2582876200387c565b915062003f338286620038a1565b60028201915062003f4582856200387c565b915062003f53828462003a5d565b506001019a995050505050505050505056fe608060405234801561001057600080fd5b5061004461003f60017f4c711eee7e3094af1816c5450bcb78a8ffe46729a7979be7e0bf539fb4d4eef361005f565b339055565b610076565b634e487b7160e01b600052601160045260246000fd5b60008282101561007157610071610049565b500390565b610aa9806100856000396000f3fe60806040526004361061004e5760003560e01c8063392e53cd146100ab5780635c60da1b146100d65780638da5cb5b146100f8578063c4d66de81461010d578063d8a06f731461012d57610055565b3661005557005b610099610060610142565b7f49736f6c6174696f6e4d6f64655570677261646561626c6550726f78790000006e139bdd081a5b9a5d1a585b1a5e9959608a1b61017e565b6100a96100a46101e1565b610260565b005b3480156100b757600080fd5b506100c0610142565b6040516100cd9190610774565b60405180910390f35b3480156100e257600080fd5b506100eb6101e1565b6040516100cd919061079c565b34801561010457600080fd5b506100eb610284565b34801561011957600080fd5b506100a96101283660046107c9565b6102b4565b34801561013957600080fd5b506100eb61046a565b600061017661017260017f059687b4dba0a8c0c94866b6d34b3f94074057ac6e4d8d39cf07d3a0a55f2050610808565b5490565b600114905090565b826101dc5761018c8261049a565b6101d160f51b61019b8361049a565b6040516020016101ad9392919061087d565b60408051601f198184030181529082905262461bcd60e51b82526101d3916004016108e0565b60405180910390fd5b505050565b60006101eb61046a565b6001600160a01b031663a6e7d83f6040518163ffffffff1660e01b815260040160206040518083038186803b15801561022357600080fd5b505afa158015610237573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061025b9190610903565b905090565b3660008037600080366000845af43d6000803e80801561027f573d6000f35b3d6000fd5b600061025b61017260017fa7b53796fd2d99cb1f5ae019b54f9e024446c3d12b483f733ccc62ed04eb126b610808565b6102fd6102bf610142565b157f49736f6c6174696f6e4d6f64655570677261646561626c6550726f787900000072105b1c9958591e481a5b9a5d1a585b1a5e9959606a1b61017e565b6103c83061030961046a565b6001600160a01b031663b01f61e1846040518263ffffffff1660e01b8152600401610334919061079c565b60206040518083038186803b15801561034c57600080fd5b505afa158015610360573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906103849190610903565b6001600160a01b0316147f49736f6c6174696f6e4d6f64655570677261646561626c6550726f78790000006e125b9d985b1a59081858d8dbdd5b9d608a1b84610535565b6103fb6103f660017fa7b53796fd2d99cb1f5ae019b54f9e024446c3d12b483f733ccc62ed04eb126b610808565b829055565b6104326104066101e1565b60405161041e9063204a7f0760e21b90602001610934565b604051602081830303815290604052610581565b5061046761046160017f059687b4dba0a8c0c94866b6d34b3f94074057ac6e4d8d39cf07d3a0a55f2050610808565b60019055565b50565b600061025b61017260017f4c711eee7e3094af1816c5450bcb78a8ffe46729a7979be7e0bf539fb4d4eef3610808565b60606000826040516020016104af919061094f565b60408051601f19818403018152919052905060205b801561051a57806104d481610964565b9150508181815181106104e9576104e961097b565b01602001516001600160f81b0319161561051557600061050a826001610991565b835250909392505050565b6104c4565b5060408051600080825260208201909252905b509392505050565b8361057b576105438361049a565b6101d160f51b6105528461049a565b61080f60f21b610561856105fa565b6040516101ad959493929190601f60f91b906020016109b9565b50505050565b6060600080846001600160a01b03168460405161059e9190610a17565b600060405180830381855af49150503d80600081146105d9576040519150601f19603f3d011682016040523d82523d6000602084013e6105de565b606091505b5091509150816105f0576105f0610a23565b9150505b92915050565b60408051602a80825260608281019093526001600160a01b03841691600091602082018180368337019050509050603060f81b816000815181106106405761064061097b565b60200101906001600160f81b031916908160001a905350607860f81b8160018151811061066f5761066f61097b565b60200101906001600160f81b031916908160001a90535060005b601481101561052d57600061069f826002610a39565b90506106ad600f8516610740565b836106b9836029610808565b815181106106c9576106c961097b565b60200101906001600160f81b031916908160001a905350600484901c93506106f3600f8516610740565b836106ff836028610808565b8151811061070f5761070f61097b565b60200101906001600160f81b031916908160001a9053505060049290921c918061073881610a58565b915050610689565b6000600a82101561075f57610756603083610991565b60f81b92915050565b610756605783610991565b8015155b82525050565b602081016105f4828461076a565b60006001600160a01b0382166105f4565b61076e81610782565b602081016105f48284610793565b6107b381610782565b811461046757600080fd5b80356105f4816107aa565b6000602082840312156107de576107de600080fd5b60006107ea84846107be565b949350505050565b634e487b7160e01b600052601160045260246000fd5b60008282101561081a5761081a6107f2565b500390565b60005b8381101561083a578181015183820152602001610822565b8381111561057b5750506000910152565b6000610855825190565b61086381856020860161081f565b9290920192915050565b6001600160f01b0319811661076e565b6000610889828661084b565b9150610895828561086d565b6002820191506108a5828461084b565b95945050505050565b60006108b8825190565b8084526020840193506108cf81856020860161081f565b601f01601f19169290920192915050565b602080825281016108f181846108ae565b9392505050565b80516105f4816107aa565b60006020828403121561091857610918600080fd5b60006107ea84846108f8565b6001600160e01b0319811661076e565b60006109408284610924565b50600401919050565b8061076e565b600061095b8284610949565b50602001919050565b600081610973576109736107f2565b506000190190565b634e487b7160e01b600052603260045260246000fd5b600082198211156109a4576109a46107f2565b500190565b6001600160f81b0319811661076e565b60006109c5828961084b565b91506109d1828861086d565b6002820191506109e1828761084b565b91506109ed828661086d565b6002820191506109fd828561084b565b9150610a0982846109a9565b506001019695505050505050565b60006108f1828461084b565b634e487b7160e01b600052600160045260246000fd5b6000816000190483118215151615610a5357610a536107f2565b500290565b6000600019821415610a6c57610a6c6107f2565b506001019056fea2646970667358221220042cd31a4ef21419de1319dd2e6091cb23c0bf7eae19c59815c14a0bd44e629164736f6c6343000809003349736f6c6174696f6e4d6f64655661756c74466163746f727900000000000000a2646970667358221220e0e9a07606baf493acaf86ec088a2ec1165bc9aa51918fe55206bbba31cc258064736f6c63430008090033608060405234801561001057600080fd5b5061004461003f60017f4c711eee7e3094af1816c5450bcb78a8ffe46729a7979be7e0bf539fb4d4eef361005f565b339055565b610076565b634e487b7160e01b600052601160045260246000fd5b60008282101561007157610071610049565b500390565b610aa9806100856000396000f3fe60806040526004361061004e5760003560e01c8063392e53cd146100ab5780635c60da1b146100d65780638da5cb5b146100f8578063c4d66de81461010d578063d8a06f731461012d57610055565b3661005557005b610099610060610142565b7f49736f6c6174696f6e4d6f64655570677261646561626c6550726f78790000006e139bdd081a5b9a5d1a585b1a5e9959608a1b61017e565b6100a96100a46101e1565b610260565b005b3480156100b757600080fd5b506100c0610142565b6040516100cd9190610774565b60405180910390f35b3480156100e257600080fd5b506100eb6101e1565b6040516100cd919061079c565b34801561010457600080fd5b506100eb610284565b34801561011957600080fd5b506100a96101283660046107c9565b6102b4565b34801561013957600080fd5b506100eb61046a565b600061017661017260017f059687b4dba0a8c0c94866b6d34b3f94074057ac6e4d8d39cf07d3a0a55f2050610808565b5490565b600114905090565b826101dc5761018c8261049a565b6101d160f51b61019b8361049a565b6040516020016101ad9392919061087d565b60408051601f198184030181529082905262461bcd60e51b82526101d3916004016108e0565b60405180910390fd5b505050565b60006101eb61046a565b6001600160a01b031663a6e7d83f6040518163ffffffff1660e01b815260040160206040518083038186803b15801561022357600080fd5b505afa158015610237573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061025b9190610903565b905090565b3660008037600080366000845af43d6000803e80801561027f573d6000f35b3d6000fd5b600061025b61017260017fa7b53796fd2d99cb1f5ae019b54f9e024446c3d12b483f733ccc62ed04eb126b610808565b6102fd6102bf610142565b157f49736f6c6174696f6e4d6f64655570677261646561626c6550726f787900000072105b1c9958591e481a5b9a5d1a585b1a5e9959606a1b61017e565b6103c83061030961046a565b6001600160a01b031663b01f61e1846040518263ffffffff1660e01b8152600401610334919061079c565b60206040518083038186803b15801561034c57600080fd5b505afa158015610360573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906103849190610903565b6001600160a01b0316147f49736f6c6174696f6e4d6f64655570677261646561626c6550726f78790000006e125b9d985b1a59081858d8dbdd5b9d608a1b84610535565b6103fb6103f660017fa7b53796fd2d99cb1f5ae019b54f9e024446c3d12b483f733ccc62ed04eb126b610808565b829055565b6104326104066101e1565b60405161041e9063204a7f0760e21b90602001610934565b604051602081830303815290604052610581565b5061046761046160017f059687b4dba0a8c0c94866b6d34b3f94074057ac6e4d8d39cf07d3a0a55f2050610808565b60019055565b50565b600061025b61017260017f4c711eee7e3094af1816c5450bcb78a8ffe46729a7979be7e0bf539fb4d4eef3610808565b60606000826040516020016104af919061094f565b60408051601f19818403018152919052905060205b801561051a57806104d481610964565b9150508181815181106104e9576104e961097b565b01602001516001600160f81b0319161561051557600061050a826001610991565b835250909392505050565b6104c4565b5060408051600080825260208201909252905b509392505050565b8361057b576105438361049a565b6101d160f51b6105528461049a565b61080f60f21b610561856105fa565b6040516101ad959493929190601f60f91b906020016109b9565b50505050565b6060600080846001600160a01b03168460405161059e9190610a17565b600060405180830381855af49150503d80600081146105d9576040519150601f19603f3d011682016040523d82523d6000602084013e6105de565b606091505b5091509150816105f0576105f0610a23565b9150505b92915050565b60408051602a80825260608281019093526001600160a01b03841691600091602082018180368337019050509050603060f81b816000815181106106405761064061097b565b60200101906001600160f81b031916908160001a905350607860f81b8160018151811061066f5761066f61097b565b60200101906001600160f81b031916908160001a90535060005b601481101561052d57600061069f826002610a39565b90506106ad600f8516610740565b836106b9836029610808565b815181106106c9576106c961097b565b60200101906001600160f81b031916908160001a905350600484901c93506106f3600f8516610740565b836106ff836028610808565b8151811061070f5761070f61097b565b60200101906001600160f81b031916908160001a9053505060049290921c918061073881610a58565b915050610689565b6000600a82101561075f57610756603083610991565b60f81b92915050565b610756605783610991565b8015155b82525050565b602081016105f4828461076a565b60006001600160a01b0382166105f4565b61076e81610782565b602081016105f48284610793565b6107b381610782565b811461046757600080fd5b80356105f4816107aa565b6000602082840312156107de576107de600080fd5b60006107ea84846107be565b949350505050565b634e487b7160e01b600052601160045260246000fd5b60008282101561081a5761081a6107f2565b500390565b60005b8381101561083a578181015183820152602001610822565b8381111561057b5750506000910152565b6000610855825190565b61086381856020860161081f565b9290920192915050565b6001600160f01b0319811661076e565b6000610889828661084b565b9150610895828561086d565b6002820191506108a5828461084b565b95945050505050565b60006108b8825190565b8084526020840193506108cf81856020860161081f565b601f01601f19169290920192915050565b602080825281016108f181846108ae565b9392505050565b80516105f4816107aa565b60006020828403121561091857610918600080fd5b60006107ea84846108f8565b6001600160e01b0319811661076e565b60006109408284610924565b50600401919050565b8061076e565b600061095b8284610949565b50602001919050565b600081610973576109736107f2565b506000190190565b634e487b7160e01b600052603260045260246000fd5b600082198211156109a4576109a46107f2565b500190565b6001600160f81b0319811661076e565b60006109c5828961084b565b91506109d1828861086d565b6002820191506109e1828761084b565b91506109ed828661086d565b6002820191506109fd828561084b565b9150610a0982846109a9565b506001019695505050505050565b60006108f1828461084b565b634e487b7160e01b600052600160045260246000fd5b6000816000190483118215151615610a5357610a536107f2565b500290565b6000600019821415610a6c57610a6c6107f2565b506001019056fea2646970667358221220042cd31a4ef21419de1319dd2e6091cb23c0bf7eae19c59815c14a0bd44e629164736f6c6343000809003300000000000000000000000066d4d46b140149dfa603de01aac4b337234950010000000000000000000000008be66a48ea1f4aff89cd2beb50b02d901dfb9584000000000000000000000000e99a7e4556caf7925fbac52765128e524e9dd793000000000000000000000000f0c0db8e4e01bd9a8e01860ef83077405a53f781000000000000000000000000e6ef4f0b2455bab92ce7cc78e35324ab58917de8

Deployed Bytecode

0x60806040523480156200001157600080fd5b50600436106200026d5760003560e01c80635b7490541162000155578063b01f61e111620000c7578063cbffd9211162000086578063cbffd921146200062e578063d143d5911462000638578063d3f5f0621462000642578063dd62ed3e146200064c578063ed4e3a35146200068857600080fd5b8063b01f61e1146200057a578063b4bd6f4614620005a9578063bc08373214620005c0578063c1090d5a14620005ef578063c6d20c85146200060657600080fd5b806389c32efb116200011457806389c32efb146200027257806395b5b196146200052957806395d89b411462000540578063a6e7d83f146200054a578063a9059cbb146200056357600080fd5b80635b749054146200049f5780636ed71ede14620004b657806370a0823114620004c057806372dcf67914620004ec578063816bbc2e146200050357600080fd5b806323b872dd11620001ef578063392e53cd11620001ae578063392e53cd14620004315780633c939dc11462000446578063516885be146200045d57806353769bbf146200047457806354441311146200048857600080fd5b806323b872dd146200039e578063260fa1a114620003b557806329db1be614620003cc5780632ee3d92f14620003f4578063313ce567146200041c57600080fd5b80630a3ee461116200023c5780630a3ee46114620002fb5780630d97c9fa146200031457806315c14a4a146200032b57806316774ba0146200035c57806318160ddd146200038b57600080fd5b8063037ec8c8146200027257806306fdde031462000296578063095ea7b314620002af57806309da2c5414620002d5575b600080fd5b604080516000815260208101918290526200028d9162002fd1565b60405180910390f35b620002a062000690565b6040516200028d919062003048565b620002c6620002c0366004620030a8565b6200072a565b6040516200028d9190620030f4565b620002ec620002e636600462003104565b62000746565b6040516200028d91906200313c565b620003126200030c366004620031a4565b62000785565b005b620003126200032536600462003208565b62000a89565b7f000000000000000000000000e6ef4f0b2455bab92ce7cc78e35324ab58917de85b6040516200028d919062003266565b620002c66200036d36600462003104565b6001600160a01b03166000908152600b602052604090205460ff1690565b6002545b6040516200028d919062003276565b620002c6620003af36600462003286565b62000adf565b62000312620003c636600462003104565b62000b09565b620002ec7f0000000000000000000000008be66a48ea1f4aff89cd2beb50b02d901dfb958481565b6200034d7f000000000000000000000000e99a7e4556caf7925fbac52765128e524e9dd79381565b60055460ff166040516200028d9190620032e8565b600554620002c690600160a81b900460ff1681565b6200031262000457366004620032f8565b62000b71565b620003126200046e36600462003333565b62000e1a565b600c546200034d906001600160a01b031681565b6200031262000499366004620030a8565b62000f01565b62000312620004b0366004620030a8565b62000fcb565b6200038f60065481565b6200038f620004d136600462003104565b6001600160a01b031660009081526020819052604090205490565b62000312620004fd36600462003104565b62001095565b6200051a6200051436600462003359565b62001181565b6040516200028d9190620033e5565b620003126200053a36600462003333565b62001251565b620002a062001334565b600554620002ec9061010090046001600160a01b031681565b620002c662000574366004620030a8565b62001345565b620002ec6200058b36600462003104565b6001600160a01b039081166000908152600a60205260409020541690565b620002ec620005ba36600462003104565b62001355565b620002ec620005d136600462003104565b6001600160a01b039081166000908152600960205260409020541690565b620002ec6200060036600462003333565b620013a3565b6200034d7f0000000000000000000000007bec164cacd60d5cbcaa7b81d9da4cf6a0f7e09b81565b620002ec6200145d565b6200038f60075481565b6200038f620014f9565b6200038f6200065d366004620033f5565b6001600160a01b03918216600090815260016020908152604080832093909416825291909152205490565b6001620002c6565b606060038054620006a1906200345a565b80601f0160208091040260200160405190810160405280929190818152602001828054620006cf906200345a565b8015620007205780601f10620006f45761010080835404028352916020019162000720565b820191906000526020600020905b8154815290600101906020018083116200070257829003601f168201915b5050505050905090565b6000336200073a8185856200160e565b60019150505b92915050565b600062000740826040516020016200075f9190620034ba565b604051602081830303815290604052805190602001206200077f620014f9565b620016ca565b33620007e6620007946200145d565b6001600160a01b0316826001600160a01b0316147127b7363ca237b637b6b4ba32a6b0b933b4b760711b7f43616c6c6572206973206e6f74206f776e6572206f6620446f6c6f6d6974650084620016d9565b6005546200082690600160a81b900460ff161560008051602062004a9483398151915272105b1c9958591e481a5b9a5d1a585b1a5e9959606a1b6200152d565b604051638fae3be160e01b81526001600160a01b037f000000000000000000000000e6ef4f0b2455bab92ce7cc78e35324ab58917de81690638fae3be190620008749030906004016200313c565b60206040518083038186803b1580156200088d57600080fd5b505afa158015620008a2573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620008c89190620034de565b60068190556040516316b1f45f60e21b8152620009a9916001600160a01b037f000000000000000000000000e6ef4f0b2455bab92ce7cc78e35324ab58917de81691635ac7d17c916200091e9160040162003276565b60206040518083038186803b1580156200093757600080fd5b505afa1580156200094c573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062000972919062003510565b60008051602062004a948339815191527f4d61726b65742063616e6e6f7420616c6c6f7720626f72726f77696e670000006200152d565b61dead6000819052600a6020527f20677881080440a9b3c87e826370bb5d9c2f74efd4dede686d52d77a6a09f8bb54620009ed91906001600160a01b031662001728565b60005b8281101562000a465762000a3184848381811062000a125762000a1262003535565b905060200201602081019062000a29919062003104565b60016200193b565b8062000a3d8162003561565b915050620009f0565b506005805460ff60a81b1916600160a81b1790556040517f5daa87a0e9463431830481fd4b6e3403442dfb9a12b9c07597e9f61d50b633c890600090a15b505050565b60055462000ac490600160a81b900460ff1660008051602062004a948339815191526e139bdd081a5b9a5d1a585b1a5e9959608a1b6200152d565b3362000ad3620007946200145d565b62000a8483836200193b565b60003362000aef858285620019e4565b62000afc85858562001a3c565b60019150505b9392505050565b3362000b18620007946200145d565b600c80546001600160a01b0319166001600160a01b0384161790556040517fe06bb3aa40c10f71cf0e0dc17d6f449f6efbc87668e14dc51db81ea21827655b9062000b659084906200313c565b60405180910390a15050565b3360008181526009602052604090205462000bb9906001600160a01b0316151560008051602062004a948339815191526c125b9d985b1a59081d985d5b1d609a1b84620016d9565b62000bec60065484141560008051602062004a948339815191526d125b9d985b1a59081b585c9ad95d60921b8662001f9c565b60408051600280825260608201909252600091816020015b604080518082019091526000808252602082015281526020019060019003908162000c045790505090506040518060400160405280336001600160a01b0316815260200160008152508160008151811062000c635762000c6362003535565b6020908102919091018101919091526040805180820182523360009081526009845291909120546001600160a01b0316815290810186905281518290600190811062000cb35762000cb362003535565b602090810291909101015260408051600280825260608201909252600091816020015b62000ce062002ee0565b81526020019060019003908162000cd657505060408051608081019091526001815290915062000d2a90600090879060208101838152602001600081526020018890523362001fcf565b8160008151811062000d405762000d4062003535565b602002602001018190525062000d666000600187600062000d6060001990565b6200203a565b8160018151811062000d7c5762000d7c62003535565b602002602001018190525062000daf7f000000000000000000000000e6ef4f0b2455bab92ce7cc78e35324ab58917de890565b6001600160a01b031663a67a6a4583836040518363ffffffff1660e01b815260040162000dde92919062003802565b600060405180830381600087803b15801562000df957600080fd5b505af115801562000e0e573d6000803e3d6000fd5b50505050505050505050565b3360008181526009602052604090205462000e62906001600160a01b0316151560008051602062004a948339815191526c125b9d985b1a59081d985d5b1d609a1b84620016d9565b3362000e91817f000000000000000000000000e6ef4f0b2455bab92ce7cc78e35324ab58917de885846200215c565b62000efb7f000000000000000000000000e6ef4f0b2455bab92ce7cc78e35324ab58917de882838760065460405180608001604052806001151581526020016000600181111562000ee65762000ee66200357f565b8152602001600081526020018a905262002388565b50505050565b336000818152600b602052604090205462000f519060ff1660008051602062004a948339815191527f43616c6c6572206973206e6f74206120746f6b656e20636f6e7665727465720084620016d9565b6001600160a01b03808416600090815260096020526040902054849162000f9d9116151560008051602062004a948339815191526c125b9d985b1a59081d985d5b1d609a1b84620016d9565b62000efb7f000000000000000000000000e6ef4f0b2455bab92ce7cc78e35324ab58917de83385876200215c565b336000818152600b60205260409020546200101b9060ff1660008051602062004a948339815191527f43616c6c6572206973206e6f74206120746f6b656e20636f6e7665727465720084620016d9565b6001600160a01b038084166000908152600960205260409020548491620010679116151560008051602062004a948339815191526c125b9d985b1a59081d985d5b1d609a1b84620016d9565b62000efb337f000000000000000000000000e6ef4f0b2455bab92ce7cc78e35324ab58917de885876200215c565b600554620010d090600160a81b900460ff1660008051602062004a948339815191526e139bdd081a5b9a5d1a585b1a5e9959608a1b6200152d565b33620010df620007946200145d565b620011266001600160a01b038316151560008051602062004a948339815191527f496e76616c6964207573657220696d706c656d656e746174696f6e00000000006200152d565b600580546001600160a01b03848116610100818102610100600160a81b031985161790945560405193909204169182907fdc5a954098cef71f25bbe48bbd58cd5866495daacabf32492424363af66dd01890600090a3505050565b6040805160a081018252600080825260208201819052918101829052606081018290526080810191909152620011ed60075483111560008051602062004a948339815191527f496e76616c6964207472616e7366657220637572736f720000000000000000006200152d565b50600090815260086020908152604091829020825160a08101845281546001600160a01b0390811682526001830154811693820193909352600282015493810193909352600301549081166060830152600160a01b900460ff161515608082015290565b3360008181526009602052604090205462001299906001600160a01b0316151560008051602062004a948339815191526c125b9d985b1a59081d985d5b1d609a1b84620016d9565b33620012c87f000000000000000000000000e6ef4f0b2455bab92ce7cc78e35324ab58917de88285846200215c565b62000efb7f000000000000000000000000e6ef4f0b2455bab92ce7cc78e35324ab58917de88286846006546040518060800160405280600015158152602001600060018111156200131d576200131d6200357f565b8152602001600081526020018a90526001620024dd565b606060048054620006a1906200345a565b6000336200073a81858562001a3c565b6005546000906200139390600160a81b900460ff1660008051602062004a948339815191526e139bdd081a5b9a5d1a585b1a5e9959608a1b6200152d565b6200074082620026a8565b919050565b600554600090620013e190600160a81b900460ff1660008051602062004a948339815191526e139bdd081a5b9a5d1a585b1a5e9959608a1b6200152d565b6000620013ee33620026a8565b604051637d49eb4d60e11b81529091506001600160a01b0382169063fa93d69a906200142190879087906004016200382b565b600060405180830381600087803b1580156200143c57600080fd5b505af115801562001451573d6000803e3d6000fd5b50929695505050505050565b60007f000000000000000000000000e6ef4f0b2455bab92ce7cc78e35324ab58917de86001600160a01b0316638da5cb5b6040518163ffffffff1660e01b815260040160206040518083038186803b158015620014b957600080fd5b505afa158015620014ce573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620014f4919062003857565b905090565b6000604051806020016200150d9062002f57565b6020820181038252601f19601f8201166040525080519060200120905090565b8262000a84576200153e8262002849565b6101d160f51b6200154f8362002849565b6040516020016200156393929190620038b2565b60408051601f198184030181529082905262461bcd60e51b82526200158b9160040162003048565b60405180910390fd5b600083471015620015b95760405162461bcd60e51b81526004016200158b9062003917565b8151620015da5760405162461bcd60e51b81526004016200158b906200395c565b8282516020840186f590506001600160a01b03811662000b025760405162461bcd60e51b81526004016200158b90620039a3565b6001600160a01b038316620016375760405162461bcd60e51b81526004016200158b90620039f9565b6001600160a01b038216620016605760405162461bcd60e51b81526004016200158b9062003a4b565b6001600160a01b0380841660008181526001602090815260408083209487168084529490915290819020849055517f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92590620016bd90859062003276565b60405180910390a3505050565b600062000b02838330620028f0565b8362000efb57620016ea8362002849565b6101d160f51b620016fb8462002849565b61080f60f21b6200170c8562002919565b60405162001563959493929190601f60f91b9060200162003a6e565b6001600160a01b038216158015906200174957506001600160a01b03811615155b62001758576200175862003ad8565b60405163189acdbd60e31b81526001600160a01b0382169063c4d66de890620017869085906004016200313c565b600060405180830381600087803b158015620017a157600080fd5b505af1158015620017b6573d6000803e3d6000fd5b505060405163f697ae9960e01b81526001600160a01b037f000000000000000000000000e99a7e4556caf7925fbac52765128e524e9dd79316925063f697ae9991506200180b90849060019060040162003aee565b600060405180830381600087803b1580156200182657600080fd5b505af11580156200183b573d6000803e3d6000fd5b505050507f0000000000000000000000007bec164cacd60d5cbcaa7b81d9da4cf6a0f7e09b6001600160a01b031663f68ebbbd6040518163ffffffff1660e01b815260040160206040518083038186803b1580156200189957600080fd5b505afa158015620018ae573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620018d4919062003b25565b6001600160a01b03166305c4fdf983836040518363ffffffff1660e01b81526004016200190392919062003b4a565b600060405180830381600087803b1580156200191e57600080fd5b505af115801562001933573d6000803e3d6000fd5b505050505050565b620019826001600160a01b038316151560008051602062004a948339815191527f496e76616c696420746f6b656e20636f6e7665727465720000000000000000006200152d565b6001600160a01b0382166000818152600b602052604090819020805460ff1916841515179055517f1a2aaf8fb443c30344ac3e041f678060eb802aa3e68057d31682b9909d5693a490620019d8908490620030f4565b60405180910390a25050565b6001600160a01b038381166000908152600160209081526040808320938616835292905220548181101562001a2d5760405162461bcd60e51b81526004016200158b9062003b9e565b62000efb84848484036200160e565b3362001aab6001600160a01b037f000000000000000000000000e6ef4f0b2455bab92ce7cc78e35324ab58917de81682147127b7363ca237b637b6b4ba32a6b0b933b4b760711b7f4f6e6c7920446f6c6f6d6974652063616e2063616c6c2066756e6374696f6e0084620016d9565b62001af26001600160a01b038516151560008051602062004a948339815191527f5472616e736665722066726f6d20746865207a65726f206164647265737300006200152d565b62001b396001600160a01b038416151560008051602062004a948339815191527f5472616e7366657220746f20746865207a65726f2061646472657373000000006200152d565b7f000000000000000000000000e6ef4f0b2455bab92ce7cc78e35324ab58917de862001bc16001600160a01b03868116908316148062001b8a5750816001600160a01b0316856001600160a01b0316145b60008051602062004a948339815191527f66726f6d2f746f206d75737420657120446f6c6f6d6974654d617267696e00006200152d565b600754600081815260086020908152604091829020825160a08101845281546001600160a01b0390811680835260018401548216948301949094526002830154948201949094526003909101548084166060830152600160a01b900460ff16151560808201529162001cc59190891614801562001c535750866001600160a01b031682602001516001600160a01b0316145b801562001c635750858260400151145b801562001c8e575060608201516001600160a01b039081166000908152600960205260409020541615155b60008051602062004a948339815191527f496e76616c696420717565756564207472616e736665720000000000000000006200152d565b62001d0781608001511560008051602062004a948339815191527f5472616e7366657220616c7265616479206578656375746564000000000000008562001f9c565b6000828152600860205260409020600301805460ff60a01b1916600160a01b1790556001600160a01b03868116908416141562001e6b576001600160a01b038088166000908152600960205260409020541662001dcc811580159062001d82575082606001516001600160a01b0316896001600160a01b0316145b8062001da657506001600160a01b0389166000908152600b602052604090205460ff165b60008051602062004a948339815191526b496e76616c69642066726f6d60a01b6200152d565b81606001516001600160a01b0316638ddab4e560006001600160a01b0316836001600160a01b0316141562001e02578962001e04565b825b886040518363ffffffff1660e01b815260040162001e2492919062003bb0565b600060405180830381600087803b15801562001e3f57600080fd5b505af115801562001e54573d6000803e3d6000fd5b5050505062001e64878762002a79565b5062001f93565b826001600160a01b0316876001600160a01b03161462001e8f5762001e8f62003ad8565b6001600160a01b038087166000908152600960205260409020541662001ef98115158062001ed557506001600160a01b0388166000908152600b602052604090205460ff165b60008051602062004a9483398151915269496e76616c696420746f60b01b6200152d565b81606001516001600160a01b031663797b512560006001600160a01b0316836001600160a01b0316141562001f2f578862001f31565b825b886040518363ffffffff1660e01b815260040162001f5192919062003bb0565b600060405180830381600087803b15801562001f6c57600080fd5b505af115801562001f81573d6000803e3d6000fd5b5050505062001f91888762002b16565b505b50505050505050565b8362000efb5762001fad8362002849565b6101d160f51b62001fbe8462002849565b61080f60f21b6200170c8562002bd5565b62001fd962002ee0565b6040805161010081019091528060005b815260200186815260200184815260200185815260200160008152602001836001600160a01b0316815260200160008152602001604051806020016040528060008152508152509050949350505050565b6200204462002ee0565b62002071604080516080810190915260008082526020820190815260200160008152602001600081525090565b600019831415620020be576040518060800160405280600015158152602001856001811115620020a557620020a56200357f565b81526020016001815260200160008152509050620020f9565b6040518060800160405280600015158152602001856001811115620020e757620020e76200357f565b81526020016000815260200184905290505b60408051610100810190915280600281526020018881526020018281526020018681526020016000815260200160006001600160a01b03168152602001878152602001604051806020016040528060008152508152509150505b95945050505050565b600754600090815260086020908152604091829020825160a08101845281546001600160a01b0390811682526001830154811693820193909352600282015493810193909352600301549081166060830152600160a01b900460ff16158015608083018190526200220257507f000000000000000000000000e6ef4f0b2455bab92ce7cc78e35324ab58917de86001600160a01b031681602001516001600160a01b0316145b156200221e576200221e8160600151826020015160006200160e565b816001600160a01b0316856001600160a01b03161480156200227157507f000000000000000000000000e6ef4f0b2455bab92ce7cc78e35324ab58917de86001600160a01b0316846001600160a01b0316145b156200228457620022848285856200160e565b60016007600082825462002299919062003bc0565b90915550506040805160a0810182526001600160a01b038088168252868116602080840191825283850188815287841660608601908152600060808701818152600780548352600890955290889020965187549087166001600160a01b03199182161788559451600188018054918816919096161790945590516002860155516003909401805492511515600160a01b026001600160a81b031990931694909316939093171790555490517f41f436ede2f45a36c2a15333e202b31f7040c914a78d7eb62d6f7caa6414a756906200237990889088908890889062003bdb565b60405180910390a25050505050565b604080516001808252818301909252600091816020015b60408051808201909152600080825260208201528152602001906001900390816200239f5790505090506040518060400160405280876001600160a01b031681526020018581525081600081518110620023fd57620023fd62003535565b6020908102919091010152604080516001808252818301909252600091816020015b6200242962002ee0565b8152602001906001900390816200241f5790505090506200244e600085858962001fcf565b8160008151811062002464576200246462003535565b602090810291909101015260405163a67a6a4560e01b81526001600160a01b0389169063a67a6a45906200249f908590859060040162003802565b600060405180830381600087803b158015620024ba57600080fd5b505af1158015620024cf573d6000803e3d6000fd5b505050505050505050505050565b604080516001808252818301909252600091816020015b6040805180820190915260008082526020820152815260200190600190039081620024f45790505090506040518060400160405280886001600160a01b03168152602001878152508160008151811062002552576200255262003535565b6020908102919091010152604080516001808252818301909252600091816020015b6200257e62002ee0565b81526020019060019003908162002574579050509050620025a3600086868962002cf9565b81600081518110620025b957620025b962003535565b602090810291909101015260405163a67a6a4560e01b81526001600160a01b038a169063a67a6a4590620025f4908590859060040162003802565b600060405180830381600087803b1580156200260f57600080fd5b505af115801562002624573d6000803e3d6000fd5b506000925062002632915050565b8360038111156200264757620026476200357f565b148062002668575060018360038111156200266657620026666200357f565b145b156200269d576200269d898360008151811062002689576200268962003535565b602002602001015160000151898862002d18565b505050505050505050565b6000620026e36001600160a01b038316151560008051602062004a948339815191526e125b9d985b1a59081858d8dbdd5b9d608a1b6200152d565b6001600160a01b038281166000908152600a60205260409020546200273291161560008051602062004a94833981519152735661756c7420616c72656164792065786973747360601b6200152d565b60006200278e6000846040516020016200274d9190620034ba565b6040516020818303038152906040528051906020012060405180602001620027759062002f57565b601f1982820381018352601f9091011660405262001594565b90506001600160a01b038116620027a957620027a962003ad8565b826001600160a01b03167f5d9c31ffa0fecffd7cf379989a3c7af252f0335e0d2a1320b55245912c781f5382604051620027e491906200313c565b60405180910390a26001600160a01b03808216600081815260096020908152604080832080549589166001600160a01b03199687168117909155808452600a909252909120805490931690911790915561dead14620007405762000740838262001728565b606060008260405160200162002860919062003c1f565b60408051601f19818403018152919052905060205b8015620028d55780620028888162003c36565b915050818181518110620028a057620028a062003535565b01602001516001600160f81b03191615620028cf576000620028c482600162003bc0565b835250909392505050565b62002875565b5060408051600080825260208201909252905b509392505050565b6000604051836040820152846020820152828152600b810160ff81536055902095945050505050565b60408051602a80825260608281019093526001600160a01b03841691600091602082018180368337019050509050603060f81b8160008151811062002962576200296262003535565b60200101906001600160f81b031916908160001a905350607860f81b8160018151811062002994576200299462003535565b60200101906001600160f81b031916908160001a90535060005b6014811015620028e8576000620029c782600262003c50565b9050620029d7600f851662002e1c565b83620029e583602962003c72565b81518110620029f857620029f862003535565b60200101906001600160f81b031916908160001a905350600484901c935062002a24600f851662002e1c565b8362002a3283602862003c72565b8151811062002a455762002a4562003535565b60200101906001600160f81b031916908160001a9053505060049290921c918062002a708162003561565b915050620029ae565b6001600160a01b03821662002aa25760405162461bcd60e51b81526004016200158b9062003cc1565b806002600082825462002ab6919062003bc0565b90915550506001600160a01b038216600081815260208190526040808220805485019055517fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9062002b0a90859062003276565b60405180910390a35050565b6001600160a01b03821662002b3f5760405162461bcd60e51b81526004016200158b9062003d12565b6001600160a01b0382166000908152602081905260409020548181101562002b7b5760405162461bcd60e51b81526004016200158b9062003d64565b6001600160a01b0383166000818152602081905260408082208585039055600280548690039055519091907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef90620016bd90869062003276565b60608162002bfa5750506040805180820190915260018152600360fc1b602082015290565b8160005b811562002c2a578062002c118162003561565b915062002c229050600a8362003d8c565b915062002bfe565b60008167ffffffffffffffff81111562002c485762002c486200342e565b6040519080825280601f01601f19166020018201604052801562002c73576020820181803683370190505b508593509050815b801562002cf0578062002c8e8162003c36565b915062002c9f9050600a8562003da3565b62002cac90603062003bc0565b60f81b82828151811062002cc45762002cc462003535565b60200101906001600160f81b031916908160001a90535062002ce8600a8562003d8c565b935062002c7b565b50949350505050565b62002d0362002ee0565b60408051610100810190915280600162001fe9565b6040805180820182526001600160a01b0380861682526020820185905291516311f46d4f60e21b81529091600091908716906347d1b53c9062002d62908590879060040162003dba565b604080518083038186803b15801562002d7a57600080fd5b505afa15801562002d8f573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062002db5919062003e92565b90506200193362002dc68262002e4b565b8062002ddd575060208201516001600160801b0316155b7020b1b1b7bab73a2130b630b731b2a634b160791b7f6163636f756e742063616e6e6f7420676f206e6567617469766500000000000088888862002e6b565b6000600a82101562002e3e5762002e3560308362003bc0565b60f81b92915050565b62002e3560578362003bc0565b8051600090801562000740575050602001516001600160801b0316151590565b85620019335762002e7c8562002849565b6101d160f51b62002e8d8662002849565b61080f60f21b62002e9e8762002919565b61016160f51b62002eaf8862002bd5565b61016160f51b62002ec08962002bd5565b6040516200156399989796959493929190601f60f91b9060200162003eb7565b60408051610100810182526000808252602082015290810162002f25604080516080810190915260008082526020820190815260200160008152602001600081525090565b8152602001600081526020016000815260200160006001600160a01b0316815260200160008152602001606081525090565b610b2e8062003f6683390190565b805b82525050565b600062002f7b838362002f65565b505060200190565b600062002f8e825190565b80845260209384019383018060005b8381101562002fc657815162002fb4888262002f6d565b97506020830192505060010162002f9d565b509495945050505050565b6020808252810162000b02818462002f83565b60005b838110156200300157818101518382015260200162002fe7565b8381111562000efb5750506000910152565b60006200301e825190565b8084526020840193506200303781856020860162002fe4565b601f01601f19169290920192915050565b6020808252810162000b02818462003013565b60006001600160a01b03821662000740565b62003078816200305b565b81146200308457600080fd5b50565b803562000740816200306d565b8062003078565b8035620007408162003094565b60008060408385031215620030c057620030c0600080fd5b6000620030ce858562003087565b9250506020620030e1858286016200309b565b9150509250929050565b80151562002f67565b60208101620007408284620030eb565b6000602082840312156200311b576200311b600080fd5b600062003129848462003087565b949350505050565b62002f67816200305b565b6020810162000740828462003131565b60008083601f840112620031635762003163600080fd5b50813567ffffffffffffffff811115620031805762003180600080fd5b6020830191508360208202830111156200319d576200319d600080fd5b9250929050565b60008060208385031215620031bc57620031bc600080fd5b823567ffffffffffffffff811115620031d857620031d8600080fd5b620031e6858286016200314c565b92509250509250929050565b80151562003078565b80356200074081620031f2565b60008060408385031215620032205762003220600080fd5b60006200322e858562003087565b9250506020620030e185828601620031fb565b600062000740826200305b565b6000620007408262003241565b62002f67816200324e565b602081016200074082846200325b565b6020810162000740828462002f65565b600080600060608486031215620032a057620032a0600080fd5b6000620032ae868662003087565b9350506020620032c18682870162003087565b9250506040620032d4868287016200309b565b9150509250925092565b60ff811662002f67565b60208101620007408284620032de565b600080600060608486031215620033125762003312600080fd5b60006200332086866200309b565b9350506020620032c1868287016200309b565b600080604083850312156200334b576200334b600080fd5b6000620030ce85856200309b565b600060208284031215620033705762003370600080fd5b60006200312984846200309b565b805160a083019062003391848262003131565b506020820151620033a6602085018262003131565b506040820151620033bb604085018262002f65565b506060820151620033d0606085018262003131565b50608082015162000efb6080850182620030eb565b60a081016200074082846200337e565b600080604083850312156200340d576200340d600080fd5b60006200341b858562003087565b9250506020620030e18582860162003087565b634e487b7160e01b600052604160045260246000fd5b634e487b7160e01b600052602260045260246000fd5b6002810460018216806200346f57607f821691505b6020821081141562003485576200348562003444565b50919050565b6000620007408260601b90565b600062000740826200348b565b62002f67620034b4826200305b565b62003498565b6000620034c88284620034a5565b50601401919050565b8051620007408162003094565b600060208284031215620034f557620034f5600080fd5b6000620031298484620034d1565b80516200074081620031f2565b600060208284031215620035275762003527600080fd5b600062003129848462003503565b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052601160045260246000fd5b60006000198214156200357857620035786200354b565b5060010190565b634e487b7160e01b600052602160045260246000fd5b80516040830190620035a8848262003131565b50602082015162000efb602085018262002f65565b6000620035cb838362003595565b505060400190565b6000620035de825190565b80845260209384019383018060005b8381101562002fc6578151620036048882620035bd565b975060208301925050600101620035ed565b600981106200308457620030846200357f565b806200139e8162003616565b6000620007408262003629565b62002f678162003635565b600281106200308457620030846200357f565b806200139e816200364d565b6000620007408262003660565b62002f67816200366c565b80516080830190620036978482620030eb565b506020820151620036ac602085018262003679565b506040820151620036c1604085018262003679565b50606082015162000efb606085018262002f65565b8051600090610160840190620036ed858262003642565b50602083015162003702602086018262002f65565b50604083015162003717604086018262003684565b5060608301516200372c60c086018262002f65565b5060808301516200374160e086018262002f65565b5060a08301516200375761010086018262003131565b5060c08301516200376d61012086018262002f65565b5060e083015184820361014086015262002153828262003013565b600062000b028383620036d6565b6000620037a1825190565b80845260208401935083602082028501620037bc8560200190565b8060005b85811015620037f55784840389528151620037dc858262003788565b94506020830160209a909a0199925050600101620037c0565b5091979650505050505050565b60408082528101620038158185620035d3565b9050818103602083015262003129818462003796565b604081016200383b828562002f65565b62000b02602083018462002f65565b805162000740816200306d565b6000602082840312156200386e576200386e600080fd5b60006200312984846200384a565b600062003887825190565b6200389781856020860162002fe4565b9290920192915050565b6001600160f01b0319811662002f67565b6000620038c082866200387c565b9150620038ce8285620038a1565b6002820191506200215382846200387c565b601d81526000602082017f437265617465323a20696e73756666696369656e742062616c616e6365000000815291505b5060200190565b602080825281016200074081620038e0565b60208082527f437265617465323a2062797465636f6465206c656e677468206973207a65726f9101908152600062003910565b60208082528101620007408162003929565b601981526000602082017f437265617465323a204661696c6564206f6e206465706c6f79000000000000008152915062003910565b6020808252810162000740816200396e565b602481526000602082017f45524332303a20417070726f76652066726f6d20746865207a65726f206164648152637265737360e01b602082015291505b5060400190565b602080825281016200074081620039b5565b602281526000602082017f45524332303a20417070726f766520746f20746865207a65726f206164647265815261737360f01b60208201529150620039f2565b60208082528101620007408162003a0b565b6001600160f81b0319811662002f67565b600062003a7c82896200387c565b915062003a8a8288620038a1565b60028201915062003a9c82876200387c565b915062003aaa8286620038a1565b60028201915062003abc82856200387c565b915062003aca828462003a5d565b506001019695505050505050565b634e487b7160e01b600052600160045260246000fd5b6040810162003afe828562003131565b62000b026020830184620030eb565b620030788162003241565b8051620007408162003b0d565b60006020828403121562003b3c5762003b3c600080fd5b600062003129848462003b18565b6040810162003b5a828562003131565b62000b02602083018462003131565b601d81526000602082017f45524332303a20496e73756666696369656e7420616c6c6f77616e63650000008152915062003910565b60208082528101620007408162003b69565b604081016200383b828562003131565b6000821982111562003bd65762003bd66200354b565b500190565b6080810162003beb828762003131565b62003bfa602083018662003131565b62003c09604083018562002f65565b62002153606083018462003131565b8062002f67565b600062003c2d828462003c18565b50602001919050565b60008162003c485762003c486200354b565b506000190190565b600081600019048311821515161562003c6d5762003c6d6200354b565b500290565b60008282101562003c875762003c876200354b565b500390565b601f81526000602082017f45524332303a204d696e7420746f20746865207a65726f2061646472657373008152915062003910565b60208082528101620007408162003c8c565b602181526000602082017f45524332303a204275726e2066726f6d20746865207a65726f206164647265738152607360f81b60208201529150620039f2565b60208082528101620007408162003cd3565b602281526000602082017f45524332303a204275726e20616d6f756e7420657863656564732062616c616e815261636560f01b60208201529150620039f2565b60208082528101620007408162003d24565b634e487b7160e01b600052601260045260246000fd5b60008262003d9e5762003d9e62003d76565b500490565b60008262003db55762003db562003d76565b500690565b6060810162003dca828562003595565b62000b02604083018462002f65565b601f19601f830116810181811067ffffffffffffffff8211171562003e025762003e026200342e565b6040525050565b600062003e1560405190565b90506200139e828262003dd9565b6001600160801b03811662003078565b8051620007408162003e23565b60006040828403121562003e575762003e57600080fd5b62003e63604062003e09565b9050600062003e73848462003503565b825250602062003e868484830162003e33565b60208301525092915050565b60006040828403121562003ea95762003ea9600080fd5b600062003129848462003e40565b600062003ec5828d6200387c565b915062003ed3828c620038a1565b60028201915062003ee5828b6200387c565b915062003ef3828a620038a1565b60028201915062003f0582896200387c565b915062003f138288620038a1565b60028201915062003f2582876200387c565b915062003f338286620038a1565b60028201915062003f4582856200387c565b915062003f53828462003a5d565b506001019a995050505050505050505056fe608060405234801561001057600080fd5b5061004461003f60017f4c711eee7e3094af1816c5450bcb78a8ffe46729a7979be7e0bf539fb4d4eef361005f565b339055565b610076565b634e487b7160e01b600052601160045260246000fd5b60008282101561007157610071610049565b500390565b610aa9806100856000396000f3fe60806040526004361061004e5760003560e01c8063392e53cd146100ab5780635c60da1b146100d65780638da5cb5b146100f8578063c4d66de81461010d578063d8a06f731461012d57610055565b3661005557005b610099610060610142565b7f49736f6c6174696f6e4d6f64655570677261646561626c6550726f78790000006e139bdd081a5b9a5d1a585b1a5e9959608a1b61017e565b6100a96100a46101e1565b610260565b005b3480156100b757600080fd5b506100c0610142565b6040516100cd9190610774565b60405180910390f35b3480156100e257600080fd5b506100eb6101e1565b6040516100cd919061079c565b34801561010457600080fd5b506100eb610284565b34801561011957600080fd5b506100a96101283660046107c9565b6102b4565b34801561013957600080fd5b506100eb61046a565b600061017661017260017f059687b4dba0a8c0c94866b6d34b3f94074057ac6e4d8d39cf07d3a0a55f2050610808565b5490565b600114905090565b826101dc5761018c8261049a565b6101d160f51b61019b8361049a565b6040516020016101ad9392919061087d565b60408051601f198184030181529082905262461bcd60e51b82526101d3916004016108e0565b60405180910390fd5b505050565b60006101eb61046a565b6001600160a01b031663a6e7d83f6040518163ffffffff1660e01b815260040160206040518083038186803b15801561022357600080fd5b505afa158015610237573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061025b9190610903565b905090565b3660008037600080366000845af43d6000803e80801561027f573d6000f35b3d6000fd5b600061025b61017260017fa7b53796fd2d99cb1f5ae019b54f9e024446c3d12b483f733ccc62ed04eb126b610808565b6102fd6102bf610142565b157f49736f6c6174696f6e4d6f64655570677261646561626c6550726f787900000072105b1c9958591e481a5b9a5d1a585b1a5e9959606a1b61017e565b6103c83061030961046a565b6001600160a01b031663b01f61e1846040518263ffffffff1660e01b8152600401610334919061079c565b60206040518083038186803b15801561034c57600080fd5b505afa158015610360573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906103849190610903565b6001600160a01b0316147f49736f6c6174696f6e4d6f64655570677261646561626c6550726f78790000006e125b9d985b1a59081858d8dbdd5b9d608a1b84610535565b6103fb6103f660017fa7b53796fd2d99cb1f5ae019b54f9e024446c3d12b483f733ccc62ed04eb126b610808565b829055565b6104326104066101e1565b60405161041e9063204a7f0760e21b90602001610934565b604051602081830303815290604052610581565b5061046761046160017f059687b4dba0a8c0c94866b6d34b3f94074057ac6e4d8d39cf07d3a0a55f2050610808565b60019055565b50565b600061025b61017260017f4c711eee7e3094af1816c5450bcb78a8ffe46729a7979be7e0bf539fb4d4eef3610808565b60606000826040516020016104af919061094f565b60408051601f19818403018152919052905060205b801561051a57806104d481610964565b9150508181815181106104e9576104e961097b565b01602001516001600160f81b0319161561051557600061050a826001610991565b835250909392505050565b6104c4565b5060408051600080825260208201909252905b509392505050565b8361057b576105438361049a565b6101d160f51b6105528461049a565b61080f60f21b610561856105fa565b6040516101ad959493929190601f60f91b906020016109b9565b50505050565b6060600080846001600160a01b03168460405161059e9190610a17565b600060405180830381855af49150503d80600081146105d9576040519150601f19603f3d011682016040523d82523d6000602084013e6105de565b606091505b5091509150816105f0576105f0610a23565b9150505b92915050565b60408051602a80825260608281019093526001600160a01b03841691600091602082018180368337019050509050603060f81b816000815181106106405761064061097b565b60200101906001600160f81b031916908160001a905350607860f81b8160018151811061066f5761066f61097b565b60200101906001600160f81b031916908160001a90535060005b601481101561052d57600061069f826002610a39565b90506106ad600f8516610740565b836106b9836029610808565b815181106106c9576106c961097b565b60200101906001600160f81b031916908160001a905350600484901c93506106f3600f8516610740565b836106ff836028610808565b8151811061070f5761070f61097b565b60200101906001600160f81b031916908160001a9053505060049290921c918061073881610a58565b915050610689565b6000600a82101561075f57610756603083610991565b60f81b92915050565b610756605783610991565b8015155b82525050565b602081016105f4828461076a565b60006001600160a01b0382166105f4565b61076e81610782565b602081016105f48284610793565b6107b381610782565b811461046757600080fd5b80356105f4816107aa565b6000602082840312156107de576107de600080fd5b60006107ea84846107be565b949350505050565b634e487b7160e01b600052601160045260246000fd5b60008282101561081a5761081a6107f2565b500390565b60005b8381101561083a578181015183820152602001610822565b8381111561057b5750506000910152565b6000610855825190565b61086381856020860161081f565b9290920192915050565b6001600160f01b0319811661076e565b6000610889828661084b565b9150610895828561086d565b6002820191506108a5828461084b565b95945050505050565b60006108b8825190565b8084526020840193506108cf81856020860161081f565b601f01601f19169290920192915050565b602080825281016108f181846108ae565b9392505050565b80516105f4816107aa565b60006020828403121561091857610918600080fd5b60006107ea84846108f8565b6001600160e01b0319811661076e565b60006109408284610924565b50600401919050565b8061076e565b600061095b8284610949565b50602001919050565b600081610973576109736107f2565b506000190190565b634e487b7160e01b600052603260045260246000fd5b600082198211156109a4576109a46107f2565b500190565b6001600160f81b0319811661076e565b60006109c5828961084b565b91506109d1828861086d565b6002820191506109e1828761084b565b91506109ed828661086d565b6002820191506109fd828561084b565b9150610a0982846109a9565b506001019695505050505050565b60006108f1828461084b565b634e487b7160e01b600052600160045260246000fd5b6000816000190483118215151615610a5357610a536107f2565b500290565b6000600019821415610a6c57610a6c6107f2565b506001019056fea2646970667358221220042cd31a4ef21419de1319dd2e6091cb23c0bf7eae19c59815c14a0bd44e629164736f6c6343000809003349736f6c6174696f6e4d6f64655661756c74466163746f727900000000000000a2646970667358221220e0e9a07606baf493acaf86ec088a2ec1165bc9aa51918fe55206bbba31cc258064736f6c63430008090033

Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)

00000000000000000000000066d4d46b140149dfa603de01aac4b337234950010000000000000000000000008be66a48ea1f4aff89cd2beb50b02d901dfb9584000000000000000000000000e99a7e4556caf7925fbac52765128e524e9dd793000000000000000000000000f0c0db8e4e01bd9a8e01860ef83077405a53f781000000000000000000000000e6ef4f0b2455bab92ce7cc78e35324ab58917de8

-----Decoded View---------------
Arg [0] : _pendleRegistry (address): 0x66D4D46B140149DfA603DE01Aac4b33723495001
Arg [1] : _ptToken (address): 0x8be66A48EA1f4AFF89cd2beb50B02D901Dfb9584
Arg [2] : _borrowPositionProxy (address): 0xe99A7e4556CaF7925fbac52765128e524E9Dd793
Arg [3] : _userVaultImplementation (address): 0xf0C0Db8E4e01BD9A8e01860ef83077405a53f781
Arg [4] : _dolomiteMargin (address): 0xE6Ef4f0B2455bAB92ce7cC78E35324ab58917De8

-----Encoded View---------------
5 Constructor Arguments found :
Arg [0] : 00000000000000000000000066d4d46b140149dfa603de01aac4b33723495001
Arg [1] : 0000000000000000000000008be66a48ea1f4aff89cd2beb50b02d901dfb9584
Arg [2] : 000000000000000000000000e99a7e4556caf7925fbac52765128e524e9dd793
Arg [3] : 000000000000000000000000f0c0db8e4e01bd9a8e01860ef83077405a53f781
Arg [4] : 000000000000000000000000e6ef4f0b2455bab92ce7cc78e35324ab58917de8


Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

Block Uncle Number Difficulty Gas Used Reward
View All Uncles
Loading...
Loading
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.