OP Sepolia Testnet

Contract

0x2f6B2d71eF966336336CD840253fD53Ea5a95788

Overview

ETH Balance

0 ETH

Sponsored

Transaction Hash
Method
Block
From
To
Value
0x6080604073078072024-01-28 5:02:34148 days ago1706418154IN
 Contract Creation
0 ETH0.000000470.00010025

Advanced mode:
Parent Transaction Hash Block From To Value
View All Internal Transactions

Loading...
Loading

Similar Match Source Code
This contract matches the deployed Bytecode of the Source Code for Contract 0x54e08ec9...5D62B388A
The constructor portion of the code might be different and could alter the actual behaviour of the contract

Contract Name:
PerpsV2MarketDelayedIntent

Compiler Version
v0.5.16+commit.9c3226ce

Optimization Enabled:
Yes with 200 runs

Other Settings:
default evmVersion

Contract Source Code (Solidity)

/**
 *Submitted for verification at sepolia-optimm.etherscan.io on 2024-01-28
*/

/*
   ____            __   __        __   _
  / __/__ __ ___  / /_ / /  ___  / /_ (_)__ __
 _\ \ / // // _ \/ __// _ \/ -_)/ __// / \ \ /
/___/ \_, //_//_/\__//_//_/\__/ \__//_/ /_\_\
     /___/

* Synthetix: PerpsV2MarketDelayedIntent.sol
*
* Latest source (may be newer): https://github.com/Synthetixio/synthetix/blob/master/contracts/PerpsV2MarketDelayedIntent.sol
* Docs: https://docs.synthetix.io/contracts/PerpsV2MarketDelayedIntent
*
* Contract Dependencies: 
*	- IAddressResolver
*	- IPerpsV2MarketBaseTypes
*	- IPerpsV2MarketDelayedIntent
*	- MixinPerpsV2MarketSettings
*	- MixinResolver
*	- Owned
*	- PerpsV2MarketBase
*	- PerpsV2MarketProxyable
*	- Proxyable
* Libraries: 
*	- SafeDecimalMath
*	- SafeMath
*	- SignedSafeDecimalMath
*	- SignedSafeMath
*
* MIT License
* ===========
*
* Copyright (c) 2024 Synthetix
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
*/



pragma solidity ^0.5.16;

// https://docs.synthetix.io/contracts/source/contracts/owned
contract Owned {
    address public owner;
    address public nominatedOwner;

    constructor(address _owner) public {
        require(_owner != address(0), "Owner address cannot be 0");
        owner = _owner;
        emit OwnerChanged(address(0), _owner);
    }

    function nominateNewOwner(address _owner) external onlyOwner {
        nominatedOwner = _owner;
        emit OwnerNominated(_owner);
    }

    function acceptOwnership() external {
        require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership");
        emit OwnerChanged(owner, nominatedOwner);
        owner = nominatedOwner;
        nominatedOwner = address(0);
    }

    modifier onlyOwner {
        _onlyOwner();
        _;
    }

    function _onlyOwner() private view {
        require(msg.sender == owner, "Only the contract owner may perform this action");
    }

    event OwnerNominated(address newOwner);
    event OwnerChanged(address oldOwner, address newOwner);
}


// Inheritance


// Internal references


// https://docs.synthetix.io/contracts/source/contracts/proxy
contract Proxy is Owned {
    Proxyable public target;

    constructor(address _owner) public Owned(_owner) {}

    function setTarget(Proxyable _target) external onlyOwner {
        target = _target;
        emit TargetUpdated(_target);
    }

    function _emit(
        bytes calldata callData,
        uint numTopics,
        bytes32 topic1,
        bytes32 topic2,
        bytes32 topic3,
        bytes32 topic4
    ) external onlyTarget {
        uint size = callData.length;
        bytes memory _callData = callData;

        assembly {
            /* The first 32 bytes of callData contain its length (as specified by the abi).
             * Length is assumed to be a uint256 and therefore maximum of 32 bytes
             * in length. It is also leftpadded to be a multiple of 32 bytes.
             * This means moving call_data across 32 bytes guarantees we correctly access
             * the data itself. */
            switch numTopics
                case 0 {
                    log0(add(_callData, 32), size)
                }
                case 1 {
                    log1(add(_callData, 32), size, topic1)
                }
                case 2 {
                    log2(add(_callData, 32), size, topic1, topic2)
                }
                case 3 {
                    log3(add(_callData, 32), size, topic1, topic2, topic3)
                }
                case 4 {
                    log4(add(_callData, 32), size, topic1, topic2, topic3, topic4)
                }
        }
    }

    // solhint-disable no-complex-fallback
    function() external payable {
        // Mutable call setting Proxyable.messageSender as this is using call not delegatecall
        target.setMessageSender(msg.sender);

        assembly {
            let free_ptr := mload(0x40)
            calldatacopy(free_ptr, 0, calldatasize)

            /* We must explicitly forward ether to the underlying contract as well. */
            let result := call(gas, sload(target_slot), callvalue, free_ptr, calldatasize, 0, 0)
            returndatacopy(free_ptr, 0, returndatasize)

            if iszero(result) {
                revert(free_ptr, returndatasize)
            }
            return(free_ptr, returndatasize)
        }
    }

    modifier onlyTarget {
        require(Proxyable(msg.sender) == target, "Must be proxy target");
        _;
    }

    event TargetUpdated(Proxyable newTarget);
}


// Inheritance


// Internal references


// https://docs.synthetix.io/contracts/source/contracts/proxyable
contract Proxyable is Owned {
    // This contract should be treated like an abstract contract

    /* The proxy this contract exists behind. */
    Proxy public proxy;

    /* The caller of the proxy, passed through to this contract.
     * Note that every function using this member must apply the onlyProxy or
     * optionalProxy modifiers, otherwise their invocations can use stale values. */
    address public messageSender;

    constructor(address payable _proxy) internal {
        // This contract is abstract, and thus cannot be instantiated directly
        require(owner != address(0), "Owner must be set");

        proxy = Proxy(_proxy);
        emit ProxyUpdated(_proxy);
    }

    function setProxy(address payable _proxy) external onlyOwner {
        proxy = Proxy(_proxy);
        emit ProxyUpdated(_proxy);
    }

    function setMessageSender(address sender) external onlyProxy {
        messageSender = sender;
    }

    modifier onlyProxy {
        _onlyProxy();
        _;
    }

    function _onlyProxy() private view {
        require(Proxy(msg.sender) == proxy, "Only the proxy can call");
    }

    modifier optionalProxy {
        _optionalProxy();
        _;
    }

    function _optionalProxy() private {
        if (Proxy(msg.sender) != proxy && messageSender != msg.sender) {
            messageSender = msg.sender;
        }
    }

    modifier optionalProxy_onlyOwner {
        _optionalProxy_onlyOwner();
        _;
    }

    // solhint-disable-next-line func-name-mixedcase
    function _optionalProxy_onlyOwner() private {
        if (Proxy(msg.sender) != proxy && messageSender != msg.sender) {
            messageSender = msg.sender;
        }
        require(messageSender == owner, "Owner only function");
    }

    event ProxyUpdated(address proxyAddress);
}


// https://docs.synthetix.io/contracts/source/interfaces/iaddressresolver
interface IAddressResolver {
    function getAddress(bytes32 name) external view returns (address);

    function getSynth(bytes32 key) external view returns (address);

    function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address);
}


// https://docs.synthetix.io/contracts/source/interfaces/isynth
interface ISynth {
    // Views
    function currencyKey() external view returns (bytes32);

    function transferableSynths(address account) external view returns (uint);

    // Mutative functions
    function transferAndSettle(address to, uint value) external returns (bool);

    function transferFromAndSettle(
        address from,
        address to,
        uint value
    ) external returns (bool);

    // Restricted: used internally to Synthetix
    function burn(address account, uint amount) external;

    function issue(address account, uint amount) external;
}


// https://docs.synthetix.io/contracts/source/interfaces/iissuer
interface IIssuer {
    // Views

    function allNetworksDebtInfo()
        external
        view
        returns (
            uint256 debt,
            uint256 sharesSupply,
            bool isStale
        );

    function anySynthOrSNXRateIsInvalid() external view returns (bool anyRateInvalid);

    function availableCurrencyKeys() external view returns (bytes32[] memory);

    function availableSynthCount() external view returns (uint);

    function availableSynths(uint index) external view returns (ISynth);

    function canBurnSynths(address account) external view returns (bool);

    function collateral(address account) external view returns (uint);

    function collateralisationRatio(address issuer) external view returns (uint);

    function collateralisationRatioAndAnyRatesInvalid(address _issuer)
        external
        view
        returns (uint cratio, bool anyRateIsInvalid);

    function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint debtBalance);

    function issuanceRatio() external view returns (uint);

    function lastIssueEvent(address account) external view returns (uint);

    function maxIssuableSynths(address issuer) external view returns (uint maxIssuable);

    function minimumStakeTime() external view returns (uint);

    function remainingIssuableSynths(address issuer)
        external
        view
        returns (
            uint maxIssuable,
            uint alreadyIssued,
            uint totalSystemDebt
        );

    function synths(bytes32 currencyKey) external view returns (ISynth);

    function getSynths(bytes32[] calldata currencyKeys) external view returns (ISynth[] memory);

    function synthsByAddress(address synthAddress) external view returns (bytes32);

    function totalIssuedSynths(bytes32 currencyKey, bool excludeOtherCollateral) external view returns (uint);

    function transferableSynthetixAndAnyRateIsInvalid(address account, uint balance)
        external
        view
        returns (uint transferable, bool anyRateIsInvalid);

    function liquidationAmounts(address account, bool isSelfLiquidation)
        external
        view
        returns (
            uint totalRedeemed,
            uint debtToRemove,
            uint escrowToLiquidate,
            uint initialDebtBalance
        );

    // Restricted: used internally to Synthetix
    function addSynths(ISynth[] calldata synthsToAdd) external;

    function issueSynths(address from, uint amount) external;

    function issueSynthsOnBehalf(
        address issueFor,
        address from,
        uint amount
    ) external;

    function issueMaxSynths(address from) external;

    function issueMaxSynthsOnBehalf(address issueFor, address from) external;

    function burnSynths(address from, uint amount) external;

    function burnSynthsOnBehalf(
        address burnForAddress,
        address from,
        uint amount
    ) external;

    function burnSynthsToTarget(address from) external;

    function burnSynthsToTargetOnBehalf(address burnForAddress, address from) external;

    function burnForRedemption(
        address deprecatedSynthProxy,
        address account,
        uint balance
    ) external;

    function setCurrentPeriodId(uint128 periodId) external;

    function liquidateAccount(address account, bool isSelfLiquidation)
        external
        returns (
            uint totalRedeemed,
            uint debtRemoved,
            uint escrowToLiquidate
        );

    function issueSynthsWithoutDebt(
        bytes32 currencyKey,
        address to,
        uint amount
    ) external returns (bool rateInvalid);

    function burnSynthsWithoutDebt(
        bytes32 currencyKey,
        address to,
        uint amount
    ) external returns (bool rateInvalid);

    function modifyDebtSharesForMigration(address account, uint amount) external;
}


// Inheritance


// Internal references


// https://docs.synthetix.io/contracts/source/contracts/addressresolver
contract AddressResolver is Owned, IAddressResolver {
    mapping(bytes32 => address) public repository;

    constructor(address _owner) public Owned(_owner) {}

    /* ========== RESTRICTED FUNCTIONS ========== */

    function importAddresses(bytes32[] calldata names, address[] calldata destinations) external onlyOwner {
        require(names.length == destinations.length, "Input lengths must match");

        for (uint i = 0; i < names.length; i++) {
            bytes32 name = names[i];
            address destination = destinations[i];
            repository[name] = destination;
            emit AddressImported(name, destination);
        }
    }

    /* ========= PUBLIC FUNCTIONS ========== */

    function rebuildCaches(MixinResolver[] calldata destinations) external {
        for (uint i = 0; i < destinations.length; i++) {
            destinations[i].rebuildCache();
        }
    }

    /* ========== VIEWS ========== */

    function areAddressesImported(bytes32[] calldata names, address[] calldata destinations) external view returns (bool) {
        for (uint i = 0; i < names.length; i++) {
            if (repository[names[i]] != destinations[i]) {
                return false;
            }
        }
        return true;
    }

    function getAddress(bytes32 name) external view returns (address) {
        return repository[name];
    }

    function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address) {
        address _foundAddress = repository[name];
        require(_foundAddress != address(0), reason);
        return _foundAddress;
    }

    function getSynth(bytes32 key) external view returns (address) {
        IIssuer issuer = IIssuer(repository["Issuer"]);
        require(address(issuer) != address(0), "Cannot find Issuer address");
        return address(issuer.synths(key));
    }

    /* ========== EVENTS ========== */

    event AddressImported(bytes32 name, address destination);
}


// Internal references


// https://docs.synthetix.io/contracts/source/contracts/mixinresolver
contract MixinResolver {
    AddressResolver public resolver;

    mapping(bytes32 => address) private addressCache;

    constructor(address _resolver) internal {
        resolver = AddressResolver(_resolver);
    }

    /* ========== INTERNAL FUNCTIONS ========== */

    function combineArrays(bytes32[] memory first, bytes32[] memory second)
        internal
        pure
        returns (bytes32[] memory combination)
    {
        combination = new bytes32[](first.length + second.length);

        for (uint i = 0; i < first.length; i++) {
            combination[i] = first[i];
        }

        for (uint j = 0; j < second.length; j++) {
            combination[first.length + j] = second[j];
        }
    }

    /* ========== PUBLIC FUNCTIONS ========== */

    // Note: this function is public not external in order for it to be overridden and invoked via super in subclasses
    function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {}

    function rebuildCache() public {
        bytes32[] memory requiredAddresses = resolverAddressesRequired();
        // The resolver must call this function whenver it updates its state
        for (uint i = 0; i < requiredAddresses.length; i++) {
            bytes32 name = requiredAddresses[i];
            // Note: can only be invoked once the resolver has all the targets needed added
            address destination =
                resolver.requireAndGetAddress(name, string(abi.encodePacked("Resolver missing target: ", name)));
            addressCache[name] = destination;
            emit CacheUpdated(name, destination);
        }
    }

    /* ========== VIEWS ========== */

    function isResolverCached() external view returns (bool) {
        bytes32[] memory requiredAddresses = resolverAddressesRequired();
        for (uint i = 0; i < requiredAddresses.length; i++) {
            bytes32 name = requiredAddresses[i];
            // false if our cache is invalid or if the resolver doesn't have the required address
            if (resolver.getAddress(name) != addressCache[name] || addressCache[name] == address(0)) {
                return false;
            }
        }

        return true;
    }

    /* ========== INTERNAL FUNCTIONS ========== */

    function requireAndGetAddress(bytes32 name) internal view returns (address) {
        address _foundAddress = addressCache[name];
        require(_foundAddress != address(0), string(abi.encodePacked("Missing address: ", name)));
        return _foundAddress;
    }

    /* ========== EVENTS ========== */

    event CacheUpdated(bytes32 name, address destination);
}


// https://docs.synthetix.io/contracts/source/interfaces/iflexiblestorage
interface IFlexibleStorage {
    // Views
    function getUIntValue(bytes32 contractName, bytes32 record) external view returns (uint);

    function getUIntValues(bytes32 contractName, bytes32[] calldata records) external view returns (uint[] memory);

    function getIntValue(bytes32 contractName, bytes32 record) external view returns (int);

    function getIntValues(bytes32 contractName, bytes32[] calldata records) external view returns (int[] memory);

    function getAddressValue(bytes32 contractName, bytes32 record) external view returns (address);

    function getAddressValues(bytes32 contractName, bytes32[] calldata records) external view returns (address[] memory);

    function getBoolValue(bytes32 contractName, bytes32 record) external view returns (bool);

    function getBoolValues(bytes32 contractName, bytes32[] calldata records) external view returns (bool[] memory);

    function getBytes32Value(bytes32 contractName, bytes32 record) external view returns (bytes32);

    function getBytes32Values(bytes32 contractName, bytes32[] calldata records) external view returns (bytes32[] memory);

    // Mutative functions
    function deleteUIntValue(bytes32 contractName, bytes32 record) external;

    function deleteIntValue(bytes32 contractName, bytes32 record) external;

    function deleteAddressValue(bytes32 contractName, bytes32 record) external;

    function deleteBoolValue(bytes32 contractName, bytes32 record) external;

    function deleteBytes32Value(bytes32 contractName, bytes32 record) external;

    function setUIntValue(
        bytes32 contractName,
        bytes32 record,
        uint value
    ) external;

    function setUIntValues(
        bytes32 contractName,
        bytes32[] calldata records,
        uint[] calldata values
    ) external;

    function setIntValue(
        bytes32 contractName,
        bytes32 record,
        int value
    ) external;

    function setIntValues(
        bytes32 contractName,
        bytes32[] calldata records,
        int[] calldata values
    ) external;

    function setAddressValue(
        bytes32 contractName,
        bytes32 record,
        address value
    ) external;

    function setAddressValues(
        bytes32 contractName,
        bytes32[] calldata records,
        address[] calldata values
    ) external;

    function setBoolValue(
        bytes32 contractName,
        bytes32 record,
        bool value
    ) external;

    function setBoolValues(
        bytes32 contractName,
        bytes32[] calldata records,
        bool[] calldata values
    ) external;

    function setBytes32Value(
        bytes32 contractName,
        bytes32 record,
        bytes32 value
    ) external;

    function setBytes32Values(
        bytes32 contractName,
        bytes32[] calldata records,
        bytes32[] calldata values
    ) external;
}


pragma experimental ABIEncoderV2;


// Internal references


