BERA Price: $3.70 (+0.53%)

Contract

0xD6C1b15716742689c5b33C19c78D9d2a1494bF33

Overview

BERA Balance

Berachain LogoBerachain LogoBerachain Logo0 BERA

BERA Value

$0.00

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To
Swap Exact Input...40883712025-04-23 13:41:1811 secs ago1745415678IN
0xD6C1b157...a1494bF33
0 BERA00.00000027
Swap Exact Input...40883682025-04-23 13:41:1118 secs ago1745415671IN
0xD6C1b157...a1494bF33
0 BERA0.000354410.29222183
Swap Exact Input...40883412025-04-23 13:40:171 min ago1745415617IN
0xD6C1b157...a1494bF33
0 BERA00.00000301
Swap Exact Input...40882742025-04-23 13:38:003 mins ago1745415480IN
0xD6C1b157...a1494bF33
0 BERA00.00000012
Swap Exact Input...40878962025-04-23 13:25:2616 mins ago1745414726IN
0xD6C1b157...a1494bF33
0 BERA00.000001
Swap Exact Input...40874182025-04-23 13:09:3831 mins ago1745413778IN
0xD6C1b157...a1494bF33
0 BERA0.000005740.004751
Swap Exact Input...40872422025-04-23 13:03:5037 mins ago1745413430IN
0xD6C1b157...a1494bF33
0 BERA0.000000480.000501
Swap Exact Input...40865292025-04-23 12:40:211 hr ago1745412021IN
0xD6C1b157...a1494bF33
0 BERA00.000001
Swap Exact Input...40864812025-04-23 12:38:471 hr ago1745411927IN
0xD6C1b157...a1494bF33
0 BERA0.000159530.15
Swap Exact Input...40861612025-04-23 12:28:171 hr ago1745411297IN
0xD6C1b157...a1494bF33
0 BERA00.000004
Swap Exact Input...40855212025-04-23 12:07:181 hr ago1745410038IN
0xD6C1b157...a1494bF33
0 BERA00.00000006
Swap Exact Input...40855072025-04-23 12:06:491 hr ago1745410009IN
0xD6C1b157...a1494bF33
0 BERA00.00000005
Swap Exact Input...40848302025-04-23 11:44:321 hr ago1745408672IN
0xD6C1b157...a1494bF33
0 BERA00.00000005
Swap Exact Input...40848122025-04-23 11:43:571 hr ago1745408637IN
0xD6C1b157...a1494bF33
0 BERA00.00000005
Swap Exact Input...40847642025-04-23 11:42:231 hr ago1745408543IN
0xD6C1b157...a1494bF33
0 BERA0.000275320.20493113
Swap Exact Input...40845432025-04-23 11:35:052 hrs ago1745408105IN
0xD6C1b157...a1494bF33
0 BERA00.000001
Swap Exact Input...40844342025-04-23 11:31:322 hrs ago1745407892IN
0xD6C1b157...a1494bF33
0 BERA00.000001
Swap Exact Input...40825912025-04-23 10:31:013 hrs ago1745404261IN
0xD6C1b157...a1494bF33
0 BERA00.000001
Swap Exact Input...40825332025-04-23 10:29:073 hrs ago1745404147IN
0xD6C1b157...a1494bF33
0 BERA00.00000005
Swap Exact Input...40821932025-04-23 10:17:573 hrs ago1745403477IN
0xD6C1b157...a1494bF33
0 BERA0.000600610.5
Swap Exact Input...40817702025-04-23 10:04:083 hrs ago1745402648IN
0xD6C1b157...a1494bF33
0 BERA00.00000032
Swap Exact Input...40812302025-04-23 9:46:253 hrs ago1745401585IN
0xD6C1b157...a1494bF33
0 BERA0.000767710.5
Swap Exact Input...40811972025-04-23 9:45:203 hrs ago1745401520IN
0xD6C1b157...a1494bF33
0 BERA0.000554250.5
Swap Exact Input...40810942025-04-23 9:41:583 hrs ago1745401318IN
0xD6C1b157...a1494bF33
0 BERA0.000261870.15
Swap Exact Input...40797732025-04-23 8:58:324 hrs ago1745398712IN
0xD6C1b157...a1494bF33
0 BERA0.000196710.15
View all transactions

Latest 1 internal transaction

Parent Transaction Hash Block From To
20301432025-03-07 15:29:3546 days ago1741361375  Contract Creation0 BERA
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
GenericTraderProxyV2

Compiler Version
v0.8.9+commit.e5eed63a

Optimization Enabled:
Yes with 200 runs

Other Settings:
default evmVersion
File 1 of 44 : GenericTraderProxyV2.sol
// SPDX-License-Identifier: GPL-3.0-or-later
/*

    Copyright 2024 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 { ReentrancyGuard } from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import { GenericTraderProxyBase } from "./GenericTraderProxyBase.sol";
import { GenericTraderProxyV2Lib } from "./GenericTraderProxyV2Lib.sol";
import { AuthorizationBase } from "../helpers/AuthorizationBase.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 { TypesLib } from "../protocol/lib/TypesLib.sol";
import { IGenericTraderProxyV2 } from "./interfaces/IGenericTraderProxyV2.sol";


/**
 * @title   GenericTraderProxyV2
 * @author  Dolomite
 *
 * Router contract for trading any asset from msg.sender
 */
contract GenericTraderProxyV2 is GenericTraderProxyBase, ReentrancyGuard, AuthorizationBase, IGenericTraderProxyV2 {
    using TypesLib for IDolomiteStructs.Wei;

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

    bytes32 private constant _FILE = "GenericTraderProxyV2";
    uint256 private constant TRANSFER_ACCOUNT_ID = 2;

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

    modifier notExpired(uint256 _deadline) {
        Require.that(
            _deadline >= block.timestamp,
            _FILE,
            "Deadline expired",
            _deadline,
            block.timestamp
        );
        _;
    }

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

    constructor(
        address _dolomiteRegistry,
        address _dolomiteMargin
    ) GenericTraderProxyBase(_dolomiteRegistry) AuthorizationBase(_dolomiteMargin) {
    }

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

    function swapExactInputForOutput(
        SwapExactInputForOutputParams memory _params
    ) public nonReentrant {
        _swapExactInputForOutput(/* _accountOwner = */ msg.sender, _params);
    }

    function swapExactInputForOutputForDifferentAccount(
        address _accountOwner,
        SwapExactInputForOutputParams memory _params
    ) public nonReentrant requireIsCallerAuthorized(msg.sender) {
        _swapExactInputForOutput(_accountOwner, _params);
    }

    function swapExactInputForOutputAndModifyPosition(
        SwapExactInputForOutputAndModifyPositionParams memory _params
    ) public nonReentrant {
        _swapExactInputForOutputAndModifyPosition(/* _accountOwner = */ msg.sender, _params);
    }

    function swapExactInputForOutputAndModifyPositionForDifferentAccount(
        address _accountOwner,
        SwapExactInputForOutputAndModifyPositionParams memory _params
    ) public nonReentrant requireIsCallerAuthorized(msg.sender) {
        _swapExactInputForOutputAndModifyPosition(_accountOwner, _params);
    }

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

    function _swapExactInputForOutput(
        address _user,
        SwapExactInputForOutputParams memory _params
    ) internal notExpired(_params.userConfig.deadline) {
        GenericTraderProxyCache memory cache = GenericTraderProxyCache({
            dolomiteMargin: DOLOMITE_MARGIN(),
            eventEmitterRegistry: DOLOMITE_REGISTRY.eventEmitter(),
            // unused for this function
            isMarginDeposit: false,
            // unused for this function
            otherAccountNumber: 0,
            feeTransferAccountIndex: 0,
            // traders go right after the trade account and zap account
            traderAccountStartIndex: ZAP_ACCOUNT_ID + 1,
            actionsCursor: 0,
            // unused for this function
            inputBalanceWeiBeforeOperate: TypesLib.zeroWei(),
            // unused for this function
            outputBalanceWeiBeforeOperate: TypesLib.zeroWei(),
            // unused for this function
            transferBalanceWeiBeforeOperate: TypesLib.zeroWei()
        });

        _validateMarketIdPath(_params.marketIdsPath);
        _params.inputAmountWei = _getActualInputAmountWei(
            cache,
            _user,
            _params.accountNumber,
            _params.marketIdsPath[0],
            _params.inputAmountWei
        );

        _validateAmountWeis(_params.inputAmountWei, _params.minOutputAmountWei);
        GenericTraderProxyV2Lib.validateTraderParams(
            cache,
            _params.marketIdsPath,
            _params.makerAccounts,
            _params.tradersPath
        );

        IDolomiteStructs.AccountInfo[] memory accounts = _getAccounts(
            cache,
            _params.makerAccounts,
            _user,
            _params.accountNumber,
            _params.tradersPath
        );
        _validateZapAccount(cache, accounts[ZAP_ACCOUNT_ID], _params.marketIdsPath);

        IDolomiteStructs.ActionArgs[] memory actions = new IDolomiteStructs.ActionArgs[](
            _getActionsLengthForTraderParams(
                cache,
                _params.tradersPath,
                accounts,
                _params.minOutputAmountWei
            )
        );
        _appendTraderActions(
            accounts,
            actions,
            cache,
            /* _isLiquidation = */ false,
            _params.marketIdsPath,
            _params.inputAmountWei,
            _params.minOutputAmountWei,
            _params.tradersPath
        );

        cache.dolomiteMargin.operate(accounts, actions);
        cache.eventEmitterRegistry.emitZapExecuted(
            _user,
            _params.accountNumber,
            _params.marketIdsPath,
            _params.tradersPath
        );

        if (
            _params.userConfig.balanceCheckFlag == AccountBalanceLib.BalanceCheckFlag.Both
            || _params.userConfig.balanceCheckFlag == AccountBalanceLib.BalanceCheckFlag.From
        ) {
            // Check that the trader's balance is not negative for the input market
            AccountBalanceLib.verifyBalanceIsNonNegative(
                cache.dolomiteMargin,
                accounts[TRADE_ACCOUNT_ID].owner,
                accounts[TRADE_ACCOUNT_ID].number,
                _params.marketIdsPath[0]
            );
        }
    }

    function _swapExactInputForOutputAndModifyPosition(
        address _accountOwner,
        SwapExactInputForOutputAndModifyPositionParams memory _params
    ) internal notExpired(_params.userConfig.deadline) {
        GenericTraderProxyCache memory cache = GenericTraderProxyCache({
            dolomiteMargin: DOLOMITE_MARGIN(),
            eventEmitterRegistry: DOLOMITE_REGISTRY.eventEmitter(),
            isMarginDeposit: _params.accountNumber == _params.transferCollateralParams.toAccountNumber,
            otherAccountNumber: _params.accountNumber == _params.transferCollateralParams.toAccountNumber
                ? _params.transferCollateralParams.fromAccountNumber
                : _params.transferCollateralParams.toAccountNumber,
            feeTransferAccountIndex: 0,
            // traders go right after the trade account, the zap account, and the transfer account ("other account")
            traderAccountStartIndex: TRANSFER_ACCOUNT_ID + 1,
            actionsCursor: 0,
            inputBalanceWeiBeforeOperate: TypesLib.zeroWei(),
            outputBalanceWeiBeforeOperate: TypesLib.zeroWei(),
            transferBalanceWeiBeforeOperate: TypesLib.zeroWei()
        });

        _validateMarketIdPath(_params.marketIdsPath);
        GenericTraderProxyV2Lib.validateTransferParams(cache, _params.transferCollateralParams, _params.accountNumber);

        // If we're transferring into the trade account and the input market is the transfer amount, we check the input
        // amount using the amount being transferred in
        if (
            _params.transferCollateralParams.toAccountNumber == _params.accountNumber
                && _params.marketIdsPath[0] == _params.transferCollateralParams.transferAmounts[0].marketId
        ) {
            _params.inputAmountWei = _getActualInputAmountWei(
                cache,
                _accountOwner,
                _params.transferCollateralParams.fromAccountNumber,
                _params.marketIdsPath[0],
                _params.transferCollateralParams.transferAmounts[0].amountWei
            );
        } else {
            _params.inputAmountWei = _getActualInputAmountWei(
                cache,
                _accountOwner,
                _params.accountNumber,
                _params.marketIdsPath[0],
                _params.inputAmountWei
            );
        }

        _validateAmountWeis(_params.inputAmountWei, _params.minOutputAmountWei);
        GenericTraderProxyV2Lib.validateTraderParams(
            cache,
            _params.marketIdsPath,
            _params.makerAccounts,
            _params.tradersPath
        );

        IDolomiteStructs.AccountInfo[] memory accounts = _getAccounts(
            cache,
            _params.makerAccounts,
            _accountOwner,
            _params.accountNumber,
            _params.tradersPath
        );
        // the call to `_getAccounts` leaves accounts[TRANSFER_ACCOUNT_ID] unset, because it only fills in the traders
        // starting at the `traderAccountCursor` index
        accounts[TRANSFER_ACCOUNT_ID] = IDolomiteStructs.AccountInfo({
            owner: _accountOwner,
            number: cache.otherAccountNumber
        });
        _validateZapAccount(cache, accounts[ZAP_ACCOUNT_ID], _params.marketIdsPath);

        uint256 transferActionsLength = _getActionsLengthForTransferCollateralParam(_params.transferCollateralParams);
        IDolomiteStructs.ActionArgs[] memory actions = new IDolomiteStructs.ActionArgs[](
            _getActionsLengthForTraderParams(
                cache,
                _params.tradersPath,
                accounts,
                _params.minOutputAmountWei
            )
                + transferActionsLength
                + _getActionsLengthForExpiryParam(_params.expiryParams)
        );

        _appendTraderActions(
            accounts,
            actions,
            cache,
            /* _isLiquidation = */ false,
            _params.marketIdsPath,
            _params.inputAmountWei,
            _params.minOutputAmountWei,
            _params.tradersPath
        );
        uint256 lastMarketId = _params.marketIdsPath[_params.marketIdsPath.length - 1];
        _appendTransferActions(
            actions,
            cache,
            _params.transferCollateralParams,
            _params.accountNumber,
            transferActionsLength,
            lastMarketId
        );

        _appendExpiryActions(
            actions,
            cache,
            _params.expiryParams,
            /* _tradeAccount = */ accounts[TRADE_ACCOUNT_ID] // solium-disable-line indentation
        );

        // snapshot the balances before so they can be logged in `_logEvents`
        _snapshotBalancesInCache(
            cache,
            /* _tradeAccount = */ accounts[TRADE_ACCOUNT_ID], // solium-disable-line indentation
            _params.marketIdsPath,
            _params.transferCollateralParams
        );

        GenericTraderProxyV2Lib.logBeforeZapEvents(
            cache,
            accounts[TRADE_ACCOUNT_ID],
            _params.userConfig.eventType
        );

        cache.dolomiteMargin.operate(accounts, actions);

        GenericTraderProxyV2Lib.logAfterZapEvents(
            cache,
            accounts[TRADE_ACCOUNT_ID],
            _params.marketIdsPath,
            _params.tradersPath,
            _params.transferCollateralParams,
            _params.userConfig.eventType
        );

        if (
            _params.userConfig.balanceCheckFlag == AccountBalanceLib.BalanceCheckFlag.Both
            || _params.userConfig.balanceCheckFlag == AccountBalanceLib.BalanceCheckFlag.From
        ) {
            // Check that the trader's balance is not negative for the input market
            uint256 inputMarketId = _params.marketIdsPath[0];
            AccountBalanceLib.verifyBalanceIsNonNegative(
                cache.dolomiteMargin,
                accounts[TRADE_ACCOUNT_ID].owner,
                accounts[TRADE_ACCOUNT_ID].number,
                inputMarketId
            );
        }

        if (
            _params.userConfig.balanceCheckFlag == AccountBalanceLib.BalanceCheckFlag.Both
            || _params.userConfig.balanceCheckFlag == AccountBalanceLib.BalanceCheckFlag.To
        ) {
            uint256 length = _params.transferCollateralParams.transferAmounts.length;
            for (uint256 i; i < length; ++i) {
                AccountBalanceLib.verifyBalanceIsNonNegative(
                    cache.dolomiteMargin,
                    accounts[TRANSFER_ACCOUNT_ID].owner,
                    accounts[TRANSFER_ACCOUNT_ID].number,
                    _params.transferCollateralParams.transferAmounts[i].marketId
                );
            }
        }
    }

    function _appendTransferActions(
        IDolomiteStructs.ActionArgs[] memory _actions,
        GenericTraderProxyCache memory _cache,
        TransferCollateralParam memory _transferCollateralParam,
        uint256 _traderAccountNumber,
        uint256 _transferActionsLength,
        uint256 _lastMarketId
    ) internal view {
        // the `_traderAccountNumber` is always `accountId=0`
        uint256 fromAccountId = _transferCollateralParam.fromAccountNumber == _traderAccountNumber
            ? TRADE_ACCOUNT_ID
            : TRANSFER_ACCOUNT_ID;

        uint256 toAccountId = _transferCollateralParam.fromAccountNumber == _traderAccountNumber
            ? TRANSFER_ACCOUNT_ID
            : TRADE_ACCOUNT_ID;

        for (uint256 i; i < _transferActionsLength; i++) {
            if (_transferCollateralParam.transferAmounts[i].amountWei == type(uint256).max - 1) {
                Require.that(
                    _transferCollateralParam.transferAmounts[i].marketId == _lastMarketId,
                    _FILE,
                    "Invalid transfer marketId",
                    _transferCollateralParam.transferAmounts[i].marketId
                );
                Require.that(
                    fromAccountId == TRADE_ACCOUNT_ID,
                    _FILE,
                    "Invalid from account ID"
                );

                // We transfer to the amount we had before the swap finished
                _actions[_cache.actionsCursor++] = AccountActionLib.encodeTransferToTargetAmountAction(
                    fromAccountId,
                    toAccountId,
                    _transferCollateralParam.transferAmounts[i].marketId,
                    _cache.dolomiteMargin.getAccountWei(
                        IDolomiteStructs.AccountInfo({
                            owner: msg.sender,
                            number: _transferCollateralParam.fromAccountNumber
                        }),
                        _transferCollateralParam.transferAmounts[i].marketId
                    )
                );
            } else {
                _actions[_cache.actionsCursor++] = AccountActionLib.encodeTransferAction(
                    fromAccountId,
                    toAccountId,
                    _transferCollateralParam.transferAmounts[i].marketId,
                    IDolomiteStructs.AssetDenomination.Wei,
                    _transferCollateralParam.transferAmounts[i].amountWei
                );
            }
        }
    }

    function _appendExpiryActions(
        IDolomiteStructs.ActionArgs[] memory _actions,
        GenericTraderProxyCache memory _cache,
        ExpiryParam memory _param,
        IDolomiteStructs.AccountInfo memory _tradeAccount
    ) internal view {
        if (_param.expiryTimeDelta == 0) {
            // Don't append it if there's no expiry
            return;
        }

        _actions[_cache.actionsCursor++] = AccountActionLib.encodeExpirationAction(
            _tradeAccount,
            TRADE_ACCOUNT_ID,
            _param.marketId,
            address(DOLOMITE_REGISTRY.expiry()),
            _param.expiryTimeDelta
        );
    }

    function _snapshotBalancesInCache(
        GenericTraderProxyCache memory _cache,
        IDolomiteStructs.AccountInfo memory _tradeAccount,
        uint256[] memory _marketIdsPath,
        TransferCollateralParam memory _param
    ) internal view {
        _cache.inputBalanceWeiBeforeOperate = _cache.dolomiteMargin.getAccountWei(
            _tradeAccount,
            _marketIdsPath[0]
        );
        _cache.outputBalanceWeiBeforeOperate = _cache.dolomiteMargin.getAccountWei(
            _tradeAccount,
            _marketIdsPath[_marketIdsPath.length - 1]
        );
        _cache.transferBalanceWeiBeforeOperate = _cache.dolomiteMargin.getAccountWei(
            _tradeAccount,
            _param.transferAmounts[0].marketId
        );
    }

    function _getActualInputAmountWei(
        GenericTraderProxyCache memory _cache,
        address _accountOwner,
        uint256 _accountNumber,
        uint256 _marketId,
        uint256 _inputAmountWei
    ) internal view returns (uint256) {
        if (_inputAmountWei != type(uint256).max) {
            return _inputAmountWei;
        }

        IDolomiteStructs.Wei memory balanceWei = _cache.dolomiteMargin.getAccountWei(
            IDolomiteStructs.AccountInfo({
                owner: _accountOwner,
                number: _accountNumber
            }),
            _marketId
        );
        Require.that(
            !balanceWei.isNegative(),
            _FILE,
            "Balance must be positive",
            _marketId
        );
        return balanceWei.value;
    }

    function _getActionsLengthForTransferCollateralParam(
        TransferCollateralParam memory _param
    ) internal pure returns (uint256) {
        return _param.transferAmounts.length;
    }

    function _getActionsLengthForExpiryParam(
        ExpiryParam memory _param
    ) internal pure returns (uint256) {
        if (_param.expiryTimeDelta == 0) {
            return 0;
        } else {
            return 1;
        }
    }

    function _otherAccountId() internal pure override returns (uint256) {
        return TRADE_ACCOUNT_ID;
    }
}

File 2 of 44 : ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;

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

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

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be _NOT_ENTERED
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

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

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

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == _ENTERED;
    }
}

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

pragma solidity ^0.8.0;

import "../IERC20.sol";

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

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

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

File 4 of 44 : IERC20.sol
// 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);
}

File 5 of 44 : EnumerableSet.sol
// 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;
    }
}

File 6 of 44 : AuthorizationBase.sol
// SPDX-License-Identifier: Apache-2.0
/*

    Copyright 2022 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 { OnlyDolomiteMarginForUpgradeable } from "./OnlyDolomiteMarginForUpgradeable.sol";
import { IAuthorizationBase } from "../interfaces/IAuthorizationBase.sol";
import { Require } from "../protocol/lib/Require.sol";


/**
 * @title   AuthorizationBase
 * @author  Dolomite
 *
 */