// https://docs.synthetix.io/contracts/source/contracts/MixinPerpsV2MarketSettings
contract MixinPerpsV2MarketSettings is MixinResolver {
    /* ========== CONSTANTS ========== */

    bytes32 internal constant SETTING_CONTRACT_NAME = "PerpsV2MarketSettings";

    /* ---------- Parameter Names ---------- */

    // Per-market settings
    bytes32 internal constant PARAMETER_TAKER_FEE = "takerFee";
    bytes32 internal constant PARAMETER_MAKER_FEE = "makerFee";
    bytes32 internal constant PARAMETER_TAKER_FEE_DELAYED_ORDER = "takerFeeDelayedOrder";
    bytes32 internal constant PARAMETER_MAKER_FEE_DELAYED_ORDER = "makerFeeDelayedOrder";
    bytes32 internal constant PARAMETER_TAKER_FEE_OFFCHAIN_DELAYED_ORDER = "takerFeeOffchainDelayedOrder";
    bytes32 internal constant PARAMETER_MAKER_FEE_OFFCHAIN_DELAYED_ORDER = "makerFeeOffchainDelayedOrder";
    bytes32 internal constant PARAMETER_NEXT_PRICE_CONFIRM_WINDOW = "nextPriceConfirmWindow";
    bytes32 internal constant PARAMETER_DELAYED_ORDER_CONFIRM_WINDOW = "delayedOrderConfirmWindow";
    bytes32 internal constant PARAMETER_OFFCHAIN_DELAYED_ORDER_MIN_AGE = "offchainDelayedOrderMinAge";
    bytes32 internal constant PARAMETER_OFFCHAIN_DELAYED_ORDER_MAX_AGE = "offchainDelayedOrderMaxAge";
    bytes32 internal constant PARAMETER_MAX_LEVERAGE = "maxLeverage";
    bytes32 internal constant PARAMETER_MAX_MARKET_VALUE = "maxMarketValue";
    bytes32 internal constant PARAMETER_MAX_FUNDING_VELOCITY = "maxFundingVelocity";
    bytes32 internal constant PARAMETER_MIN_SKEW_SCALE = "skewScale";
    bytes32 internal constant PARAMETER_MIN_DELAY_TIME_DELTA = "minDelayTimeDelta";
    bytes32 internal constant PARAMETER_MAX_DELAY_TIME_DELTA = "maxDelayTimeDelta";
    bytes32 internal constant PARAMETER_OFFCHAIN_MARKET_KEY = "offchainMarketKey";
    bytes32 internal constant PARAMETER_OFFCHAIN_PRICE_DIVERGENCE = "offchainPriceDivergence";
    bytes32 internal constant PARAMETER_LIQUIDATION_PREMIUM_MULTIPLIER = "liquidationPremiumMultiplier";
    bytes32 internal constant PARAMETER_MAX_LIQUIDAION_DELTA = "maxLiquidationDelta";
    bytes32 internal constant PARAMETER_MAX_LIQUIDATION_PD = "maxPD";
    // liquidation buffer to prevent negative margin upon liquidation
    bytes32 internal constant PARAMETER_LIQUIDATION_BUFFER_RATIO = "liquidationBufferRatio";

    // Global settings
    // minimum liquidation fee payable to liquidator
    bytes32 internal constant SETTING_MIN_KEEPER_FEE = "perpsV2MinKeeperFee";
    // maximum liquidation fee payable to liquidator
    bytes32 internal constant SETTING_MAX_KEEPER_FEE = "perpsV2MaxKeeperFee";
    // liquidation fee basis points payed to liquidator
    bytes32 internal constant SETTING_LIQUIDATION_FEE_RATIO = "perpsV2LiquidationFeeRatio";
    // minimum initial margin
    bytes32 internal constant SETTING_MIN_INITIAL_MARGIN = "perpsV2MinInitialMargin";
    // fixed liquidation fee to be paid to liquidator keeper (not flagger)
    bytes32 internal constant SETTING_KEEPER_LIQUIRATION_FEE = "keeperLiquidationFee";

    /* ---------- Address Resolver Configuration ---------- */

    bytes32 internal constant CONTRACT_FLEXIBLESTORAGE = "FlexibleStorage";

    /* ========== CONSTRUCTOR ========== */

    constructor(address _resolver) internal MixinResolver(_resolver) {}

    /* ========== VIEWS ========== */

    function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
        addresses = new bytes32[](1);
        addresses[0] = CONTRACT_FLEXIBLESTORAGE;
    }

    function _flexibleStorage() internal view returns (IFlexibleStorage) {
        return IFlexibleStorage(requireAndGetAddress(CONTRACT_FLEXIBLESTORAGE));
    }

    /* ---------- Internals ---------- */

    function _parameter(bytes32 _marketKey, bytes32 key) internal view returns (uint value) {
        return _flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(_marketKey, key)));
    }

    function _takerFee(bytes32 _marketKey) internal view returns (uint) {
        return _parameter(_marketKey, PARAMETER_TAKER_FEE);
    }

    function _makerFee(bytes32 _marketKey) internal view returns (uint) {
        return _parameter(_marketKey, PARAMETER_MAKER_FEE);
    }

    function _takerFeeDelayedOrder(bytes32 _marketKey) internal view returns (uint) {
        return _parameter(_marketKey, PARAMETER_TAKER_FEE_DELAYED_ORDER);
    }

    function _makerFeeDelayedOrder(bytes32 _marketKey) internal view returns (uint) {
        return _parameter(_marketKey, PARAMETER_MAKER_FEE_DELAYED_ORDER);
    }

    function _takerFeeOffchainDelayedOrder(bytes32 _marketKey) internal view returns (uint) {
        return _parameter(_marketKey, PARAMETER_TAKER_FEE_OFFCHAIN_DELAYED_ORDER);
    }

    function _makerFeeOffchainDelayedOrder(bytes32 _marketKey) internal view returns (uint) {
        return _parameter(_marketKey, PARAMETER_MAKER_FEE_OFFCHAIN_DELAYED_ORDER);
    }

    function _nextPriceConfirmWindow(bytes32 _marketKey) internal view returns (uint) {
        return _parameter(_marketKey, PARAMETER_NEXT_PRICE_CONFIRM_WINDOW);
    }

    function _delayedOrderConfirmWindow(bytes32 _marketKey) internal view returns (uint) {
        return _parameter(_marketKey, PARAMETER_DELAYED_ORDER_CONFIRM_WINDOW);
    }

    function _offchainDelayedOrderMinAge(bytes32 _marketKey) internal view returns (uint) {
        return _parameter(_marketKey, PARAMETER_OFFCHAIN_DELAYED_ORDER_MIN_AGE);
    }

    function _offchainDelayedOrderMaxAge(bytes32 _marketKey) internal view returns (uint) {
        return _parameter(_marketKey, PARAMETER_OFFCHAIN_DELAYED_ORDER_MAX_AGE);
    }

    function _maxLeverage(bytes32 _marketKey) internal view returns (uint) {
        return _parameter(_marketKey, PARAMETER_MAX_LEVERAGE);
    }

    function _maxMarketValue(bytes32 _marketKey) internal view returns (uint) {
        return _parameter(_marketKey, PARAMETER_MAX_MARKET_VALUE);
    }

    function _skewScale(bytes32 _marketKey) internal view returns (uint) {
        return _parameter(_marketKey, PARAMETER_MIN_SKEW_SCALE);
    }

    function _maxFundingVelocity(bytes32 _marketKey) internal view returns (uint) {
        return _parameter(_marketKey, PARAMETER_MAX_FUNDING_VELOCITY);
    }

    function _minDelayTimeDelta(bytes32 _marketKey) internal view returns (uint) {
        return _parameter(_marketKey, PARAMETER_MIN_DELAY_TIME_DELTA);
    }

    function _maxDelayTimeDelta(bytes32 _marketKey) internal view returns (uint) {
        return _parameter(_marketKey, PARAMETER_MAX_DELAY_TIME_DELTA);
    }

    function _offchainMarketKey(bytes32 _marketKey) internal view returns (bytes32) {
        return
            _flexibleStorage().getBytes32Value(
                SETTING_CONTRACT_NAME,
                keccak256(abi.encodePacked(_marketKey, PARAMETER_OFFCHAIN_MARKET_KEY))
            );
    }

    function _offchainPriceDivergence(bytes32 _marketKey) internal view returns (uint) {
        return _parameter(_marketKey, PARAMETER_OFFCHAIN_PRICE_DIVERGENCE);
    }

    function _liquidationPremiumMultiplier(bytes32 _marketKey) internal view returns (uint) {
        return _parameter(_marketKey, PARAMETER_LIQUIDATION_PREMIUM_MULTIPLIER);
    }

    function _maxLiquidationDelta(bytes32 _marketKey) internal view returns (uint) {
        return _parameter(_marketKey, PARAMETER_MAX_LIQUIDAION_DELTA);
    }

    function _maxPD(bytes32 _marketKey) internal view returns (uint) {
        return _parameter(_marketKey, PARAMETER_MAX_LIQUIDATION_PD);
    }

    function _liquidationBufferRatio(bytes32 _marketKey) internal view returns (uint) {
        return _parameter(_marketKey, PARAMETER_LIQUIDATION_BUFFER_RATIO);
    }

    function _minKeeperFee() internal view returns (uint) {
        return _flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_MIN_KEEPER_FEE);
    }

    function _maxKeeperFee() internal view returns (uint) {
        return _flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_MAX_KEEPER_FEE);
    }

    function _liquidationFeeRatio() internal view returns (uint) {
        return _flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_FEE_RATIO);
    }

    function _minInitialMargin() internal view returns (uint) {
        return _flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_MIN_INITIAL_MARGIN);
    }

    function _keeperLiquidationFee() internal view returns (uint) {
        return _flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_KEEPER_LIQUIRATION_FEE);
    }
}


interface IPerpsV2MarketBaseTypes {
    /* ========== TYPES ========== */

    enum OrderType {Atomic, Delayed, Offchain}

    enum Status {
        Ok,
        InvalidPrice,
        InvalidOrderType,
        PriceOutOfBounds,
        CanLiquidate,
        CannotLiquidate,
        MaxMarketSizeExceeded,
        MaxLeverageExceeded,
        InsufficientMargin,
        NotPermitted,
        NilOrder,
        NoPositionOpen,
        PriceTooVolatile,
        PriceImpactToleranceExceeded,
        PositionFlagged,
        PositionNotFlagged
    }

    // If margin/size are positive, the position is long; if negative then it is short.
    struct Position {
        uint64 id;
        uint64 lastFundingIndex;
        uint128 margin;
        uint128 lastPrice;
        int128 size;
    }

    // Delayed order storage
    struct DelayedOrder {
        bool isOffchain; // flag indicating the delayed order is offchain
        int128 sizeDelta; // difference in position to pass to modifyPosition
        uint128 desiredFillPrice; // desired fill price as usd used on fillPrice at execution
        uint128 targetRoundId; // price oracle roundId using which price this order needs to executed
        uint128 commitDeposit; // the commitDeposit paid upon submitting that needs to be refunded if order succeeds
        uint128 keeperDeposit; // the keeperDeposit paid upon submitting that needs to be paid / refunded on tx confirmation
        uint256 executableAtTime; // The timestamp at which this order is executable at
        uint256 intentionTime; // The block timestamp of submission
        bytes32 trackingCode; // tracking code to emit on execution for volume source fee sharing
    }
}


/**
 * @dev Wrappers over Solidity's arithmetic operations with added overflow
 * checks.
 *
 * Arithmetic operations in Solidity wrap on overflow. This can easily result
 * in bugs, because programmers usually assume that an overflow raises an
 * error, which is the standard behavior in high level programming languages.
 * `SafeMath` restores this intuition by reverting the transaction when an
 * operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeMath {
    /**
     * @dev Returns the addition of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `+` operator.
     *
     * Requirements:
     * - Addition cannot overflow.
     */
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        uint256 c = a + b;
        require(c >= a, "SafeMath: addition overflow");

        return c;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        require(b <= a, "SafeMath: subtraction overflow");
        uint256 c = a - b;

        return c;
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `*` operator.
     *
     * Requirements:
     * - Multiplication cannot overflow.
     */
    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
        // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
        // benefit is lost if 'b' is also tested.
        // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
        if (a == 0) {
            return 0;
        }

        uint256 c = a * b;
        require(c / a == b, "SafeMath: multiplication overflow");

        return c;
    }

    /**
     * @dev Returns the integer division of two unsigned integers. Reverts on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        // Solidity only automatically asserts when dividing by 0
        require(b > 0, "SafeMath: division by zero");
        uint256 c = a / b;
        // assert(a == b * c + a % b); // There is no case in which this doesn't hold

        return c;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * Reverts when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b) internal pure returns (uint256) {
        require(b != 0, "SafeMath: modulo by zero");
        return a % b;
    }
}


// SPDX-License-Identifier: MIT

/*
The MIT License (MIT)

Copyright (c) 2016-2020 zOS Global Limited

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

/*
 * When we upgrade to solidity v0.6.0 or above, we should be able to
 * just do import `"openzeppelin-solidity-3.0.0/contracts/math/SignedSafeMath.sol";`
 * wherever this is used.
 */


/**
 * @title SignedSafeMath
 * @dev Signed math operations with safety checks that revert on error.
 */
library SignedSafeMath {
    int256 private constant _INT256_MIN = -2**255;

    /**
     * @dev Returns the multiplication of two signed integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `*` operator.
     *
     * Requirements:
     *
     * - Multiplication cannot overflow.
     */
    function mul(int256 a, int256 b) internal pure returns (int256) {
        // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
        // benefit is lost if 'b' is also tested.
        // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
        if (a == 0) {
            return 0;
        }

        require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");

        int256 c = a * b;
        require(c / a == b, "SignedSafeMath: multiplication overflow");

        return c;
    }

    /**
     * @dev Returns the integer division of two signed integers. Reverts on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(int256 a, int256 b) internal pure returns (int256) {
        require(b != 0, "SignedSafeMath: division by zero");
        require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");

        int256 c = a / b;

        return c;
    }

    /**
     * @dev Returns the subtraction of two signed integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(int256 a, int256 b) internal pure returns (int256) {
        int256 c = a - b;
        require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");

        return c;
    }

    /**
     * @dev Returns the addition of two signed integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `+` operator.
     *
     * Requirements:
     *
     * - Addition cannot overflow.
     */
    function add(int256 a, int256 b) internal pure returns (int256) {
        int256 c = a + b;
        require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");

        return c;
    }
}


// TODO: Test suite

// https://docs.synthetix.io/contracts/SignedSafeDecimalMath
library SignedSafeDecimalMath {
    using SignedSafeMath for int;

    /* Number of decimal places in the representations. */
    uint8 public constant decimals = 18;
    uint8 public constant highPrecisionDecimals = 27;

    /* The number representing 1.0. */
    int public constant UNIT = int(10**uint(decimals));

    /* The number representing 1.0 for higher fidelity numbers. */
    int public constant PRECISE_UNIT = int(10**uint(highPrecisionDecimals));
    int private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = int(10**uint(highPrecisionDecimals - decimals));

    /**
     * @return Provides an interface to UNIT.
     */
    function unit() external pure returns (int) {
        return UNIT;
    }

    /**
     * @return Provides an interface to PRECISE_UNIT.
     */
    function preciseUnit() external pure returns (int) {
        return PRECISE_UNIT;
    }

    /**
     * @dev Rounds an input with an extra zero of precision, returning the result without the extra zero.
     * Half increments round away from zero; positive numbers at a half increment are rounded up,
     * while negative such numbers are rounded down. This behaviour is designed to be consistent with the
     * unsigned version of this library (SafeDecimalMath).
     */
    function _roundDividingByTen(int valueTimesTen) private pure returns (int) {
        int increment;
        if (valueTimesTen % 10 >= 5) {
            increment = 10;
        } else if (valueTimesTen % 10 <= -5) {
            increment = -10;
        }
        return (valueTimesTen + increment) / 10;
    }

    /**
     * @return The result of multiplying x and y, interpreting the operands as fixed-point
     * decimals.
     *
     * @dev A unit factor is divided out after the product of x and y is evaluated,
     * so that product must be less than 2**256. As this is an integer division,
     * the internal division always rounds down. This helps save on gas. Rounding
     * is more expensive on gas.
     */
    function multiplyDecimal(int x, int y) internal pure returns (int) {
        /* Divide by UNIT to remove the extra factor introduced by the product. */
        return x.mul(y) / UNIT;
    }

    /**
     * @return The result of safely multiplying x and y, interpreting the operands
     * as fixed-point decimals of the specified precision unit.
     *
     * @dev The operands should be in the form of a the specified unit factor which will be
     * divided out after the product of x and y is evaluated, so that product must be
     * less than 2**256.
     *
     * Unlike multiplyDecimal, this function rounds the result to the nearest increment.
     * Rounding is useful when you need to retain fidelity for small decimal numbers
     * (eg. small fractions or percentages).
     */
    function _multiplyDecimalRound(
        int x,
        int y,
        int precisionUnit
    ) private pure returns (int) {
        /* Divide by UNIT to remove the extra factor introduced by the product. */
        int quotientTimesTen = x.mul(y) / (precisionUnit / 10);
        return _roundDividingByTen(quotientTimesTen);
    }

    /**
     * @return The result of safely multiplying x and y, interpreting the operands
     * as fixed-point decimals of a precise unit.
     *
     * @dev The operands should be in the precise unit factor which will be
     * divided out after the product of x and y is evaluated, so that product must be
     * less than 2**256.
     *
     * Unlike multiplyDecimal, this function rounds the result to the nearest increment.
     * Rounding is useful when you need to retain fidelity for small decimal numbers
     * (eg. small fractions or percentages).
     */
    function multiplyDecimalRoundPrecise(int x, int y) internal pure returns (int) {
        return _multiplyDecimalRound(x, y, PRECISE_UNIT);
    }

    /**
     * @return The result of safely multiplying x and y, interpreting the operands
     * as fixed-point decimals of a standard unit.
     *
     * @dev The operands should be in the standard unit factor which will be
     * divided out after the product of x and y is evaluated, so that product must be
     * less than 2**256.
     *
     * Unlike multiplyDecimal, this function rounds the result to the nearest increment.
     * Rounding is useful when you need to retain fidelity for small decimal numbers
     * (eg. small fractions or percentages).
     */
    function multiplyDecimalRound(int x, int y) internal pure returns (int) {
        return _multiplyDecimalRound(x, y, UNIT);
    }

    /**
     * @return The result of safely dividing x and y. The return value is a high
     * precision decimal.
     *
     * @dev y is divided after the product of x and the standard precision unit
     * is evaluated, so the product of x and UNIT must be less than 2**256. As
     * this is an integer division, the result is always rounded down.
     * This helps save on gas. Rounding is more expensive on gas.
     */
    function divideDecimal(int x, int y) internal pure returns (int) {
        /* Reintroduce the UNIT factor that will be divided out by y. */
        return x.mul(UNIT).div(y);
    }

    /**
     * @return The result of safely dividing x and y. The return value is as a rounded
     * decimal in the precision unit specified in the parameter.
     *
     * @dev y is divided after the product of x and the specified precision unit
     * is evaluated, so the product of x and the specified precision unit must
     * be less than 2**256. The result is rounded to the nearest increment.
     */
    function _divideDecimalRound(
        int x,
        int y,
        int precisionUnit
    ) private pure returns (int) {
        int resultTimesTen = x.mul(precisionUnit * 10).div(y);
        return _roundDividingByTen(resultTimesTen);
    }

    /**
     * @return The result of safely dividing x and y. The return value is as a rounded
     * standard precision decimal.
     *
     * @dev y is divided after the product of x and the standard precision unit
     * is evaluated, so the product of x and the standard precision unit must
     * be less than 2**256. The result is rounded to the nearest increment.
     */
    function divideDecimalRound(int x, int y) internal pure returns (int) {
        return _divideDecimalRound(x, y, UNIT);
    }

    /**
     * @return The result of safely dividing x and y. The return value is as a rounded
     * high precision decimal.
     *
     * @dev y is divided after the product of x and the high precision unit
     * is evaluated, so the product of x and the high precision unit must
     * be less than 2**256. The result is rounded to the nearest increment.
     */
    function divideDecimalRoundPrecise(int x, int y) internal pure returns (int) {
        return _divideDecimalRound(x, y, PRECISE_UNIT);
    }

    /**
     * @dev Convert a standard decimal representation to a high precision one.
     */
    function decimalToPreciseDecimal(int i) internal pure returns (int) {
        return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR);
    }

    /**
     * @dev Convert a high precision decimal to a standard decimal representation.
     */
    function preciseDecimalToDecimal(int i) internal pure returns (int) {
        int quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10);
        return _roundDividingByTen(quotientTimesTen);
    }
}


// Libraries