contract AuthorizationBase is IAuthorizationBase, OnlyDolomiteMarginForUpgradeable {

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

    bytes32 private constant _FILE = "AuthorizationBase";

    // ============ State Variables ============

    mapping(address => bool) private _isCallerAuthorized;

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

    modifier requireIsCallerAuthorized(address _caller) {
        Require.that(
            _isCallerAuthorized[_caller],
            _FILE,
            "unauthorized",
            _caller
        );
        _;
    }

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

    constructor(address _dolomiteMargin) {
        _setDolomiteMarginViaSlot(_dolomiteMargin);
    }

    function setIsCallerAuthorized(address _caller, bool _isAuthorized) external onlyDolomiteMarginOwner(msg.sender) {
        Require.that(
            DOLOMITE_MARGIN().getIsGlobalOperator(msg.sender) || DOLOMITE_MARGIN().owner() == msg.sender,
            _FILE,
            "unauthorized",
            _caller
        );
        _isCallerAuthorized[_caller] = _isAuthorized;
    }

    function isCallerAuthorized(address _caller) external view returns (bool) {
        return _isCallerAuthorized[_caller];
    }
}

File 7 of 44 : OnlyDolomiteMarginForUpgradeable.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 { 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) {
        _requireOnlyDolomiteMargin(_from);
        _;
    }

    modifier onlyDolomiteMarginOwner(address _from) {
        _requireOnlyDolomiteMarginOwner(_from);
        _;
    }

    modifier onlyDolomiteMarginGlobalOperator(address _from) {
        _requireOnlyDolomiteMarginGlobalOperator(_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);
    }

    function _requireOnlyDolomiteMargin(address _from) internal view {
        Require.that(
            _from == address(DOLOMITE_MARGIN()),
            _FILE,
            "Only Dolomite can call function",
            _from
        );
    }

    function _requireOnlyDolomiteMarginOwner(address _from) internal view {
        Require.that(
            _from == DOLOMITE_MARGIN_OWNER(),
            _FILE,
            "Caller is not owner of Dolomite",
            _from
        );
    }

    function _requireOnlyDolomiteMarginGlobalOperator(address _from) internal view {
        Require.that(
            DOLOMITE_MARGIN().getIsGlobalOperator(_from),
            _FILE,
            "Caller is not a global operator",
            _from
        );
    }
}

File 8 of 44 : ProxyContractHelpers.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;


/**
 * @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 _setAddressInMap(bytes32 slot, address key, address _value) internal {
        // solhint-disable-next-line no-inline-assembly
        bytes32 mappingSlot = keccak256(abi.encode(key, slot));
        assembly {
            sstore(mappingSlot, _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 _getAddressFromMap(bytes32 slot, address key) internal view returns (address value) {
        // solhint-disable-next-line no-inline-assembly
        bytes32 mappingSlot = keccak256(abi.encode(key, slot));
        assembly {
            value := sload(mappingSlot)
        }
    }

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

File 9 of 44 : IAuthorizationBase.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;


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

File 10 of 44 : IBorrowPositionProxyV1.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 { 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;
}

File 11 of 44 : IBorrowPositionProxyV2.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 { 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;
}

File 12 of 44 : IDolomiteAccountRegistry.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 { 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 TransferTokenOverrideSet(address indexed _token, address _override);
    event VaultAddedToAccount(address _account, address _vault);

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

    function registerVault(
        address _account,
        address _vault
    ) external;

    function ownerSetRestrictedAccount(
        address _account,
        bool _isRestricted
    ) external;

    function ownerSetTransferTokenOverride(
        address _token,
        address _override
    ) 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);

    /**
     *
     * @param  _token   The token to check if there is an override. Must be listed by Dolomite Margin.
     * @return          The token that is used for conducting transfers for this token. For example, BGT is not
     *                  transferable and must be redeemed to BERA. Thus, inputting BGT should return a token override of
     *                  BERA.
     */
    function getTransferTokenOverride(address _token) 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);
}

File 13 of 44 : IDolomiteMigrator.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 "../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);
}

File 14 of 44 : IDolomiteRegistry.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 { IBorrowPositionProxyV2 } from "./IBorrowPositionProxyV2.sol";
import { IDolomiteAccountRegistry } from "./IDolomiteAccountRegistry.sol";
import { IDolomiteMigrator } from "./IDolomiteMigrator.sol";
import { IEventEmitterRegistry } from "./IEventEmitterRegistry.sol";
import { IExpiry } from "./IExpiry.sol";
import { ILiquidatorAssetRegistry } from "./ILiquidatorAssetRegistry.sol";
import { IDolomitePriceOracle } from "../protocol/interfaces/IDolomitePriceOracle.sol";
import { IGenericTraderProxyV2 } from "../proxies/interfaces/IGenericTraderProxyV2.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 {

    struct IsolationModeStorage {
        bytes4[] isolationModeMulticallFunctions;
    }

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

    event BorrowPositionProxySet(address indexed _borrowPositionProxy);
    event GenericTraderProxySet(address indexed _genericTraderProxy);
    event ExpirySet(address indexed _expiry);
    event FeeAgentSet(address indexed _feeAgent);
    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);
    event TrustedInternalTradersSet(address[] _trustedInternalTraders, bool[] _isTrusted);
    event IsolationModeMulticallFunctionsSet(bytes4[] _selectors);

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

    function lazyInitialize(address _dolomiteMigrator, address _oracleAggregator) external;

    /**
     *
     * @param  _borrowPositionProxy  The new address of the borrow position proxy
     */
    function ownerSetBorrowPositionProxy(address _borrowPositionProxy) 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  _feeAgent  The new address of the fee agent
     */
    function ownerSetFeeAgent(address _feeAgent) 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;

    /**
     *
     * @param  _trustedInternalTraders    The addresses of the trusted internal traders
     * @param  _isTrusted                 The boolean values for whether the traders are trusted
     */
    function ownerSetTrustedInternalTraders(
        address[] memory _trustedInternalTraders,
        bool[] memory _isTrusted
    ) external;

    /**
     *
     * @param  _selectors    Allowed function selectors for isolation mode multicall
     */
    function ownerSetIsolationModeMulticallFunctions(bytes4[] memory _selectors) external;

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

    /**
     * @return  The address of the borrow position proxy
     */
    function borrowPositionProxy() external view returns (IBorrowPositionProxyV2);

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

    /**
     * @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 fee agent
     */
    function feeAgent() external view returns (address);

    /**
     * @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 array of allowed function selectors for isolation mode multicall
     */
    function isolationModeMulticallFunctions() external view returns (bytes4[] memory);

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

    /**
     *
     * @param  _trader  The address of the trader
     * @return  Whether the trader is trusted
     */
    function isTrustedInternalTrader(address _trader) external view returns (bool);
}

File 15 of 44 : IEventEmitterRegistry.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 { 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;
}

File 16 of 44 : IExpiry.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";
import { IDolomiteStructs } from "../protocol/interfaces/IDolomiteStructs.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 callFunction(
        address /* sender */,
        IDolomiteStructs.AccountInfo memory account,
        bytes memory data
    ) external;

    function getLiquidationSpreadAdjustedPrices(
        IDolomiteStructs.AccountInfo calldata liquidAccount,
        uint256 heldMarketId,
        uint256 owedMarketId,
        uint32 expiry
    )
        external
        view
        returns (IDolomiteStructs.MonetaryPrice memory heldPrice, IDolomiteStructs.MonetaryPrice memory owedPriceAdj);

    /**
     * @notice Backwards-compatible version of this function for Dolomite Margin V1
     */
    function getSpreadAdjustedPrices(
        uint256 heldMarketId,
        uint256 owedMarketId,
        uint32 expiry
    )
        external
        view
        returns (IDolomiteStructs.MonetaryPrice memory heldPrice, IDolomiteStructs.MonetaryPrice memory owedPriceAdj);

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

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

File 17 of 44 : 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 { IEventEmitterRegistry } from "./IEventEmitterRegistry.sol";
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;
        IEventEmitterRegistry eventEmitterRegistry;
        /// @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 the fee transfer account is located.
        uint256 feeTransferAccountIndex;
        /// @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;
    }
}

File 18 of 44 : ILiquidatorAssetRegistry.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;

/**
 * @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 19 of 44 : 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);
}

File 20 of 44 : IInternalAutoTraderBase.sol
// SPDX-License-Identifier: GPL-3.0-or-later
/*

    Copyright 2025 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 { IDolomiteAutoTrader } from "../../protocol/interfaces/IDolomiteAutoTrader.sol";
import { IDolomiteStructs } from "../../protocol/interfaces/IDolomiteStructs.sol";


/**
 * @title   IInternalAutoTraderBase
 * @author  Dolomite
 *
 * Base interface for performing internal trades
 */
interface IInternalAutoTraderBase is IDolomiteAutoTrader {

    // ========================================================
    // ================== Structs Functions ==================
    // ========================================================

    struct InternalTradeParams {
        IDolomiteStructs.AccountInfo makerAccount;
        uint256 makerAccountId;
        uint256 amount;
        uint256 minOutputAmount;
    }

    struct InternalTraderBaseStorage {
        bool tradeEnabled;
        uint256 globalFee;
        uint256 adminFee;
    }

    struct CreateActionsForInternalTradeParams {
        uint256 takerAccountId;
        IDolomiteStructs.AccountInfo takerAccount;
        uint256 feeAccountId;
        IDolomiteStructs.AccountInfo feeAccount;
        uint256 inputMarketId;
        uint256 outputMarketId;
        uint256 inputAmountWei;
        InternalTradeParams[] trades;
        bytes extraData;
    }

    // ========================================================
    // ================== Events Functions ==================
    // ========================================================

    event GlobalFeeSet(uint256 indexed globalFee);
    event AdminFeeSet(uint256 indexed adminFee);
    event PairFeeSet(bytes32 indexed pairBytes, uint256 indexed fee);

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

    function ownerSetGlobalFee(uint256 _globalFee) external;
    function ownerSetAdminFee(uint256 _adminFee) external;

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

    function createActionsForInternalTrade(
        CreateActionsForInternalTradeParams memory _params
    ) external view returns (IDolomiteStructs.ActionArgs[] memory);

    function actionsLength(InternalTradeParams[] calldata _trades) external view returns (uint256);
}

File 21 of 44 : IIsolationModeUnwrapperTraderV2.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";
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);
}

File 22 of 44 : IIsolationModeVaultFactory.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 { 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);
}

File 23 of 44 : IIsolationModeWrapperTraderV2.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";
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);
}

File 24 of 44 : IUpgradeableAsyncIsolationModeUnwrapperTrader.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 { 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);
}

File 25 of 44 : IUpgradeableAsyncIsolationModeWrapperTrader.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 { 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);
}

File 26 of 44 : AccountActionLib.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 { 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 encodeInternalTradeActionWithCustomData(
        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) {
        // internal trades calculate inputAmount based on `_toAccountId` (the maker account), so the sign should be
        // positive to reflect this
        return IDolomiteStructs.ActionArgs({
            actionType: IDolomiteStructs.ActionType.Trade,
            accountId: _fromAccountId,
            amount: IDolomiteStructs.AssetAmount({
                sign: false,
                denomination: IDolomiteStructs.AssetDenomination.Wei,
                ref: _amountInWei == _ALL
                    ? IDolomiteStructs.AssetReference.Target
                    : IDolomiteStructs.AssetReference.Delta,
                value: _amountInWei == _ALL ? 0 : _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 encodeTransferToTargetAmountAction(
        uint256 _fromAccountId,
        uint256 _toAccountId,
        uint256 _marketId,
        IDolomiteStructs.Wei memory _targetAmountWei
    ) internal pure returns (IDolomiteStructs.ActionArgs memory) {
        return IDolomiteStructs.ActionArgs({
            actionType : IDolomiteStructs.ActionType.Transfer,
            accountId : _fromAccountId,
            amount : IDolomiteStructs.AssetAmount({
                sign: _targetAmountWei.sign,
                denomination: IDolomiteStructs.AssetDenomination.Wei,
                ref: IDolomiteStructs.AssetReference.Target,
                value: _targetAmountWei.value
            }),
            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("")
        });
    }
}

File 27 of 44 : AccountBalanceLib.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";
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
        );
    }
}

File 28 of 44 : ChainHelperLib.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;


/**
 * @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 29 of 44 : 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 {

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

    event CategorySet(uint256 indexed marketId, Category category);
    event CategoryParamSet(
        Category category,
        IDolomiteStructs.Decimal marginRatioOverride,
        IDolomiteStructs.Decimal liquidationRewardOverride
    );
    event RiskFeatureSet(uint256 indexed marketId, RiskFeature riskFeature, bytes extraData);
    event DefaultAccountCheckActivated();

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

    enum Category {
        NONE,
        BERA,
        BTC,
        ETH,
        STABLE
    }

    enum RiskFeature {
        NONE,
        /// @dev The asset cannot be used as collateral in a position and can only be borrowed
        BORROW_ONLY,
        /// @dev The asset cannot have other collateral assets held in the position and can only borrow specific debt
        SINGLE_COLLATERAL_WITH_STRICT_DEBT
    }

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

    struct CategoryStruct {
        Category category;
        IDolomiteStructs.Decimal marginRatioOverride;
        IDolomiteStructs.Decimal liquidationRewardOverride;
    }

    struct RiskFeatureStruct {
        RiskFeature riskFeature;
        bytes extraData;
    }

    struct SingleCollateralRiskStruct {
        uint256[] debtMarketIds;
        IDolomiteStructs.Decimal marginRatioOverride;
        IDolomiteStructs.Decimal liquidationRewardOverride;
    }

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

    function ownerSetCategoriesByMarketIds(
        uint256[] memory _marketIds,
        Category[] memory _categories
    ) external;

    function ownerSetCategoryByMarketId(
        uint256 _marketId,
        Category _category
    ) external;

    function ownerSetCategoryParam(
        Category _category,
        IDolomiteStructs.Decimal calldata _marginRatioOverride,
        IDolomiteStructs.Decimal calldata _liquidationRewardOverride
    ) external;

    function ownerSetRiskFeatureByMarketId(
        uint256 _marketId,
        RiskFeature _riskFeature,
        bytes calldata _extraData
    ) external;

    /**
     * @notice  Gets the risk overrides for a given account owner. In the context of an operation, this function is
     *          called within `_verifyFinalState`, after all of the operation's actions have occurred. Thus, it is safe
     *          to read the account's state from Dolomite Margin's storage.
     *
     * @param  _account                    The account whose risk override should be retrieved.
     * @return _marginRatioOverride         The margin ratio override for this account.
     * @return _liquidationRewardOverride   The liquidation spread override for this account.
     */
    function getAccountRiskOverride(
        IDolomiteStructs.AccountInfo calldata _account
    )
    external
    view
    returns
    (
        IDolomiteStructs.Decimal memory _marginRatioOverride,
        IDolomiteStructs.Decimal memory _liquidationRewardOverride
    );

    function getCategoryMaskByMarketIds(uint256[] memory _marketIds) external view returns (uint256);

    function getCategoryByMarketId(uint256 _marketId) external view returns (Category);

    function getCategoryParamByCategory(Category _category) external view returns (CategoryStruct memory);

    function getRiskFeatureByMarketId(uint256 _marketId) external view returns (RiskFeature);

    function getRiskFeatureForSingleCollateralByMarketId(
        uint256 _marketId
    ) external view returns (SingleCollateralRiskStruct[] memory params);
}

File 30 of 44 : IDolomiteAutoTrader.sol
// SPDX-License-Identifier: GPL-3.0-or-later
/*

    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 { IDolomiteStructs } from "./IDolomiteStructs.sol";


/**
 * @title   IDolomiteAutoTrader
 * @author  Dolomite
 *
 * Interface for Dolomite Auto-Traders
 */
interface IDolomiteAutoTrader {

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

    /**
     * Allows traders to make trades approved by this smart contract. The active trader's account is
     * the takerAccount and the passive account (for which this contract approves trades
     * on-behalf-of) is the makerAccount.
     *
     * @param  _inputMarketId   The market for which the trader specified the original amount
     * @param  _outputMarketId  The market for which the trader wants the resulting amount specified
     * @param  _makerAccount    The account for which this contract is making trades
     * @param  _takerAccount    The account requesting the trade
     * @param  _oldInputPar     The old principal amount for the makerAccount for the inputMarketId
     * @param  _newInputPar     The new principal amount for the makerAccount for the inputMarketId
     * @param  _inputDeltaWei   The change in token amount for the makerAccount for the inputMarketId
     * @param  _data            Arbitrary data passed in by the trader
     * @return                  The AssetAmount for the makerAccount for the outputMarketId
     */
    function getTradeCost(
        uint256 _inputMarketId,
        uint256 _outputMarketId,
        IDolomiteStructs.AccountInfo calldata _makerAccount,
        IDolomiteStructs.AccountInfo calldata _takerAccount,
        IDolomiteStructs.Par calldata _oldInputPar,
        IDolomiteStructs.Par calldata _newInputPar,
        IDolomiteStructs.Wei calldata _inputDeltaWei,
        bytes calldata _data
    )
        external
        returns (IDolomiteStructs.AssetAmount memory);
}

File 31 of 44 : IDolomiteInterestSetter.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;


/**
 * @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 32 of 44 : 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);

    function getLiquidationSpreadForAccountAndPair(
        AccountInfo calldata account,
        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);
}

File 33 of 44 : IDolomiteMarginAdmin.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 { 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;

    // ============ Owner Functions ============

    /**
     * Transfer ownership of DolomiteMargin to a new address
     */
    function transferOwnership(
        address newOwner
    )
    external;
}

File 34 of 44 : IDolomiteMarginExchangeWrapper.sol
// 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);
}

File 35 of 44 : IDolomiteOracleSentinel.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;


/**
 * @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 36 of 44 : 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 37 of 44 : 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;
    }
}

File 38 of 44 : DolomiteMarginMath.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 { 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;
    }
}

File 39 of 44 : ExcessivelySafeCall.sol
// SPDX-License-Identifier: Apache-2.0
/*

    Copyright 2022 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   ExcessivelySafeCall
 * @author  https://github.com/nomad-xyz
 *
 * @notice  This contract should be used to call other contracts that are potentially untrusted
 */
library ExcessivelySafeCall {

    function safeStaticCall(
        address _target,
        bytes4 _selector,
        bytes memory _calldata
    ) internal view returns (bool isSuccess, bytes memory returnData) {
        (isSuccess, returnData) = _target.staticcall(abi.encodeWithSelector(_selector, _calldata));
    }

    /**
     * @notice Use when you _really_ really _really_ don't trust the called
     * contract. This prevents the called contract from causing reversion of
     * the caller in as many ways as we can.
     *
     * @dev The main difference between this and a solidity low-level call is
     * that we limit the number of bytes that the callee can cause to be
     * copied to caller memory. This prevents stupid things like malicious
     * contracts returning 10,000,000 bytes causing a local OOG when copying
     * to memory.
     *
     * @param  _target      The address to call
     * @param  _gas         The amount of gas to forward to the remote contract
     * @param  _maxCopy     The maximum number of bytes of returndata to copy to memory.
     * @param  _calldata    The data to send to the remote contract
     * @return  success and returndata, as `.call()`. Returndata is capped to `_maxCopy` bytes.
     */
    function excessivelySafeCall(
        address _target,
        uint256 _gas,
        uint16 _maxCopy,
        bytes memory _calldata
    ) internal returns (bool, bytes memory) {
        // set up for assembly call
        uint256 _toCopy;
        bool _success;
        bytes memory _returndata = new bytes(_maxCopy);
        // dispatch message to recipient
        // by assembly calling "handle" function
        // we call via assembly to avoid mem-copying a very large returnData
        // returned by a malicious contract
        /* solium-disable security/no-inline-assembly */
        assembly {
            _success := call(
                _gas, // gas
                _target, // recipient
                0, // ether value
                add(_calldata, 0x20), // inloc
                mload(_calldata), // inlen
                0, // outloc
                0 // outlen
            )
            // limit our copy to 256 bytes
            _toCopy := returndatasize()
            if gt(_toCopy, _maxCopy) {
                _toCopy := _maxCopy
            }
            // Store the length of the copied bytes
            mstore(_returndata, _toCopy)
            // copy the bytes from returndata[0:_toCopy]
            returndatacopy(add(_returndata, 0x20), 0, _toCopy)
        }
        /* solium-enable security/no-inline-assembly */
        return (_success, _returndata);
    }

    /**
     * @notice Use when you _really_ really _really_ don't trust the called
     * contract. This prevents the called contract from causing reversion of
     * the caller in as many ways as we can.
     *
     * @dev The main difference between this and a solidity low-level call is
     * that we limit the number of bytes that the callee can cause to be
     * copied to caller memory. This prevents stupid things like malicious
     * contracts returning 10,000,000 bytes causing a local OOG when copying
     * to memory.
     *
     * @param  _target      The address to call
     * @param  _gas         The amount of gas to forward to the remote contract
     * @param  _maxCopy     The maximum number of bytes of returndata to copy to memory.
     * @param  _calldata    The data to send to the remote contract
     * @return success and returndata, as `.call()`. Returndata is capped to `_maxCopy` bytes.
     */
    function excessivelySafeStaticCall(
        address _target,
        uint256 _gas,
        uint16 _maxCopy,
        bytes memory _calldata
    ) internal view returns (bool, bytes memory) {
        // set up for assembly call
        uint256 _toCopy;
        bool _success;
        bytes memory _returndata = new bytes(_maxCopy);
        // dispatch message to recipient
        // by assembly calling "handle" function
        // we call via assembly to avoid mem-copying a very large returndata
        // returned by a malicious contract
        /* solium-disable security/no-inline-assembly */
        assembly {
            _success := staticcall(
                _gas, // gas
                _target, // recipient
                add(_calldata, 0x20), // inloc
                mload(_calldata), // inlen
                0, // outloc
                0 // outlen
            )
            // limit our copy to 256 bytes
            _toCopy := returndatasize()
            if gt(_toCopy, _maxCopy) {
                _toCopy := _maxCopy
            }
            // Store the length of the copied bytes
            mstore(_returndata, _toCopy)
            // copy the bytes from returndata[0:_toCopy]
            returndatacopy(add(_returndata, 0x20), 0, _toCopy)
        }
        /* solium-enable security/no-inline-assembly */
        return (_success, _returndata);
    }
}

File 40 of 44 : Require.sol
// 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));
    }
}

File 41 of 44 : TypesLib.sol
// 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;
    }
}