// https://docs.synthetix.io/contracts/source/libraries/safedecimalmath
library SafeDecimalMath {
    using SafeMath for uint;

    /* Number of decimal places in the representations. */
    uint8 public constant decimals = 18;
    uint8 public constant highPrecisionDecimals = 27;

    /* The number representing 1.0. */
    uint public constant UNIT = 10**uint(decimals);

    /* The number representing 1.0 for higher fidelity numbers. */
    uint public constant PRECISE_UNIT = 10**uint(highPrecisionDecimals);
    uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10**uint(highPrecisionDecimals - decimals);

    /**
     * @return Provides an interface to UNIT.
     */
    function unit() external pure returns (uint) {
        return UNIT;
    }

    /**
     * @return Provides an interface to PRECISE_UNIT.
     */
    function preciseUnit() external pure returns (uint) {
        return PRECISE_UNIT;
    }

    /**
     * @return The result of multiplying x and y, interpreting the operands as fixed-point
     * decimals.
     *
     * @dev A unit factor is divided out after the product of x and y is evaluated,
     * so that product must be less than 2**256. As this is an integer division,
     * the internal division always rounds down. This helps save on gas. Rounding
     * is more expensive on gas.
     */
    function multiplyDecimal(uint x, uint y) internal pure returns (uint) {
        /* Divide by UNIT to remove the extra factor introduced by the product. */
        return x.mul(y) / UNIT;
    }

    /**
     * @return The result of safely multiplying x and y, interpreting the operands
     * as fixed-point decimals of the specified precision unit.
     *
     * @dev The operands should be in the form of a the specified unit factor which will be
     * divided out after the product of x and y is evaluated, so that product must be
     * less than 2**256.
     *
     * Unlike multiplyDecimal, this function rounds the result to the nearest increment.
     * Rounding is useful when you need to retain fidelity for small decimal numbers
     * (eg. small fractions or percentages).
     */
    function _multiplyDecimalRound(
        uint x,
        uint y,
        uint precisionUnit
    ) private pure returns (uint) {
        /* Divide by UNIT to remove the extra factor introduced by the product. */
        uint quotientTimesTen = x.mul(y) / (precisionUnit / 10);

        if (quotientTimesTen % 10 >= 5) {
            quotientTimesTen += 10;
        }

        return quotientTimesTen / 10;
    }

    /**
     * @return The result of safely multiplying x and y, interpreting the operands
     * as fixed-point decimals of a precise unit.
     *
     * @dev The operands should be in the precise unit factor which will be
     * divided out after the product of x and y is evaluated, so that product must be
     * less than 2**256.
     *
     * Unlike multiplyDecimal, this function rounds the result to the nearest increment.
     * Rounding is useful when you need to retain fidelity for small decimal numbers
     * (eg. small fractions or percentages).
     */
    function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) {
        return _multiplyDecimalRound(x, y, PRECISE_UNIT);
    }

    /**
     * @return The result of safely multiplying x and y, interpreting the operands
     * as fixed-point decimals of a standard unit.
     *
     * @dev The operands should be in the standard unit factor which will be
     * divided out after the product of x and y is evaluated, so that product must be
     * less than 2**256.
     *
     * Unlike multiplyDecimal, this function rounds the result to the nearest increment.
     * Rounding is useful when you need to retain fidelity for small decimal numbers
     * (eg. small fractions or percentages).
     */
    function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) {
        return _multiplyDecimalRound(x, y, UNIT);
    }

    /**
     * @return The result of safely dividing x and y. The return value is a high
     * precision decimal.
     *
     * @dev y is divided after the product of x and the standard precision unit
     * is evaluated, so the product of x and UNIT must be less than 2**256. As
     * this is an integer division, the result is always rounded down.
     * This helps save on gas. Rounding is more expensive on gas.
     */
    function divideDecimal(uint x, uint y) internal pure returns (uint) {
        /* Reintroduce the UNIT factor that will be divided out by y. */
        return x.mul(UNIT).div(y);
    }

    /**
     * @return The result of safely dividing x and y. The return value is as a rounded
     * decimal in the precision unit specified in the parameter.
     *
     * @dev y is divided after the product of x and the specified precision unit
     * is evaluated, so the product of x and the specified precision unit must
     * be less than 2**256. The result is rounded to the nearest increment.
     */
    function _divideDecimalRound(
        uint x,
        uint y,
        uint precisionUnit
    ) private pure returns (uint) {
        uint resultTimesTen = x.mul(precisionUnit * 10).div(y);

        if (resultTimesTen % 10 >= 5) {
            resultTimesTen += 10;
        }

        return resultTimesTen / 10;
    }

    /**
     * @return The result of safely dividing x and y. The return value is as a rounded
     * standard precision decimal.
     *
     * @dev y is divided after the product of x and the standard precision unit
     * is evaluated, so the product of x and the standard precision unit must
     * be less than 2**256. The result is rounded to the nearest increment.
     */
    function divideDecimalRound(uint x, uint y) internal pure returns (uint) {
        return _divideDecimalRound(x, y, UNIT);
    }

    /**
     * @return The result of safely dividing x and y. The return value is as a rounded
     * high precision decimal.
     *
     * @dev y is divided after the product of x and the high precision unit
     * is evaluated, so the product of x and the high precision unit must
     * be less than 2**256. The result is rounded to the nearest increment.
     */
    function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) {
        return _divideDecimalRound(x, y, PRECISE_UNIT);
    }

    /**
     * @dev Convert a standard decimal representation to a high precision one.
     */
    function decimalToPreciseDecimal(uint i) internal pure returns (uint) {
        return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR);
    }

    /**
     * @dev Convert a high precision decimal to a standard decimal representation.
     */
    function preciseDecimalToDecimal(uint i) internal pure returns (uint) {
        uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10);

        if (quotientTimesTen % 10 >= 5) {
            quotientTimesTen += 10;
        }

        return quotientTimesTen / 10;
    }

    // Computes `a - b`, setting the value to 0 if b > a.
    function floorsub(uint a, uint b) internal pure returns (uint) {
        return b >= a ? 0 : a - b;
    }

    /* ---------- Utilities ---------- */
    /*
     * Absolute value of the input, returned as a signed number.
     */
    function signedAbs(int x) internal pure returns (int) {
        return x < 0 ? -x : x;
    }

    /*
     * Absolute value of the input, returned as an unsigned number.
     */
    function abs(int x) internal pure returns (uint) {
        return uint(signedAbs(x));
    }
}


// https://docs.synthetix.io/contracts/source/interfaces/IDirectIntegration
interface IDirectIntegrationManager {
    struct ParameterIntegrationSettings {
        bytes32 currencyKey;
        address dexPriceAggregator;
        address atomicEquivalentForDexPricing;
        uint atomicExchangeFeeRate;
        uint atomicTwapWindow;
        uint atomicMaxVolumePerBlock;
        uint atomicVolatilityConsiderationWindow;
        uint atomicVolatilityUpdateThreshold;
        uint exchangeFeeRate;
        uint exchangeMaxDynamicFee;
        uint exchangeDynamicFeeRounds;
        uint exchangeDynamicFeeThreshold;
        uint exchangeDynamicFeeWeightDecay;
    }

    function getExchangeParameters(address integration, bytes32 key)
        external
        view
        returns (ParameterIntegrationSettings memory settings);

    function setExchangeParameters(
        address integration,
        bytes32[] calldata currencyKeys,
        ParameterIntegrationSettings calldata params
    ) external;
}


// https://docs.synthetix.io/contracts/source/interfaces/iexchangerates
interface IExchangeRates {
    // Structs
    struct RateAndUpdatedTime {
        uint216 rate;
        uint40 time;
    }

    // Views
    function aggregators(bytes32 currencyKey) external view returns (address);

    function aggregatorWarningFlags() external view returns (address);

    function anyRateIsInvalid(bytes32[] calldata currencyKeys) external view returns (bool);

    function anyRateIsInvalidAtRound(bytes32[] calldata currencyKeys, uint[] calldata roundIds) external view returns (bool);

    function currenciesUsingAggregator(address aggregator) external view returns (bytes32[] memory);

    function effectiveValue(
        bytes32 sourceCurrencyKey,
        uint sourceAmount,
        bytes32 destinationCurrencyKey
    ) external view returns (uint value);

    function effectiveValueAndRates(
        bytes32 sourceCurrencyKey,
        uint sourceAmount,
        bytes32 destinationCurrencyKey
    )
        external
        view
        returns (
            uint value,
            uint sourceRate,
            uint destinationRate
        );

    function effectiveValueAndRatesAtRound(
        bytes32 sourceCurrencyKey,
        uint sourceAmount,
        bytes32 destinationCurrencyKey,
        uint roundIdForSrc,
        uint roundIdForDest
    )
        external
        view
        returns (
            uint value,
            uint sourceRate,
            uint destinationRate
        );

    function effectiveAtomicValueAndRates(
        bytes32 sourceCurrencyKey,
        uint sourceAmount,
        bytes32 destinationCurrencyKey
    )
        external
        view
        returns (
            uint value,
            uint systemValue,
            uint systemSourceRate,
            uint systemDestinationRate
        );

    function effectiveAtomicValueAndRates(
        IDirectIntegrationManager.ParameterIntegrationSettings calldata sourceSettings,
        uint sourceAmount,
        IDirectIntegrationManager.ParameterIntegrationSettings calldata destinationSettings,
        IDirectIntegrationManager.ParameterIntegrationSettings calldata usdSettings
    )
        external
        view
        returns (
            uint value,
            uint systemValue,
            uint systemSourceRate,
            uint systemDestinationRate
        );

    function getCurrentRoundId(bytes32 currencyKey) external view returns (uint);

    function getLastRoundIdBeforeElapsedSecs(
        bytes32 currencyKey,
        uint startingRoundId,
        uint startingTimestamp,
        uint timediff
    ) external view returns (uint);

    function lastRateUpdateTimes(bytes32 currencyKey) external view returns (uint256);

    function rateAndTimestampAtRound(bytes32 currencyKey, uint roundId) external view returns (uint rate, uint time);

    function rateAndUpdatedTime(bytes32 currencyKey) external view returns (uint rate, uint time);

    function rateAndInvalid(bytes32 currencyKey) external view returns (uint rate, bool isInvalid);

    function rateForCurrency(bytes32 currencyKey) external view returns (uint);

    function rateIsFlagged(bytes32 currencyKey) external view returns (bool);

    function rateIsInvalid(bytes32 currencyKey) external view returns (bool);

    function rateIsStale(bytes32 currencyKey) external view returns (bool);

    function rateStalePeriod() external view returns (uint);

    function ratesAndUpdatedTimeForCurrencyLastNRounds(
        bytes32 currencyKey,
        uint numRounds,
        uint roundId
    ) external view returns (uint[] memory rates, uint[] memory times);

    function ratesAndInvalidForCurrencies(bytes32[] calldata currencyKeys)
        external
        view
        returns (uint[] memory rates, bool anyRateInvalid);

    function ratesForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory);

    function synthTooVolatileForAtomicExchange(bytes32 currencyKey) external view returns (bool);

    function synthTooVolatileForAtomicExchange(IDirectIntegrationManager.ParameterIntegrationSettings calldata settings)
        external
        view
        returns (bool);

    function rateWithSafetyChecks(bytes32 currencyKey)
        external
        returns (
            uint rate,
            bool broken,
            bool invalid
        );
}


interface IVirtualSynth {
    // Views
    function balanceOfUnderlying(address account) external view returns (uint);

    function rate() external view returns (uint);

    function readyToSettle() external view returns (bool);

    function secsLeftInWaitingPeriod() external view returns (uint);

    function settled() external view returns (bool);

    function synth() external view returns (ISynth);

    // Mutative functions
    function settle(address account) external;
}


// https://docs.synthetix.io/contracts/source/interfaces/iexchanger
interface IExchanger {
    struct ExchangeEntrySettlement {
        bytes32 src;
        uint amount;
        bytes32 dest;
        uint reclaim;
        uint rebate;
        uint srcRoundIdAtPeriodEnd;
        uint destRoundIdAtPeriodEnd;
        uint timestamp;
    }

    struct ExchangeEntry {
        uint sourceRate;
        uint destinationRate;
        uint destinationAmount;
        uint exchangeFeeRate;
        uint exchangeDynamicFeeRate;
        uint roundIdForSrc;
        uint roundIdForDest;
        uint sourceAmountAfterSettlement;
    }

    // Views
    function calculateAmountAfterSettlement(
        address from,
        bytes32 currencyKey,
        uint amount,
        uint refunded
    ) external view returns (uint amountAfterSettlement);

    function isSynthRateInvalid(bytes32 currencyKey) external view returns (bool);

    function maxSecsLeftInWaitingPeriod(address account, bytes32 currencyKey) external view returns (uint);

    function settlementOwing(address account, bytes32 currencyKey)
        external
        view
        returns (
            uint reclaimAmount,
            uint rebateAmount,
            uint numEntries
        );

    function hasWaitingPeriodOrSettlementOwing(address account, bytes32 currencyKey) external view returns (bool);

    function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view returns (uint);

    function dynamicFeeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey)
        external
        view
        returns (uint feeRate, bool tooVolatile);

    function getAmountsForExchange(
        uint sourceAmount,
        bytes32 sourceCurrencyKey,
        bytes32 destinationCurrencyKey
    )
        external
        view
        returns (
            uint amountReceived,
            uint fee,
            uint exchangeFeeRate
        );

    function priceDeviationThresholdFactor() external view returns (uint);

    function waitingPeriodSecs() external view returns (uint);

    function lastExchangeRate(bytes32 currencyKey) external view returns (uint);

    // Mutative functions
    function exchange(
        address exchangeForAddress,
        address from,
        bytes32 sourceCurrencyKey,
        uint sourceAmount,
        bytes32 destinationCurrencyKey,
        address destinationAddress,
        bool virtualSynth,
        address rewardAddress,
        bytes32 trackingCode
    ) external returns (uint amountReceived, IVirtualSynth vSynth);

    function exchangeAtomically(
        address from,
        bytes32 sourceCurrencyKey,
        uint sourceAmount,
        bytes32 destinationCurrencyKey,
        address destinationAddress,
        bytes32 trackingCode,
        uint minAmount
    ) external returns (uint amountReceived);

    function settle(address from, bytes32 currencyKey)
        external
        returns (
            uint reclaimed,
            uint refunded,
            uint numEntries
        );
}

// Used to have strongly-typed access to internal mutative functions in Synthetix
interface ISynthetixInternal {
    function emitExchangeTracking(
        bytes32 trackingCode,
        bytes32 toCurrencyKey,
        uint256 toAmount,
        uint256 fee
    ) external;

    function emitSynthExchange(
        address account,
        bytes32 fromCurrencyKey,
        uint fromAmount,
        bytes32 toCurrencyKey,
        uint toAmount,
        address toAddress
    ) external;

    function emitAtomicSynthExchange(
        address account,
        bytes32 fromCurrencyKey,
        uint fromAmount,
        bytes32 toCurrencyKey,
        uint toAmount,
        address toAddress
    ) external;

    function emitExchangeReclaim(
        address account,
        bytes32 currencyKey,
        uint amount
    ) external;

    function emitExchangeRebate(
        address account,
        bytes32 currencyKey,
        uint amount
    ) external;
}

interface IExchangerInternalDebtCache {
    function updateCachedSynthDebtsWithRates(bytes32[] calldata currencyKeys, uint[] calldata currencyRates) external;

    function updateCachedSynthDebts(bytes32[] calldata currencyKeys) external;
}


// https://docs.synthetix.io/contracts/source/interfaces/isystemstatus
interface ISystemStatus {
    struct Status {
        bool canSuspend;
        bool canResume;
    }

    struct Suspension {
        bool suspended;
        // reason is an integer code,
        // 0 => no reason, 1 => upgrading, 2+ => defined by system usage
        uint248 reason;
    }

    // Views
    function accessControl(bytes32 section, address account) external view returns (bool canSuspend, bool canResume);

    function requireSystemActive() external view;

    function systemSuspended() external view returns (bool);

    function requireIssuanceActive() external view;

    function requireExchangeActive() external view;

    function requireFuturesActive() external view;

    function requireFuturesMarketActive(bytes32 marketKey) external view;