File 42 of 44 : GenericTraderProxyBase.sol
// SPDX-License-Identifier: GPL-3.0-or-later
/*

    Copyright 2024 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 "../interfaces/IDolomiteRegistry.sol";
import { IGenericTraderBase } from "../interfaces/IGenericTraderBase.sol";
import { IInternalAutoTraderBase } from "../interfaces/traders/IInternalAutoTraderBase.sol";
import { IIsolationModeUnwrapperTraderV2 } from "../isolation-mode/interfaces/IIsolationModeUnwrapperTraderV2.sol";
import { IIsolationModeWrapperTraderV2 } from "../isolation-mode/interfaces/IIsolationModeWrapperTraderV2.sol";
import { AccountActionLib } from "../lib/AccountActionLib.sol";
import { IDolomiteStructs } from "../protocol/interfaces/IDolomiteStructs.sol";
import { Require } from "../protocol/lib/Require.sol";


/**
 * @title   GenericTraderProxyBase
 * @author  Dolomite
 *
 * @notice  Base contract with validation and utilities for trading any asset from an account
 */
abstract contract GenericTraderProxyBase is IGenericTraderBase {

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

    bytes32 private constant _FILE = "GenericTraderProxyBase";

    uint256 internal constant DEFAULT_ACCOUNT_NUMBER = 0;
    /// @dev The index of the trade account in the accounts array (for executing an operation)
    uint256 internal constant TRADE_ACCOUNT_ID = 0;
    uint256 internal constant ZAP_ACCOUNT_ID = 1;

    IDolomiteRegistry public immutable DOLOMITE_REGISTRY;

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

    constructor (
        address _dolomiteRegistry
    ) {
        DOLOMITE_REGISTRY = IDolomiteRegistry(_dolomiteRegistry);
    }

    function _validateMarketIdPath(
        uint256[] memory _marketIdsPath
    ) internal pure {
        Require.that(
            _marketIdsPath.length >= 2,
            _FILE,
            "Invalid market path length"
        );
    }

    function _validateAmountWeis(
        uint256 _inputAmountWei,
        uint256 _minOutputAmountWei
    ) internal pure {
        Require.that(
            _inputAmountWei != 0,
            _FILE,
            "Invalid inputAmountWei"
        );
        Require.that(
            _minOutputAmountWei != 0,
            _FILE,
            "Invalid minOutputAmountWei"
        );
    }

    function _validateZapAccount(
        GenericTraderProxyCache memory _cache,
        IDolomiteStructs.AccountInfo memory _account,
        uint256[] memory _marketIdsPath
    ) internal view {
        uint256 marketIdsLength = _marketIdsPath.length;
        for (uint256 i; i < marketIdsLength; ++i) {
            // Panic if we're zapping to an account that has any value in it. Why? Because we don't want execute trades
            // where we sell ALL if there's already value in the account. That would mess up the user's holdings and
            // unintentionally sell assets the user does not want to sell.
            assert(_cache.dolomiteMargin.getAccountPar(_account, _marketIdsPath[i]).value == 0);
        }
    }

    function _getAccounts(
        GenericTraderProxyCache memory _cache,
        IDolomiteStructs.AccountInfo[] memory _makerAccounts,
        address _tradeAccountOwner,
        uint256 _tradeAccountNumber,
        IGenericTraderBase.TraderParam[] memory _tradersPath
    )
        internal
        view
        returns (IDolomiteStructs.AccountInfo[] memory)
    {
        bool foundInternalLiq = false;
        for (uint256 i; i < _tradersPath.length; ++i) {
            if (_tradersPath[i].traderType == TraderType.InternalLiquidity) {
                foundInternalLiq = true;
                _cache.feeTransferAccountIndex = _cache.traderAccountStartIndex;
                _cache.traderAccountStartIndex = _cache.feeTransferAccountIndex + 1;
                break;
            }
        }

        IDolomiteStructs.AccountInfo[] memory accounts = new IDolomiteStructs.AccountInfo[](
            _cache.traderAccountStartIndex + _makerAccounts.length
        );
        accounts[TRADE_ACCOUNT_ID] = IDolomiteStructs.AccountInfo({
            owner: _tradeAccountOwner,
            number: _tradeAccountNumber
        });
        accounts[ZAP_ACCOUNT_ID] = IDolomiteStructs.AccountInfo({
            owner: _tradeAccountOwner,
            number: _calculateZapAccountNumber(_tradeAccountOwner, _tradeAccountNumber)
        });

        if (foundInternalLiq) {
            accounts[_cache.feeTransferAccountIndex] = IDolomiteStructs.AccountInfo({
                owner: DOLOMITE_REGISTRY.feeAgent(),
                number: DEFAULT_ACCOUNT_NUMBER
            });
        }

        _appendTradersToAccounts(_cache, _makerAccounts, accounts);
        return accounts;
    }

    function _appendTradersToAccounts(
        GenericTraderProxyCache memory _cache,
        IDolomiteStructs.AccountInfo[] memory _makerAccounts,
        IDolomiteStructs.AccountInfo[] memory _accounts
    )
        internal
        pure
    {
        uint256 makerAccountsLength = _makerAccounts.length;
        for (uint256 i; i < makerAccountsLength; ++i) {
            IDolomiteStructs.AccountInfo memory account = _accounts[_cache.traderAccountStartIndex + i];
            assert(account.owner == address(0) && account.number == 0);

            _accounts[_cache.traderAccountStartIndex + i] = IDolomiteStructs.AccountInfo({
                owner: _makerAccounts[i].owner,
                number: _makerAccounts[i].number
            });
        }
    }

    function _getActionsLengthForTraderParams(
        GenericTraderProxyCache memory _cache,
        TraderParam[] memory _tradersPath,
        IDolomiteStructs.AccountInfo[] memory _accounts,
        uint256 _minOutputAmountWei
    )
        internal
        view
        returns (uint256)
    {
        uint256 actionsLength = 2; // start at 2 for the zap in/out of the zap account (2 transfer actions)
        uint256 tradersPathLength = _tradersPath.length;
        for (uint256 i; i < tradersPathLength; ++i) {
            if (_isUnwrapperTraderType(_tradersPath[i].traderType)) {
                actionsLength += IIsolationModeUnwrapperTraderV2(_tradersPath[i].trader).actionsLength();
            } else if (_isWrapperTraderType(_tradersPath[i].traderType)) {
                actionsLength += IIsolationModeWrapperTraderV2(_tradersPath[i].trader).actionsLength();
            } else if (_tradersPath[i].traderType == TraderType.InternalLiquidity) {
                actionsLength += IInternalAutoTraderBase(_tradersPath[i].trader).actionsLength(
                    _createSwapDataFromTradeParams(
                        _cache,
                        _tradersPath,
                        _accounts,
                        _minOutputAmountWei,
                        i
                    )
                );
            } else {
                // If it's not a `wrap` or `unwrap`, trades only require 1 action
                actionsLength += 1;
            }
        }
        return actionsLength;
    }

    function _appendTraderActions(
        IDolomiteStructs.AccountInfo[] memory _accounts,
        IDolomiteStructs.ActionArgs[] memory _actions,
        GenericTraderProxyCache memory _cache,
        bool _isLiquidation,
        uint256[] memory _marketIdsPath,
        uint256 _inputAmountWei,
        uint256 _minOutputAmountWei,
        TraderParam[] memory _tradersPath
    )
        internal
        view
    {
        // Before the trades are started, transfer inputAmountWei of the inputMarket
        // from the TRADE account to the ZAP account
        if (_inputAmountWei == AccountActionLib.all()) {

            IDolomiteStructs.Wei memory targetAmountWei;
            if (_isLiquidation) {
                // For liquidations, we TARGET whatever the trader has right now, before the operation occurs
                targetAmountWei = _cache.dolomiteMargin.getAccountWei(
                    _accounts[TRADE_ACCOUNT_ID],
                    _marketIdsPath[0]
                );
            } else {
                // For non-liquidations, we want to run the balance down to zero
                targetAmountWei = IDolomiteStructs.Wei({
                    sign: false,
                    value: 0
                });
            }

            _actions[_cache.actionsCursor++] = AccountActionLib.encodeTransferToTargetAmountAction(
                TRADE_ACCOUNT_ID,
                ZAP_ACCOUNT_ID,
                _marketIdsPath[0],
                targetAmountWei
            );
        } else {
            _actions[_cache.actionsCursor++] = AccountActionLib.encodeTransferAction(
                TRADE_ACCOUNT_ID,
                ZAP_ACCOUNT_ID,
                _marketIdsPath[0],
                IDolomiteStructs.AssetDenomination.Wei,
                _inputAmountWei
            );
        }

        uint256 tradersPathLength = _tradersPath.length;
        for (uint256 i; i < tradersPathLength; ++i) {
            if (_tradersPath[i].traderType == TraderType.ExternalLiquidity) {
                _actions[_cache.actionsCursor++] = AccountActionLib.encodeExternalSellAction(
                    ZAP_ACCOUNT_ID,
                    _marketIdsPath[i],
                    _marketIdsPath[i + 1],
                    _tradersPath[i].trader,
                    AccountActionLib.all(),
                    _getMinOutputAmountWeiForIndex(_minOutputAmountWei, i, tradersPathLength),
                    _tradersPath[i].tradeData
                );
            } else if (_tradersPath[i].traderType == TraderType.InternalLiquidity) {
                Require.that(
                    DOLOMITE_REGISTRY.isTrustedInternalTrader(_tradersPath[i].trader),
                    _FILE,
                    "Internal trader not whitelisted"
                );

                IInternalAutoTraderBase.InternalTradeParams[] memory trades =
                    _createSwapDataFromTradeParams(
                        _cache,
                        _tradersPath,
                        _accounts,
                        _minOutputAmountWei,
                        i
                    );

                IDolomiteStructs.ActionArgs[] memory tradeActions;
                {
                    IDolomiteStructs.AccountInfo[] memory accounts = _accounts;
                    GenericTraderProxyCache memory cache = _cache;
                    tradeActions = IInternalAutoTraderBase(_tradersPath[i].trader)
                        .createActionsForInternalTrade(
                            IInternalAutoTraderBase.CreateActionsForInternalTradeParams({
                                takerAccountId: ZAP_ACCOUNT_ID,
                                takerAccount: accounts[ZAP_ACCOUNT_ID],
                                feeAccountId: cache.feeTransferAccountIndex,
                                feeAccount: accounts[cache.feeTransferAccountIndex],
                                inputMarketId: _marketIdsPath[i],
                                outputMarketId: _marketIdsPath[i + 1],
                                inputAmountWei: AccountActionLib.all(),
                                trades: trades,
                                extraData: _tradersPath[i].tradeData
                            })
                        );
                }

                for (uint256 j; j < tradeActions.length; ++j) {
                    _actions[_cache.actionsCursor++] = tradeActions[j];
                }
            } else if (_isUnwrapperTraderType(_tradersPath[i].traderType)) {
                // We can't use a Require for the following assert, because there's already an invariant that enforces
                // the trader is an `IsolationModeWrapper` if the market ID at `i + 1` is in isolation mode. Meaning,
                // an unwrapper can never appear at the non-zero index because there is an invariant that checks the
                // `IsolationModeWrapper` is the last index
                assert(i == 0);
                IDolomiteStructs.ActionArgs[] memory unwrapActions =
                    IIsolationModeUnwrapperTraderV2(_tradersPath[i].trader).createActionsForUnwrapping(
                        IIsolationModeUnwrapperTraderV2.CreateActionsForUnwrappingParams({
                            primaryAccountId: ZAP_ACCOUNT_ID,
                            otherAccountId: _otherAccountId(),
                            primaryAccountOwner: _accounts[ZAP_ACCOUNT_ID].owner,
                            primaryAccountNumber: _accounts[ZAP_ACCOUNT_ID].number,
                            otherAccountOwner: _accounts[_otherAccountId()].owner,
                            otherAccountNumber: _accounts[_otherAccountId()].number,
                            outputMarket: _marketIdsPath[i + 1],
                            inputMarket: _marketIdsPath[i],
                            minOutputAmount: _getMinOutputAmountWeiForIndex(
                                _minOutputAmountWei,
                                /* _index = */ i, // solium-disable-line indentation
                                _tradersPath.length
                            ),
                            /* Cannot use ALL since it messes up the actions */
                            inputAmount: _inputAmountWei,
                            orderData: _tradersPath[i].tradeData
                        })
                    );

                for (uint256 j; j < unwrapActions.length; ++j) {
                    _actions[_cache.actionsCursor++] = unwrapActions[j];
                }
            } else {
                // Panic if the developer messed up the `else` statement here
                assert(_isWrapperTraderType(_tradersPath[i].traderType));
                Require.that(
                    i == tradersPathLength - 1,
                    _FILE,
                    "Wrapper must be the last trader"
                );

                IDolomiteStructs.ActionArgs[] memory wrapActions = IIsolationModeWrapperTraderV2(_tradersPath[i].trader)
                    .createActionsForWrapping(
                        IIsolationModeWrapperTraderV2.CreateActionsForWrappingParams({
                            primaryAccountId: ZAP_ACCOUNT_ID,
                            otherAccountId: _otherAccountId(),
                            primaryAccountOwner: _accounts[ZAP_ACCOUNT_ID].owner,
                            primaryAccountNumber: _accounts[ZAP_ACCOUNT_ID].number,
                            otherAccountOwner: _accounts[_otherAccountId()].owner,
                            otherAccountNumber: _accounts[_otherAccountId()].number,
                            outputMarket: _marketIdsPath[i + 1],
                            inputMarket: _marketIdsPath[i],
                            minOutputAmount: _getMinOutputAmountWeiForIndex(
                                _minOutputAmountWei,
                                /* _index = */ i, // solium-disable-line indentation
                                _tradersPath.length
                            ),
                            inputAmount: AccountActionLib.all(),
                            orderData: _tradersPath[i].tradeData
                        })
                    );

                for (uint256 j; j < wrapActions.length; ++j) {
                    _actions[_cache.actionsCursor++] = wrapActions[j];
                }
            }
        }

        // When the trades are finished, transfer all of the outputMarket from the ZAP account to the TRADE account
        _actions[_cache.actionsCursor++] = AccountActionLib.encodeTransferAction(
            ZAP_ACCOUNT_ID,
            TRADE_ACCOUNT_ID,
            _marketIdsPath[_marketIdsPath.length - 1],
            IDolomiteStructs.AssetDenomination.Wei,
            AccountActionLib.all()
        );
    }

    /**
     * @return  The index of the account that is not the Zap account. For the liquidation contract, this is
     *          the account being liquidated. For the GenericTrader contract this is the same as the trader account.
     */
    function _otherAccountId() internal pure virtual returns (uint256);

    function _isWrapperTraderType(
        TraderType _traderType
    )
        internal
        pure
        returns (bool)
    {
        return TraderType.IsolationModeWrapper == _traderType;
    }

    function _isUnwrapperTraderType(
        TraderType _traderType
    )
        internal
        pure
        returns (bool)
    {
        return TraderType.IsolationModeUnwrapper == _traderType;
    }

    function _createSwapDataFromTradeParams(
        GenericTraderProxyCache memory _cache,
        TraderParam[] memory _traderParams,
        IDolomiteStructs.AccountInfo[] memory _accounts,
        uint256 _minOutputAmountWei,
        uint256 _index
    ) internal pure returns (IInternalAutoTraderBase.InternalTradeParams[] memory) {
        IInternalAutoTraderBase.InternalTradeParams[] memory trades =
            new IInternalAutoTraderBase.InternalTradeParams[](1);
        trades[0].makerAccount = _accounts[_traderParams[_index].makerAccountIndex + _cache.traderAccountStartIndex];
        trades[0].makerAccountId = _traderParams[_index].makerAccountIndex + _cache.traderAccountStartIndex;
        trades[0].amount = AccountActionLib.all();
        trades[0].minOutputAmount = _getMinOutputAmountWeiForIndex(_minOutputAmountWei, _index, _traderParams.length);
        return trades;
    }

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

    /// @dev Calculate a randomized sub-account for where the zap occurs (and any intermediate swaps)
    function _calculateZapAccountNumber(
        address _tradeAccountOwner,
        uint256 _tradeAccountNumber
    )
        private
        view
        returns (uint256)
    {
        return uint256(keccak256(abi.encodePacked(_tradeAccountOwner, _tradeAccountNumber, block.timestamp)));
    }

    function _getMinOutputAmountWeiForIndex(
        uint256 _minOutputAmountWei,
        uint256 _index,
        uint256 _tradersPathLength
    )
        private
        pure
        returns (uint256)
    {
        return _index == _tradersPathLength - 1 ? _minOutputAmountWei : 1;
    }
}

File 43 of 44 : GenericTraderProxyV2Lib.sol
// SPDX-License-Identifier: GPL-3.0-or-later
/*

    Copyright 2024 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 { IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import { IEventEmitterRegistry } from "../interfaces/IEventEmitterRegistry.sol";
import { IGenericTraderBase } from "../interfaces/IGenericTraderBase.sol";
import { IIsolationModeUnwrapperTraderV2 } from "../isolation-mode/interfaces/IIsolationModeUnwrapperTraderV2.sol";
import { IIsolationModeVaultFactory } from "../isolation-mode/interfaces/IIsolationModeVaultFactory.sol";
import { IIsolationModeWrapperTraderV2 } from "../isolation-mode/interfaces/IIsolationModeWrapperTraderV2.sol";
import { IDolomiteMargin } from "../protocol/interfaces/IDolomiteMargin.sol";
import { IDolomiteStructs } from "../protocol/interfaces/IDolomiteStructs.sol";
import { ExcessivelySafeCall } from "../protocol/lib/ExcessivelySafeCall.sol";
import { Require } from "../protocol/lib/Require.sol";
import { TypesLib } from "../protocol/lib/TypesLib.sol";
import { IGenericTraderProxyV2 } from "./interfaces/IGenericTraderProxyV2.sol";


/**
 * @title   GenericTraderProxyV2Lib
 * @author  Dolomite
 *
 * @notice  Library contract for reducing code size of the GenericTraderRouter contract
 */