    function requireExchangeBetweenSynthsAllowed(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view;

    function requireSynthActive(bytes32 currencyKey) external view;

    function synthSuspended(bytes32 currencyKey) external view returns (bool);

    function requireSynthsActive(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view;

    function systemSuspension() external view returns (bool suspended, uint248 reason);

    function issuanceSuspension() external view returns (bool suspended, uint248 reason);

    function exchangeSuspension() external view returns (bool suspended, uint248 reason);

    function futuresSuspension() external view returns (bool suspended, uint248 reason);

    function synthExchangeSuspension(bytes32 currencyKey) external view returns (bool suspended, uint248 reason);

    function synthSuspension(bytes32 currencyKey) external view returns (bool suspended, uint248 reason);

    function futuresMarketSuspension(bytes32 marketKey) external view returns (bool suspended, uint248 reason);

    function getSynthExchangeSuspensions(bytes32[] calldata synths)
        external
        view
        returns (bool[] memory exchangeSuspensions, uint256[] memory reasons);

    function getSynthSuspensions(bytes32[] calldata synths)
        external
        view
        returns (bool[] memory suspensions, uint256[] memory reasons);

    function getFuturesMarketSuspensions(bytes32[] calldata marketKeys)
        external
        view
        returns (bool[] memory suspensions, uint256[] memory reasons);

    // Restricted functions
    function suspendIssuance(uint256 reason) external;

    function suspendSynth(bytes32 currencyKey, uint256 reason) external;

    function suspendFuturesMarket(bytes32 marketKey, uint256 reason) external;

    function updateAccessControl(
        bytes32 section,
        address account,
        bool canSuspend,
        bool canResume
    ) external;
}


interface IFuturesMarketManager {
    function markets(uint index, uint pageSize) external view returns (address[] memory);

    function markets(
        uint index,
        uint pageSize,
        bool proxiedMarkets
    ) external view returns (address[] memory);

    function numMarkets() external view returns (uint);

    function numMarkets(bool proxiedMarkets) external view returns (uint);

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

    function allMarkets(bool proxiedMarkets) external view returns (address[] memory);

    function marketForKey(bytes32 marketKey) external view returns (address);

    function marketsForKeys(bytes32[] calldata marketKeys) external view returns (address[] memory);

    function totalDebt() external view returns (uint debt, bool isInvalid);

    function isEndorsed(address account) external view returns (bool);

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

    function addEndorsedAddresses(address[] calldata addresses) external;

    function removeEndorsedAddresses(address[] calldata addresses) external;
}


// https://docs.synthetix.io/contracts/source/contracts/PerpsV2MarketState
interface IPerpsV2MarketState {
    function marketKey() external view returns (bytes32);

    function baseAsset() external view returns (bytes32);

    function marketSize() external view returns (uint128);

    function marketSkew() external view returns (int128);

    function fundingLastRecomputed() external view returns (uint32);

    function fundingSequence(uint) external view returns (int128);

    function fundingRateLastRecomputed() external view returns (int128);

    function positions(address) external view returns (IPerpsV2MarketBaseTypes.Position memory);

    function delayedOrders(address) external view returns (IPerpsV2MarketBaseTypes.DelayedOrder memory);

    function positionFlagger(address) external view returns (address);

    function entryDebtCorrection() external view returns (int128);

    function nextPositionId() external view returns (uint64);

    function fundingSequenceLength() external view returns (uint);

    function isFlagged(address) external view returns (bool);

    function getPositionAddressesPage(uint, uint) external view returns (address[] memory);

    function getPositionAddressesLength() external view returns (uint);

    function getDelayedOrderAddressesPage(uint, uint) external view returns (address[] memory);

    function getDelayedOrderAddressesLength() external view returns (uint);

    function getFlaggedAddressesPage(uint, uint) external view returns (address[] memory);

    function getFlaggedAddressesLength() external view returns (uint);

    function setMarketKey(bytes32) external;

    function setBaseAsset(bytes32) external;

    function setMarketSize(uint128) external;

    function setEntryDebtCorrection(int128) external;

    function setNextPositionId(uint64) external;

    function setMarketSkew(int128) external;

    function setFundingLastRecomputed(uint32) external;

    function setFundingRateLastRecomputed(int128 _fundingRateLastRecomputed) external;

    function pushFundingSequence(int128) external;

    function updatePosition(
        address account,
        uint64 id,
        uint64 lastFundingIndex,
        uint128 margin,
        uint128 lastPrice,
        int128 size
    ) external;

    function updateDelayedOrder(
        address account,
        bool isOffchain,
        int128 sizeDelta,
        uint128 desiredFillPrice,
        uint128 targetRoundId,
        uint128 commitDeposit,
        uint128 keeperDeposit,
        uint256 executableAtTime,
        uint256 intentionTime,
        bytes32 trackingCode
    ) external;

    function deletePosition(address) external;

    function deleteDelayedOrder(address) external;

    function flag(address account, address flagger) external;

    function unflag(address) external;
}


// Inheritance


// Libraries


// Internal references


// Internal references


// Use internal interface (external functions not present in IFuturesMarketManager)
interface IFuturesMarketManagerInternal {
    function issueSUSD(address account, uint amount) external;

    function burnSUSD(address account, uint amount) external returns (uint postReclamationAmount);

    function payFee(uint amount) external;

    function isEndorsed(address account) external view returns (bool);
}

// https://docs.synthetix.io/contracts/source/contracts/PerpsV2MarketBase
contract PerpsV2MarketBase is Owned, MixinPerpsV2MarketSettings, IPerpsV2MarketBaseTypes {
    /* ========== LIBRARIES ========== */

    using SafeMath for uint;
    using SafeDecimalMath for uint;
    using SignedSafeMath for int;
    using SignedSafeDecimalMath for int;

    /* ========== CONSTANTS ========== */

    // This is the same unit as used inside `SignedSafeDecimalMath`.
    int private constant _UNIT = int(10**uint(18));

    //slither-disable-next-line naming-convention
    bytes32 internal constant sUSD = "sUSD";

    /* ========== STATE VARIABLES ========== */

    IPerpsV2MarketState public marketState;

    /* ---------- Address Resolver Configuration ---------- */

    bytes32 private constant CONTRACT_EXRATES = "ExchangeRates";
    bytes32 internal constant CONTRACT_EXCHANGER = "Exchanger";
    bytes32 internal constant CONTRACT_SYSTEMSTATUS = "SystemStatus";
    bytes32 internal constant CONTRACT_FUTURESMARKETMANAGER = "FuturesMarketManager";
    bytes32 internal constant CONTRACT_PERPSV2MARKETSETTINGS = "PerpsV2MarketSettings";
    bytes32 internal constant CONTRACT_PERPSV2EXCHANGERATE = "PerpsV2ExchangeRate";
    bytes32 internal constant CONTRACT_FLEXIBLESTORAGE = "FlexibleStorage";

    // Holds the revert message for each type of error.
    mapping(uint8 => string) internal _errorMessages;

    // convenience struct for passing params between position modification helper functions
    struct TradeParams {
        int sizeDelta;
        uint oraclePrice;
        uint fillPrice;
        uint desiredFillPrice;
        uint takerFee;
        uint makerFee;
        bytes32 trackingCode; // optional tracking code for volume source fee sharing
    }

    /* ========== CONSTRUCTOR ========== */

    constructor(
        address _marketState,
        address _owner,
        address _resolver
    ) public MixinPerpsV2MarketSettings(_resolver) Owned(_owner) {
        marketState = IPerpsV2MarketState(_marketState);

        // Set up the mapping between error codes and their revert messages.
        _errorMessages[uint8(Status.InvalidPrice)] = "Invalid price";
        _errorMessages[uint8(Status.InvalidOrderType)] = "Invalid order type";
        _errorMessages[uint8(Status.PriceOutOfBounds)] = "Price out of acceptable range";
        _errorMessages[uint8(Status.CanLiquidate)] = "Position can be liquidated";
        _errorMessages[uint8(Status.CannotLiquidate)] = "Position cannot be liquidated";
        _errorMessages[uint8(Status.MaxMarketSizeExceeded)] = "Max market size exceeded";
        _errorMessages[uint8(Status.MaxLeverageExceeded)] = "Max leverage exceeded";
        _errorMessages[uint8(Status.InsufficientMargin)] = "Insufficient margin";
        _errorMessages[uint8(Status.NotPermitted)] = "Not permitted by this address";
        _errorMessages[uint8(Status.NilOrder)] = "Cannot submit empty order";
        _errorMessages[uint8(Status.NoPositionOpen)] = "No position open";
        _errorMessages[uint8(Status.PriceTooVolatile)] = "Price too volatile";
        _errorMessages[uint8(Status.PriceImpactToleranceExceeded)] = "Price impact exceeded";
        _errorMessages[uint8(Status.PositionFlagged)] = "Position flagged";
        _errorMessages[uint8(Status.PositionNotFlagged)] = "Position not flagged";
    }

    /* ---------- External Contracts ---------- */

    function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
        bytes32[] memory existingAddresses = MixinPerpsV2MarketSettings.resolverAddressesRequired();
        bytes32[] memory newAddresses = new bytes32[](7);
        newAddresses[0] = CONTRACT_EXCHANGER;
        newAddresses[1] = CONTRACT_EXRATES;
        newAddresses[2] = CONTRACT_SYSTEMSTATUS;
        newAddresses[3] = CONTRACT_FUTURESMARKETMANAGER;
        newAddresses[4] = CONTRACT_PERPSV2MARKETSETTINGS;
        newAddresses[5] = CONTRACT_PERPSV2EXCHANGERATE;
        newAddresses[6] = CONTRACT_FLEXIBLESTORAGE;
        addresses = combineArrays(existingAddresses, newAddresses);
    }

    function _exchangeRates() internal view returns (IExchangeRates) {
        return IExchangeRates(requireAndGetAddress(CONTRACT_EXRATES));
    }

    function _exchanger() internal view returns (IExchanger) {
        return IExchanger(requireAndGetAddress(CONTRACT_EXCHANGER));
    }

    function _systemStatus() internal view returns (ISystemStatus) {
        return ISystemStatus(requireAndGetAddress(CONTRACT_SYSTEMSTATUS));
    }

    function _manager() internal view returns (IFuturesMarketManagerInternal) {
        return IFuturesMarketManagerInternal(requireAndGetAddress(CONTRACT_FUTURESMARKETMANAGER));
    }

    function _settings() internal view returns (address) {
        return requireAndGetAddress(CONTRACT_PERPSV2MARKETSETTINGS);
    }

    /* ---------- Market Details ---------- */
    function _baseAsset() internal view returns (bytes32) {
        return marketState.baseAsset();
    }

    function _marketKey() internal view returns (bytes32) {
        return marketState.marketKey();
    }

    /*
     * Returns the pSkew = skew / skewScale capping the pSkew between [-1, 1].
     */
    function _proportionalSkew() internal view returns (int) {
        int pSkew = int(marketState.marketSkew()).divideDecimal(int(_skewScale(_marketKey())));

        // Ensures the proportionalSkew is between -1 and 1.
        return _min(_max(-_UNIT, pSkew), _UNIT);
    }

    function _proportionalElapsed() internal view returns (int) {
        return int(block.timestamp.sub(marketState.fundingLastRecomputed())).divideDecimal(1 days);
    }

    function _currentFundingVelocity() internal view returns (int) {
        int maxFundingVelocity = int(_maxFundingVelocity(_marketKey()));
        return _proportionalSkew().multiplyDecimal(maxFundingVelocity);
    }

    /*
     * @dev Retrieves the _current_ funding rate given the current market conditions.
     *
     * This is used during funding computation _before_ the market is modified (e.g. closing or
     * opening a position). However, called via the `currentFundingRate` view, will return the
     * 'instantaneous' funding rate. It's similar but subtle in that velocity now includes the most
     * recent skew modification.
     *
     * There is no variance in computation but will be affected based on outside modifications to
     * the market skew, max funding velocity, price, and time delta.
     */
    function _currentFundingRate() internal view returns (int) {
        // calculations:
        //  - velocity          = proportional_skew * max_funding_velocity
        //  - proportional_skew = skew / skew_scale
        //
        // example:
        //  - prev_funding_rate     = 0
        //  - prev_velocity         = 0.0025
        //  - time_delta            = 29,000s
        //  - max_funding_velocity  = 0.025 (2.5%)
        //  - skew                  = 300
        //  - skew_scale            = 10,000
        //
        // note: prev_velocity just refs to the velocity _before_ modifying the market skew.
        //
        // funding_rate = prev_funding_rate + prev_velocity * (time_delta / seconds_in_day)
        // funding_rate = 0 + 0.0025 * (29,000 / 86,400)
        //              = 0 + 0.0025 * 0.33564815
        //              = 0.00083912
        return
            int(marketState.fundingRateLastRecomputed()).add(
                _currentFundingVelocity().multiplyDecimal(_proportionalElapsed())
            );
    }

    function _unrecordedFunding(uint price) internal view returns (int) {
        int nextFundingRate = _currentFundingRate();
        // note the minus sign: funding flows in the opposite direction to the skew.
        int avgFundingRate = -(int(marketState.fundingRateLastRecomputed()).add(nextFundingRate)).divideDecimal(_UNIT * 2);
        return avgFundingRate.multiplyDecimal(_proportionalElapsed()).multiplyDecimal(int(price));
    }

    /*
     * The new entry in the funding sequence, appended when funding is recomputed. It is the sum of the
     * last entry and the unrecorded funding, so the sequence accumulates running total over the market's lifetime.
     */
    function _nextFundingEntry(uint price) internal view returns (int) {
        return int(marketState.fundingSequence(_latestFundingIndex())).add(_unrecordedFunding(price));
    }

    function _netFundingPerUnit(uint startIndex, uint price) internal view returns (int) {
        // Compute the net difference between start and end indices.
        return _nextFundingEntry(price).sub(marketState.fundingSequence(startIndex));
    }

    /* ---------- Position Details ---------- */

    /*
     * Determines whether a change in a position's size would violate the max market value constraint.
     */
    function _orderSizeTooLarge(
        uint maxSize,
        int oldSize,
        int newSize
    ) internal view returns (bool) {
        // Allow users to reduce an order no matter the market conditions.
        if (_sameSide(oldSize, newSize) && _abs(newSize) <= _abs(oldSize)) {
            return false;
        }

        // Either the user is flipping sides, or they are increasing an order on the same side they're already on;
        // we check that the side of the market their order is on would not break the limit.
        int newSkew = int(marketState.marketSkew()).sub(oldSize).add(newSize);
        int newMarketSize = int(marketState.marketSize()).sub(_signedAbs(oldSize)).add(_signedAbs(newSize));

        int newSideSize;
        if (0 < newSize) {
            // long case: marketSize + skew
            //            = (|longSize| + |shortSize|) + (longSize + shortSize)
            //            = 2 * longSize
            newSideSize = newMarketSize.add(newSkew);
        } else {
            // short case: marketSize - skew
            //            = (|longSize| + |shortSize|) - (longSize + shortSize)
            //            = 2 * -shortSize
            newSideSize = newMarketSize.sub(newSkew);
        }

        // newSideSize still includes an extra factor of 2 here, so we will divide by 2 in the actual condition
        if (maxSize < _abs(newSideSize.div(2))) {
            return true;
        }

        return false;
    }

    function _notionalValue(int positionSize, uint price) internal pure returns (int value) {
        return positionSize.multiplyDecimal(int(price));
    }

    function _profitLoss(Position memory position, uint price) internal pure returns (int pnl) {
        int priceShift = int(price).sub(int(position.lastPrice));
        return int(position.size).multiplyDecimal(priceShift);
    }

    function _accruedFunding(Position memory position, uint price) internal view returns (int funding) {
        uint lastModifiedIndex = position.lastFundingIndex;
        if (lastModifiedIndex == 0) {
            return 0; // The position does not exist -- no funding.
        }
        int net = _netFundingPerUnit(lastModifiedIndex, price);
        return int(position.size).multiplyDecimal(net);
    }

    /*
     * The initial margin of a position, plus any PnL and funding it has accrued. The resulting value may be negative.
     */
    function _marginPlusProfitFunding(Position memory position, uint price) internal view returns (int) {
        int funding = _accruedFunding(position, price);
        return int(position.margin).add(_profitLoss(position, price)).add(funding);
    }

    /*
     * The value in a position's margin after a deposit or withdrawal, accounting for funding and profit.
     * If the resulting margin would be negative or below the liquidation threshold, an appropriate error is returned.
     * If the result is not an error, callers of this function that use it to update a position's margin
     * must ensure that this is accompanied by a corresponding debt correction update, as per `_applyDebtCorrection`.
     */
    function _recomputeMarginWithDelta(
        Position memory position,
        uint price,
        int marginDelta
    ) internal view returns (uint margin, Status statusCode) {
        int newMargin = _marginPlusProfitFunding(position, price).add(marginDelta);
        if (newMargin < 0) {
            return (0, Status.InsufficientMargin);
        }

        uint uMargin = uint(newMargin);
        int positionSize = int(position.size);
        // minimum margin beyond which position can be liquidated
        uint lMargin = _liquidationMargin(positionSize, price);
        if (positionSize != 0 && uMargin <= lMargin) {
            return (uMargin, Status.CanLiquidate);
        }

        return (uMargin, Status.Ok);
    }

    function _remainingMargin(Position memory position, uint price) internal view returns (uint) {
        int remaining = _marginPlusProfitFunding(position, price);

        // If the margin went past zero, the position should have been liquidated - return zero remaining margin.
        return uint(_max(0, remaining));
    }

    /*
     * @dev Similar to _remainingMargin except it accounts for the premium and fees to be paid upon liquidation.
     */
    function _remainingLiquidatableMargin(Position memory position, uint price) internal view returns (uint) {
        int remaining = _marginPlusProfitFunding(position, price).sub(int(_liquidationPremium(position.size, price)));
        return uint(_max(0, remaining));
    }

    function _accessibleMargin(Position memory position, uint price) internal view returns (uint) {
        // Ugly solution to rounding safety: leave up to an extra tenth of a cent in the account/leverage
        // This should guarantee that the value returned here can always be withdrawn, but there may be
        // a little extra actually-accessible value left over, depending on the position size and margin.
        uint milli = uint(_UNIT / 1000);
        int maxLeverage = int(_maxLeverage(_marketKey()).sub(milli));
        uint inaccessible = _abs(_notionalValue(position.size, price).divideDecimal(maxLeverage));

        // If the user has a position open, we'll enforce a min initial margin requirement.
        if (0 < inaccessible) {
            uint minInitialMargin = _minInitialMargin();
            if (inaccessible < minInitialMargin) {
                inaccessible = minInitialMargin;
            }
            inaccessible = inaccessible.add(milli);
        }

        uint remaining = _remainingMargin(position, price);
        if (remaining <= inaccessible) {
            return 0;
        }

        return remaining.sub(inaccessible);
    }

    /**
     * The fee charged from the margin during liquidation. Fee is proportional to position size
     * but is between _minKeeperFee() and _maxKeeperFee() expressed in sUSD to prevent underincentivising
     * liquidations of small positions, or overpaying.
     * @param positionSize size of position in fixed point decimal baseAsset units
     * @param price price of single baseAsset unit in sUSD fixed point decimal units
     * @return lFee liquidation fee to be paid to liquidator in sUSD fixed point decimal units
     */
    function _liquidationFee(int positionSize, uint price) internal view returns (uint lFee) {
        // size * price * fee-ratio
        uint proportionalFee = _abs(positionSize).multiplyDecimal(price).multiplyDecimal(_liquidationFeeRatio());
        uint maxFee = _maxKeeperFee();
        uint cappedProportionalFee = proportionalFee > maxFee ? maxFee : proportionalFee;
        uint minFee = _minKeeperFee();

        // max(proportionalFee, minFee) - to prevent not incentivising liquidations enough
        return cappedProportionalFee > minFee ? cappedProportionalFee : minFee; // not using _max() helper because it's for signed ints
    }

    /**
     * The minimal margin at which liquidation can happen.
     * Is the sum of liquidationBuffer, liquidationFee (for flagger) and keeperLiquidationFee (for liquidator)
     * @param positionSize size of position in fixed point decimal baseAsset units
     * @param price price of single baseAsset unit in sUSD fixed point decimal units
     * @return lMargin liquidation margin to maintain in sUSD fixed point decimal units
     * @dev The liquidation margin contains a buffer that is proportional to the position
     * size. The buffer should prevent liquidation happening at negative margin (due to next price being worse)
     * so that stakers would not leak value to liquidators through minting rewards that are not from the
     * account's margin.
     */
    function _liquidationMargin(int positionSize, uint price) internal view returns (uint lMargin) {
        uint liquidationBuffer =
            _abs(positionSize).multiplyDecimal(price).multiplyDecimal(_liquidationBufferRatio(_marketKey()));
        return liquidationBuffer.add(_liquidationFee(positionSize, price)).add(_keeperLiquidationFee());
    }

    /**
     * @dev This is the additional premium we charge upon liquidation.
     *
     * Similar to fillPrice, but we disregard the skew (by assuming it's zero). Which is basically the calculation
     * when we compute as if taking the position from 0 to x. In practice, the premium component of the
     * liquidation will just be (size / skewScale) * (size * price).
     *
     * It adds a configurable multiplier that can be used to increase the margin that goes to feePool.
     *
     * For instance, if size of the liquidation position is 100, oracle price is 1200 and skewScale is 1M then,
     *
     *  size    = abs(-100)
     *          = 100
     *  premium = 100 / 1000000 * (100 * 1200) * multiplier
     *          = 12 * multiplier
     *  if multiplier is set to 1
     *          = 12 * 1 = 12
     *
     * @param positionSize Size of the position we want to liquidate
     * @param currentPrice The current oracle price (not fillPrice)
     * @return The premium to be paid upon liquidation in sUSD
     */
    function _liquidationPremium(int positionSize, uint currentPrice) internal view returns (uint) {
        if (positionSize == 0) {
            return 0;
        }

        // note: this is the same as fillPrice() where the skew is 0.
        uint notional = _abs(_notionalValue(positionSize, currentPrice));

        return
            _abs(positionSize).divideDecimal(_skewScale(_marketKey())).multiplyDecimal(notional).multiplyDecimal(
                _liquidationPremiumMultiplier(_marketKey())
            );
    }

    function _canLiquidate(Position memory position, uint price) internal view returns (bool) {
        // No liquidating empty positions.
        if (position.size == 0) {
            return false;
        }

        return _remainingLiquidatableMargin(position, price) <= _liquidationMargin(int(position.size), price);
    }

    function _currentLeverage(
        Position memory position,
        uint price,
        uint remainingMargin_
    ) internal pure returns (int leverage) {
        // No position is open, or it is ready to be liquidated; leverage goes to nil
        if (remainingMargin_ == 0) {
            return 0;
        }

        return _notionalValue(position.size, price).divideDecimal(int(remainingMargin_));
    }

    function _orderFee(TradeParams memory params, uint dynamicFeeRate) internal view returns (uint fee) {
        // usd value of the difference in position (using the p/d-adjusted price).
        int marketSkew = marketState.marketSkew();
        int notionalDiff = params.sizeDelta.multiplyDecimal(int(params.fillPrice));

        // minimum fee to pay regardless (due to dynamic fees).
        uint baseFee = _abs(notionalDiff).multiplyDecimal(dynamicFeeRate);

        // does this trade keep the skew on one side?
        if (_sameSide(marketSkew + params.sizeDelta, marketSkew)) {
            // use a flat maker/taker fee for the entire size depending on whether the skew is increased or reduced.
            //
            // if the order is submitted on the same side as the skew (increasing it) - the taker fee is charged.
            // otherwise if the order is opposite to the skew, the maker fee is charged.
            uint staticRate = _sameSide(notionalDiff, marketState.marketSkew()) ? params.takerFee : params.makerFee;
            return baseFee + _abs(notionalDiff.multiplyDecimal(int(staticRate)));
        }

        // this trade flips the skew.
        //
        // the proportion of size that moves in the direction after the flip should not be considered
        // as a maker (reducing skew) as it's now taking (increasing skew) in the opposite direction. hence,
        // a different fee is applied on the proportion increasing the skew.

        // proportion of size that's on the other direction
        uint takerSize = _abs((marketSkew + params.sizeDelta).divideDecimal(params.sizeDelta));
        uint makerSize = uint(_UNIT) - takerSize;
        uint takerFee = _abs(notionalDiff).multiplyDecimal(takerSize).multiplyDecimal(params.takerFee);
        uint makerFee = _abs(notionalDiff).multiplyDecimal(makerSize).multiplyDecimal(params.makerFee);

        return baseFee + takerFee + makerFee;
    }

    /// Uses the exchanger to get the dynamic fee (SIP-184) for trading from sUSD to baseAsset
    /// this assumes dynamic fee is symmetric in direction of trade.
    /// @dev this is a pretty expensive action in terms of execution gas as it queries a lot
    ///   of past rates from oracle. Shouldn't be much of an issue on a rollup though.
    function _dynamicFeeRate() internal view returns (uint feeRate, bool tooVolatile) {
        return _exchanger().dynamicFeeRateForExchange(sUSD, _baseAsset());
    }

    function _latestFundingIndex() internal view returns (uint) {
        return marketState.fundingSequenceLength().sub(1); // at least one element is pushed in constructor
    }

    function _postTradeDetails(Position memory oldPos, TradeParams memory params)
        internal
        view
        returns (
            Position memory newPosition,
            uint fee,
            Status tradeStatus
        )
    {
        // Reverts if the user is trying to submit a size-zero order.
        if (params.sizeDelta == 0) {
            return (oldPos, 0, Status.NilOrder);
        }

        // The order is not submitted if the user's existing position needs to be liquidated.
        if (_canLiquidate(oldPos, params.oraclePrice)) {
            return (oldPos, 0, Status.CanLiquidate);
        }

        // get the dynamic fee rate SIP-184
        (uint dynamicFeeRate, bool tooVolatile) = _dynamicFeeRate();
        if (tooVolatile) {
            return (oldPos, 0, Status.PriceTooVolatile);
        }

        // calculate the total fee for exchange
        fee = _orderFee(params, dynamicFeeRate);

        // Deduct the fee.
        // It is an error if the realised margin minus the fee is negative or subject to liquidation.
        (uint newMargin, Status status) = _recomputeMarginWithDelta(oldPos, params.fillPrice, -int(fee));
        if (_isError(status)) {
            return (oldPos, 0, status);
        }

        // construct new position
        Position memory newPos =
            Position({
                id: oldPos.id,
                lastFundingIndex: uint64(_latestFundingIndex()),
                margin: uint128(newMargin),
                lastPrice: uint128(params.fillPrice),
                size: int128(int(oldPos.size).add(params.sizeDelta))
            });

        // always allow to decrease a position, otherwise a margin of minInitialMargin can never
        // decrease a position as the price goes against them.
        // we also add the paid out fee for the minInitialMargin because otherwise minInitialMargin
        // is never the actual minMargin, because the first trade will always deduct
        // a fee (so the margin that otherwise would need to be transferred would have to include the future
        // fee as well, making the UX and definition of min-margin confusing).
        bool positionDecreasing = _sameSide(oldPos.size, newPos.size) && _abs(newPos.size) < _abs(oldPos.size);
        if (!positionDecreasing) {
            // minMargin + fee <= margin is equivalent to minMargin <= margin - fee
            // except that we get a nicer error message if fee > margin, rather than arithmetic overflow.
            if (uint(newPos.margin).add(fee) < _minInitialMargin()) {
                return (oldPos, 0, Status.InsufficientMargin);
            }
        }

        // check that new position margin is above liquidation margin
        // (above, in _recomputeMarginWithDelta() we checked the old position, here we check the new one)
        //
        // Liquidation margin is considered without a fee (but including premium), because it wouldn't make sense to allow
        // a trade that will make the position liquidatable.
        //
        // note: we use `oraclePrice` here as `liquidationPremium` calcs premium based not current skew.
        uint liqPremium = _liquidationPremium(newPos.size, params.oraclePrice);
        uint liqMargin = _liquidationMargin(newPos.size, params.oraclePrice).add(liqPremium);
        if (newMargin <= liqMargin) {
            return (newPos, 0, Status.CanLiquidate);
        }

        // Check that the maximum leverage is not exceeded when considering new margin including the paid fee.
        // The paid fee is considered for the benefit of UX of allowed max leverage, otherwise, the actual
        // max leverage is always below the max leverage parameter since the fee paid for a trade reduces the margin.
        // We'll allow a little extra headroom for rounding errors.
        {
            // stack too deep
            int leverage = int(newPos.size).multiplyDecimal(int(params.fillPrice)).divideDecimal(int(newMargin.add(fee)));
            if (_maxLeverage(_marketKey()).add(uint(_UNIT) / 100) < _abs(leverage)) {
                return (oldPos, 0, Status.MaxLeverageExceeded);
            }
        }

        // Check that the order isn't too large for the markets.
        if (_orderSizeTooLarge(_maxMarketValue(_marketKey()), oldPos.size, newPos.size)) {
            return (oldPos, 0, Status.MaxMarketSizeExceeded);
        }

        return (newPos, fee, Status.Ok);
    }

    /* ---------- Utilities ---------- */

    /*
     * The current base price from the oracle, and whether that price was invalid. Zero prices count as invalid.
     * Public because used both externally and internally
     */
    function _assetPrice() internal view returns (uint price, bool invalid) {
        (price, invalid) = _exchangeRates().rateAndInvalid(_baseAsset());
        // Ensure we catch uninitialised rates or suspended state / synth
        invalid = invalid || price == 0 || _systemStatus().synthSuspended(_baseAsset());
        return (price, invalid);
    }

    /*
     * @dev SIP-279 fillPrice price at which a trade is executed against accounting for how this position's
     * size impacts the skew. If the size contracts the skew (reduces) then a discount is applied on the price
     * whereas expanding the skew incurs an additional premium.
     */
    function _fillPrice(int size, uint price) internal view returns (uint) {
        int skew = marketState.marketSkew();
        int skewScale = int(_skewScale(_marketKey()));

        int pdBefore = skew.divideDecimal(skewScale);
        int pdAfter = skew.add(size).divideDecimal(skewScale);
        int priceBefore = int(price).add(int(price).multiplyDecimal(pdBefore));
        int priceAfter = int(price).add(int(price).multiplyDecimal(pdAfter));

        // How is the p/d-adjusted price calculated using an example:
        //
        // price      = $1200 USD (oracle)
        // size       = 100
        // skew       = 0
        // skew_scale = 1,000,000 (1M)
        //
        // Then,
        //
        // pd_before = 0 / 1,000,000
        //           = 0
        // pd_after  = (0 + 100) / 1,000,000
        //           = 100 / 1,000,000
        //           = 0.0001
        //
        // price_before = 1200 * (1 + pd_before)
        //              = 1200 * (1 + 0)
        //              = 1200
        // price_after  = 1200 * (1 + pd_after)
        //              = 1200 * (1 + 0.0001)
        //              = 1200 * (1.0001)
        //              = 1200.12
        // Finally,
        //
        // fill_price = (price_before + price_after) / 2
        //            = (1200 + 1200.12) / 2
        //            = 1200.06
        return uint(priceBefore.add(priceAfter).divideDecimal(_UNIT * 2));
    }

    /*
     * Absolute value of the input, returned as a signed number.
     */
    function _signedAbs(int x) internal pure returns (int) {
        return x < 0 ? -x : x;
    }

    /*
     * Absolute value of the input, returned as an unsigned number.
     */
    function _abs(int x) internal pure returns (uint) {
        return uint(_signedAbs(x));
    }

    function _max(int x, int y) internal pure returns (int) {
        return x < y ? y : x;
    }

    function _min(int x, int y) internal pure returns (int) {
        return x < y ? x : y;
    }

    /*
     * True if and only if two positions a and b are on the same side of the market; that is, if they have the same
     * sign, or either of them is zero.
     */
    function _sameSide(int a, int b) internal pure returns (bool) {
        return (a == 0) || (b == 0) || (a > 0) == (b > 0);
    }

    /*
     * True if and only if the given status indicates an error.
     */
    function _isError(Status status) internal pure returns (bool) {
        return status != Status.Ok;
    }

    /*
     * Revert with an appropriate message if the first argument is true.
     */
    function _revertIfError(bool isError, Status status) internal view {
        if (isError) {
            revert(_errorMessages[uint8(status)]);
        }
    }

    /*
     * Revert with an appropriate message if the input is an error.
     */
    function _revertIfError(Status status) internal view {
        if (_isError(status)) {
            revert(_errorMessages[uint8(status)]);
        }
    }
}


// Inheritance


// https://docs.synthetix.io/contracts/source/contracts/PerpsV2MarketProxyable
contract PerpsV2MarketProxyable is PerpsV2MarketBase, Proxyable {
    /* ========== CONSTRUCTOR ========== */

    constructor(
        address payable _proxy,
        address _marketState,
        address _owner,
        address _resolver
    ) public PerpsV2MarketBase(_marketState, _owner, _resolver) Proxyable(_proxy) {}

    /* ---------- Market Operations ---------- */

    /*
     * Alter the debt correction to account for the net result of altering a position.
     */
    function _applyDebtCorrection(Position memory newPosition, Position memory oldPosition) internal {
        int newCorrection = _positionDebtCorrection(newPosition);
        int oldCorrection = _positionDebtCorrection(oldPosition);
        marketState.setEntryDebtCorrection(
            int128(int(marketState.entryDebtCorrection()).add(newCorrection).sub(oldCorrection))
        );
    }

    /*
     * The impact of a given position on the debt correction.
     */
    function _positionDebtCorrection(Position memory position) internal view returns (int) {
        /**
        This method only returns the correction term for the debt calculation of the position, and not it's 
        debt. This is needed for keeping track of the marketDebt() in an efficient manner to allow O(1) marketDebt
        calculation in marketDebt().

        Explanation of the full market debt calculation from the SIP https://sips.synthetix.io/sips/sip-80/:

        The overall market debt is the sum of the remaining margin in all positions. The intuition is that
        the debt of a single position is the value withdrawn upon closing that position.

        single position remaining margin = initial-margin + profit-loss + accrued-funding =
            = initial-margin + q * (price - last-price) + q * funding-accrued-per-unit
            = initial-margin + q * price - q * last-price + q * (funding - initial-funding)

        Total debt = sum ( position remaining margins )
            = sum ( initial-margin + q * price - q * last-price + q * (funding - initial-funding) )
            = sum( q * price ) + sum( q * funding ) + sum( initial-margin - q * last-price - q * initial-funding )
            = skew * price + skew * funding + sum( initial-margin - q * ( last-price + initial-funding ) )
            = skew (price + funding) + sum( initial-margin - q * ( last-price + initial-funding ) )

        The last term: sum( initial-margin - q * ( last-price + initial-funding ) ) being the position debt correction
            that is tracked with each position change using this method. 
        
        The first term and the full debt calculation using current skew, price, and funding is calculated globally in marketDebt().
         */
        return
            int(position.margin).sub(
                int(position.size).multiplyDecimal(
                    int(position.lastPrice).add(marketState.fundingSequence(position.lastFundingIndex))
                )
            );
    }

    /*
     * The current base price, reverting if it is invalid, or if system or synth is suspended.
     * This is mutative because the circuit breaker stores the last price on every invocation.
     */
    function _assetPriceRequireSystemChecks(bool checkOffchainMarket) internal returns (uint) {
        // check that futures market isn't suspended, revert with appropriate message
        _systemStatus().requireFuturesMarketActive(_marketKey()); // asset and market may be different
        // check that synth is active, and wasn't suspended, revert with appropriate message
        _systemStatus().requireSynthActive(_baseAsset());

        if (checkOffchainMarket) {
            // offchain PerpsV2 virtual market
            _systemStatus().requireFuturesMarketActive(_offchainMarketKey(_marketKey()));
        }
        // check if circuit breaker if price is within deviation tolerance and system & synth is active
        // note: rateWithBreakCircuit (mutative) is used here instead of rateWithInvalid (view). This is
        //  despite reverting immediately after if circuit is broken, which may seem silly.
        //  This is in order to persist last-rate in exchangeCircuitBreaker in the happy case
        //  because last-rate is what used for measuring the deviation for subsequent trades.
        (uint price, bool circuitBroken, bool staleOrInvalid) = _exchangeRates().rateWithSafetyChecks(_baseAsset());
        // revert if price is invalid or circuit was broken
        // note: we revert here, which means that circuit is not really broken (is not persisted), this is
        //  because the futures methods and interface are designed for reverts, and do not support no-op
        //  return values.
        _revertIfError(circuitBroken || staleOrInvalid, Status.InvalidPrice);
        return price;
    }

    /** TODO: Docs */
    function _assertFillPrice(
        uint fillPrice,
        uint desiredFillPrice,
        int sizeDelta
    ) internal view returns (uint) {
        _revertIfError(
            sizeDelta > 0 ? fillPrice > desiredFillPrice : fillPrice < desiredFillPrice,
            Status.PriceImpactToleranceExceeded
        );
        return fillPrice;
    }

    function _recomputeFunding(uint price) internal returns (uint lastIndex) {
        uint sequenceLengthBefore = marketState.fundingSequenceLength();

        int fundingRate = _currentFundingRate();
        int funding = _nextFundingEntry(price);
        marketState.pushFundingSequence(int128(funding));
        marketState.setFundingLastRecomputed(uint32(block.timestamp));
        marketState.setFundingRateLastRecomputed(int128(fundingRate));

        emitFundingRecomputed(funding, fundingRate, sequenceLengthBefore, marketState.fundingLastRecomputed());

        return sequenceLengthBefore;
    }

    // updates the stored position margin in place (on the stored position)
    function _updatePositionMargin(
        address account,
        Position memory position,
        int orderSizeDelta,
        uint price,
        int marginDelta
    ) internal {
        Position memory oldPosition = position;
        // Determine new margin, ensuring that the result is positive.
        (uint margin, Status status) = _recomputeMarginWithDelta(oldPosition, price, marginDelta);
        _revertIfError(status);

        // Update the debt correction.
        uint fundingIndex = _latestFundingIndex();
        _applyDebtCorrection(
            Position(0, uint64(fundingIndex), uint128(margin), uint128(price), int128(position.size)),
            Position(0, position.lastFundingIndex, position.margin, position.lastPrice, int128(position.size))
        );

        // Update the account's position with the realised margin.
        position.margin = uint128(margin);

        // We only need to update their funding/PnL details if they actually have a position open
        if (position.size != 0) {
            position.lastPrice = uint128(price);
            position.lastFundingIndex = uint64(fundingIndex);

            // The user can always decrease their margin if they have no position, or as long as:
            //   * the resulting margin would not be lower than the liquidation margin or min initial margin
            //     * liqMargin accounting for the liqPremium
            if (marginDelta < 0) {
                // note: We .add `liqPremium` to increase the req margin to avoid entering into liquidation
                uint liqPremium = _liquidationPremium(position.size, price);
                uint liqMargin = _liquidationMargin(position.size, price).add(liqPremium);

                _revertIfError(margin <= liqMargin, Status.InsufficientMargin);

                // `marginDelta` can be decreasing (due to e.g. fees). However, price could also have moved in the
                // opposite direction resulting in a loss. A reduced remainingMargin to calc currentLeverage can
                // put the position above maxLeverage.
                //
                // To account for this, a check on `positionDecreasing` ensures that we can always perform this action
                // so long as we're reducing the position size and not liquidatable.
                int newPositionSize = int(position.size).add(orderSizeDelta);
                bool positionDecreasing =
                    _sameSide(position.size, newPositionSize) && _abs(newPositionSize) < _abs(position.size);

                if (!positionDecreasing) {
                    _revertIfError(
                        _maxLeverage(_marketKey()) < _abs(_currentLeverage(position, price, margin)),
                        Status.MaxLeverageExceeded
                    );
                    _revertIfError(margin < _minInitialMargin(), Status.InsufficientMargin);
                }
            }
        }

        // persist position changes
        marketState.updatePosition(
            account,
            position.id,
            position.lastFundingIndex,
            position.margin,
            position.lastPrice,
            position.size
        );
    }

    function _trade(address sender, TradeParams memory params) internal notFlagged(sender) {
        Position memory position = marketState.positions(sender);
        Position memory oldPosition =
            Position({
                id: position.id,
                lastFundingIndex: position.lastFundingIndex,
                margin: position.margin,
                lastPrice: position.lastPrice,
                size: position.size
            });

        // Compute the new position after performing the trade
        (Position memory newPosition, uint fee, Status status) = _postTradeDetails(oldPosition, params);
        _revertIfError(status);

        _assertFillPrice(params.fillPrice, params.desiredFillPrice, params.sizeDelta);

        // Update the aggregated market size and skew with the new order size
        marketState.setMarketSkew(int128(int(marketState.marketSkew()).add(newPosition.size).sub(oldPosition.size)));
        marketState.setMarketSize(
            uint128(uint(marketState.marketSize()).add(_abs(newPosition.size)).sub(_abs(oldPosition.size)))
        );

        // Send the fee to the fee pool
        if (0 < fee) {
            _manager().payFee(fee);
        }
        // emit tracking code event
        if (params.trackingCode != bytes32(0)) {
            emitPerpsTracking(params.trackingCode, _baseAsset(), _marketKey(), params.sizeDelta, fee);
        }

        // Update the margin, and apply the resulting debt correction
        position.margin = newPosition.margin;
        _applyDebtCorrection(newPosition, oldPosition);

        // Record the trade
        uint64 id = oldPosition.id;
        uint fundingIndex = _latestFundingIndex();
        if (newPosition.size == 0) {
            // If the position is being closed, we no longer need to track these details.
            delete position.id;
            delete position.size;
            delete position.lastPrice;
            delete position.lastFundingIndex;
        } else {
            if (oldPosition.size == 0) {
                // New positions get new ids.
                id = marketState.nextPositionId();
                marketState.setNextPositionId(id + 1);
            }
            position.id = id;
            position.size = newPosition.size;
            position.lastPrice = uint128(params.fillPrice);
            position.lastFundingIndex = uint64(fundingIndex);
        }

        // persist position changes
        marketState.updatePosition(
            sender,
            position.id,
            position.lastFundingIndex,
            position.margin,
            position.lastPrice,
            position.size
        );

        // emit the modification event
        emitPositionModified(
            id,
            sender,
            newPosition.margin,
            newPosition.size,
            params.sizeDelta,
            params.fillPrice,
            fundingIndex,
            fee,
            marketState.marketSkew()
        );
    }

    /* ========== EVENTS ========== */

    function addressToBytes32(address input) internal pure returns (bytes32) {
        return bytes32(uint256(uint160(input)));
    }

    event PositionModified(
        uint indexed id,
        address indexed account,
        uint margin,
        int size,
        int tradeSize,
        uint lastPrice,
        uint fundingIndex,
        uint fee,
        int skew
    );
    bytes32 internal constant POSITIONMODIFIED_SIG =
        keccak256("PositionModified(uint256,address,uint256,int256,int256,uint256,uint256,uint256,int256)");

    function emitPositionModified(
        uint id,
        address account,
        uint margin,
        int size,
        int tradeSize,
        uint lastPrice,
        uint fundingIndex,
        uint fee,
        int skew
    ) internal {
        proxy._emit(
            abi.encode(margin, size, tradeSize, lastPrice, fundingIndex, fee, skew),
            3,
            POSITIONMODIFIED_SIG,
            bytes32(id),
            addressToBytes32(account),
            0
        );
    }

    event FundingRecomputed(int funding, int fundingRate, uint index, uint timestamp);
    bytes32 internal constant FUNDINGRECOMPUTED_SIG = keccak256("FundingRecomputed(int256,int256,uint256,uint256)");

    function emitFundingRecomputed(
        int funding,
        int fundingRate,
        uint index,
        uint timestamp
    ) internal {
        proxy._emit(abi.encode(funding, fundingRate, index, timestamp), 1, FUNDINGRECOMPUTED_SIG, 0, 0, 0);
    }

    event PerpsTracking(bytes32 indexed trackingCode, bytes32 baseAsset, bytes32 marketKey, int sizeDelta, uint fee);
    bytes32 internal constant PERPSTRACKING_SIG = keccak256("PerpsTracking(bytes32,bytes32,bytes32,int256,uint256)");

    function emitPerpsTracking(
        bytes32 trackingCode,
        bytes32 baseAsset,
        bytes32 marketKey,
        int sizeDelta,
        uint fee
    ) internal {
        proxy._emit(abi.encode(baseAsset, marketKey, sizeDelta, fee), 2, PERPSTRACKING_SIG, trackingCode, 0, 0);
    }

    /* ========== MODIFIERS ========== */

    modifier flagged(address account) {
        if (!marketState.isFlagged(account)) {
            revert(_errorMessages[uint8(Status.PositionNotFlagged)]);
        }
        _;
    }

    modifier notFlagged(address account) {
        if (marketState.isFlagged(account)) {
            revert(_errorMessages[uint8(Status.PositionFlagged)]);
        }
        _;
    }
}


interface IPerpsV2MarketDelayedIntent {
    function submitCloseOffchainDelayedOrderWithTracking(uint desiredFillPrice, bytes32 trackingCode) external;