library GenericTraderProxyV2Lib {
    using TypesLib for IDolomiteStructs.Wei;

    bytes32 private constant _FILE = "GenericTraderProxyV2Lib";

    bytes32 internal constant DOLOMITE_FS_GLP_HASH = keccak256(bytes("Dolomite: Fee + Staked GLP"));
    string internal constant DOLOMITE_ISOLATION_PREFIX = "Dolomite Isolation:";

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

    function validateTraderParams(
        IGenericTraderBase.GenericTraderProxyCache memory _cache,
        uint256[] memory _marketIdsPath,
        IDolomiteStructs.AccountInfo[] memory _makerAccounts,
        IGenericTraderBase.TraderParam[] memory _traderParamsPath
    ) public view {
        Require.that(
            _marketIdsPath.length == _traderParamsPath.length + 1,
            _FILE,
            "Invalid traders params length"
        );

        uint256 traderParamsPathLength = _traderParamsPath.length;
        for (uint256 i; i < traderParamsPathLength; ++i) {
            validateTraderParam(
                _cache,
                _marketIdsPath,
                _makerAccounts,
                _traderParamsPath[i],
                /* _index = */ i // solium-disable-line indentation
            );
        }
    }

    function validateTraderParam(
        IGenericTraderBase.GenericTraderProxyCache memory _cache,
        uint256[] memory _marketIdsPath,
        IDolomiteStructs.AccountInfo[] memory _makerAccounts,
        IGenericTraderBase.TraderParam memory _traderParam,
        uint256 _index
    ) public view {
        Require.that(
            _traderParam.trader != address(0),
            _FILE,
            "Invalid trader at index",
            _index
        );

        uint256 marketId = _marketIdsPath[_index];
        uint256 nextMarketId = _marketIdsPath[_index + 1];
        validateIsolationModeStatusForTraderParam(
            _cache,
            marketId,
            nextMarketId,
            _traderParam
        );
        validateTraderTypeForTraderParam(
            _cache,
            marketId,
            nextMarketId,
            _traderParam,
            _index
        );
        validateMakerAccountForTraderParam(
            _makerAccounts,
            _traderParam,
            _index
        );
    }

    function validateIsolationModeStatusForTraderParam(
        IGenericTraderBase.GenericTraderProxyCache memory _cache,
        uint256 _marketId,
        uint256 _nextMarketId,
        IGenericTraderBase.TraderParam memory _traderParam
    ) public view {
        if (isIsolationModeMarket(_cache.dolomiteMargin, _marketId)) {
            // If the current market is in isolation mode, the trader type must be for isolation mode assets
            Require.that(
                _isUnwrapperTraderType(_traderParam.traderType),
                _FILE,
                "Invalid isolation mode unwrapper",
                _marketId,
                uint256(uint8(_traderParam.traderType))
            );

            if (isIsolationModeMarket(_cache.dolomiteMargin, _nextMarketId)) {
                // If the user is unwrapping into an isolation mode asset, the next market must trust this trader
                address isolationModeToken = _cache.dolomiteMargin.getMarketTokenAddress(_nextMarketId);
                Require.that(
                    IIsolationModeVaultFactory(isolationModeToken).isTokenConverterTrusted(_traderParam.trader),
                    _FILE,
                    "Invalid unwrap sequence",
                    _marketId,
                    _nextMarketId
                );
            }
        } else if (isIsolationModeMarket(_cache.dolomiteMargin, _nextMarketId)) {
            // If the next market is in isolation mode, the trader must wrap the current asset into the isolation asset.
            Require.that(
                _isWrapperTraderType(_traderParam.traderType),
                _FILE,
                "Invalid isolation mode wrapper",
                _nextMarketId,
                uint256(uint8(_traderParam.traderType))
            );
        } else {
            // If neither asset is in isolation mode, the trader type must be for non-isolation mode assets
            Require.that(
                _traderParam.traderType == IGenericTraderBase.TraderType.ExternalLiquidity
                    || _traderParam.traderType == IGenericTraderBase.TraderType.InternalLiquidity,
                _FILE,
                "Invalid trader type",
                uint256(uint8(_traderParam.traderType))
            );
        }
    }

    function validateTraderTypeForTraderParam(
        IGenericTraderBase.GenericTraderProxyCache memory _cache,
        uint256 _marketId,
        uint256 _nextMarketId,
        IGenericTraderBase.TraderParam memory _traderParam,
        uint256 _index
    ) public view {
        if (_isUnwrapperTraderType(_traderParam.traderType)) {
            IIsolationModeUnwrapperTraderV2 unwrapperTrader = IIsolationModeUnwrapperTraderV2(_traderParam.trader);
            address isolationModeToken = _cache.dolomiteMargin.getMarketTokenAddress(_marketId);
            Require.that(
                unwrapperTrader.token() == isolationModeToken,
                _FILE,
                "Invalid input for unwrapper",
                _index,
                _marketId
            );
            Require.that(
                unwrapperTrader.isValidOutputToken(_cache.dolomiteMargin.getMarketTokenAddress(_nextMarketId)),
                _FILE,
                "Invalid output for unwrapper",
                _index + 1,
                _nextMarketId
            );
            Require.that(
                IIsolationModeVaultFactory(isolationModeToken).isTokenConverterTrusted(_traderParam.trader),
                _FILE,
                "Unwrapper trader not enabled",
                _traderParam.trader,
                _marketId
            );
        } else if (_isWrapperTraderType(_traderParam.traderType)) {
            IIsolationModeWrapperTraderV2 wrapperTrader = IIsolationModeWrapperTraderV2(_traderParam.trader);
            address isolationModeToken = _cache.dolomiteMargin.getMarketTokenAddress(_nextMarketId);
            Require.that(
                wrapperTrader.isValidInputToken(_cache.dolomiteMargin.getMarketTokenAddress(_marketId)),
                _FILE,
                "Invalid input for wrapper",
                _index,
                _marketId
            );
            Require.that(
                wrapperTrader.token() == isolationModeToken,
                _FILE,
                "Invalid output for wrapper",
                _index + 1,
                _nextMarketId
            );
            Require.that(
                IIsolationModeVaultFactory(isolationModeToken).isTokenConverterTrusted(_traderParam.trader),
                _FILE,
                "Wrapper trader not enabled",
                _traderParam.trader,
                _nextMarketId
            );
        }
    }

    function validateMakerAccountForTraderParam(
        IDolomiteStructs.AccountInfo[] memory _makerAccounts,
        IGenericTraderBase.TraderParam memory _traderParam,
        uint256 _index
    ) public pure {
        if (IGenericTraderBase.TraderType.InternalLiquidity == _traderParam.traderType) {
            // The makerAccountOwner should be set if the traderType is InternalLiquidity
            Require.that(
                _traderParam.makerAccountIndex < _makerAccounts.length
                && _makerAccounts[_traderParam.makerAccountIndex].owner != address(0),
                _FILE,
                "Invalid maker account owner",
                _index
            );
        } else {
            // The makerAccountOwner and makerAccountNumber is not used if the traderType is not InternalLiquidity
            Require.that(
                _traderParam.makerAccountIndex == 0,
                _FILE,
                "Invalid maker account owner",
                _index
            );
        }
    }

    function validateTransferParams(
        IGenericTraderBase.GenericTraderProxyCache memory _cache,
        IGenericTraderProxyV2.TransferCollateralParam memory _param,
        uint256 _tradeAccountNumber
    ) public pure {
        Require.that(
            _param.transferAmounts.length != 0,
            _FILE,
            "Invalid transfer amounts length"
        );
        Require.that(
            _param.fromAccountNumber != _param.toAccountNumber,
            _FILE,
            "Cannot transfer to same account"
        );
        Require.that(
            _tradeAccountNumber == _param.fromAccountNumber ||  _tradeAccountNumber == _param.toAccountNumber,
            _FILE,
            "Invalid trade account number"
        );
        _cache.otherAccountNumber = _tradeAccountNumber == _param.toAccountNumber
            ? _param.fromAccountNumber
            : _param.toAccountNumber;

        uint256 length = _param.transferAmounts.length;
        for (uint256 i; i < length; ++i) {
            Require.that(
                _param.transferAmounts[i].amountWei != 0,
                _FILE,
                "Invalid transfer amount at index",
                i
            );
        }
    }

    function isIsolationModeMarket(IDolomiteMargin _dolomiteMargin, uint256 _marketId) public view returns (bool) {
        return isIsolationModeAsset(_dolomiteMargin.getMarketTokenAddress(_marketId));
    }

    function logBeforeZapEvents(
        IGenericTraderBase.GenericTraderProxyCache memory _cache,
        IDolomiteStructs.AccountInfo memory _tradeAccount,
        IGenericTraderProxyV2.EventEmissionType _eventType
    ) public {
        if (_eventType == IGenericTraderProxyV2.EventEmissionType.BorrowPosition) {
            _cache.eventEmitterRegistry.emitBorrowPositionOpen(
                _tradeAccount.owner,
                _tradeAccount.number
            );
        }
    }

    function logAfterZapEvents(
        IGenericTraderBase.GenericTraderProxyCache memory _cache,
        IDolomiteStructs.AccountInfo memory _tradeAccount,
        uint256[] memory _marketIdsPath,
        IGenericTraderBase.TraderParam[] memory _tradersPath,
        IGenericTraderProxyV2.TransferCollateralParam memory _transferParam,
        IGenericTraderProxyV2.EventEmissionType _eventType
    ) public {
        _cache.eventEmitterRegistry.emitZapExecuted(
            _tradeAccount.owner,
            _tradeAccount.number,
            _marketIdsPath,
            _tradersPath
        );

        if (_eventType == IGenericTraderProxyV2.EventEmissionType.MarginPosition) {
            _logMarginPositionEvent(
                _cache,
                _tradeAccount,
                _marketIdsPath,
                _transferParam
            );
        }
    }

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

    function isIsolationModeAsset(address _token) public view returns (bool) {
        (bool isSuccess, bytes memory returnData) = ExcessivelySafeCall.safeStaticCall(
            _token,
            IERC20Metadata(address(0)).name.selector,
            bytes("")
        );
        if (!isSuccess) {
            return false;
        }

        string memory name = abi.decode(returnData, (string));
        if (keccak256(bytes(name)) == DOLOMITE_FS_GLP_HASH) {
            return true;
        }
        return _startsWith(DOLOMITE_ISOLATION_PREFIX, name);
    }

    function _startsWith(string memory _start, string memory _str) internal pure returns (bool) {
        if (bytes(_start).length > bytes(_str).length) {
            return false;
        }

        bytes32 hash;
        assembly {
            let size := mload(_start)
            hash := keccak256(add(_str, 32), size)
        }
        return hash == keccak256(bytes(_start));
    }

    function _isWrapperTraderType(
        IGenericTraderBase.TraderType _traderType
    )
        internal
        pure
        returns (bool)
    {
        return IGenericTraderBase.TraderType.IsolationModeWrapper == _traderType;
    }

    function _isUnwrapperTraderType(
        IGenericTraderBase.TraderType _traderType
    )
        internal
        pure
        returns (bool)
    {
        return IGenericTraderBase.TraderType.IsolationModeUnwrapper == _traderType;
    }

    function _logMarginPositionEvent(
        IGenericTraderBase.GenericTraderProxyCache memory _cache,
        IDolomiteStructs.AccountInfo memory _tradeAccount,
        uint256[] memory _marketIdsPath,
        IGenericTraderProxyV2.TransferCollateralParam memory _param
    ) internal {
        IEventEmitterRegistry.BalanceUpdate memory inputBalanceUpdate;
        // solium-disable indentation
        {
            IDolomiteStructs.Wei memory inputBalanceWeiAfter = _cache.dolomiteMargin.getAccountWei(
                _tradeAccount,
                /* _inputToken = */ _marketIdsPath[0]
            );
            inputBalanceUpdate = IEventEmitterRegistry.BalanceUpdate({
                deltaWei: inputBalanceWeiAfter.sub(_cache.inputBalanceWeiBeforeOperate),
                newPar: _cache.dolomiteMargin.getAccountPar(_tradeAccount, _marketIdsPath[0])
            });
        }
        // solium-enable indentation

        IEventEmitterRegistry.BalanceUpdate memory outputBalanceUpdate;
        // solium-disable indentation
        {
            IDolomiteStructs.Wei memory outputBalanceWeiAfter = _cache.dolomiteMargin.getAccountWei(
                _tradeAccount,
                /* _outputToken = */ _marketIdsPath[_marketIdsPath.length - 1]
            );
            outputBalanceUpdate = IEventEmitterRegistry.BalanceUpdate({
                deltaWei: outputBalanceWeiAfter.sub(_cache.outputBalanceWeiBeforeOperate),
                newPar: _cache.dolomiteMargin.getAccountPar(_tradeAccount, _marketIdsPath[_marketIdsPath.length - 1])
            });
        }
        // solium-enable indentation

        IEventEmitterRegistry.BalanceUpdate memory marginBalanceUpdate;
        // solium-disable indentation
        {
            IDolomiteStructs.Wei memory marginBalanceWeiAfter = _cache.dolomiteMargin.getAccountWei(
                _tradeAccount,
                /* _transferToken = */_param.transferAmounts[0].marketId
            );
            marginBalanceUpdate = IEventEmitterRegistry.BalanceUpdate({
                deltaWei: marginBalanceWeiAfter.sub(_cache.transferBalanceWeiBeforeOperate),
                newPar: _cache.dolomiteMargin.getAccountPar(
                    _tradeAccount,
                    _param.transferAmounts[0].marketId
                )
            });
        }
        // solium-enable indentation

        // solhint-disable max-line-length
        if (_cache.isMarginDeposit) {
            _cache.eventEmitterRegistry.emitMarginPositionOpen(
                _tradeAccount.owner,
                _tradeAccount.number,
                /* _inputToken = */ _cache.dolomiteMargin.getMarketTokenAddress(_marketIdsPath[0]),
                /* _outputToken = */ _cache.dolomiteMargin.getMarketTokenAddress(_marketIdsPath[_marketIdsPath.length - 1]),
                /* _depositToken = */ _cache.dolomiteMargin.getMarketTokenAddress(_param.transferAmounts[0].marketId),
                inputBalanceUpdate,
                outputBalanceUpdate,
                marginBalanceUpdate
            );
        } else {
            _cache.eventEmitterRegistry.emitMarginPositionClose(
                _tradeAccount.owner,
                _tradeAccount.number,
                /* _inputToken = */ _cache.dolomiteMargin.getMarketTokenAddress(_marketIdsPath[0]),
                /* _outputToken = */ _cache.dolomiteMargin.getMarketTokenAddress(_marketIdsPath[_marketIdsPath.length - 1]),
                /* _withdrawalToken = */ _cache.dolomiteMargin.getMarketTokenAddress(_param.transferAmounts[0].marketId),
                inputBalanceUpdate,
                outputBalanceUpdate,
                marginBalanceUpdate
            );
        }
        // solhint-enable max-line-length
    }
}

File 44 of 44 : IGenericTraderProxyV2.sol
// SPDX-License-Identifier: GPL-3.0-or-later
/*

    Copyright 2024 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 "../../interfaces/IGenericTraderBase.sol";
import { AccountBalanceLib } from "../../lib/AccountBalanceLib.sol";
import { IDolomiteMargin } from "../../protocol/interfaces/IDolomiteMargin.sol";
import { IDolomiteStructs } from "../../protocol/interfaces/IDolomiteStructs.sol";


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

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

    enum EventEmissionType {
        None,
        BorrowPosition,
        MarginPosition
    }

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

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

    /**
     *
     * @param  _accountNumber               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.
     */
    struct SwapExactInputForOutputParams {
        uint256 accountNumber;
        uint256[] marketIdsPath;
        uint256 inputAmountWei;
        uint256 minOutputAmountWei;
        TraderParam[] tradersPath;
        IDolomiteMargin.AccountInfo[] makerAccounts;
        UserConfig userConfig;
    }

    /**
     *
     * @param  _accountNumber               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
     *                                      `_accountNumber` once the trades settle. One of
     *                                      `_params.fromAccountNumber` or `_params.toAccountNumber` must be equal to
     *                                      `_accountNumber`.
     * @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.
     */
    struct SwapExactInputForOutputAndModifyPositionParams {
        uint256 accountNumber;
        uint256[] marketIdsPath;
        uint256 inputAmountWei;
        uint256 minOutputAmountWei;
        TraderParam[] tradersPath;
        IDolomiteStructs.AccountInfo[] makerAccounts;
        TransferCollateralParam transferCollateralParams;
        ExpiryParam expiryParams;
        UserConfig userConfig;
    }

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

    /**
     * @dev     Swaps an exact amount of input for a minimum amount of output.
     *
     */
    function swapExactInputForOutput(
        SwapExactInputForOutputParams memory _params
    ) external;

    /**
     * @dev     Swaps an exact amount of input for a minimum amount of output.
     *
     */
    function swapExactInputForOutputForDifferentAccount(
        address _accountOwner,
        SwapExactInputForOutputParams memory _params
    ) external;


    function swapExactInputForOutputAndModifyPositionForDifferentAccount(
        address tradeAccountOwner,
        SwapExactInputForOutputAndModifyPositionParams memory params
    ) external;


    function swapExactInputForOutputAndModifyPosition(
        SwapExactInputForOutputAndModifyPositionParams memory _params
    ) external;
}

Settings
{
  "optimizer": {
    "enabled": true,
    "runs": 200,
    "details": {
      "yul": false
    }
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "libraries": {
    "contracts/proxies/GenericTraderProxyV2Lib.sol": {
      "GenericTraderProxyV2Lib": "0x76f0f76F1b2F2474f7e22f56A5c1573e8C604e6f"
    }
  }
}

Contract Security Audit

Contract ABI

API
[{"inputs":[{"internalType":"address","name":"_dolomiteRegistry","type":"address"},{"internalType":"address","name":"_dolomiteMargin","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"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":[{"internalType":"address","name":"_caller","type":"address"}],"name":"isCallerAuthorized","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_caller","type":"address"},{"internalType":"bool","name":"_isAuthorized","type":"bool"}],"name":"setIsCallerAuthorized","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"uint256","name":"accountNumber","type":"uint256"},{"internalType":"uint256[]","name":"marketIdsPath","type":"uint256[]"},{"internalType":"uint256","name":"inputAmountWei","type":"uint256"},{"internalType":"uint256","name":"minOutputAmountWei","type":"uint256"},{"components":[{"internalType":"enum IGenericTraderBase.TraderType","name":"traderType","type":"uint8"},{"internalType":"uint256","name":"makerAccountIndex","type":"uint256"},{"internalType":"address","name":"trader","type":"address"},{"internalType":"bytes","name":"tradeData","type":"bytes"}],"internalType":"struct IGenericTraderBase.TraderParam[]","name":"tradersPath","type":"tuple[]"},{"components":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"number","type":"uint256"}],"internalType":"struct IDolomiteStructs.AccountInfo[]","name":"makerAccounts","type":"tuple[]"},{"components":[{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"enum AccountBalanceLib.BalanceCheckFlag","name":"balanceCheckFlag","type":"uint8"},{"internalType":"enum IGenericTraderProxyV2.EventEmissionType","name":"eventType","type":"uint8"}],"internalType":"struct IGenericTraderProxyV2.UserConfig","name":"userConfig","type":"tuple"}],"internalType":"struct IGenericTraderProxyV2.SwapExactInputForOutputParams","name":"_params","type":"tuple"}],"name":"swapExactInputForOutput","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"uint256","name":"accountNumber","type":"uint256"},{"internalType":"uint256[]","name":"marketIdsPath","type":"uint256[]"},{"internalType":"uint256","name":"inputAmountWei","type":"uint256"},{"internalType":"uint256","name":"minOutputAmountWei","type":"uint256"},{"components":[{"internalType":"enum IGenericTraderBase.TraderType","name":"traderType","type":"uint8"},{"internalType":"uint256","name":"makerAccountIndex","type":"uint256"},{"internalType":"address","name":"trader","type":"address"},{"internalType":"bytes","name":"tradeData","type":"bytes"}],"internalType":"struct IGenericTraderBase.TraderParam[]","name":"tradersPath","type":"tuple[]"},{"components":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"number","type":"uint256"}],"internalType":"struct IDolomiteStructs.AccountInfo[]","name":"makerAccounts","type":"tuple[]"},{"components":[{"internalType":"uint256","name":"fromAccountNumber","type":"uint256"},{"internalType":"uint256","name":"toAccountNumber","type":"uint256"},{"components":[{"internalType":"uint256","name":"marketId","type":"uint256"},{"internalType":"uint256","name":"amountWei","type":"uint256"}],"internalType":"struct IGenericTraderProxyV2.TransferAmount[]","name":"transferAmounts","type":"tuple[]"}],"internalType":"struct IGenericTraderProxyV2.TransferCollateralParam","name":"transferCollateralParams","type":"tuple"},{"components":[{"internalType":"uint256","name":"marketId","type":"uint256"},{"internalType":"uint32","name":"expiryTimeDelta","type":"uint32"}],"internalType":"struct IGenericTraderProxyV2.ExpiryParam","name":"expiryParams","type":"tuple"},{"components":[{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"enum AccountBalanceLib.BalanceCheckFlag","name":"balanceCheckFlag","type":"uint8"},{"internalType":"enum IGenericTraderProxyV2.EventEmissionType","name":"eventType","type":"uint8"}],"internalType":"struct IGenericTraderProxyV2.UserConfig","name":"userConfig","type":"tuple"}],"internalType":"struct IGenericTraderProxyV2.SwapExactInputForOutputAndModifyPositionParams","name":"_params","type":"tuple"}],"name":"swapExactInputForOutputAndModifyPosition","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_accountOwner","type":"address"},{"components":[{"internalType":"uint256","name":"accountNumber","type":"uint256"},{"internalType":"uint256[]","name":"marketIdsPath","type":"uint256[]"},{"internalType":"uint256","name":"inputAmountWei","type":"uint256"},{"internalType":"uint256","name":"minOutputAmountWei","type":"uint256"},{"components":[{"internalType":"enum IGenericTraderBase.TraderType","name":"traderType","type":"uint8"},{"internalType":"uint256","name":"makerAccountIndex","type":"uint256"},{"internalType":"address","name":"trader","type":"address"},{"internalType":"bytes","name":"tradeData","type":"bytes"}],"internalType":"struct IGenericTraderBase.TraderParam[]","name":"tradersPath","type":"tuple[]"},{"components":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"number","type":"uint256"}],"internalType":"struct IDolomiteStructs.AccountInfo[]","name":"makerAccounts","type":"tuple[]"},{"components":[{"internalType":"uint256","name":"fromAccountNumber","type":"uint256"},{"internalType":"uint256","name":"toAccountNumber","type":"uint256"},{"components":[{"internalType":"uint256","name":"marketId","type":"uint256"},{"internalType":"uint256","name":"amountWei","type":"uint256"}],"internalType":"struct IGenericTraderProxyV2.TransferAmount[]","name":"transferAmounts","type":"tuple[]"}],"internalType":"struct IGenericTraderProxyV2.TransferCollateralParam","name":"transferCollateralParams","type":"tuple"},{"components":[{"internalType":"uint256","name":"marketId","type":"uint256"},{"internalType":"uint32","name":"expiryTimeDelta","type":"uint32"}],"internalType":"struct IGenericTraderProxyV2.ExpiryParam","name":"expiryParams","type":"tuple"},{"components":[{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"enum AccountBalanceLib.BalanceCheckFlag","name":"balanceCheckFlag","type":"uint8"},{"internalType":"enum IGenericTraderProxyV2.EventEmissionType","name":"eventType","type":"uint8"}],"internalType":"struct IGenericTraderProxyV2.UserConfig","name":"userConfig","type":"tuple"}],"internalType":"struct IGenericTraderProxyV2.SwapExactInputForOutputAndModifyPositionParams","name":"_params","type":"tuple"}],"name":"swapExactInputForOutputAndModifyPositionForDifferentAccount","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_accountOwner","type":"address"},{"components":[{"internalType":"uint256","name":"accountNumber","type":"uint256"},{"internalType":"uint256[]","name":"marketIdsPath","type":"uint256[]"},{"internalType":"uint256","name":"inputAmountWei","type":"uint256"},{"internalType":"uint256","name":"minOutputAmountWei","type":"uint256"},{"components":[{"internalType":"enum IGenericTraderBase.TraderType","name":"traderType","type":"uint8"},{"internalType":"uint256","name":"makerAccountIndex","type":"uint256"},{"internalType":"address","name":"trader","type":"address"},{"internalType":"bytes","name":"tradeData","type":"bytes"}],"internalType":"struct IGenericTraderBase.TraderParam[]","name":"tradersPath","type":"tuple[]"},{"components":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"number","type":"uint256"}],"internalType":"struct IDolomiteStructs.AccountInfo[]","name":"makerAccounts","type":"tuple[]"},{"components":[{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"enum AccountBalanceLib.BalanceCheckFlag","name":"balanceCheckFlag","type":"uint8"},{"internalType":"enum IGenericTraderProxyV2.EventEmissionType","name":"eventType","type":"uint8"}],"internalType":"struct IGenericTraderProxyV2.UserConfig","name":"userConfig","type":"tuple"}],"internalType":"struct IGenericTraderProxyV2.SwapExactInputForOutputParams","name":"_params","type":"tuple"}],"name":"swapExactInputForOutputForDifferentAccount","outputs":[],"stateMutability":"nonpayable","type":"function"}]