    function submitCloseDelayedOrderWithTracking(
        uint desiredTimeDelta,
        uint desiredFillPrice,
        bytes32 trackingCode
    ) external;

    function submitDelayedOrder(
        int sizeDelta,
        uint desiredTimeDelta,
        uint desiredFillPrice
    ) external;

    function submitDelayedOrderWithTracking(
        int sizeDelta,
        uint desiredTimeDelta,
        uint desiredFillPrice,
        bytes32 trackingCode
    ) external;

    function submitOffchainDelayedOrder(int sizeDelta, uint desiredFillPrice) external;

    function submitOffchainDelayedOrderWithTracking(
        int sizeDelta,
        uint desiredFillPrice,
        bytes32 trackingCode
    ) external;
}


// Inheritance


// Reference


/**
 Contract that implements DelayedOrders (on-chain & off-chain) mechanism for the PerpsV2 market.
 The purpose of the mechanism is to allow reduced fees for trades that commit to next price instead
 of current price. Specifically, this should serve funding rate arbitrageurs, such that funding rate
 arb is profitable for smaller skews. This in turn serves the protocol by reducing the skew, and so
 the risk to the debt pool, and funding rate for traders.
 The fees can be reduced when committing to next price, because front-running (MEV and oracle delay)
 is less of a risk when committing to next price.
 The relative complexity of the mechanism is due to having to enforce the "commitment" to the trade
 without either introducing free (or cheap) optionality to cause cancellations, and without large
 sacrifices to the UX / risk of the traders (e.g. blocking all actions, or penalizing failures too much).
 */
// https://docs.synthetix.io/contracts/source/contracts/PerpsV2MarketDelayedIntent
contract PerpsV2MarketDelayedIntent is IPerpsV2MarketDelayedIntent, PerpsV2MarketProxyable {
    /* ========== CONSTRUCTOR ========== */

    constructor(
        address payable _proxy,
        address _marketState,
        address _owner,
        address _resolver
    ) public PerpsV2MarketProxyable(_proxy, _marketState, _owner, _resolver) {}

    ///// Mutative methods

    function submitCloseOffchainDelayedOrderWithTracking(uint desiredFillPrice, bytes32 trackingCode)
        external
        onlyProxy
        notFlagged(messageSender)
    {
        _submitCloseDelayedOrder(0, desiredFillPrice, trackingCode, IPerpsV2MarketBaseTypes.OrderType.Offchain);
    }

    function submitCloseDelayedOrderWithTracking(
        uint desiredTimeDelta,
        uint desiredFillPrice,
        bytes32 trackingCode
    ) external onlyProxy notFlagged(messageSender) {
        _submitCloseDelayedOrder(
            desiredTimeDelta,
            desiredFillPrice,
            trackingCode,
            IPerpsV2MarketBaseTypes.OrderType.Delayed
        );
    }

    /**
     * @notice submits an order to be filled some time in the future or at a price of the next oracle update.
     * Reverts if a previous order still exists (wasn't executed or cancelled).
     * Reverts if the order cannot be filled at current price to prevent withholding commitFee for
     * incorrectly submitted orders (that cannot be filled).
     *
     * The order is executable after desiredTimeDelta. However, we also allow execution if the next price update
     * occurs before the desiredTimeDelta.
     * Reverts if the desiredTimeDelta is < minimum required delay.
     *
     * @param sizeDelta size in baseAsset (notional terms) of the order, similar to `modifyPosition` interface
     * @param desiredTimeDelta maximum time in seconds to wait before filling this order
     * @param desiredFillPrice an exact upper/lower bound price used on execution
     */
    function submitDelayedOrder(
        int sizeDelta,
        uint desiredTimeDelta,
        uint desiredFillPrice
    ) external onlyProxy notFlagged(messageSender) {
        // @dev market key is obtained here and not in internal function to prevent stack too deep there
        // bytes32 marketKey = _marketKey();

        _submitDelayedOrder(_marketKey(), sizeDelta, desiredTimeDelta, desiredFillPrice, bytes32(0), false);
    }

    /// Same as submitDelayedOrder but emits an event with the tracking code to allow volume source
    /// fee sharing for integrations.
    function submitDelayedOrderWithTracking(
        int sizeDelta,
        uint desiredTimeDelta,
        uint desiredFillPrice,
        bytes32 trackingCode
    ) external onlyProxy notFlagged(messageSender) {
        // @dev market key is obtained here and not in internal function to prevent stack too deep there
        // bytes32 marketKey = _marketKey();

        _submitDelayedOrder(_marketKey(), sizeDelta, desiredTimeDelta, desiredFillPrice, trackingCode, false);
    }

    /**
     * @notice submits an order to be filled some time in the future or at a price of the next oracle update.
     * Reverts if a previous order still exists (wasn't executed or cancelled).
     * Reverts if the order cannot be filled at current price to prevent withholding commitFee for
     * incorrectly submitted orders (that cannot be filled).
     *
     * The order is executable after desiredTimeDelta. However, we also allow execution if the next price update
     * occurs before the desiredTimeDelta.
     * Reverts if the desiredTimeDelta is < minimum required delay.
     *
     * @param sizeDelta size in baseAsset (notional terms) of the order, similar to `modifyPosition` interface
     * @param desiredFillPrice an exact upper/lower bound price used on execution
     */
    function submitOffchainDelayedOrder(int sizeDelta, uint desiredFillPrice) external onlyProxy notFlagged(messageSender) {
        // @dev market key is obtained here and not in internal function to prevent stack too deep there
        // bytes32 marketKey = _marketKey();

        // enforcing desiredTimeDelta to 0 to use default (not needed for offchain delayed order)
        _submitDelayedOrder(_marketKey(), sizeDelta, 0, desiredFillPrice, bytes32(0), true);
    }

    function submitOffchainDelayedOrderWithTracking(
        int sizeDelta,
        uint desiredFillPrice,
        bytes32 trackingCode
    ) external onlyProxy notFlagged(messageSender) {
        // @dev market key is obtained here and not in internal function to prevent stack too deep there
        // bytes32 marketKey = _marketKey();

        _submitDelayedOrder(_marketKey(), sizeDelta, 0, desiredFillPrice, trackingCode, true);
    }

    ///// Internal

    function _submitCloseDelayedOrder(
        uint desiredTimeDelta,
        uint desiredFillPrice,
        bytes32 trackingCode,
        IPerpsV2MarketBaseTypes.OrderType orderType
    ) internal {
        Position memory position = marketState.positions(messageSender);

        // a position must be present before closing.
        _revertIfError(position.size == 0, Status.NoPositionOpen);

        // we only allow off-chain and delayed orders.
        //
        // note: although this is internal and may _never_ be called incorrectly, just a safety check.
        require(orderType != IPerpsV2MarketBaseTypes.OrderType.Atomic, "invalid order type");

        _submitDelayedOrder(
            _marketKey(),
            -position.size,
            desiredTimeDelta,
            desiredFillPrice,
            trackingCode,
            orderType == IPerpsV2MarketBaseTypes.OrderType.Offchain
        );
    }

    function _submitDelayedOrder(
        bytes32 marketKey,
        int sizeDelta,
        uint desiredTimeDelta,
        uint desiredFillPrice,
        bytes32 trackingCode,
        bool isOffchain
    ) internal {
        // check that a previous order doesn't exist
        require(marketState.delayedOrders(messageSender).sizeDelta == 0, "previous order exists");

        // automatically set desiredTimeDelta to min if 0 is specified
        if (desiredTimeDelta == 0) {
            desiredTimeDelta = _minDelayTimeDelta(marketKey);
        }

        // ensure the desiredTimeDelta is above the minimum required delay
        require(
            desiredTimeDelta >= _minDelayTimeDelta(marketKey) && desiredTimeDelta <= _maxDelayTimeDelta(marketKey),
            "delay out of bounds"
        );

        // storage position as it's going to be modified to deduct commitFee and keeperFee
        Position memory position = marketState.positions(messageSender);

        // to prevent submitting bad orders in good faith and being charged commitDeposit for them
        // simulate the order with current price (+ p/d) and market and check that the order doesn't revert
        uint price = _assetPriceRequireSystemChecks(isOffchain);
        uint fillPrice = _fillPrice(sizeDelta, price);
        uint fundingIndex = _recomputeFunding(price);

        TradeParams memory params =
            TradeParams({
                sizeDelta: sizeDelta,
                oraclePrice: price,
                fillPrice: fillPrice,
                takerFee: isOffchain ? _takerFeeOffchainDelayedOrder(marketKey) : _takerFeeDelayedOrder(marketKey),
                makerFee: isOffchain ? _makerFeeOffchainDelayedOrder(marketKey) : _makerFeeDelayedOrder(marketKey),
                desiredFillPrice: desiredFillPrice,
                trackingCode: trackingCode
            });

        // stack too deep
        {
            (, , Status status) = _postTradeDetails(position, params);
            _revertIfError(status);
        }

        uint keeperDeposit = _minKeeperFee();

        _updatePositionMargin(messageSender, position, sizeDelta, fillPrice, -int(keeperDeposit));
        emitPositionModified(
            position.id,
            messageSender,
            position.margin,
            position.size,
            0,
            fillPrice,
            fundingIndex,
            0,
            marketState.marketSkew()
        );

        uint targetRoundId = _exchangeRates().getCurrentRoundId(_baseAsset()) + 1; // next round
        DelayedOrder memory order =
            DelayedOrder({
                isOffchain: isOffchain,
                sizeDelta: int128(sizeDelta),
                desiredFillPrice: uint128(desiredFillPrice),
                targetRoundId: isOffchain ? 0 : uint128(targetRoundId),
                commitDeposit: 0, // note: legacy as no longer charge a commitFee on submit
                keeperDeposit: uint128(keeperDeposit), // offchain orders do _not_ have an executableAtTime as it's based on price age.
                executableAtTime: isOffchain ? 0 : block.timestamp + desiredTimeDelta, // zero out - not used and minimise confusion.
                intentionTime: block.timestamp,
                trackingCode: trackingCode
            });

        emitDelayedOrderSubmitted(messageSender, order);
        marketState.updateDelayedOrder(
            messageSender,
            order.isOffchain,
            order.sizeDelta,
            order.desiredFillPrice,
            order.targetRoundId,
            order.commitDeposit,
            order.keeperDeposit,
            order.executableAtTime,
            order.intentionTime,
            order.trackingCode
        );
    }

    event DelayedOrderSubmitted(
        address indexed account,
        bool isOffchain,
        int sizeDelta,
        uint targetRoundId,
        uint intentionTime,
        uint executableAtTime,
        uint commitDeposit,
        uint keeperDeposit,
        bytes32 trackingCode
    );
    bytes32 internal constant DELAYEDORDERSUBMITTED_SIG =
        keccak256("DelayedOrderSubmitted(address,bool,int256,uint256,uint256,uint256,uint256,uint256,bytes32)");

    function emitDelayedOrderSubmitted(address account, DelayedOrder memory order) internal {
        proxy._emit(
            abi.encode(
                order.isOffchain,
                order.sizeDelta,
                order.targetRoundId,
                order.intentionTime,
                order.executableAtTime,
                order.commitDeposit,
                order.keeperDeposit,
                order.trackingCode
            ),
            2,
            DELAYEDORDERSUBMITTED_SIG,
            addressToBytes32(account),
            0,
            0
        );
    }
}

Contract ABI

[{"inputs":[{"internalType":"address payable","name":"_proxy","type":"address"},{"internalType":"address","name":"_marketState","type":"address"},{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address","name":"_resolver","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes32","name":"name","type":"bytes32"},{"indexed":false,"internalType":"address","name":"destination","type":"address"}],"name":"CacheUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"bool","name":"isOffchain","type":"bool"},{"indexed":false,"internalType":"int256","name":"sizeDelta","type":"int256"},{"indexed":false,"internalType":"uint256","name":"targetRoundId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"intentionTime","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"executableAtTime","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"commitDeposit","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"keeperDeposit","type":"uint256"},{"indexed":false,"internalType":"bytes32","name":"trackingCode","type":"bytes32"}],"name":"DelayedOrderSubmitted","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"int256","name":"funding","type":"int256"},{"indexed":false,"internalType":"int256","name":"fundingRate","type":"int256"},{"indexed":false,"internalType":"uint256","name":"index","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"timestamp","type":"uint256"}],"name":"FundingRecomputed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"oldOwner","type":"address"},{"indexed":false,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnerChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnerNominated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"trackingCode","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"baseAsset","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"marketKey","type":"bytes32"},{"indexed":false,"internalType":"int256","name":"sizeDelta","type":"int256"},{"indexed":false,"internalType":"uint256","name":"fee","type":"uint256"}],"name":"PerpsTracking","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"id","type":"uint256"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"uint256","name":"margin","type":"uint256"},{"indexed":false,"internalType":"int256","name":"size","type":"int256"},{"indexed":false,"internalType":"int256","name":"tradeSize","type":"int256"},{"indexed":false,"internalType":"uint256","name":"lastPrice","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"fundingIndex","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"fee","type":"uint256"},{"indexed":false,"internalType":"int256","name":"skew","type":"int256"}],"name":"PositionModified","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"proxyAddress","type":"address"}],"name":"ProxyUpdated","type":"event"},{"constant":false,"inputs":[],"name":"acceptOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"isResolverCached","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"marketState","outputs":[{"internalType":"contract IPerpsV2MarketState","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"messageSender","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_owner","type":"address"}],"name":"nominateNewOwner","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"nominatedOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"proxy","outputs":[{"internalType":"contract Proxy","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"rebuildCache","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"resolver","outputs":[{"internalType":"contract AddressResolver","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"resolverAddressesRequired","outputs":[{"internalType":"bytes32[]","name":"addresses","type":"bytes32[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"sender","type":"address"}],"name":"setMessageSender","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address payable","name":"_proxy","type":"address"}],"name":"setProxy","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"desiredTimeDelta","type":"uint256"},{"internalType":"uint256","name":"desiredFillPrice","type":"uint256"},{"internalType":"bytes32","name":"trackingCode","type":"bytes32"}],"name":"submitCloseDelayedOrderWithTracking","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"desiredFillPrice","type":"uint256"},{"internalType":"bytes32","name":"trackingCode","type":"bytes32"}],"name":"submitCloseOffchainDelayedOrderWithTracking","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"int256","name":"sizeDelta","type":"int256"},{"internalType":"uint256","name":"desiredTimeDelta","type":"uint256"},{"internalType":"uint256","name":"desiredFillPrice","type":"uint256"}],"name":"submitDelayedOrder","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"int256","name":"sizeDelta","type":"int256"},{"internalType":"uint256","name":"desiredTimeDelta","type":"uint256"},{"internalType":"uint256","name":"desiredFillPrice","type":"uint256"},{"internalType":"bytes32","name":"trackingCode","type":"bytes32"}],"name":"submitDelayedOrderWithTracking","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"int256","name":"sizeDelta","type":"int256"},{"internalType":"uint256","name":"desiredFillPrice","type":"uint256"}],"name":"submitOffchainDelayedOrder","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"int256","name":"sizeDelta","type":"int256"},{"internalType":"uint256","name":"desiredFillPrice","type":"uint256"},{"internalType":"bytes32","name":"trackingCode","type":"bytes32"}],"name":"submitOffchainDelayedOrderWithTracking","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]

Deployed Bytecode

0x608060405234801561001057600080fd5b50600436106101215760003560e01c806385f05ab5116100ad578063bc67f83211610071578063bc67f83214610217578063c5a4b07a1461022a578063d67bdd251461023d578063ec55688914610245578063ed44a2db1461024d57610121565b806385f05ab5146101c1578063899ffef4146101d45780638da5cb5b146101e957806397107d6d146101f1578063a1c35a351461020457610121565b80632af64bd3116100f45780632af64bd31461017457806353a47bb714610189578063741853601461019e578063787d6c30146101a657806379ba5097146101b957610121565b806304f3bcec1461012657806308fb1b771461014457806309461cfe1461014c5780631627540c14610161575b600080fd5b61012e610260565b60405161013b91906147dd565b60405180910390f35b61012e61026f565b61015f61015a366004613be9565b61027e565b005b61015f61016f366004613b19565b61036a565b61017c6103c8565b60405161013b9190614639565b6101916104e0565b60405161013b919061450d565b61015f6104ef565b61015f6101b4366004613c36565b610645565b61015f610700565b61015f6101cf366004613be9565b61079c565b6101dc610851565b60405161013b9190614628565b6101916109c3565b61015f6101ff366004613b19565b6109d2565b61015f610212366004613baf565b610a25565b61015f610225366004613b19565b610adf565b61015f610238366004613be9565b610b09565b610191610bb4565b61012e610bc3565b61015f61025b366004613baf565b610bd2565b6002546001600160a01b031681565b6004546001600160a01b031681565b610286610c7e565b6007546004805460405163fef48a9960e01b81526001600160a01b03938416939091169163fef48a99916102bc9185910161450d565b60206040518083038186803b1580156102d457600080fd5b505afa1580156102e8573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525061030c9190810190613b55565b1561034e5760056000600e5b60ff1660ff16815260200190815260200160002060405162461bcd60e51b8152600401610345919061483f565b60405180910390fd5b610364610359610caa565b858585600080610d37565b50505050565b610372611231565b600180546001600160a01b0319166001600160a01b0383161790556040517f906a1c6bd7e3091ea86693dd029a831c19049ce77f1dce2ce0bab1cacbabce22906103bd90839061450d565b60405180910390a150565b600060606103d4610851565b905060005b81518110156104d65760008282815181106103f057fe5b602090810291909101810151600081815260039092526040918290205460025492516321f8a72160e01b81529193506001600160a01b039081169216906321f8a721906104419085906004016146b1565b60206040518083038186803b15801561045957600080fd5b505afa15801561046d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052506104919190810190613b37565b6001600160a01b03161415806104bc57506000818152600360205260409020546001600160a01b0316155b156104cd57600093505050506104dd565b506001016103d9565b5060019150505b90565b6001546001600160a01b031681565b60606104f9610851565b905060005b815181101561064157600082828151811061051557fe5b602002602001015190506000600260009054906101000a90046001600160a01b03166001600160a01b031663dacb2d01838460405160200161055791906144ec565b6040516020818303038152906040526040518363ffffffff1660e01b81526004016105839291906146e8565b60206040518083038186803b15801561059b57600080fd5b505afa1580156105af573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052506105d39190810190613b37565b6000838152600360205260409081902080546001600160a01b0319166001600160a01b038416179055519091507f88a93678a3692f6789d9546fc621bf7234b101ddb7d4fe479455112831b8aa689061062f90849084906146bf565b60405180910390a150506001016104fe565b5050565b61064d610c7e565b6007546004805460405163fef48a9960e01b81526001600160a01b03938416939091169163fef48a99916106839185910161450d565b60206040518083038186803b15801561069b57600080fd5b505afa1580156106af573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052506106d39190810190613b55565b156106e35760056000600e610318565b6106f96106ee610caa565b868686866000610d37565b5050505050565b6001546001600160a01b0316331461072a5760405162461bcd60e51b815260040161034590614860565b6000546001546040517fb532073b38c83145e3e5135377a08bf9aab55bc0fd7c1179cd4fb995d2a5159c9261076d926001600160a01b0391821692911690614529565b60405180910390a160018054600080546001600160a01b03199081166001600160a01b03841617909155169055565b6107a4610c7e565b6007546004805460405163fef48a9960e01b81526001600160a01b03938416939091169163fef48a99916107da9185910161450d565b60206040518083038186803b1580156107f257600080fd5b505afa158015610806573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525061082a9190810190613b55565b1561083a5760056000600e610318565b610364610845610caa565b85600086866001610d37565b60608061085c61125b565b6040805160078082526101008201909252919250606091906020820160e0803883390190505090506822bc31b430b733b2b960b91b8160008151811061089e57fe5b6020026020010181815250506c45786368616e6765526174657360981b816001815181106108c857fe5b6020026020010181815250506b53797374656d53746174757360a01b816002815181106108f157fe5b60200260200101818152505073233aba3ab932b9a6b0b935b2ba26b0b730b3b2b960611b8160038151811061092257fe5b602002602001018181525050600080516020614afe8339815191528160048151811061094a57fe5b602002602001018181525050725065727073563245786368616e67655261746560681b8160058151811061097a57fe5b6020026020010181815250506e466c657869626c6553746f7261676560881b816006815181106109a657fe5b6020026020010181815250506109bc82826112ac565b9250505090565b6000546001600160a01b031681565b6109da611231565b600680546001600160a01b0319166001600160a01b0383161790556040517ffc80377ca9c49cc11ae6982f390a42db976d5530af7c43889264b13fbbd7c57e906103bd90839061451b565b610a2d610c7e565b6007546004805460405163fef48a9960e01b81526001600160a01b03938416939091169163fef48a9991610a639185910161450d565b60206040518083038186803b158015610a7b57600080fd5b505afa158015610a8f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250610ab39190810190613b55565b15610ac35760056000600e610318565b610ada610ace610caa565b84600085816001610d37565b505050565b610ae7610c7e565b600780546001600160a01b0319166001600160a01b0392909216919091179055565b610b11610c7e565b6007546004805460405163fef48a9960e01b81526001600160a01b03938416939091169163fef48a9991610b479185910161450d565b60206040518083038186803b158015610b5f57600080fd5b505afa158015610b73573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250610b979190810190613b55565b15610ba75760056000600e610318565b6103648484846001611368565b6007546001600160a01b031681565b6006546001600160a01b031681565b610bda610c7e565b6007546004805460405163fef48a9960e01b81526001600160a01b03938416939091169163fef48a9991610c109185910161450d565b60206040518083038186803b158015610c2857600080fd5b505afa158015610c3c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250610c609190810190613b55565b15610c705760056000600e610318565b610ada600084846002611368565b6006546001600160a01b03163314610ca85760405162461bcd60e51b815260040161034590614920565b565b6000600460009054906101000a90046001600160a01b03166001600160a01b031663d7103a466040518163ffffffff1660e01b815260040160206040518083038186803b158015610cfa57600080fd5b505afa158015610d0e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250610d329190810190613b73565b905090565b6004805460075460405163645c04d560e11b81526001600160a01b039283169363c8b809aa93610d699316910161450d565b6101206040518083038186803b158015610d8257600080fd5b505afa158015610d96573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250610dba9190810190613c97565b60200151600f0b15610dde5760405162461bcd60e51b815260040161034590614910565b83610def57610dec86611462565b93505b610df886611462565b8410158015610e0f5750610e0b86611488565b8411155b610e2b5760405162461bcd60e51b8152600401610345906148b0565b610e336138a2565b6004805460075460405163055f575160e41b81526001600160a01b03928316936355f5751093610e659316910161450d565b60a06040518083038186803b158015610e7d57600080fd5b505afa158015610e91573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250610eb59190810190613cb6565b90506000610ec2836114a8565b90506000610ed088836116aa565b90506000610edd836117e8565b9050610ee76138d0565b6040518060e001604052808b815260200185815260200184815260200189815260200187610f1d57610f188d611a2d565b610f26565b610f268d611a50565b815260200187610f3e57610f398d611a7c565b610f47565b610f478d611a9f565b815260200188905290506000610f5d8683611acb565b92505050610f6a81611dc6565b506000610f75611de7565b600754909150610f95906001600160a01b0316878d876000869003611e5a565b611067866000015167ffffffffffffffff16600760009054906101000a90046001600160a01b031688604001516001600160801b03168960800151600f0b600089896000600460009054906101000a90046001600160a01b03166001600160a01b0316632b58ecef6040518163ffffffff1660e01b815260040160206040518083038186803b15801561102757600080fd5b505afa15801561103b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525061105f9190810190613b91565b600f0b612100565b6000611071612185565b6001600160a01b0316637a018a1e6110876121a0565b6040518263ffffffff1660e01b81526004016110a391906146b1565b60206040518083038186803b1580156110bb57600080fd5b505afa1580156110cf573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052506110f39190810190613b73565b6001019050611100613910565b6040518061012001604052808a151581526020018e600f0b81526020018c6001600160801b031681526020018a611137578361113a565b60005b6001600160801b03908116825260006020830152851660408201526060018a611165578d4201611168565b60005b81524260208201526040018b905260075490915061118f906001600160a01b0316826121f0565b60048054600754835160208501516040808701516060880151608089015160a08a015160c08b015160e08c01516101008d01519651632055462760e11b81526001600160a01b039b8c169c6340aa8c4e9c6111ef9c169a99989101614544565b600060405180830381600087803b15801561120957600080fd5b505af115801561121d573d6000803e3d6000fd5b505050505050505050505050505050505050565b6000546001600160a01b03163314610ca85760405162461bcd60e51b8152600401610345906148d0565b604080516001808252818301909252606091602080830190803883390190505090506e466c657869626c6553746f7261676560881b8160008151811061129d57fe5b60200260200101818152505090565b606081518351016040519080825280602002602001820160405280156112dc578160200160208202803883390190505b50905060005b835181101561131e578381815181106112f757fe5b602002602001015182828151811061130b57fe5b60209081029190910101526001016112e2565b5060005b82518110156113615782818151811061133757fe5b602002602001015182828651018151811061134e57fe5b6020908102919091010152600101611322565b5092915050565b6113706138a2565b6004805460075460405163055f575160e41b81526001600160a01b03928316936355f57510936113a29316910161450d565b60a06040518083038186803b1580156113ba57600080fd5b505afa1580156113ce573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052506113f29190810190613cb6565b90506114098160800151600f0b600014600b6122ca565b600082600281111561141757fe5b14156114355760405162461bcd60e51b815260040161034590614850565b6106f9611440610caa565b6080830151600003600f0b878787600288600281111561145c57fe5b14610d37565b600061148282706d696e44656c617954696d6544656c746160781b6122e0565b92915050565b600061148282706d617844656c617954696d6544656c746160781b6122e0565b60006114b26123a4565b6001600160a01b031663856aae6c6114c8610caa565b6040518263ffffffff1660e01b81526004016114e491906146b1565b60006040518083038186803b1580156114fc57600080fd5b505afa158015611510573d6000803e3d6000fd5b5050505061151c6123a4565b6001600160a01b03166342a28e216115326121a0565b6040518263ffffffff1660e01b815260040161154e91906146b1565b60006040518083038186803b15801561156657600080fd5b505afa15801561157a573d6000803e3d6000fd5b5050505081156115f75761158c6123a4565b6001600160a01b031663856aae6c6115aa6115a5610caa565b6123be565b6040518263ffffffff1660e01b81526004016115c691906146b1565b60006040518083038186803b1580156115de57600080fd5b505afa1580156115f2573d6000803e3d6000fd5b505050505b6000806000611604612185565b6001600160a01b031663045056f861161a6121a0565b6040518263ffffffff1660e01b815260040161163691906146b1565b606060405180830381600087803b15801561165057600080fd5b505af1158015611664573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052506116889190810190613d22565b9250925092506116a1828061169a5750815b60016122ca565b50909392505050565b6004805460408051632b58ecef60e01b8152905160009384936001600160a01b031692632b58ecef9281830192602092829003018186803b1580156116ee57600080fd5b505afa158015611702573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052506117269190810190613b91565b600f0b9050600061173d611738610caa565b61248f565b90506000611751838363ffffffff6124a716565b9050600061177583611769868a63ffffffff6124d116565b9063ffffffff6124a716565b9050600061179961178c888563ffffffff61251716565b889063ffffffff6124d116565b905060006117bd6117b0898563ffffffff61251716565b899063ffffffff6124d116565b90506117db671bc16d674ec80000611769848463ffffffff6124d116565b9998505050505050505050565b60048054604080516366f6867560e11b8152905160009384936001600160a01b03169263cded0cea9281830192602092829003018186803b15801561182c57600080fd5b505afa158015611840573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052506118649190810190613b73565b90506000611870612541565b9050600061187d856125ee565b60048054604051637e35d8f960e11b81529293506001600160a01b03169163fc6bb1f2916118ad918591016147eb565b600060405180830381600087803b1580156118c757600080fd5b505af11580156118db573d6000803e3d6000fd5b505060048054604051634af3b2b160e11b81526001600160a01b0390911693506395e76562925061190e914291016149a8565b600060405180830381600087803b15801561192857600080fd5b505af115801561193c573d6000803e3d6000fd5b5050600480546040516315e88f9160e11b81526001600160a01b039091169350632bd11f22925061196f918691016147eb565b600060405180830381600087803b15801561198957600080fd5b505af115801561199d573d6000803e3d6000fd5b505060048054604080516313dcd11b60e11b815290516116a19550869450879389936001600160a01b0316926327b9a2369281830192602092829003018186803b1580156119ea57600080fd5b505afa1580156119fe573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250611a229190810190613d65565b63ffffffff16612649565b600061148282733a30b5b2b92332b2a232b630bcb2b227b93232b960611b6122e0565b6000611482827f74616b65724665654f6666636861696e44656c617965644f72646572000000006122e0565b6000611482827336b0b5b2b92332b2a232b630bcb2b227b93232b960611b6122e0565b6000611482827f6d616b65724665654f6666636861696e44656c617965644f72646572000000006122e0565b611ad36138a2565b81516000908190611aed575083915060009050600a611dbf565b611afb8585602001516126f9565b15611b0f5750839150600090506004611dbf565b600080611b1a612737565b915091508015611b37575085935060009250600c9150611dbf9050565b611b4186836127d4565b9350600080611b58898960400151886000036129da565b91509150611b6581612a61565b15611b7c57889650600095509350611dbf92505050565b611b846138a2565b6040518060a001604052808b6000015167ffffffffffffffff168152602001611bab612a78565b67ffffffffffffffff168152602001846001600160801b031681526020018a604001516001600160801b03168152602001611bfa8b600001518d60800151600f0b6124d190919063ffffffff16565b600f0b81525090506000611c1c8b60800151600f0b8360800151600f0b612b11565b8015611c455750611c338b60800151600f0b612b30565b611c438360800151600f0b612b30565b105b905080611c8f57611c54612b3b565b6040830151611c72906001600160801b03168a63ffffffff612ba016565b1015611c8f57508997506000965060089550611dbf945050505050565b6000611ca68360800151600f0b8c60200151612bc5565b90506000611ccf82611cc38660800151600f0b8f60200151612c27565b9063ffffffff612ba016565b9050808611611cf057509198506000975060049650611dbf95505050505050565b6000611d23611d05888d63ffffffff612ba016565b6117698f604001518860800151600f0b61251790919063ffffffff16565b9050611d2e81612b30565b611d49662386f26fc10000611cc3611d44610caa565b612c71565b1015611d6957508c9a506000995060079850611dbf975050505050505050565b50611d92611d7d611d78610caa565b612c8b565b8e60800151600f0b8660800151600f0b612ca8565b15611db057508b99506000985060069750611dbf9650505050505050565b50919850600096505050505050505b9250925092565b611dcf81612a61565b15611de4576005600082600f81111561031857fe5b50565b6000611df1612e92565b6001600160a01b03166323257c2b600080516020614afe83398151915272706572707356324d696e4b656570657246656560681b6040518363ffffffff1660e01b8152600401611e429291906146cd565b60206040518083038186803b158015610cfa57600080fd5b611e626138a2565b5083600080611e728386866129da565b91509150611e7f81611dc6565b6000611e89612a78565b9050611f496040518060a00160405280600067ffffffffffffffff1681526020018367ffffffffffffffff168152602001856001600160801b03168152602001886001600160801b031681526020018a60800151600f0b8152506040518060a00160405280600067ffffffffffffffff1681526020018b6020015167ffffffffffffffff1681526020018b604001516001600160801b031681526020018b606001516001600160801b031681526020018b60800151600f0b815250612eaf565b6001600160801b03831660408901526080880151600f0b15612064576001600160801b038616606089015267ffffffffffffffff811660208901526000851215612064576000611fa08960800151600f0b88612bc5565b90506000611fb982611cc38c60800151600f0b8b612c27565b9050611fc98186111560086122ca565b60808a0151600090611fe490600f0b8b63ffffffff6124d116565b90506000611ff98c60800151600f0b83612b11565b801561201b57506120108c60800151600f0b612b30565b61201983612b30565b105b90508061205f5761204b6120386120338e8d8b612f49565b612b30565b612043611d44610caa565b1060076122ca565b61205f612056612b3b565b881060086122ca565b505050505b600460009054906101000a90046001600160a01b03166001600160a01b0316635af0d81f8a8a600001518b602001518c604001518d606001518e608001516040518763ffffffff1660e01b81526004016120c3969594939291906145d9565b600060405180830381600087803b1580156120dd57600080fd5b505af11580156120f1573d6000803e3d6000fd5b50505050505050505050505050565b6006546040516001600160a01b039091169063907dff9790612132908a908a908a908a908a908a908a90602001614940565b604051602081830303815290604052600360405161214f906144f7565b6040519081900390208d6121628e612f6d565b60006040518763ffffffff1660e01b81526004016120c396959493929190614796565b6000610d326c45786368616e6765526174657360981b612f79565b6000600460009054906101000a90046001600160a01b03166001600160a01b031663cdf456e16040518163ffffffff1660e01b815260040160206040518083038186803b158015610cfa57600080fd5b6006548151602080840151606085015160e086015160c0870151608088015160a08901516101008a01516040516001600160a01b03909a169963907dff97996122429990989796959493929101614647565b604051602081830303815290604052600260405161225f906144e1565b604051809103902061227087612f6d565b6000806040518763ffffffff1660e01b81526004016122949695949392919061475c565b600060405180830381600087803b1580156122ae57600080fd5b505af11580156122c2573d6000803e3d6000fd5b505050505050565b8115610641576005600082600f81111561031857fe5b60006122ea612e92565b6001600160a01b03166323257c2b600080516020614afe833981519152858560405160200161231a92919061449b565b604051602081830303815290604052805190602001206040518363ffffffff1660e01b815260040161234d9291906146cd565b60206040518083038186803b15801561236557600080fd5b505afa158015612379573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525061239d9190810190613b73565b9392505050565b6000610d326b53797374656d53746174757360a01b612f79565b60006123c8612e92565b6001600160a01b031663f7833c5d600080516020614afe83398151915284706f6666636861696e4d61726b65744b657960781b60405160200161240c92919061449b565b604051602081830303815290604052805190602001206040518363ffffffff1660e01b815260040161243f9291906146cd565b60206040518083038186803b15801561245757600080fd5b505afa15801561246b573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052506114829190810190613b73565b60006114828268736b65775363616c6560b81b6122e0565b600061239d826124c585670de0b6b3a764000063ffffffff612fd616565b9063ffffffff61304116565b60008282018183128015906124e65750838112155b806124fb57506000831280156124fb57508381125b61239d5760405162461bcd60e51b815260040161034590614880565b6000670de0b6b3a7640000612532848463ffffffff612fd616565b8161253957fe5b059392505050565b6000610d326125656125516130a5565b61255961314c565b9063ffffffff61251716565b6004805460408051637226426160e11b815290516001600160a01b039092169263e44c84c2928282019260209290829003018186803b1580156125a757600080fd5b505afa1580156125bb573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052506125df9190810190613b91565b600f0b9063ffffffff6124d116565b60006114826125fc83613173565b6004546001600160a01b03166341108cf2612615612a78565b6040518263ffffffff1660e01b815260040161263191906146b1565b60206040518083038186803b1580156125a757600080fd5b6006546040516001600160a01b039091169063907dff97906126759087908790879087906020016147f9565b604051602081830303815290604052600160405161269290614502565b6040519081900381206001600160e01b031960e086901b1682526126c193929160009081908190600401614708565b600060405180830381600087803b1580156126db57600080fd5b505af11580156126ef573d6000803e3d6000fd5b5050505050505050565b60008260800151600f0b6000141561271357506000611482565b6127248360800151600f0b83612c27565b61272e8484613200565b11159392505050565b60008061274261322e565b6001600160a01b031663c39def0b631cd554d160e21b6127606121a0565b6040518363ffffffff1660e01b815260040161277d9291906146cd565b604080518083038186803b15801561279457600080fd5b505afa1580156127a8573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052506127cc9190810190613cf2565b915091509091565b6004805460408051632b58ecef60e01b8152905160009384936001600160a01b031692632b58ecef9281830192602092829003018186803b15801561281857600080fd5b505afa15801561282c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052506128509190810190613b91565b600f0b905060006128728560400151866000015161251790919063ffffffff16565b9050600061288f8561288384612b30565b9063ffffffff61324516565b90506128a18660000151840184612b11565b1561297057600061293a83600460009054906101000a90046001600160a01b03166001600160a01b0316632b58ecef6040518163ffffffff1660e01b815260040160206040518083038186803b1580156128fa57600080fd5b505afa15801561290e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052506129329190810190613b91565b600f0b612b11565b612948578660a0015161294e565b86608001515b9050612963612033848363ffffffff61251716565b8201945050505050611482565b855160009061298c90612033908681019063ffffffff6124a716565b90506000816012600a0a03905060006129b089608001516128838561288389612b30565b905060006129c98a60a00151612883856128838a612b30565b919094010198975050505050505050565b60008060006129f9846129ed888861326f565b9063ffffffff6124d116565b90506000811215612a1257506000915060089050612a59565b60808601518190600f0b6000612a288289612c27565b90508115801590612a395750808311155b15612a4e578260049550955050505050612a59565b509093506000925050505b935093915050565b60008082600f811115612a7057fe5b141592915050565b6000610d326001600460009054906101000a90046001600160a01b03166001600160a01b031663cded0cea6040518163ffffffff1660e01b815260040160206040518083038186803b158015612acd57600080fd5b505afa158015612ae1573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250612b059190810190613b73565b9063ffffffff6132a916565b6000821580612b1e575081155b8061239d575050600090811291131490565b6000611482826132d1565b6000612b45612e92565b6001600160a01b03166323257c2b600080516020614afe8339815191527f706572707356324d696e496e697469616c4d617267696e0000000000000000006040518363ffffffff1660e01b8152600401611e429291906146cd565b60008282018381101561239d5760405162461bcd60e51b815260040161034590614870565b600082612bd457506000611482565b6000612be361203385856132e7565b9050612c1f612bf8612bf3610caa565b6132f9565b61288383612883612c0a611738610caa565b612c138a612b30565b9063ffffffff61332516565b949350505050565b600080612c4a612c3d612c38610caa565b61334f565b6128838561288388612b30565b9050612c1f612c57613374565b611cc3612c6487876133d0565b849063ffffffff612ba016565b6000611482826a6d61784c6576657261676560a81b6122e0565b6000611482826d6d61784d61726b657456616c756560901b6122e0565b6000612cb48383612b11565b8015612cd05750612cc483612b30565b612ccd83612b30565b11155b15612cdd5750600061239d565b6000612d7c836129ed86600460009054906101000a90046001600160a01b03166001600160a01b0316632b58ecef6040518163ffffffff1660e01b815260040160206040518083038186803b158015612d3557600080fd5b505afa158015612d49573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250612d6d9190810190613b91565b600f0b9063ffffffff61342516565b90506000612e27612d8c856132d1565b6129ed612d98886132d1565b600480546040805163eb56105d60e01b815290516001600160a01b039092169263eb56105d928282019260209290829003018186803b158015612dda57600080fd5b505afa158015612dee573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250612e129190810190613cd4565b6001600160801b03169063ffffffff61342516565b905060008460001215612e4b57612e44828463ffffffff6124d116565b9050612e5e565b612e5b828463ffffffff61342516565b90505b612e7261203382600263ffffffff61304116565b871015612e85576001935050505061239d565b5060009695505050505050565b6000610d326e466c657869626c6553746f7261676560881b612f79565b6000612eba8361346b565b90506000612ec78361346b565b6004805460408051631169848560e11b815290519394506001600160a01b039091169263104d46f792612f2d928692612f2192899288926322d3090a92828101926020929190829003018186803b1580156125a757600080fd5b9063ffffffff61342516565b6040518263ffffffff1660e01b81526004016126c191906147eb565b600081612f585750600061239d565b612c1f826117698660800151600f0b866132e7565b6001600160a01b031690565b60008181526003602090815260408083205490516001600160a01b039091169182151591612fa9918691016144c1565b604051602081830303815290604052906113615760405162461bcd60e51b8152600401610345919061482e565b600082612fe557506000611482565b82600019148015612ff95750600160ff1b82145b156130165760405162461bcd60e51b8152600401610345906148f0565b8282028284828161302357fe5b051461239d5760405162461bcd60e51b8152600401610345906148f0565b6000816130605760405162461bcd60e51b815260040161034590614930565b816000191480156130745750600160ff1b83145b156130915760405162461bcd60e51b8152600401610345906148c0565b600082848161309c57fe5b05949350505050565b6000610d3262015180611769600460009054906101000a90046001600160a01b03166001600160a01b03166327b9a2366040518163ffffffff1660e01b815260040160206040518083038186803b1580156130ff57600080fd5b505afa158015613113573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052506131379190810190613d65565b63ffffffff16426132a990919063ffffffff16565b60008061315f61315a610caa565b613548565b905061316d81612559613569565b91505090565b60008061317e612541565b905060006131df6012600a0a60020261176984600460009054906101000a90046001600160a01b03166001600160a01b031663e44c84c26040518163ffffffff1660e01b815260040160206040518083038186803b1580156125a757600080fd5b6000039050612c1f846125596131f36130a5565b849063ffffffff61251716565b6000806132216132178560800151600f0b85612bc5565b612f21868661326f565b9050612c1f600082613629565b6000610d326822bc31b430b733b2b960b91b612f79565b6000670de0b6b3a7640000613260848463ffffffff61363e16565b8161326757fe5b049392505050565b60008061327c8484613678565b9050612c1f816129ed61328f87876136c9565b60408801516001600160801b03169063ffffffff6124d116565b6000828211156132cb5760405162461bcd60e51b815260040161034590614890565b50900390565b60008082126132e05781611482565b5060000390565b600061239d838363ffffffff61251716565b6000611482827f6c69717569646174696f6e5072656d69756d4d756c7469706c696572000000006122e0565b600061239d8261334385670de0b6b3a764000063ffffffff61363e16565b9063ffffffff61370716565b600061148282756c69717569646174696f6e427566666572526174696f60501b6122e0565b600061337e612e92565b6001600160a01b03166323257c2b600080516020614afe833981519152736b65657065724c69717569646174696f6e46656560601b6040518363ffffffff1660e01b8152600401611e429291906146cd565b6000806133de612c3d61373c565b905060006133ea6137a1565b905060008183116133fb57826133fd565b815b90506000613409611de7565b9050808211613418578061341a565b815b979650505050505050565b600081830381831280159061343a5750838113155b8061344f575060008312801561344f57508381135b61239d5760405162461bcd60e51b815260040161034590614900565b600480546020830151604051632088467960e11b81526000936114829361352e9361351a936001600160a01b03909216926341108cf2926134ad9291016149b6565b60206040518083038186803b1580156134c557600080fd5b505afa1580156134d9573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052506134fd9190810190613b91565b60608601516001600160801b031690600f0b63ffffffff6124d116565b6080850151600f0b9063ffffffff61251716565b60408401516001600160801b03169063ffffffff61342516565b600061148282716d617846756e64696e6756656c6f6369747960701b6122e0565b60008061360361357a611738610caa565b6004805460408051632b58ecef60e01b815290516001600160a01b0390921692632b58ecef928282019260209290829003018186803b1580156135bc57600080fd5b505afa1580156135d0573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052506135f49190810190613b91565b600f0b9063ffffffff6124a716565b905061316d61361b670de0b6b3a763ffff1983613629565b670de0b6b3a76400006137fc565b6000818312613638578261239d565b50919050565b60008261364d57506000611482565b8282028284828161365a57fe5b041461239d5760405162461bcd60e51b8152600401610345906148e0565b602082015160009067ffffffffffffffff1680613699576000915050611482565b60006136a58285613812565b60808601519091506136c090600f0b8263ffffffff61251716565b95945050505050565b6000806136ec84606001516001600160801b03168461342590919063ffffffff16565b6080850151909150612c1f90600f0b8263ffffffff61251716565b60008082116137285760405162461bcd60e51b8152600401610345906148a0565b600082848161373357fe5b04949350505050565b6000613746612e92565b6001600160a01b03166323257c2b600080516020614afe8339815191527f706572707356324c69717569646174696f6e466565526174696f0000000000006040518363ffffffff1660e01b8152600401611e429291906146cd565b60006137ab612e92565b6001600160a01b03166323257c2b600080516020614afe83398151915272706572707356324d61784b656570657246656560681b6040518363ffffffff1660e01b8152600401611e429291906146cd565b600081831261380b578161239d565b5090919050565b60048054604051632088467960e11b815260009261239d926001600160a01b0316916341108cf291613846918891016146b1565b60206040518083038186803b15801561385e57600080fd5b505afa158015613872573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052506138969190810190613b91565b600f0b612f21846125ee565b6040805160a08101825260008082526020820181905291810182905260608101829052608081019190915290565b6040518060e00160405280600081526020016000815260200160008152602001600081526020016000815260200160008152602001600080191681525090565b6040805161012081018252600080825260208201819052918101829052606081018290526080810182905260a0810182905260c0810182905260e0810182905261010081019190915290565b803561148281614ab3565b805161148281614ab3565b805161148281614ac7565b803561148281614ad0565b805161148281614ad0565b805161148281614ad9565b600061012082840312156139b157600080fd5b6139bc6101206149c4565b905060006139ca8484613972565b82525060206139db84848301613993565b60208301525060406139ef84828501613af8565b6040830152506060613a0384828501613af8565b6060830152506080613a1784828501613af8565b60808301525060a0613a2b84828501613af8565b60a08301525060c0613a3f84828501613988565b60c08301525060e0613a5384828501613988565b60e083015250610100613a6884828501613988565b6101008301525092915050565b600060a08284031215613a8757600080fd5b613a9160a06149c4565b90506000613a9f8484613b0e565b8252506020613ab084848301613b0e565b6020830152506040613ac484828501613af8565b6040830152506060613ad884828501613af8565b6060830152506080613aec84828501613993565b60808301525092915050565b805161148281614ae2565b805161148281614aeb565b805161148281614af4565b600060208284031215613b2b57600080fd5b6000612c1f848461395c565b600060208284031215613b4957600080fd5b6000612c1f8484613967565b600060208284031215613b6757600080fd5b6000612c1f8484613972565b600060208284031215613b8557600080fd5b6000612c1f8484613988565b600060208284031215613ba357600080fd5b6000612c1f8484613993565b60008060408385031215613bc257600080fd5b6000613bce858561397d565b9250506020613bdf8582860161397d565b9150509250929050565b600080600060608486031215613bfe57600080fd5b6000613c0a868661397d565b9350506020613c1b8682870161397d565b9250506040613c2c8682870161397d565b9150509250925092565b60008060008060808587031215613c4c57600080fd5b6000613c58878761397d565b9450506020613c698782880161397d565b9350506040613c7a8782880161397d565b9250506060613c8b8782880161397d565b91505092959194509250565b60006101208284031215613caa57600080fd5b6000612c1f848461399e565b600060a08284031215613cc857600080fd5b6000612c1f8484613a75565b600060208284031215613ce657600080fd5b6000612c1f8484613af8565b60008060408385031215613d0557600080fd5b6000613d118585613988565b9250506020613bdf85828601613972565b600080600060608486031215613d3757600080fd5b6000613d438686613988565b9350506020613d5486828701613972565b9250506040613c2c86828701613972565b600060208284031215613d7757600080fd5b6000612c1f8484613b03565b6000613d8f8383613e11565b505060200190565b613da081614a47565b82525050565b613da081614a0f565b6000613dba826149fd565b613dc48185614a01565b9350613dcf836149eb565b8060005b83811015613dfd578151613de78882613d83565b9750613df2836149eb565b925050600101613dd3565b509495945050505050565b613da081614a1a565b613da0816104dd565b613da0613e26826104dd565b6104dd565b6000613e36826149fd565b613e408185614a01565b9350613e50818560208601614a7d565b613e5981614aa9565b9093019392505050565b613da081614a4e565b613da081614a1f565b613da081614a59565b613da081614a67565b600081546001811660008114613ea45760018114613eca57613f09565b607f6002830416613eb58187614a01565b60ff1984168152955050602085019250613f09565b60028204613ed88187614a01565b9550613ee3856149f1565b60005b82811015613f0257815488820152600190910190602001613ee6565b8701945050505b505092915050565b6000613f1e601283614a01565b71696e76616c6964206f72646572207479706560701b815260200192915050565b6000613f4c603583614a01565b7f596f75206d757374206265206e6f6d696e61746564206265666f726520796f7581527402063616e20616363657074206f776e65727368697605c1b602082015260400192915050565b6000613fa3601b83614a01565b7f536166654d6174683a206164646974696f6e206f766572666c6f770000000000815260200192915050565b6000613fdc602183614a01565b7f5369676e6564536166654d6174683a206164646974696f6e206f766572666c6f8152607760f81b602082015260400192915050565b600061401f601e83614a01565b7f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815260200192915050565b6000614058601a83614a01565b7f536166654d6174683a206469766973696f6e206279207a65726f000000000000815260200192915050565b6000614091601183614a0a565b70026b4b9b9b4b7339030b2323932b9b99d1607d1b815260110192915050565b60006140be601383614a01565b7264656c6179206f7574206f6620626f756e647360681b815260200192915050565b60006140ed602183614a01565b7f5369676e6564536166654d6174683a206469766973696f6e206f766572666c6f8152607760f81b602082015260400192915050565b6000614130602f83614a01565b7f4f6e6c792074686520636f6e7472616374206f776e6572206d6179207065726681526e37b936903a3434b99030b1ba34b7b760891b602082015260400192915050565b6000614181602183614a01565b7f536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f8152607760f81b602082015260400192915050565b60006141c4605a83614a0a565b7f44656c617965644f726465725375626d697474656428616464726573732c626f81527f6f6c2c696e743235362c75696e743235362c75696e743235362c75696e74323560208201527f362c75696e743235362c75696e743235362c62797465733332290000000000006040820152605a0192915050565b6000614249602783614a01565b7f5369676e6564536166654d6174683a206d756c7469706c69636174696f6e206f815266766572666c6f7760c81b602082015260400192915050565b6000614292601983614a0a565b7f5265736f6c766572206d697373696e67207461726765743a2000000000000000815260190192915050565b60006142cb605683614a0a565b7f506f736974696f6e4d6f6469666965642875696e743235362c6164647265737381527f2c75696e743235362c696e743235362c696e743235362c75696e743235362c75602082015275696e743235362c75696e743235362c696e743235362960501b604082015260560192915050565b6000614349602483614a01565b7f5369676e6564536166654d6174683a207375627472616374696f6e206f766572815263666c6f7760e01b602082015260400192915050565b600061438f601583614a01565b7470726576696f7573206f726465722065786973747360581b815260200192915050565b60006143c0601783614a01565b7f4f6e6c79207468652070726f78792063616e2063616c6c000000000000000000815260200192915050565b60006143f9602083614a01565b7f5369676e6564536166654d6174683a206469766973696f6e206279207a65726f815260200192915050565b6000614432603083614a0a565b7f46756e64696e675265636f6d707574656428696e743235362c696e743235362c81526f75696e743235362c75696e743235362960801b602082015260300192915050565b613da081614a25565b613da081614a31565b613da081614a72565b613da081614a3a565b60006144a78285613e1a565b6020820191506144b78284613e1a565b5060200192915050565b60006144cc82614084565b91506144d88284613e1a565b50602001919050565b6000611482826141b7565b60006144cc82614285565b6000611482826142be565b600061148282614425565b602081016114828284613da6565b602081016114828284613d97565b604081016145378285613da6565b61239d6020830184613da6565b6101408101614553828d613da6565b614560602083018c613e08565b61456d604083018b613e6c565b61457a606083018a614477565b6145876080830189614477565b61459460a0830188614477565b6145a160c0830187614477565b6145ae60e0830186613e11565b6145bc610100830185613e11565b6145ca610120830184613e11565b9b9a5050505050505050505050565b60c081016145e78289613da6565b6145f46020830188614492565b6146016040830187614492565b61460e6060830186614477565b61461b6080830185614477565b61341a60a0830184613e6c565b6020808252810161239d8184613daf565b602081016114828284613e08565b6101008101614656828b613e08565b614663602083018a613e6c565b6146706040830189614477565b61467d6060830188613e11565b61468a6080830187613e11565b61469760a0830186614477565b6146a460c0830185614477565b6117db60e0830184613e11565b602081016114828284613e11565b604081016145378285613e11565b604081016146db8285613e11565b61239d6020830184613e11565b604081016146f68285613e11565b8181036020830152612c1f8184613e2b565b60c080825281016147198189613e2b565b90506147286020830188613e7e565b6147356040830187613e11565b6147426060830186613e75565b61474f6080830185613e75565b61341a60a0830184613e75565b60c0808252810161476d8189613e2b565b905061477c6020830188613e7e565b6147896040830187613e11565b6147426060830186613e11565b60c080825281016147a78189613e2b565b90506147b66020830188613e7e565b6147c36040830187613e11565b6147d06060830186613e11565b61474f6080830185613e11565b602081016114828284613e63565b602081016114828284613e6c565b608081016148078287613e11565b6148146020830186613e11565b6148216040830185613e11565b6136c06060830184613e11565b6020808252810161239d8184613e2b565b6020808252810161239d8184613e87565b6020808252810161148281613f11565b6020808252810161148281613f3f565b6020808252810161148281613f96565b6020808252810161148281613fcf565b6020808252810161148281614012565b602080825281016114828161404b565b60208082528101611482816140b1565b60208082528101611482816140e0565b6020808252810161148281614123565b6020808252810161148281614174565b602080825281016114828161423c565b602080825281016114828161433c565b6020808252810161148281614382565b60208082528101611482816143b3565b60208082528101611482816143ec565b60e0810161494e828a613e11565b61495b6020830189613e11565b6149686040830188613e11565b6149756060830187613e11565b6149826080830186613e11565b61498f60a0830185613e11565b61499c60c0830184613e11565b98975050505050505050565b602081016114828284614480565b602081016114828284614489565b60405181810167ffffffffffffffff811182821017156149e357600080fd5b604052919050565b60200190565b60009081526020902090565b5190565b90815260200190565b919050565b600061148282612f6d565b151590565b600f0b90565b6001600160801b031690565b63ffffffff1690565b67ffffffffffffffff1690565b6000611482825b600061148282614a0f565b6000611482613e26836104dd565b6000611482826104dd565b600061148282614a3a565b60005b83811015614a98578181015183820152602001614a80565b838111156103645750506000910152565b601f01601f191690565b614abc81614a0f565b8114611de457600080fd5b614abc81614a1a565b614abc816104dd565b614abc81614a1f565b614abc81614a25565b614abc81614a31565b614abc81614a3a56fe506572707356324d61726b657453657474696e67730000000000000000000000a365627a7a72315820231ef69835bcad00e57cc37857ad92a7aaf335e7bac7e0897985e6e64a4c8c1f6c6578706572696d656e74616cf564736f6c63430005100040

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  ]

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.