60a06040523480156200001157600080fd5b506040516200584e3803806200584e8339810160408190526200003491620000cb565b6001600160a01b03821660805260016000558062000052816200005b565b5050506200013e565b620000916200008c60017f01095cd170b13c49f67c675e3bc004094df00c531fa118e86b230655aba7aa1762000124565b829055565b50565b60006001600160a01b0382165b92915050565b620000b28162000094565b81146200009157600080fd5b8051620000a181620000a7565b60008060408385031215620000e357620000e3600080fd5b6000620000f18585620000be565b92505060206200010485828601620000be565b9150509250929050565b634e487b7160e01b600052601160045260246000fd5b6000828210156200013957620001396200010e565b500390565b6080516156d16200017d6000396000818161012f015281816105a701528181610ebd0152818161191501528181611fcb0152612bc101526156d16000f3fe608060405234801561001057600080fd5b50600436106100935760003560e01c80639c9f553e116100665780639c9f553e14610117578063c6d20c851461012a578063cbffd92114610151578063f5f713dc14610166578063f697ae991461017957600080fd5b806315c14a4a146100985780633b7ac16a146100b65780634929d081146100cb5780635f974be914610104575b600080fd5b6100a061018c565b6040516100ad91906139c9565b60405180910390f35b6100c96100c43660046140a8565b6101c5565b005b6100f76100d93660046140ff565b6001600160a01b031660009081526001602052604090205460ff1690565b6040516100ad9190614128565b6100c9610112366004614233565b610228565b6100c961012536600461426d565b610247565b6100a07f000000000000000000000000000000000000000000000000000000000000000081565b610159610259565b6040516100ad91906142b0565b6100c96101743660046142be565b6102d3565b6100c961018736600461431e565b610327565b60006101c06101bc60017f01095cd170b13c49f67c675e3bc004094df00c531fa118e86b230655aba7aa17614367565b5490565b905090565b6101cd610498565b3360008181526001602052604090205461020f9060ff1670417574686f72697a6174696f6e4261736560781b6b1d5b985d5d1a1bdc9a5e995960a21b846104cb565b610219838361053d565b506102246001600055565b5050565b610230610498565b61023a3382610e54565b6102446001600055565b50565b61024f610498565b61023a338261053d565b600061026361018c565b6001600160a01b0316638da5cb5b6040518163ffffffff1660e01b815260040160206040518083038186803b15801561029b57600080fd5b505afa1580156102af573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101c09190614389565b6102db610498565b3360008181526001602052604090205461031d9060ff1670417574686f72697a6174696f6e4261736560781b6b1d5b985d5d1a1bdc9a5e995960a21b846104cb565b6102198383610e54565b3361033181611325565b61046c61033c61018c565b6001600160a01b031663052f72d7336040518263ffffffff1660e01b815260040161036791906142b0565b60206040518083038186803b15801561037f57600080fd5b505afa158015610393573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906103b791906143b5565b806104415750336103c661018c565b6001600160a01b0316638da5cb5b6040518163ffffffff1660e01b815260040160206040518083038186803b1580156103fe57600080fd5b505afa158015610412573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906104369190614389565b6001600160a01b0316145b70417574686f72697a6174696f6e4261736560781b6b1d5b985d5d1a1bdc9a5e995960a21b866104cb565b506001600160a01b03919091166000908152600160205260409020805460ff1916911515919091179055565b600260005414156104c45760405162461bcd60e51b81526004016104bb906143d6565b60405180910390fd5b6002600055565b83610537576104d983611381565b6101d160f51b6104e884611381565b61080f60f21b6104f78561141c565b604051610511959493929190601f60f91b9060200161447f565b60408051601f198184030181529082905262461bcd60e51b82526104bb9160040161450f565b50505050565b80610100015160000151610581428210157323b2b732b934b1aa3930b232b9283937bc3cab1960611b6f111958591b1a5b9948195e1c1a5c995960821b8442611562565b600060405180610140016040528061059761018c565b6001600160a01b031681526020017f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316639ff78c306040518163ffffffff1660e01b815260040160206040518083038186803b1580156105fe57600080fd5b505afa158015610612573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106369190614534565b6001600160a01b0316815260c0850180516020908101518751148184015290510151855160409092019114610673578460c001516020015161067a565b60c0850151515b81526000602082015260400161069260026001614555565b8152602001600081526020016106c96040805180820182526000808252602091820181905282518084019093528083529082015290565b81526020016106f96040805180820182526000808252602091820181905282518084019093528083529082015290565b81526020016107296040805180820182526000808252602091820181905282518084019093528083529082015290565b815250905061073b83602001516115c0565b60c0830151835160405163133ebe9d60e21b81527376f0f76f1b2f2474f7e22f56a5c1573e8c604e6f92634cfafa749261077b9286929190600401614705565b60006040518083038186803b15801561079357600080fd5b505af41580156107a7573d6000803e3d6000fd5b5050845160c08601516020015114915050801561080757508260c00151604001516000815181106107da576107da614737565b60200260200101516000015183602001516000815181106107fd576107fd614737565b6020026020010151145b1561086f5761086581858560c0015160000151866020015160008151811061083157610831614737565b60200260200101518760c001516040015160008151811061085457610854614737565b602002602001015160200151611609565b60408401526108a8565b6108a281858560000151866020015160008151811061089057610890614737565b60200260200101518760400151611609565b60408401525b6108ba8360400151846060015161170f565b602083015160a0840151608085015160405160016229857d60e11b031981527376f0f76f1b2f2474f7e22f56a5c1573e8c604e6f9363ffacf50693610903938793600401614902565b60006040518083038186803b15801561091b57600080fd5b505af415801561092f573d6000803e3d6000fd5b50505050600061094e828560a001518787600001518860800151611794565b90506040518060400160405280866001600160a01b0316815260200183606001518152508160028151811061098557610985614737565b60200260200101819052506109b982826001815181106109a7576109a7614737565b602002602001015186602001516119ef565b60006109cb8560c00151604001515190565b905060006109dc8660e00151611ac0565b826109f1868960800151878b60600151611aea565b6109fb9190614555565b610a059190614555565b6001600160401b03811115610a1c57610a1c6139f6565b604051908082528060200260200182016040528015610a5557816020015b610a4261391d565b815260200190600190039081610a3a5790505b509050610a7983828660008a602001518b604001518c606001518d60800151611cd3565b6020860151805160009190610a9090600190614367565b81518110610aa057610aa0614737565b60200260200101519050610ac082868960c001518a6000015187866128a8565b610aea82868960e0015187600081518110610add57610add614737565b6020026020010151612ba0565b610b188585600081518110610b0157610b01614737565b602002602001015189602001518a60c00151612c94565b7376f0f76f1b2f2474f7e22f56a5c1573e8c604e6f63396b96168686600081518110610b4657610b46614737565b60200260200101518a6101000151604001516040518463ffffffff1660e01b8152600401610b7693929190614986565b60006040518083038186803b158015610b8e57600080fd5b505af4158015610ba2573d6000803e3d6000fd5b5050865160405163a67a6a4560e01b81526001600160a01b03909116925063a67a6a459150610bd79087908690600401614b9c565b600060405180830381600087803b158015610bf157600080fd5b505af1158015610c05573d6000803e3d6000fd5b505050507376f0f76f1b2f2474f7e22f56a5c1573e8c604e6f63dce467af8686600081518110610c3757610c37614737565b60200260200101518a602001518b608001518c60c001518d6101000151604001516040518763ffffffff1660e01b8152600401610c7996959493929190614bc1565b60006040518083038186803b158015610c9157600080fd5b505af4158015610ca5573d6000803e3d6000fd5b5060009250610cb2915050565b876101000151602001516003811115610ccd57610ccd6147fa565b1480610cf357506001876101000151602001516003811115610cf157610cf16147fa565b145b15610d695760008760200151600081518110610d1157610d11614737565b60200260200101519050610d67866000015186600081518110610d3657610d36614737565b60200260200101516000015187600081518110610d5557610d55614737565b60200260200101516020015184612e99565b505b6000876101000151602001516003811115610d8657610d866147fa565b1480610dac57506002876101000151602001516003811115610daa57610daa6147fa565b145b15610e4a5760c0870151604001515160005b81811015610e4757610e37876000015187600281518110610de157610de1614737565b60200260200101516000015188600281518110610e0057610e00614737565b6020026020010151602001518c60c00151604001518581518110610e2657610e26614737565b602002602001015160000151612e99565b610e4081614c2b565b9050610dbe565b50505b5050505050505050565b8060c0015160000151610e97428210157323b2b732b934b1aa3930b232b9283937bc3cab1960611b6f111958591b1a5b9948195e1c1a5c995960821b8442611562565b6000604051806101400160405280610ead61018c565b6001600160a01b031681526020017f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316639ff78c306040518163ffffffff1660e01b815260040160206040518083038186803b158015610f1457600080fd5b505afa158015610f28573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f4c9190614534565b6001600160a01b03168152600060208201819052604082018190526060820152608001610f7a600180614555565b815260200160008152602001610fb16040805180820182526000808252602091820181905282518084019093528083529082015290565b8152602001610fe16040805180820182526000808252602091820181905282518084019093528083529082015290565b81526020016110116040805180820182526000808252602091820181905282518084019093528083529082015290565b815250905061102383602001516115c0565b61104481858560000151866020015160008151811061089057610890614737565b60408401819052606084015161105a919061170f565b602083015160a0840151608085015160405160016229857d60e11b031981527376f0f76f1b2f2474f7e22f56a5c1573e8c604e6f9363ffacf506936110a3938793600401614902565b60006040518083038186803b1580156110bb57600080fd5b505af41580156110cf573d6000803e3d6000fd5b5050505060006110ee828560a001518787600001518860800151611794565b905061110782826001815181106109a7576109a7614737565b600061111d838660800151848860600151611aea565b6001600160401b03811115611134576111346139f6565b60405190808252806020026020018201604052801561116d57816020015b61115a61391d565b8152602001906001900390816111525790505b509050611191828285600089602001518a604001518b606001518c60800151611cd3565b825160405163a67a6a4560e01b81526001600160a01b039091169063a67a6a45906111c29085908590600401614b9c565b600060405180830381600087803b1580156111dc57600080fd5b505af11580156111f0573d6000803e3d6000fd5b50505050602083810151865191870151608088015160405163255a3bf760e01b81526001600160a01b039093169363255a3bf793611234938c939091600401614cdd565b600060405180830381600087803b15801561124e57600080fd5b505af1158015611262573d6000803e3d6000fd5b506000925061126f915050565b8560c00151602001516003811115611289576112896147fa565b14806112ae575060018560c001516020015160038111156112ac576112ac6147fa565b145b1561131d5761131d8360000151836000815181106112ce576112ce614737565b602002602001015160000151846000815181106112ed576112ed614737565b602002602001015160200151886020015160008151811061131057611310614737565b6020026020010151612e99565b505050505050565b610244611330610259565b6001600160a01b0316826001600160a01b0316147127b7363ca237b637b6b4ba32a6b0b933b4b760711b7f43616c6c6572206973206e6f74206f776e6572206f6620446f6c6f6d69746500846104cb565b60606000826040516020016113969190614d1e565b60408051601f19818403018152919052905060205b801561140157806113bb81614d33565b9150508181815181106113d0576113d0614737565b01602001516001600160f81b031916156113fc5760006113f1826001614555565b835250909392505050565b6113ab565b5060408051600080825260208201909252905b509392505050565b60408051602a80825260608281019093526001600160a01b03841691600091602082018180368337019050509050603060f81b8160008151811061146257611462614737565b60200101906001600160f81b031916908160001a905350607860f81b8160018151811061149157611491614737565b60200101906001600160f81b031916908160001a90535060005b60148110156114145760006114c1826002614d4a565b90506114cf600f8516612f92565b836114db836029614367565b815181106114eb576114eb614737565b60200101906001600160f81b031916908160001a905350600484901c9350611515600f8516612f92565b83611521836028614367565b8151811061153157611531614737565b60200101906001600160f81b031916908160001a9053505060049290921c918061155a81614c2b565b9150506114ab565b846115b95761157084611381565b6101d160f51b61157f85611381565b61080f60f21b61158e86612fbc565b61016160f51b61159d87612fbc565b6040516105119796959493929190601f60f91b90602001614d69565b5050505050565b6102446002825110157547656e6572696354726164657250726f78794261736560501b7f496e76616c6964206d61726b65742070617468206c656e6774680000000000006130c7565b6000600019821461161b575080611706565b85516040805180820182526001600160a01b03888116825260208201889052915163306430bb60e21b8152600093929092169163c190c2ec91611662918890600401614de5565b604080518083038186803b15801561167957600080fd5b505afa15801561168d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116b19190614e49565b90506116ff6116bf826130fb565b157323b2b732b934b1aa3930b232b9283937bc3cab1960611b7f42616c616e6365206d75737420626520706f736974697665000000000000000087613117565b6020015190505b95945050505050565b61174e8215157547656e6572696354726164657250726f78794261736560501b75496e76616c696420696e707574416d6f756e7457656960501b6130c7565b6102248115157547656e6572696354726164657250726f78794261736560501b7f496e76616c6964206d696e4f7574707574416d6f756e745765690000000000006130c7565b60606000805b835181101561180e5760018482815181106117b7576117b7614737565b60200260200101516000015160038111156117d4576117d46147fa565b14156117fe5760a088015160808901819052600192506117f49083614555565b60a089015261180e565b61180781614c2b565b905061179a565b50600086518860a001516118229190614555565b6001600160401b03811115611839576118396139f6565b60405190808252806020026020018201604052801561187e57816020015b60408051808201909152600080825260208201528152602001906001900390816118575790505b5090506040518060400160405280876001600160a01b0316815260200186815250816000815181106118b2576118b2614737565b60200260200101819052506040518060400160405280876001600160a01b031681526020016118e18888613143565b815250816001815181106118f7576118f7614737565b602002602001018190525081156119d95760405180604001604052807f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663b6ab3bc96040518163ffffffff1660e01b815260040160206040518083038186803b15801561196c57600080fd5b505afa158015611980573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119a49190614389565b6001600160a01b031681526020016000815250818960800151815181106119cd576119cd614737565b60200260200101819052505b6119e4888883613179565b979650505050505050565b805160005b818110156115b95784600001516001600160a01b03166347d1b53c85858481518110611a2257611a22614737565b60200260200101516040518363ffffffff1660e01b8152600401611a47929190614de5565b604080518083038186803b158015611a5e57600080fd5b505afa158015611a72573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a969190614ec2565b602001516001600160801b031615611ab057611ab0614ee3565b611ab981614c2b565b90506119f4565b6000816020015163ffffffff1660001415611add57506000919050565b506001919050565b919050565b8251600090600290825b81811015611cc557611b22878281518110611b1157611b11614737565b60200260200101516000015161327d565b15611bc657868181518110611b3957611b39614737565b6020026020010151604001516001600160a01b031663b189111a6040518163ffffffff1660e01b815260040160206040518083038186803b158015611b7d57600080fd5b505afa158015611b91573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611bb59190614ef9565b611bbf9084614555565b9250611cb5565b611bec878281518110611bdb57611bdb614737565b60200260200101516000015161329b565b15611c0357868181518110611b3957611b39614737565b6001878281518110611c1757611c17614737565b6020026020010151600001516003811115611c3457611c346147fa565b1415611ca757868181518110611c4c57611c4c614737565b6020026020010151604001516001600160a01b03166376367b5f611c738a8a8a8a876132b6565b6040518263ffffffff1660e01b8152600401611c8f9190614fb6565b60206040518083038186803b158015611b7d57600080fd5b611cb2600184614555565b92505b611cbe81614c2b565b9050611af4565b50909150505b949350505050565b600019831415611e255760408051808201909152600080825260208201528515611db35786600001516001600160a01b031663c190c2ec8a600081518110611d1d57611d1d614737565b602002602001015187600081518110611d3857611d38614737565b60200260200101516040518363ffffffff1660e01b8152600401611d5d929190614de5565b604080518083038186803b158015611d7457600080fd5b505afa158015611d88573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611dac9190614e49565b9050611dc9565b5060408051808201909152600080825260208201525b611df16000600187600081518110611de357611de3614737565b602002602001015184613428565b60c0880180518a91611e0282614c2b565b905281518110611e1457611e14614737565b602002602001018190525050611e7e565b611e4f6000600186600081518110611e3f57611e3f614737565b60200260200101516000876134ba565b60c0870180518991611e6082614c2b565b905281518110611e7257611e72614737565b60200260200101819052505b805160005b81811015612830576000838281518110611e9f57611e9f614737565b6020026020010151600001516003811115611ebc57611ebc6147fa565b1415611f8f57611f5c6001878381518110611ed957611ed9614737565b602002602001015188846001611eef9190614555565b81518110611eff57611eff614737565b6020026020010151868581518110611f1957611f19614737565b602002602001015160400151611f2e60001990565b611f398a888a6135d0565b898881518110611f4b57611f4b614737565b6020026020010151606001516135f6565b60c0890180518b91611f6d82614c2b565b905281518110611f7f57611f7f614737565b6020026020010181905250612820565b6001838281518110611fa357611fa3614737565b6020026020010151600001516003811115611fc057611fc06147fa565b14156122cd576120c27f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316630d9215f285848151811061200a5761200a614737565b6020026020010151604001516040518263ffffffff1660e01b815260040161203291906142b0565b60206040518083038186803b15801561204a57600080fd5b505afa15801561205e573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061208291906143b5565b7547656e6572696354726164657250726f78794261736560501b7f496e7465726e616c20747261646572206e6f742077686974656c6973746564006130c7565b60006120d189858d88866132b6565b9050606060008c905060008b90508685815181106120f1576120f1614737565b6020026020010151604001516001600160a01b0316631ad08fad604051806101200160405280600181526020018560018151811061213157612131614737565b60200260200101518152602001846080015181526020018585608001518151811061215e5761215e614737565b602002602001015181526020018d898151811061217d5761217d614737565b602002602001015181526020018d8960016121989190614555565b815181106121a8576121a8614737565b602002602001015181526020016121be60001990565b81526020018781526020018a89815181106121db576121db614737565b6020026020010151606001518152506040518263ffffffff1660e01b815260040161220691906150c2565b60006040518083038186803b15801561221e57600080fd5b505afa158015612232573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261225a9190810190615333565b9250505060005b81518110156122c55781818151811061227c5761227c614737565b60200260200101518c8c60c001805180919061229790614c2b565b9052815181106122a9576122a9614737565b6020026020010181905250806122be90614c2b565b9050612261565b505050612820565b6122e2838281518110611b1157611b11614737565b156125535780156122f5576122f5614ee3565b600083828151811061230957612309614737565b6020026020010151604001516001600160a01b031663f93cffde6040518061016001604052806001815260200161233e600090565b81526020018e60018151811061235657612356614737565b6020026020010151600001516001600160a01b031681526020018e60018151811061238357612383614737565b60200260200101516020015181526020018e61239d600090565b815181106123ad576123ad614737565b6020026020010151600001516001600160a01b031681526020018e6123d0600090565b815181106123e0576123e0614737565b60200260200101516020015181526020018a8660016123ff9190614555565b8151811061240f5761240f614737565b602002602001015181526020018a868151811061242e5761242e614737565b6020026020010151815260200161244789878a516135d0565b815260200189815260200187868151811061246457612464614737565b6020026020010151606001518152506040518263ffffffff1660e01b815260040161248f919061544b565b60006040518083038186803b1580156124a757600080fd5b505afa1580156124bb573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526124e39190810190615333565b905060005b815181101561254c5781818151811061250357612503614737565b60200260200101518b8b60c001805180919061251e90614c2b565b90528151811061253057612530614737565b60200260200101819052508061254590614c2b565b90506124e8565b5050612820565b612568838281518110611bdb57611bdb614737565b61257457612574614ee3565b6125c4612582600184614367565b82147547656e6572696354726164657250726f78794261736560501b7f57726170706572206d75737420626520746865206c61737420747261646572006130c7565b60008382815181106125d8576125d8614737565b6020026020010151604001516001600160a01b0316634e2e55806040518061016001604052806001815260200161260d600090565b81526020018e60018151811061262557612625614737565b6020026020010151600001516001600160a01b031681526020018e60018151811061265257612652614737565b60200260200101516020015181526020018e61266c600090565b8151811061267c5761267c614737565b6020026020010151600001516001600160a01b031681526020018e61269f600090565b815181106126af576126af614737565b60200260200101516020015181526020018a8660016126ce9190614555565b815181106126de576126de614737565b602002602001015181526020018a86815181106126fd576126fd614737565b6020026020010151815260200161271689878a516135d0565b8152602001600019815260200187868151811061273557612735614737565b6020026020010151606001518152506040518263ffffffff1660e01b8152600401612760919061544b565b60006040518083038186803b15801561277857600080fd5b505afa15801561278c573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526127b49190810190615333565b905060005b815181101561281d578181815181106127d4576127d4614737565b60200260200101518b8b60c00180518091906127ef90614c2b565b90528151811061280157612801614737565b60200260200101819052508061281690614c2b565b90506127b9565b50505b61282981614c2b565b9050611e83565b5061286f6001600087600189516128479190614367565b8151811061285757612857614737565b6020026020010151600061286a60001990565b6134ba565b60c0880180518a9161288082614c2b565b90528151811061289257612892614737565b6020026020010181905250505050505050505050565b835160009084146128ba5760026128bd565b60005b90506000848660000151146128d35760006128d6565b60025b905060005b84811015612b95576128f06001600019614367565b8760400151828151811061290657612906614737565b6020026020010151602001511415612b045761299f848860400151838151811061293257612932614737565b602002602001015160000151147323b2b732b934b1aa3930b232b9283937bc3cab1960611b7f496e76616c6964207472616e73666572206d61726b65744964000000000000008a60400151858151811061298e5761298e614737565b602002602001015160000151613117565b6129e283157323b2b732b934b1aa3930b232b9283937bc3cab1960611b7f496e76616c69642066726f6d206163636f756e742049440000000000000000006130c7565b612ad18383896040015184815181106129fd576129fd614737565b6020026020010151600001518b600001516001600160a01b031663c190c2ec6040518060400160405280336001600160a01b031681526020018e600001518152508d604001518881518110612a5457612a54614737565b6020026020010151600001516040518363ffffffff1660e01b8152600401612a7d929190614de5565b604080518083038186803b158015612a9457600080fd5b505afa158015612aa8573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612acc9190614e49565b613428565b60c0890180518b91612ae282614c2b565b905281518110612af457612af4614737565b6020026020010181905250612b83565b612b54838389604001518481518110612b1f57612b1f614737565b60200260200101516000015160008b604001518681518110612b4357612b43614737565b6020026020010151602001516134ba565b60c0890180518b91612b6582614c2b565b905281518110612b7757612b77614737565b60200260200101819052505b80612b8d81614c2b565b9150506128db565b505050505050505050565b602082015163ffffffff16612bb457610537565b612c6081600084600001517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663e184c9be6040518163ffffffff1660e01b815260040160206040518083038186803b158015612c1857600080fd5b505afa158015612c2c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612c509190614534565b866020015163ffffffff166136fc565b60c0840180518691612c7182614c2b565b905281518110612c8357612c83614737565b602002602001018190525050505050565b83600001516001600160a01b031663c190c2ec8484600081518110612cbb57612cbb614737565b60200260200101516040518363ffffffff1660e01b8152600401612ce0929190614de5565b604080518083038186803b158015612cf757600080fd5b505afa158015612d0b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612d2f9190614e49565b8460e0018190525083600001516001600160a01b031663c190c2ec848460018651612d5a9190614367565b81518110612d6a57612d6a614737565b60200260200101516040518363ffffffff1660e01b8152600401612d8f929190614de5565b604080518083038186803b158015612da657600080fd5b505afa158015612dba573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612dde9190614e49565b84610100018190525083600001516001600160a01b031663c190c2ec848360400151600081518110612e1257612e12614737565b6020026020010151600001516040518363ffffffff1660e01b8152600401612e3b929190614de5565b604080518083038186803b158015612e5257600080fd5b505afa158015612e66573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612e8a9190614e49565b84610120018190525050505050565b6040805180820182526001600160a01b0380861682526020820185905291516311f46d4f60e21b81529091600091908716906347d1b53c90612ee19085908790600401614de5565b604080518083038186803b158015612ef857600080fd5b505afa158015612f0c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612f309190614ec2565b905061131d612f3e82613819565b80612f54575060208201516001600160801b0316155b7020b1b1b7bab73a2130b630b731b2a634b160791b7f6163636f756e742063616e6e6f7420676f206e65676174697665000000000000888888613838565b6000600a821015612fb157612fa8603083614555565b60f81b92915050565b612fa8605783614555565b606081612fe05750506040805180820190915260018152600360fc1b602082015290565b8160005b811561300a5780612ff481614c2b565b91506130039050600a83615472565b9150612fe4565b6000816001600160401b03811115613024576130246139f6565b6040519080825280601f01601f19166020018201604052801561304e576020820181803683370190505b508593509050815b80156130be578061306681614d33565b91506130759050600a85615486565b613080906030614555565b60f81b82828151811061309557613095614737565b60200101906001600160f81b031916908160001a9053506130b7600a85615472565b9350613056565b50949350505050565b826130f6576130d582611381565b6101d160f51b6130e483611381565b6040516020016105119392919061549a565b505050565b8051600090158015613111575060008260200151115b92915050565b836105375761312583611381565b6101d160f51b61313484611381565b61080f60f21b6104f785612fbc565b600082824260405160200161315a939291906154ea565b60408051601f1981840301815291905280516020909101209392505050565b815160005b818110156115b957600083828760a001516131999190614555565b815181106131a9576131a9614737565b6020026020010151905060006001600160a01b031681600001516001600160a01b03161480156131db57506020810151155b6131e7576131e7614ee3565b604051806040016040528086848151811061320457613204614737565b6020026020010151600001516001600160a01b0316815260200186848151811061323057613230614737565b60200260200101516020015181525084838860a001516132509190614555565b8151811061326057613260614737565b6020026020010181905250508061327690614c2b565b905061317e565b6000816003811115613291576132916147fa565b60025b1492915050565b60008160038111156132af576132af6147fa565b6003613294565b60408051600180825281830190925260609160009190816020015b6040805160c08101825260006080820181815260a0830182905282526020808301829052928201819052606082015282526000199092019101816132d1579050509050848760a0015187858151811061332c5761332c614737565b6020026020010151602001516133429190614555565b8151811061335257613352614737565b60200260200101518160008151811061336d5761336d614737565b6020026020010151600001819052508660a0015186848151811061339357613393614737565b6020026020010151602001516133a99190614555565b816000815181106133bc576133bc614737565b6020908102919091018101510152600019816000815181106133e0576133e0614737565b602002602001015160400181815250506133fc848488516135d0565b8160008151811061340f5761340f614737565b6020908102919091010151606001529695505050505050565b61343061391d565b60408051610100810190915280600281526020808201889052604080516080810182528651151581529201919081016000815260200160018152602001856020015181525081526020018481526020016000815260200160006001600160a01b03168152602001858152602001604051806020016040528060008152508152509050949350505050565b6134c261391d565b6134ee604080516080810190915260008082526020820190815260200160008152602001600081525090565b60001983141561353657604051806080016040528060001515815260200185600181111561351e5761351e6147fa565b8152602001600181526020016000815250905061356e565b604051806080016040528060001515815260200185600181111561355c5761355c6147fa565b81526020016000815260200184905290505b60408051610100810190915280600281526020018881526020018281526020018681526020016000815260200160006001600160a01b031681526020018781526020016040518060200160405280600081525081525091505095945050505050565b60006135dd600183614367565b83146135ea5760016135ec565b835b90505b9392505050565b6135fe61391d565b61362a604080516080810190915260008082526020820190815260200160008152602001600081525090565b6000198514156136615760408051608081019091526000808252602082019081526020016001815260200160008152509050613688565b60408051608081019091526000808252602082019081526020016000815260200186905290505b60408051610100810190915280600481526020018a8152602001828152602001898152602001888152602001876001600160a01b031681526020016000815260200185856040516020016136dd929190615521565b60408051601f1981840301815291905290529998505050505050505050565b61370461391d565b61374a8263ffffffff1683146f20b1b1b7bab73a20b1ba34b7b72634b160811b7f496e76616c6964206578706972792074696d652064656c7461000000000000006130c7565b604080516001808252818301909252600091816020015b6040805160c08101825260006080820181815260a08301829052825260208083018290529282018190526060820152825260001990920191018161376157905050905060405180608001604052808881526020018681526020018463ffffffff16815260200160011515815250816000815181106137e1576137e1614737565b60200260200101819052506119e486856000846040516020016138059291906155e1565b6040516020818303038152906040526138a0565b80516000908015613111575050602001516001600160801b0316151590565b8561131d5761384685611381565b6101d160f51b61385586611381565b61080f60f21b6138648761141c565b61016160f51b61387388612fbc565b61016160f51b61388289612fbc565b60405161051199989796959493929190601f60f91b90602001615601565b6138a861391d565b60408051610100810182526008815260208082018790528251608081018452600080825292938401929091820190815260200160008152602001600081525081526020016000815260200160008152602001846001600160a01b03168152602001600081526020018381525090509392505050565b604080516101008101825260008082526020820152908101613961604080516080810190915260008082526020820190815260200160008152602001600081525090565b8152602001600081526020016000815260200160006001600160a01b0316815260200160008152602001606081525090565b60006001600160a01b038216613111565b600061311182613993565b6000613111826139a4565b6139c3816139af565b82525050565b6020810161311182846139ba565b6139e081613993565b811461024457600080fd5b8035613111816139d7565b634e487b7160e01b600052604160045260246000fd5b601f19601f83011681018181106001600160401b0382111715613a3157613a316139f6565b6040525050565b6000613a4360405190565b9050611ae58282613a0c565b806139e0565b803561311181613a4f565b60006001600160401b03821115613a7957613a796139f6565b5060209081020190565b6000613a96613a9184613a60565b613a38565b83815290506020808201908402830185811115613ab557613ab5600080fd5b835b81811015613ad95780613aca8882613a55565b84525060209283019201613ab7565b5050509392505050565b600082601f830112613af757613af7600080fd5b8135611ccb848260208601613a83565b6004811061024457600080fd5b803561311181613b07565b60006001600160401b03821115613b3857613b386139f6565b601f19601f83011660200192915050565b82818337506000910152565b6000613b63613a9184613b1f565b905082815260208101848484011115613b7e57613b7e600080fd5b611414848285613b49565b600082601f830112613b9d57613b9d600080fd5b8135611ccb848260208601613b55565b600060808284031215613bc257613bc2600080fd5b613bcc6080613a38565b90506000613bda8484613b14565b8252506020613beb84848301613a55565b6020830152506040613bff848285016139eb565b60408301525060608201356001600160401b03811115613c2157613c21600080fd5b613c2d84828501613b89565b60608301525092915050565b6000613c47613a9184613a60565b83815290506020808201908402830185811115613c6657613c66600080fd5b835b81811015613ad95780356001600160401b03811115613c8957613c89600080fd5b808601613c968982613bad565b8552505060209283019201613c68565b600082601f830112613cba57613cba600080fd5b8135611ccb848260208601613c39565b600060408284031215613cdf57613cdf600080fd5b613ce96040613a38565b90506000613cf784846139eb565b8252506020613d0884848301613a55565b60208301525092915050565b6000613d22613a9184613a60565b83815290506020810160408402830185811115613d4157613d41600080fd5b835b81811015613ad95780613d568882613cca565b845250602090920191604001613d43565b600082601f830112613d7b57613d7b600080fd5b8135611ccb848260208601613d14565b600060408284031215613da057613da0600080fd5b613daa6040613a38565b90506000613cf78484613a55565b6000613dc6613a9184613a60565b83815290506020810160408402830185811115613de557613de5600080fd5b835b81811015613ad95780613dfa8882613d8b565b845250602090920191604001613de7565b600082601f830112613e1f57613e1f600080fd5b8135611ccb848260208601613db8565b600060608284031215613e4457613e44600080fd5b613e4e6060613a38565b90506000613e5c8484613a55565b8252506020613e6d84848301613a55565b60208301525060408201356001600160401b03811115613e8f57613e8f600080fd5b613e9b84828501613e0b565b60408301525092915050565b63ffffffff81166139e0565b803561311181613ea7565b600060408284031215613ed357613ed3600080fd5b613edd6040613a38565b90506000613eeb8484613a55565b8252506020613d0884848301613eb3565b6003811061024457600080fd5b803561311181613efc565b600060608284031215613f2957613f29600080fd5b613f336060613a38565b90506000613f418484613a55565b8252506020613f5284848301613b14565b6020830152506040613e9b84828501613f09565b60006101808284031215613f7c57613f7c600080fd5b613f87610120613a38565b90506000613f958484613a55565b82525060208201356001600160401b03811115613fb457613fb4600080fd5b613fc084828501613ae3565b6020830152506040613fd484828501613a55565b6040830152506060613fe884828501613a55565b60608301525060808201356001600160401b0381111561400a5761400a600080fd5b61401684828501613ca6565b60808301525060a08201356001600160401b0381111561403857614038600080fd5b61404484828501613d67565b60a08301525060c08201356001600160401b0381111561406657614066600080fd5b61407284828501613e2f565b60c08301525060e061408684828501613ebe565b60e08301525061012061409b84828501613f14565b6101008301525092915050565b600080604083850312156140be576140be600080fd5b60006140ca85856139eb565b92505060208301356001600160401b038111156140e9576140e9600080fd5b6140f585828601613f66565b9150509250929050565b60006020828403121561411457614114600080fd5b6000611ccb84846139eb565b8015156139c3565b602081016131118284614120565b6000610120828403121561414c5761414c600080fd5b61415660e0613a38565b905060006141648484613a55565b82525060208201356001600160401b0381111561418357614183600080fd5b61418f84828501613ae3565b60208301525060406141a384828501613a55565b60408301525060606141b784828501613a55565b60608301525060808201356001600160401b038111156141d9576141d9600080fd5b6141e584828501613ca6565b60808301525060a08201356001600160401b0381111561420757614207600080fd5b61421384828501613d67565b60a08301525060c061422784828501613f14565b60c08301525092915050565b60006020828403121561424857614248600080fd5b81356001600160401b0381111561426157614261600080fd5b611ccb84828501614136565b60006020828403121561428257614282600080fd5b81356001600160401b0381111561429b5761429b600080fd5b611ccb84828501613f66565b6139c381613993565b6020810161311182846142a7565b600080604083850312156142d4576142d4600080fd5b60006142e085856139eb565b92505060208301356001600160401b038111156142ff576142ff600080fd5b6140f585828601614136565b8015156139e0565b80356131118161430b565b6000806040838503121561433457614334600080fd5b600061434085856139eb565b92505060206140f585828601614313565b634e487b7160e01b600052601160045260246000fd5b60008282101561437957614379614351565b500390565b8051613111816139d7565b60006020828403121561439e5761439e600080fd5b6000611ccb848461437e565b80516131118161430b565b6000602082840312156143ca576143ca600080fd5b6000611ccb84846143aa565b6020808252810161311181601f81527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c00602082015260400190565b60005b8381101561442c578181015183820152602001614414565b838111156105375750506000910152565b6000614447825190565b614455818560208601614411565b9290920192915050565b6001600160f01b031981166139c3565b6001600160f81b031981166139c3565b600061448b828961443d565b9150614497828861445f565b6002820191506144a7828761443d565b91506144b3828661445f565b6002820191506144c3828561443d565b91506144cf828461446f565b506001019695505050505050565b60006144e7825190565b8084526020840193506144fe818560208601614411565b601f01601f19169290920192915050565b602080825281016135ef81846144dd565b6139e0816139a4565b805161311181614520565b60006020828403121561454957614549600080fd5b6000611ccb8484614529565b6000821982111561456857614568614351565b500190565b806139c3565b805160408301906145848482614120565b506020820151610537602085018261456d565b80516101a08301906145a984826139ba565b5060208201516145bc60208501826139ba565b5060408201516145cf6040850182614120565b5060608201516145e2606085018261456d565b5060808201516145f5608085018261456d565b5060a082015161460860a085018261456d565b5060c082015161461b60c085018261456d565b5060e082015161462e60e0850182614573565b50610100820151614643610120850182614573565b50610120820151610537610160850182614573565b80516040830190614584848261456d565b60006146758383614658565b505060400190565b6000614687825190565b80845260209384019383018060005b838110156146bb5781516146aa8882614669565b975060208301925050600101614696565b509495945050505050565b805160009060608401906146da858261456d565b5060208301516146ed602086018261456d565b5060408301518482036040860152611706828261467d565b6101e081016147148286614597565b8181036101a083015261472781856146c6565b9050611ccb6101c083018461456d565b634e487b7160e01b600052603260045260246000fd5b6000614759838361456d565b505060200190565b600061476b825190565b80845260209384019383018060005b838110156146bb57815161478e888261474d565b97506020830192505060010161477a565b8051604083019061458484826142a7565b6000614675838361479f565b60006147c6825190565b80845260209384019383018060005b838110156146bb5781516147e988826147b0565b9750602083019250506001016147d5565b634e487b7160e01b600052602160045260246000fd5b60048110610244576102446147fa565b80611ae581614810565b600061311182614820565b6139c38161482a565b805160009060808401906148528582614835565b506020830151614865602086018261456d565b50604083015161487860408601826142a7565b506060830151848203606086015261170682826144dd565b60006135ef838361483e565b60006148a6825190565b808452602084019350836020820285016148c08560200190565b8060005b858110156148f557848403895281516148dd8582614890565b94506020830160209a909a01999250506001016148c4565b5091979650505050505050565b61020081016149118287614597565b8181036101a08301526149248186614761565b90508181036101c083015261493981856147bc565b90508181036101e083015261494e818461489c565b9695505050505050565b60038110610244576102446147fa565b80611ae581614958565b600061311182614968565b6139c381614972565b61020081016149958286614597565b6149a36101a083018561479f565b611ccb6101e083018461497d565b60006149bb825190565b80845260209384019383018060005b838110156146bb5781516149de88826147b0565b9750602083019250506001016149ca565b60098110610244576102446147fa565b80611ae5816149ef565b6000613111826149ff565b6139c381614a09565b60028110610244576102446147fa565b80611ae581614a1d565b600061311182614a2d565b6139c381614a37565b80516080830190614a5c8482614120565b506020820151614a6f6020850182614a42565b506040820151614a826040850182614a42565b506060820151610537606085018261456d565b8051600090610160840190614aaa8582614a14565b506020830151614abd602086018261456d565b506040830151614ad06040860182614a4b565b506060830151614ae360c086018261456d565b506080830151614af660e086018261456d565b5060a0830151614b0a6101008601826142a7565b5060c0830151614b1e61012086018261456d565b5060e083015184820361014086015261170682826144dd565b60006135ef8383614a95565b6000614b4d825190565b80845260208401935083602082028501614b678560200190565b8060005b858110156148f55784840389528151614b848582614b37565b94506020830160209a909a0199925050600101614b6b565b60408082528101614bad81856149b1565b905081810360208301526135ec8184614b43565b6102608101614bd08289614597565b614bde6101a083018861479f565b8181036101e0830152614bf18187614761565b9050818103610200830152614c06818661489c565b9050818103610220830152614c1b81856146c6565b90506119e461024083018461497d565b6000600019821415614c3f57614c3f614351565b5060010190565b6000614c50825190565b80845260209384019383018060005b838110156146bb578151614c73888261474d565b975060208301925050600101614c5f565b6000614c8e825190565b80845260208401935083602082028501614ca88560200190565b8060005b858110156148f55784840389528151614cc58582614890565b94506020830160209a909a0199925050600101614cac565b60808101614ceb82876142a7565b614cf8602083018661456d565b8181036040830152614d0a8185614c46565b9050818103606083015261494e8184614c84565b6000614d2a828461456d565b50602001919050565b600081614d4257614d42614351565b506000190190565b6000816000190483118215151615614d6457614d64614351565b500290565b6000614d75828b61443d565b9150614d81828a61445f565b600282019150614d91828961443d565b9150614d9d828861445f565b600282019150614dad828761443d565b9150614db9828661445f565b600282019150614dc9828561443d565b9150614dd5828461446f565b5060010198975050505050505050565b60608101614df3828561479f565b6135ef604083018461456d565b805161311181613a4f565b600060408284031215614e2057614e20600080fd5b614e2a6040613a38565b90506000614e3884846143aa565b8252506020613d0884848301614e00565b600060408284031215614e5e57614e5e600080fd5b6000611ccb8484614e0b565b6001600160801b0381166139e0565b805161311181614e6a565b600060408284031215614e9957614e99600080fd5b614ea36040613a38565b90506000614eb184846143aa565b8252506020613d0884848301614e79565b600060408284031215614ed757614ed7600080fd5b6000611ccb8484614e84565b634e487b7160e01b600052600160045260246000fd5b600060208284031215614f0e57614f0e600080fd5b6000611ccb8484614e00565b805160a0830190614f2b848261479f565b506020820151614f3e604085018261456d565b506040820151614f51606085018261456d565b506060820151610537608085018261456d565b6000614f708383614f1a565b505060a00190565b6000614f82825190565b80845260209384019383018060005b838110156146bb578151614fa58882614f64565b975060208301925050600101614f91565b602080825281016135ef8184614f78565b6000614fd1825190565b80845260209384019383018060005b838110156146bb578151614ff48882614f64565b975060208301925050600101614fe0565b805160009061016084019061501a858261456d565b50602083015161502d602086018261479f565b506040830151615040606086018261456d565b506060830151615053608086018261479f565b50608083015161506660c086018261456d565b5060a083015161507960e086018261456d565b5060c083015161508d61010086018261456d565b5060e08301518482036101208601526150a68282614fc7565b91505061010083015184820361014086015261170682826144dd565b602080825281016135ef8184615005565b6009811061024457600080fd5b8051613111816150d3565b6002811061024457600080fd5b8051613111816150eb565b60006080828403121561511857615118600080fd5b6151226080613a38565b9050600061513084846143aa565b8252506020615141848483016150f8565b6020830152506040615155848285016150f8565b6040830152506060613c2d84828501614e00565b6000615177613a9184613b1f565b90508281526020810184848401111561519257615192600080fd5b611414848285614411565b600082601f8301126151b1576151b1600080fd5b8151611ccb848260208601615169565b600061016082840312156151d7576151d7600080fd5b6151e2610100613a38565b905060006151f084846150e0565b825250602061520184848301614e00565b602083015250604061521584828501615103565b60408301525060c061522984828501614e00565b60608301525060e061523d84828501614e00565b6080830152506101006152528482850161437e565b60a08301525061012061526784828501614e00565b60c0830152506101408201516001600160401b0381111561528a5761528a600080fd5b6152968482850161519d565b60e08301525092915050565b60006152b0613a9184613a60565b838152905060208082019084028301858111156152cf576152cf600080fd5b835b81811015613ad95780516001600160401b038111156152f2576152f2600080fd5b8086016152ff89826151c1565b85525050602092830192016152d1565b600082601f83011261532357615323600080fd5b8151611ccb8482602086016152a2565b60006020828403121561534857615348600080fd5b81516001600160401b0381111561536157615361600080fd5b611ccb8482850161530f565b8051600090610160840190615382858261456d565b506020830151615395602086018261456d565b5060408301516153a860408601826142a7565b5060608301516153bb606086018261456d565b5060808301516153ce60808601826142a7565b5060a08301516153e160a086018261456d565b5060c08301516153f460c086018261456d565b5060e083015161540760e086018261456d565b5061010083015161541c61010086018261456d565b5061012083015161543161012086018261456d565b5061014083015184820361014086015261170682826144dd565b602080825281016135ef818461536d565b634e487b7160e01b600052601260045260246000fd5b6000826154815761548161545c565b500490565b6000826154955761549561545c565b500690565b60006154a6828661443d565b91506154b2828561445f565b600282019150611706828461443d565b60006131118260601b90565b6000613111826154c2565b6139c36154e582613993565b6154ce565b60006154f682866154d9565b601482019150615506828561456d565b602082019150615516828461456d565b506020019392505050565b6040810161552f828561456d565b81810360208301526135ec81846144dd565b63ffffffff81166139c3565b805160a083019061555e848261479f565b506020820151615571604085018261456d565b5060408201516155846060850182615541565b5060608201516105376080850182614120565b6000614f70838361554d565b60006155ad825190565b80845260209384019383018060005b838110156146bb5781516155d08882615597565b9750602083019250506001016155bc565b604081016155ef8285614a42565b81810360208301526135ec81846155a3565b600061560d828d61443d565b9150615619828c61445f565b600282019150615629828b61443d565b9150615635828a61445f565b600282019150615645828961443d565b9150615651828861445f565b600282019150615661828761443d565b915061566d828661445f565b60028201915061567d828561443d565b9150615689828461446f565b506001019a995050505050505050505056fea26469706673582212202985b1277e05e4d26502dcb32bc298a55a2a9a2eb9e244f0622f387d1e1ca70b64736f6c634300080900330000000000000000000000000f38bfbd9c1450bcf7a758e80e148ce78cfe09fd000000000000000000000000003ca23fd5f0ca87d01f6ec6cd14a8ae60c2b97d

Deployed Bytecode

0x608060405234801561001057600080fd5b50600436106100935760003560e01c80639c9f553e116100665780639c9f553e14610117578063c6d20c851461012a578063cbffd92114610151578063f5f713dc14610166578063f697ae991461017957600080fd5b806315c14a4a146100985780633b7ac16a146100b65780634929d081146100cb5780635f974be914610104575b600080fd5b6100a061018c565b6040516100ad91906139c9565b60405180910390f35b6100c96100c43660046140a8565b6101c5565b005b6100f76100d93660046140ff565b6001600160a01b031660009081526001602052604090205460ff1690565b6040516100ad9190614128565b6100c9610112366004614233565b610228565b6100c961012536600461426d565b610247565b6100a07f0000000000000000000000000f38bfbd9c1450bcf7a758e80e148ce78cfe09fd81565b610159610259565b6040516100ad91906142b0565b6100c96101743660046142be565b6102d3565b6100c961018736600461431e565b610327565b60006101c06101bc60017f01095cd170b13c49f67c675e3bc004094df00c531fa118e86b230655aba7aa17614367565b5490565b905090565b6101cd610498565b3360008181526001602052604090205461020f9060ff1670417574686f72697a6174696f6e4261736560781b6b1d5b985d5d1a1bdc9a5e995960a21b846104cb565b610219838361053d565b506102246001600055565b5050565b610230610498565b61023a3382610e54565b6102446001600055565b50565b61024f610498565b61023a338261053d565b600061026361018c565b6001600160a01b0316638da5cb5b6040518163ffffffff1660e01b815260040160206040518083038186803b15801561029b57600080fd5b505afa1580156102af573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101c09190614389565b6102db610498565b3360008181526001602052604090205461031d9060ff1670417574686f72697a6174696f6e4261736560781b6b1d5b985d5d1a1bdc9a5e995960a21b846104cb565b6102198383610e54565b3361033181611325565b61046c61033c61018c565b6001600160a01b031663052f72d7336040518263ffffffff1660e01b815260040161036791906142b0565b60206040518083038186803b15801561037f57600080fd5b505afa158015610393573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906103b791906143b5565b806104415750336103c661018c565b6001600160a01b0316638da5cb5b6040518163ffffffff1660e01b815260040160206040518083038186803b1580156103fe57600080fd5b505afa158015610412573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906104369190614389565b6001600160a01b0316145b70417574686f72697a6174696f6e4261736560781b6b1d5b985d5d1a1bdc9a5e995960a21b866104cb565b506001600160a01b03919091166000908152600160205260409020805460ff1916911515919091179055565b600260005414156104c45760405162461bcd60e51b81526004016104bb906143d6565b60405180910390fd5b6002600055565b83610537576104d983611381565b6101d160f51b6104e884611381565b61080f60f21b6104f78561141c565b604051610511959493929190601f60f91b9060200161447f565b60408051601f198184030181529082905262461bcd60e51b82526104bb9160040161450f565b50505050565b80610100015160000151610581428210157323b2b732b934b1aa3930b232b9283937bc3cab1960611b6f111958591b1a5b9948195e1c1a5c995960821b8442611562565b600060405180610140016040528061059761018c565b6001600160a01b031681526020017f0000000000000000000000000f38bfbd9c1450bcf7a758e80e148ce78cfe09fd6001600160a01b0316639ff78c306040518163ffffffff1660e01b815260040160206040518083038186803b1580156105fe57600080fd5b505afa158015610612573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106369190614534565b6001600160a01b0316815260c0850180516020908101518751148184015290510151855160409092019114610673578460c001516020015161067a565b60c0850151515b81526000602082015260400161069260026001614555565b8152602001600081526020016106c96040805180820182526000808252602091820181905282518084019093528083529082015290565b81526020016106f96040805180820182526000808252602091820181905282518084019093528083529082015290565b81526020016107296040805180820182526000808252602091820181905282518084019093528083529082015290565b815250905061073b83602001516115c0565b60c0830151835160405163133ebe9d60e21b81527376f0f76f1b2f2474f7e22f56a5c1573e8c604e6f92634cfafa749261077b9286929190600401614705565b60006040518083038186803b15801561079357600080fd5b505af41580156107a7573d6000803e3d6000fd5b5050845160c08601516020015114915050801561080757508260c00151604001516000815181106107da576107da614737565b60200260200101516000015183602001516000815181106107fd576107fd614737565b6020026020010151145b1561086f5761086581858560c0015160000151866020015160008151811061083157610831614737565b60200260200101518760c001516040015160008151811061085457610854614737565b602002602001015160200151611609565b60408401526108a8565b6108a281858560000151866020015160008151811061089057610890614737565b60200260200101518760400151611609565b60408401525b6108ba8360400151846060015161170f565b602083015160a0840151608085015160405160016229857d60e11b031981527376f0f76f1b2f2474f7e22f56a5c1573e8c604e6f9363ffacf50693610903938793600401614902565b60006040518083038186803b15801561091b57600080fd5b505af415801561092f573d6000803e3d6000fd5b50505050600061094e828560a001518787600001518860800151611794565b90506040518060400160405280866001600160a01b0316815260200183606001518152508160028151811061098557610985614737565b60200260200101819052506109b982826001815181106109a7576109a7614737565b602002602001015186602001516119ef565b60006109cb8560c00151604001515190565b905060006109dc8660e00151611ac0565b826109f1868960800151878b60600151611aea565b6109fb9190614555565b610a059190614555565b6001600160401b03811115610a1c57610a1c6139f6565b604051908082528060200260200182016040528015610a5557816020015b610a4261391d565b815260200190600190039081610a3a5790505b509050610a7983828660008a602001518b604001518c606001518d60800151611cd3565b6020860151805160009190610a9090600190614367565b81518110610aa057610aa0614737565b60200260200101519050610ac082868960c001518a6000015187866128a8565b610aea82868960e0015187600081518110610add57610add614737565b6020026020010151612ba0565b610b188585600081518110610b0157610b01614737565b602002602001015189602001518a60c00151612c94565b7376f0f76f1b2f2474f7e22f56a5c1573e8c604e6f63396b96168686600081518110610b4657610b46614737565b60200260200101518a6101000151604001516040518463ffffffff1660e01b8152600401610b7693929190614986565b60006040518083038186803b158015610b8e57600080fd5b505af4158015610ba2573d6000803e3d6000fd5b5050865160405163a67a6a4560e01b81526001600160a01b03909116925063a67a6a459150610bd79087908690600401614b9c565b600060405180830381600087803b158015610bf157600080fd5b505af1158015610c05573d6000803e3d6000fd5b505050507376f0f76f1b2f2474f7e22f56a5c1573e8c604e6f63dce467af8686600081518110610c3757610c37614737565b60200260200101518a602001518b608001518c60c001518d6101000151604001516040518763ffffffff1660e01b8152600401610c7996959493929190614bc1565b60006040518083038186803b158015610c9157600080fd5b505af4158015610ca5573d6000803e3d6000fd5b5060009250610cb2915050565b876101000151602001516003811115610ccd57610ccd6147fa565b1480610cf357506001876101000151602001516003811115610cf157610cf16147fa565b145b15610d695760008760200151600081518110610d1157610d11614737565b60200260200101519050610d67866000015186600081518110610d3657610d36614737565b60200260200101516000015187600081518110610d5557610d55614737565b60200260200101516020015184612e99565b505b6000876101000151602001516003811115610d8657610d866147fa565b1480610dac57506002876101000151602001516003811115610daa57610daa6147fa565b145b15610e4a5760c0870151604001515160005b81811015610e4757610e37876000015187600281518110610de157610de1614737565b60200260200101516000015188600281518110610e0057610e00614737565b6020026020010151602001518c60c00151604001518581518110610e2657610e26614737565b602002602001015160000151612e99565b610e4081614c2b565b9050610dbe565b50505b5050505050505050565b8060c0015160000151610e97428210157323b2b732b934b1aa3930b232b9283937bc3cab1960611b6f111958591b1a5b9948195e1c1a5c995960821b8442611562565b6000604051806101400160405280610ead61018c565b6001600160a01b031681526020017f0000000000000000000000000f38bfbd9c1450bcf7a758e80e148ce78cfe09fd6001600160a01b0316639ff78c306040518163ffffffff1660e01b815260040160206040518083038186803b158015610f1457600080fd5b505afa158015610f28573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f4c9190614534565b6001600160a01b03168152600060208201819052604082018190526060820152608001610f7a600180614555565b815260200160008152602001610fb16040805180820182526000808252602091820181905282518084019093528083529082015290565b8152602001610fe16040805180820182526000808252602091820181905282518084019093528083529082015290565b81526020016110116040805180820182526000808252602091820181905282518084019093528083529082015290565b815250905061102383602001516115c0565b61104481858560000151866020015160008151811061089057610890614737565b60408401819052606084015161105a919061170f565b602083015160a0840151608085015160405160016229857d60e11b031981527376f0f76f1b2f2474f7e22f56a5c1573e8c604e6f9363ffacf506936110a3938793600401614902565b60006040518083038186803b1580156110bb57600080fd5b505af41580156110cf573d6000803e3d6000fd5b5050505060006110ee828560a001518787600001518860800151611794565b905061110782826001815181106109a7576109a7614737565b600061111d838660800151848860600151611aea565b6001600160401b03811115611134576111346139f6565b60405190808252806020026020018201604052801561116d57816020015b61115a61391d565b8152602001906001900390816111525790505b509050611191828285600089602001518a604001518b606001518c60800151611cd3565b825160405163a67a6a4560e01b81526001600160a01b039091169063a67a6a45906111c29085908590600401614b9c565b600060405180830381600087803b1580156111dc57600080fd5b505af11580156111f0573d6000803e3d6000fd5b50505050602083810151865191870151608088015160405163255a3bf760e01b81526001600160a01b039093169363255a3bf793611234938c939091600401614cdd565b600060405180830381600087803b15801561124e57600080fd5b505af1158015611262573d6000803e3d6000fd5b506000925061126f915050565b8560c00151602001516003811115611289576112896147fa565b14806112ae575060018560c001516020015160038111156112ac576112ac6147fa565b145b1561131d5761131d8360000151836000815181106112ce576112ce614737565b602002602001015160000151846000815181106112ed576112ed614737565b602002602001015160200151886020015160008151811061131057611310614737565b6020026020010151612e99565b505050505050565b610244611330610259565b6001600160a01b0316826001600160a01b0316147127b7363ca237b637b6b4ba32a6b0b933b4b760711b7f43616c6c6572206973206e6f74206f776e6572206f6620446f6c6f6d69746500846104cb565b60606000826040516020016113969190614d1e565b60408051601f19818403018152919052905060205b801561140157806113bb81614d33565b9150508181815181106113d0576113d0614737565b01602001516001600160f81b031916156113fc5760006113f1826001614555565b835250909392505050565b6113ab565b5060408051600080825260208201909252905b509392505050565b60408051602a80825260608281019093526001600160a01b03841691600091602082018180368337019050509050603060f81b8160008151811061146257611462614737565b60200101906001600160f81b031916908160001a905350607860f81b8160018151811061149157611491614737565b60200101906001600160f81b031916908160001a90535060005b60148110156114145760006114c1826002614d4a565b90506114cf600f8516612f92565b836114db836029614367565b815181106114eb576114eb614737565b60200101906001600160f81b031916908160001a905350600484901c9350611515600f8516612f92565b83611521836028614367565b8151811061153157611531614737565b60200101906001600160f81b031916908160001a9053505060049290921c918061155a81614c2b565b9150506114ab565b846115b95761157084611381565b6101d160f51b61157f85611381565b61080f60f21b61158e86612fbc565b61016160f51b61159d87612fbc565b6040516105119796959493929190601f60f91b90602001614d69565b5050505050565b6102446002825110157547656e6572696354726164657250726f78794261736560501b7f496e76616c6964206d61726b65742070617468206c656e6774680000000000006130c7565b6000600019821461161b575080611706565b85516040805180820182526001600160a01b03888116825260208201889052915163306430bb60e21b8152600093929092169163c190c2ec91611662918890600401614de5565b604080518083038186803b15801561167957600080fd5b505afa15801561168d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116b19190614e49565b90506116ff6116bf826130fb565b157323b2b732b934b1aa3930b232b9283937bc3cab1960611b7f42616c616e6365206d75737420626520706f736974697665000000000000000087613117565b6020015190505b95945050505050565b61174e8215157547656e6572696354726164657250726f78794261736560501b75496e76616c696420696e707574416d6f756e7457656960501b6130c7565b6102248115157547656e6572696354726164657250726f78794261736560501b7f496e76616c6964206d696e4f7574707574416d6f756e745765690000000000006130c7565b60606000805b835181101561180e5760018482815181106117b7576117b7614737565b60200260200101516000015160038111156117d4576117d46147fa565b14156117fe5760a088015160808901819052600192506117f49083614555565b60a089015261180e565b61180781614c2b565b905061179a565b50600086518860a001516118229190614555565b6001600160401b03811115611839576118396139f6565b60405190808252806020026020018201604052801561187e57816020015b60408051808201909152600080825260208201528152602001906001900390816118575790505b5090506040518060400160405280876001600160a01b0316815260200186815250816000815181106118b2576118b2614737565b60200260200101819052506040518060400160405280876001600160a01b031681526020016118e18888613143565b815250816001815181106118f7576118f7614737565b602002602001018190525081156119d95760405180604001604052807f0000000000000000000000000f38bfbd9c1450bcf7a758e80e148ce78cfe09fd6001600160a01b031663b6ab3bc96040518163ffffffff1660e01b815260040160206040518083038186803b15801561196c57600080fd5b505afa158015611980573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119a49190614389565b6001600160a01b031681526020016000815250818960800151815181106119cd576119cd614737565b60200260200101819052505b6119e4888883613179565b979650505050505050565b805160005b818110156115b95784600001516001600160a01b03166347d1b53c85858481518110611a2257611a22614737565b60200260200101516040518363ffffffff1660e01b8152600401611a47929190614de5565b604080518083038186803b158015611a5e57600080fd5b505afa158015611a72573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a969190614ec2565b602001516001600160801b031615611ab057611ab0614ee3565b611ab981614c2b565b90506119f4565b6000816020015163ffffffff1660001415611add57506000919050565b506001919050565b919050565b8251600090600290825b81811015611cc557611b22878281518110611b1157611b11614737565b60200260200101516000015161327d565b15611bc657868181518110611b3957611b39614737565b6020026020010151604001516001600160a01b031663b189111a6040518163ffffffff1660e01b815260040160206040518083038186803b158015611b7d57600080fd5b505afa158015611b91573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611bb59190614ef9565b611bbf9084614555565b9250611cb5565b611bec878281518110611bdb57611bdb614737565b60200260200101516000015161329b565b15611c0357868181518110611b3957611b39614737565b6001878281518110611c1757611c17614737565b6020026020010151600001516003811115611c3457611c346147fa565b1415611ca757868181518110611c4c57611c4c614737565b6020026020010151604001516001600160a01b03166376367b5f611c738a8a8a8a876132b6565b6040518263ffffffff1660e01b8152600401611c8f9190614fb6565b60206040518083038186803b158015611b7d57600080fd5b611cb2600184614555565b92505b611cbe81614c2b565b9050611af4565b50909150505b949350505050565b600019831415611e255760408051808201909152600080825260208201528515611db35786600001516001600160a01b031663c190c2ec8a600081518110611d1d57611d1d614737565b602002602001015187600081518110611d3857611d38614737565b60200260200101516040518363ffffffff1660e01b8152600401611d5d929190614de5565b604080518083038186803b158015611d7457600080fd5b505afa158015611d88573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611dac9190614e49565b9050611dc9565b5060408051808201909152600080825260208201525b611df16000600187600081518110611de357611de3614737565b602002602001015184613428565b60c0880180518a91611e0282614c2b565b905281518110611e1457611e14614737565b602002602001018190525050611e7e565b611e4f6000600186600081518110611e3f57611e3f614737565b60200260200101516000876134ba565b60c0870180518991611e6082614c2b565b905281518110611e7257611e72614737565b60200260200101819052505b805160005b81811015612830576000838281518110611e9f57611e9f614737565b6020026020010151600001516003811115611ebc57611ebc6147fa565b1415611f8f57611f5c6001878381518110611ed957611ed9614737565b602002602001015188846001611eef9190614555565b81518110611eff57611eff614737565b6020026020010151868581518110611f1957611f19614737565b602002602001015160400151611f2e60001990565b611f398a888a6135d0565b898881518110611f4b57611f4b614737565b6020026020010151606001516135f6565b60c0890180518b91611f6d82614c2b565b905281518110611f7f57611f7f614737565b6020026020010181905250612820565b6001838281518110611fa357611fa3614737565b6020026020010151600001516003811115611fc057611fc06147fa565b14156122cd576120c27f0000000000000000000000000f38bfbd9c1450bcf7a758e80e148ce78cfe09fd6001600160a01b0316630d9215f285848151811061200a5761200a614737565b6020026020010151604001516040518263ffffffff1660e01b815260040161203291906142b0565b60206040518083038186803b15801561204a57600080fd5b505afa15801561205e573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061208291906143b5565b7547656e6572696354726164657250726f78794261736560501b7f496e7465726e616c20747261646572206e6f742077686974656c6973746564006130c7565b60006120d189858d88866132b6565b9050606060008c905060008b90508685815181106120f1576120f1614737565b6020026020010151604001516001600160a01b0316631ad08fad604051806101200160405280600181526020018560018151811061213157612131614737565b60200260200101518152602001846080015181526020018585608001518151811061215e5761215e614737565b602002602001015181526020018d898151811061217d5761217d614737565b602002602001015181526020018d8960016121989190614555565b815181106121a8576121a8614737565b602002602001015181526020016121be60001990565b81526020018781526020018a89815181106121db576121db614737565b6020026020010151606001518152506040518263ffffffff1660e01b815260040161220691906150c2565b60006040518083038186803b15801561221e57600080fd5b505afa158015612232573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261225a9190810190615333565b9250505060005b81518110156122c55781818151811061227c5761227c614737565b60200260200101518c8c60c001805180919061229790614c2b565b9052815181106122a9576122a9614737565b6020026020010181905250806122be90614c2b565b9050612261565b505050612820565b6122e2838281518110611b1157611b11614737565b156125535780156122f5576122f5614ee3565b600083828151811061230957612309614737565b6020026020010151604001516001600160a01b031663f93cffde6040518061016001604052806001815260200161233e600090565b81526020018e60018151811061235657612356614737565b6020026020010151600001516001600160a01b031681526020018e60018151811061238357612383614737565b60200260200101516020015181526020018e61239d600090565b815181106123ad576123ad614737565b6020026020010151600001516001600160a01b031681526020018e6123d0600090565b815181106123e0576123e0614737565b60200260200101516020015181526020018a8660016123ff9190614555565b8151811061240f5761240f614737565b602002602001015181526020018a868151811061242e5761242e614737565b6020026020010151815260200161244789878a516135d0565b815260200189815260200187868151811061246457612464614737565b6020026020010151606001518152506040518263ffffffff1660e01b815260040161248f919061544b565b60006040518083038186803b1580156124a757600080fd5b505afa1580156124bb573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526124e39190810190615333565b905060005b815181101561254c5781818151811061250357612503614737565b60200260200101518b8b60c001805180919061251e90614c2b565b90528151811061253057612530614737565b60200260200101819052508061254590614c2b565b90506124e8565b5050612820565b612568838281518110611bdb57611bdb614737565b61257457612574614ee3565b6125c4612582600184614367565b82147547656e6572696354726164657250726f78794261736560501b7f57726170706572206d75737420626520746865206c61737420747261646572006130c7565b60008382815181106125d8576125d8614737565b6020026020010151604001516001600160a01b0316634e2e55806040518061016001604052806001815260200161260d600090565b81526020018e60018151811061262557612625614737565b6020026020010151600001516001600160a01b031681526020018e60018151811061265257612652614737565b60200260200101516020015181526020018e61266c600090565b8151811061267c5761267c614737565b6020026020010151600001516001600160a01b031681526020018e61269f600090565b815181106126af576126af614737565b60200260200101516020015181526020018a8660016126ce9190614555565b815181106126de576126de614737565b602002602001015181526020018a86815181106126fd576126fd614737565b6020026020010151815260200161271689878a516135d0565b8152602001600019815260200187868151811061273557612735614737565b6020026020010151606001518152506040518263ffffffff1660e01b8152600401612760919061544b565b60006040518083038186803b15801561277857600080fd5b505afa15801561278c573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526127b49190810190615333565b905060005b815181101561281d578181815181106127d4576127d4614737565b60200260200101518b8b60c00180518091906127ef90614c2b565b90528151811061280157612801614737565b60200260200101819052508061281690614c2b565b90506127b9565b50505b61282981614c2b565b9050611e83565b5061286f6001600087600189516128479190614367565b8151811061285757612857614737565b6020026020010151600061286a60001990565b6134ba565b60c0880180518a9161288082614c2b565b90528151811061289257612892614737565b6020026020010181905250505050505050505050565b835160009084146128ba5760026128bd565b60005b90506000848660000151146128d35760006128d6565b60025b905060005b84811015612b95576128f06001600019614367565b8760400151828151811061290657612906614737565b6020026020010151602001511415612b045761299f848860400151838151811061293257612932614737565b602002602001015160000151147323b2b732b934b1aa3930b232b9283937bc3cab1960611b7f496e76616c6964207472616e73666572206d61726b65744964000000000000008a60400151858151811061298e5761298e614737565b602002602001015160000151613117565b6129e283157323b2b732b934b1aa3930b232b9283937bc3cab1960611b7f496e76616c69642066726f6d206163636f756e742049440000000000000000006130c7565b612ad18383896040015184815181106129fd576129fd614737565b6020026020010151600001518b600001516001600160a01b031663c190c2ec6040518060400160405280336001600160a01b031681526020018e600001518152508d604001518881518110612a5457612a54614737565b6020026020010151600001516040518363ffffffff1660e01b8152600401612a7d929190614de5565b604080518083038186803b158015612a9457600080fd5b505afa158015612aa8573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612acc9190614e49565b613428565b60c0890180518b91612ae282614c2b565b905281518110612af457612af4614737565b6020026020010181905250612b83565b612b54838389604001518481518110612b1f57612b1f614737565b60200260200101516000015160008b604001518681518110612b4357612b43614737565b6020026020010151602001516134ba565b60c0890180518b91612b6582614c2b565b905281518110612b7757612b77614737565b60200260200101819052505b80612b8d81614c2b565b9150506128db565b505050505050505050565b602082015163ffffffff16612bb457610537565b612c6081600084600001517f0000000000000000000000000f38bfbd9c1450bcf7a758e80e148ce78cfe09fd6001600160a01b031663e184c9be6040518163ffffffff1660e01b815260040160206040518083038186803b158015612c1857600080fd5b505afa158015612c2c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612c509190614534565b866020015163ffffffff166136fc565b60c0840180518691612c7182614c2b565b905281518110612c8357612c83614737565b602002602001018190525050505050565b83600001516001600160a01b031663c190c2ec8484600081518110612cbb57612cbb614737565b60200260200101516040518363ffffffff1660e01b8152600401612ce0929190614de5565b604080518083038186803b158015612cf757600080fd5b505afa158015612d0b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612d2f9190614e49565b8460e0018190525083600001516001600160a01b031663c190c2ec848460018651612d5a9190614367565b81518110612d6a57612d6a614737565b60200260200101516040518363ffffffff1660e01b8152600401612d8f929190614de5565b604080518083038186803b158015612da657600080fd5b505afa158015612dba573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612dde9190614e49565b84610100018190525083600001516001600160a01b031663c190c2ec848360400151600081518110612e1257612e12614737565b6020026020010151600001516040518363ffffffff1660e01b8152600401612e3b929190614de5565b604080518083038186803b158015612e5257600080fd5b505afa158015612e66573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612e8a9190614e49565b84610120018190525050505050565b6040805180820182526001600160a01b0380861682526020820185905291516311f46d4f60e21b81529091600091908716906347d1b53c90612ee19085908790600401614de5565b604080518083038186803b158015612ef857600080fd5b505afa158015612f0c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612f309190614ec2565b905061131d612f3e82613819565b80612f54575060208201516001600160801b0316155b7020b1b1b7bab73a2130b630b731b2a634b160791b7f6163636f756e742063616e6e6f7420676f206e65676174697665000000000000888888613838565b6000600a821015612fb157612fa8603083614555565b60f81b92915050565b612fa8605783614555565b606081612fe05750506040805180820190915260018152600360fc1b602082015290565b8160005b811561300a5780612ff481614c2b565b91506130039050600a83615472565b9150612fe4565b6000816001600160401b03811115613024576130246139f6565b6040519080825280601f01601f19166020018201604052801561304e576020820181803683370190505b508593509050815b80156130be578061306681614d33565b91506130759050600a85615486565b613080906030614555565b60f81b82828151811061309557613095614737565b60200101906001600160f81b031916908160001a9053506130b7600a85615472565b9350613056565b50949350505050565b826130f6576130d582611381565b6101d160f51b6130e483611381565b6040516020016105119392919061549a565b505050565b8051600090158015613111575060008260200151115b92915050565b836105375761312583611381565b6101d160f51b61313484611381565b61080f60f21b6104f785612fbc565b600082824260405160200161315a939291906154ea565b60408051601f1981840301815291905280516020909101209392505050565b815160005b818110156115b957600083828760a001516131999190614555565b815181106131a9576131a9614737565b6020026020010151905060006001600160a01b031681600001516001600160a01b03161480156131db57506020810151155b6131e7576131e7614ee3565b604051806040016040528086848151811061320457613204614737565b6020026020010151600001516001600160a01b0316815260200186848151811061323057613230614737565b60200260200101516020015181525084838860a001516132509190614555565b8151811061326057613260614737565b6020026020010181905250508061327690614c2b565b905061317e565b6000816003811115613291576132916147fa565b60025b1492915050565b60008160038111156132af576132af6147fa565b6003613294565b60408051600180825281830190925260609160009190816020015b6040805160c08101825260006080820181815260a0830182905282526020808301829052928201819052606082015282526000199092019101816132d1579050509050848760a0015187858151811061332c5761332c614737565b6020026020010151602001516133429190614555565b8151811061335257613352614737565b60200260200101518160008151811061336d5761336d614737565b6020026020010151600001819052508660a0015186848151811061339357613393614737565b6020026020010151602001516133a99190614555565b816000815181106133bc576133bc614737565b6020908102919091018101510152600019816000815181106133e0576133e0614737565b602002602001015160400181815250506133fc848488516135d0565b8160008151811061340f5761340f614737565b6020908102919091010151606001529695505050505050565b61343061391d565b60408051610100810190915280600281526020808201889052604080516080810182528651151581529201919081016000815260200160018152602001856020015181525081526020018481526020016000815260200160006001600160a01b03168152602001858152602001604051806020016040528060008152508152509050949350505050565b6134c261391d565b6134ee604080516080810190915260008082526020820190815260200160008152602001600081525090565b60001983141561353657604051806080016040528060001515815260200185600181111561351e5761351e6147fa565b8152602001600181526020016000815250905061356e565b604051806080016040528060001515815260200185600181111561355c5761355c6147fa565b81526020016000815260200184905290505b60408051610100810190915280600281526020018881526020018281526020018681526020016000815260200160006001600160a01b031681526020018781526020016040518060200160405280600081525081525091505095945050505050565b60006135dd600183614367565b83146135ea5760016135ec565b835b90505b9392505050565b6135fe61391d565b61362a604080516080810190915260008082526020820190815260200160008152602001600081525090565b6000198514156136615760408051608081019091526000808252602082019081526020016001815260200160008152509050613688565b60408051608081019091526000808252602082019081526020016000815260200186905290505b60408051610100810190915280600481526020018a8152602001828152602001898152602001888152602001876001600160a01b031681526020016000815260200185856040516020016136dd929190615521565b60408051601f1981840301815291905290529998505050505050505050565b61370461391d565b61374a8263ffffffff1683146f20b1b1b7bab73a20b1ba34b7b72634b160811b7f496e76616c6964206578706972792074696d652064656c7461000000000000006130c7565b604080516001808252818301909252600091816020015b6040805160c08101825260006080820181815260a08301829052825260208083018290529282018190526060820152825260001990920191018161376157905050905060405180608001604052808881526020018681526020018463ffffffff16815260200160011515815250816000815181106137e1576137e1614737565b60200260200101819052506119e486856000846040516020016138059291906155e1565b6040516020818303038152906040526138a0565b80516000908015613111575050602001516001600160801b0316151590565b8561131d5761384685611381565b6101d160f51b61385586611381565b61080f60f21b6138648761141c565b61016160f51b61387388612fbc565b61016160f51b61388289612fbc565b60405161051199989796959493929190601f60f91b90602001615601565b6138a861391d565b60408051610100810182526008815260208082018790528251608081018452600080825292938401929091820190815260200160008152602001600081525081526020016000815260200160008152602001846001600160a01b03168152602001600081526020018381525090509392505050565b604080516101008101825260008082526020820152908101613961604080516080810190915260008082526020820190815260200160008152602001600081525090565b8152602001600081526020016000815260200160006001600160a01b0316815260200160008152602001606081525090565b60006001600160a01b038216613111565b600061311182613993565b6000613111826139a4565b6139c3816139af565b82525050565b6020810161311182846139ba565b6139e081613993565b811461024457600080fd5b8035613111816139d7565b634e487b7160e01b600052604160045260246000fd5b601f19601f83011681018181106001600160401b0382111715613a3157613a316139f6565b6040525050565b6000613a4360405190565b9050611ae58282613a0c565b806139e0565b803561311181613a4f565b60006001600160401b03821115613a7957613a796139f6565b5060209081020190565b6000613a96613a9184613a60565b613a38565b83815290506020808201908402830185811115613ab557613ab5600080fd5b835b81811015613ad95780613aca8882613a55565b84525060209283019201613ab7565b5050509392505050565b600082601f830112613af757613af7600080fd5b8135611ccb848260208601613a83565b6004811061024457600080fd5b803561311181613b07565b60006001600160401b03821115613b3857613b386139f6565b601f19601f83011660200192915050565b82818337506000910152565b6000613b63613a9184613b1f565b905082815260208101848484011115613b7e57613b7e600080fd5b611414848285613b49565b600082601f830112613b9d57613b9d600080fd5b8135611ccb848260208601613b55565b600060808284031215613bc257613bc2600080fd5b613bcc6080613a38565b90506000613bda8484613b14565b8252506020613beb84848301613a55565b6020830152506040613bff848285016139eb565b60408301525060608201356001600160401b03811115613c2157613c21600080fd5b613c2d84828501613b89565b60608301525092915050565b6000613c47613a9184613a60565b83815290506020808201908402830185811115613c6657613c66600080fd5b835b81811015613ad95780356001600160401b03811115613c8957613c89600080fd5b808601613c968982613bad565b8552505060209283019201613c68565b600082601f830112613cba57613cba600080fd5b8135611ccb848260208601613c39565b600060408284031215613cdf57613cdf600080fd5b613ce96040613a38565b90506000613cf784846139eb565b8252506020613d0884848301613a55565b60208301525092915050565b6000613d22613a9184613a60565b83815290506020810160408402830185811115613d4157613d41600080fd5b835b81811015613ad95780613d568882613cca565b845250602090920191604001613d43565b600082601f830112613d7b57613d7b600080fd5b8135611ccb848260208601613d14565b600060408284031215613da057613da0600080fd5b613daa6040613a38565b90506000613cf78484613a55565b6000613dc6613a9184613a60565b83815290506020810160408402830185811115613de557613de5600080fd5b835b81811015613ad95780613dfa8882613d8b565b845250602090920191604001613de7565b600082601f830112613e1f57613e1f600080fd5b8135611ccb848260208601613db8565b600060608284031215613e4457613e44600080fd5b613e4e6060613a38565b90506000613e5c8484613a55565b8252506020613e6d84848301613a55565b60208301525060408201356001600160401b03811115613e8f57613e8f600080fd5b613e9b84828501613e0b565b60408301525092915050565b63ffffffff81166139e0565b803561311181613ea7565b600060408284031215613ed357613ed3600080fd5b613edd6040613a38565b90506000613eeb8484613a55565b8252506020613d0884848301613eb3565b6003811061024457600080fd5b803561311181613efc565b600060608284031215613f2957613f29600080fd5b613f336060613a38565b90506000613f418484613a55565b8252506020613f5284848301613b14565b6020830152506040613e9b84828501613f09565b60006101808284031215613f7c57613f7c600080fd5b613f87610120613a38565b90506000613f958484613a55565b82525060208201356001600160401b03811115613fb457613fb4600080fd5b613fc084828501613ae3565b6020830152506040613fd484828501613a55565b6040830152506060613fe884828501613a55565b60608301525060808201356001600160401b0381111561400a5761400a600080fd5b61401684828501613ca6565b60808301525060a08201356001600160401b0381111561403857614038600080fd5b61404484828501613d67565b60a08301525060c08201356001600160401b0381111561406657614066600080fd5b61407284828501613e2f565b60c08301525060e061408684828501613ebe565b60e08301525061012061409b84828501613f14565b6101008301525092915050565b600080604083850312156140be576140be600080fd5b60006140ca85856139eb565b92505060208301356001600160401b038111156140e9576140e9600080fd5b6140f585828601613f66565b9150509250929050565b60006020828403121561411457614114600080fd5b6000611ccb84846139eb565b8015156139c3565b602081016131118284614120565b6000610120828403121561414c5761414c600080fd5b61415660e0613a38565b905060006141648484613a55565b82525060208201356001600160401b0381111561418357614183600080fd5b61418f84828501613ae3565b60208301525060406141a384828501613a55565b60408301525060606141b784828501613a55565b60608301525060808201356001600160401b038111156141d9576141d9600080fd5b6141e584828501613ca6565b60808301525060a08201356001600160401b0381111561420757614207600080fd5b61421384828501613d67565b60a08301525060c061422784828501613f14565b60c08301525092915050565b60006020828403121561424857614248600080fd5b81356001600160401b0381111561426157614261600080fd5b611ccb84828501614136565b60006020828403121561428257614282600080fd5b81356001600160401b0381111561429b5761429b600080fd5b611ccb84828501613f66565b6139c381613993565b6020810161311182846142a7565b600080604083850312156142d4576142d4600080fd5b60006142e085856139eb565b92505060208301356001600160401b038111156142ff576142ff600080fd5b6140f585828601614136565b8015156139e0565b80356131118161430b565b6000806040838503121561433457614334600080fd5b600061434085856139eb565b92505060206140f585828601614313565b634e487b7160e01b600052601160045260246000fd5b60008282101561437957614379614351565b500390565b8051613111816139d7565b60006020828403121561439e5761439e600080fd5b6000611ccb848461437e565b80516131118161430b565b6000602082840312156143ca576143ca600080fd5b6000611ccb84846143aa565b6020808252810161311181601f81527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c00602082015260400190565b60005b8381101561442c578181015183820152602001614414565b838111156105375750506000910152565b6000614447825190565b614455818560208601614411565b9290920192915050565b6001600160f01b031981166139c3565b6001600160f81b031981166139c3565b600061448b828961443d565b9150614497828861445f565b6002820191506144a7828761443d565b91506144b3828661445f565b6002820191506144c3828561443d565b91506144cf828461446f565b506001019695505050505050565b60006144e7825190565b8084526020840193506144fe818560208601614411565b601f01601f19169290920192915050565b602080825281016135ef81846144dd565b6139e0816139a4565b805161311181614520565b60006020828403121561454957614549600080fd5b6000611ccb8484614529565b6000821982111561456857614568614351565b500190565b806139c3565b805160408301906145848482614120565b506020820151610537602085018261456d565b80516101a08301906145a984826139ba565b5060208201516145bc60208501826139ba565b5060408201516145cf6040850182614120565b5060608201516145e2606085018261456d565b5060808201516145f5608085018261456d565b5060a082015161460860a085018261456d565b5060c082015161461b60c085018261456d565b5060e082015161462e60e0850182614573565b50610100820151614643610120850182614573565b50610120820151610537610160850182614573565b80516040830190614584848261456d565b60006146758383614658565b505060400190565b6000614687825190565b80845260209384019383018060005b838110156146bb5781516146aa8882614669565b975060208301925050600101614696565b509495945050505050565b805160009060608401906146da858261456d565b5060208301516146ed602086018261456d565b5060408301518482036040860152611706828261467d565b6101e081016147148286614597565b8181036101a083015261472781856146c6565b9050611ccb6101c083018461456d565b634e487b7160e01b600052603260045260246000fd5b6000614759838361456d565b505060200190565b600061476b825190565b80845260209384019383018060005b838110156146bb57815161478e888261474d565b97506020830192505060010161477a565b8051604083019061458484826142a7565b6000614675838361479f565b60006147c6825190565b80845260209384019383018060005b838110156146bb5781516147e988826147b0565b9750602083019250506001016147d5565b634e487b7160e01b600052602160045260246000fd5b60048110610244576102446147fa565b80611ae581614810565b600061311182614820565b6139c38161482a565b805160009060808401906148528582614835565b506020830151614865602086018261456d565b50604083015161487860408601826142a7565b506060830151848203606086015261170682826144dd565b60006135ef838361483e565b60006148a6825190565b808452602084019350836020820285016148c08560200190565b8060005b858110156148f557848403895281516148dd8582614890565b94506020830160209a909a01999250506001016148c4565b5091979650505050505050565b61020081016149118287614597565b8181036101a08301526149248186614761565b90508181036101c083015261493981856147bc565b90508181036101e083015261494e818461489c565b9695505050505050565b60038110610244576102446147fa565b80611ae581614958565b600061311182614968565b6139c381614972565b61020081016149958286614597565b6149a36101a083018561479f565b611ccb6101e083018461497d565b60006149bb825190565b80845260209384019383018060005b838110156146bb5781516149de88826147b0565b9750602083019250506001016149ca565b60098110610244576102446147fa565b80611ae5816149ef565b6000613111826149ff565b6139c381614a09565b60028110610244576102446147fa565b80611ae581614a1d565b600061311182614a2d565b6139c381614a37565b80516080830190614a5c8482614120565b506020820151614a6f6020850182614a42565b506040820151614a826040850182614a42565b506060820151610537606085018261456d565b8051600090610160840190614aaa8582614a14565b506020830151614abd602086018261456d565b506040830151614ad06040860182614a4b565b506060830151614ae360c086018261456d565b506080830151614af660e086018261456d565b5060a0830151614b0a6101008601826142a7565b5060c0830151614b1e61012086018261456d565b5060e083015184820361014086015261170682826144dd565b60006135ef8383614a95565b6000614b4d825190565b80845260208401935083602082028501614b678560200190565b8060005b858110156148f55784840389528151614b848582614b37565b94506020830160209a909a0199925050600101614b6b565b60408082528101614bad81856149b1565b905081810360208301526135ec8184614b43565b6102608101614bd08289614597565b614bde6101a083018861479f565b8181036101e0830152614bf18187614761565b9050818103610200830152614c06818661489c565b9050818103610220830152614c1b81856146c6565b90506119e461024083018461497d565b6000600019821415614c3f57614c3f614351565b5060010190565b6000614c50825190565b80845260209384019383018060005b838110156146bb578151614c73888261474d565b975060208301925050600101614c5f565b6000614c8e825190565b80845260208401935083602082028501614ca88560200190565b8060005b858110156148f55784840389528151614cc58582614890565b94506020830160209a909a0199925050600101614cac565b60808101614ceb82876142a7565b614cf8602083018661456d565b8181036040830152614d0a8185614c46565b9050818103606083015261494e8184614c84565b6000614d2a828461456d565b50602001919050565b600081614d4257614d42614351565b506000190190565b6000816000190483118215151615614d6457614d64614351565b500290565b6000614d75828b61443d565b9150614d81828a61445f565b600282019150614d91828961443d565b9150614d9d828861445f565b600282019150614dad828761443d565b9150614db9828661445f565b600282019150614dc9828561443d565b9150614dd5828461446f565b5060010198975050505050505050565b60608101614df3828561479f565b6135ef604083018461456d565b805161311181613a4f565b600060408284031215614e2057614e20600080fd5b614e2a6040613a38565b90506000614e3884846143aa565b8252506020613d0884848301614e00565b600060408284031215614e5e57614e5e600080fd5b6000611ccb8484614e0b565b6001600160801b0381166139e0565b805161311181614e6a565b600060408284031215614e9957614e99600080fd5b614ea36040613a38565b90506000614eb184846143aa565b8252506020613d0884848301614e79565b600060408284031215614ed757614ed7600080fd5b6000611ccb8484614e84565b634e487b7160e01b600052600160045260246000fd5b600060208284031215614f0e57614f0e600080fd5b6000611ccb8484614e00565b805160a0830190614f2b848261479f565b506020820151614f3e604085018261456d565b506040820151614f51606085018261456d565b506060820151610537608085018261456d565b6000614f708383614f1a565b505060a00190565b6000614f82825190565b80845260209384019383018060005b838110156146bb578151614fa58882614f64565b975060208301925050600101614f91565b602080825281016135ef8184614f78565b6000614fd1825190565b80845260209384019383018060005b838110156146bb578151614ff48882614f64565b975060208301925050600101614fe0565b805160009061016084019061501a858261456d565b50602083015161502d602086018261479f565b506040830151615040606086018261456d565b506060830151615053608086018261479f565b50608083015161506660c086018261456d565b5060a083015161507960e086018261456d565b5060c083015161508d61010086018261456d565b5060e08301518482036101208601526150a68282614fc7565b91505061010083015184820361014086015261170682826144dd565b602080825281016135ef8184615005565b6009811061024457600080fd5b8051613111816150d3565b6002811061024457600080fd5b8051613111816150eb565b60006080828403121561511857615118600080fd5b6151226080613a38565b9050600061513084846143aa565b8252506020615141848483016150f8565b6020830152506040615155848285016150f8565b6040830152506060613c2d84828501614e00565b6000615177613a9184613b1f565b90508281526020810184848401111561519257615192600080fd5b611414848285614411565b600082601f8301126151b1576151b1600080fd5b8151611ccb848260208601615169565b600061016082840312156151d7576151d7600080fd5b6151e2610100613a38565b905060006151f084846150e0565b825250602061520184848301614e00565b602083015250604061521584828501615103565b60408301525060c061522984828501614e00565b60608301525060e061523d84828501614e00565b6080830152506101006152528482850161437e565b60a08301525061012061526784828501614e00565b60c0830152506101408201516001600160401b0381111561528a5761528a600080fd5b6152968482850161519d565b60e08301525092915050565b60006152b0613a9184613a60565b838152905060208082019084028301858111156152cf576152cf600080fd5b835b81811015613ad95780516001600160401b038111156152f2576152f2600080fd5b8086016152ff89826151c1565b85525050602092830192016152d1565b600082601f83011261532357615323600080fd5b8151611ccb8482602086016152a2565b60006020828403121561534857615348600080fd5b81516001600160401b0381111561536157615361600080fd5b611ccb8482850161530f565b8051600090610160840190615382858261456d565b506020830151615395602086018261456d565b5060408301516153a860408601826142a7565b5060608301516153bb606086018261456d565b5060808301516153ce60808601826142a7565b5060a08301516153e160a086018261456d565b5060c08301516153f460c086018261456d565b5060e083015161540760e086018261456d565b5061010083015161541c61010086018261456d565b5061012083015161543161012086018261456d565b5061014083015184820361014086015261170682826144dd565b602080825281016135ef818461536d565b634e487b7160e01b600052601260045260246000fd5b6000826154815761548161545c565b500490565b6000826154955761549561545c565b500690565b60006154a6828661443d565b91506154b2828561445f565b600282019150611706828461443d565b60006131118260601b90565b6000613111826154c2565b6139c36154e582613993565b6154ce565b60006154f682866154d9565b601482019150615506828561456d565b602082019150615516828461456d565b506020019392505050565b6040810161552f828561456d565b81810360208301526135ec81846144dd565b63ffffffff81166139c3565b805160a083019061555e848261479f565b506020820151615571604085018261456d565b5060408201516155846060850182615541565b5060608201516105376080850182614120565b6000614f70838361554d565b60006155ad825190565b80845260209384019383018060005b838110156146bb5781516155d08882615597565b9750602083019250506001016155bc565b604081016155ef8285614a42565b81810360208301526135ec81846155a3565b600061560d828d61443d565b9150615619828c61445f565b600282019150615629828b61443d565b9150615635828a61445f565b600282019150615645828961443d565b9150615651828861445f565b600282019150615661828761443d565b915061566d828661445f565b60028201915061567d828561443d565b9150615689828461446f565b506001019a995050505050505050505056fea26469706673582212202985b1277e05e4d26502dcb32bc298a55a2a9a2eb9e244f0622f387d1e1ca70b64736f6c63430008090033

Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)

0000000000000000000000000f38bfbd9c1450bcf7a758e80e148ce78cfe09fd000000000000000000000000003ca23fd5f0ca87d01f6ec6cd14a8ae60c2b97d

-----Decoded View---------------
Arg [0] : _dolomiteRegistry (address): 0x0F38bFBd9c1450BCF7A758e80E148CE78cfE09fD
Arg [1] : _dolomiteMargin (address): 0x003Ca23Fd5F0ca87D01F6eC6CD14A8AE60c2b97D

-----Encoded View---------------
2 Constructor Arguments found :
Arg [0] : 0000000000000000000000000f38bfbd9c1450bcf7a758e80e148ce78cfe09fd
Arg [1] : 000000000000000000000000003ca23fd5f0ca87d01f6ec6cd14a8ae60c2b97d


Block Transaction Gas Used Reward
view all blocks produced

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

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
[ 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.