Overview
ETH Balance
0 ETH
ETH Value
$0.00More Info
Private Name Tags
ContractCreator
Loading...
Loading
Contract Name:
ChainlinkPriceOracleV1
Compiler Version
v0.5.16+commit.9c3226ce
Optimization Enabled:
Yes with 10000 runs
Other Settings:
default evmVersion
Contract Source Code (Solidity Standard Json-Input format)
/* Copyright 2020 Dolomite. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.7; pragma experimental ABIEncoderV2; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { Monetary } from "../../protocol/lib/Monetary.sol"; import { Require } from "../../protocol/lib/Require.sol"; import { OnlyDolomiteMargin } from "../helpers/OnlyDolomiteMargin.sol"; import { IChainlinkAggregator } from "../interfaces/IChainlinkAggregator.sol"; import { IChainlinkAccessControlAggregator } from "../interfaces/IChainlinkAccessControlAggregator.sol"; import { IChainlinkPriceOracleV1 } from "../interfaces/IChainlinkPriceOracleV1.sol"; /** * @title ChainlinkPriceOracleV1 * @author Dolomite * * An implementation of the IPriceOracle interface that makes Chainlink prices compatible with the protocol. */ contract ChainlinkPriceOracleV1 is IChainlinkPriceOracleV1, OnlyDolomiteMargin { using SafeMath for uint; // ========================= Constants ========================= bytes32 private constant FILE = "ChainlinkPriceOracleV1"; // ========================= Storage ========================= mapping(address => IChainlinkAggregator) private _tokenToAggregatorMap; mapping(address => uint8) private _tokenToDecimalsMap; /// @dev Defaults to USD if the value is the ZERO address mapping(address => address) private _tokenToPairingMap; uint256 public stalenessThreshold; // ========================= Constructor ========================= /** * Note, these arrays are set up such that each index corresponds with one-another. * * @param _tokens The tokens that are supported by this adapter. * @param _chainlinkAggregators The Chainlink aggregators that have on-chain prices. * @param _tokenDecimals The number of decimals that each token has. * @param _tokenPairs The token against which this token's value is compared using the aggregator. The * zero address means USD. * @param _dolomiteMargin The address of the DolomiteMargin contract. */ constructor( address[] memory _tokens, address[] memory _chainlinkAggregators, uint8[] memory _tokenDecimals, address[] memory _tokenPairs, address _dolomiteMargin ) public OnlyDolomiteMargin(_dolomiteMargin) { Require.that( _tokens.length == _chainlinkAggregators.length, FILE, "Invalid tokens length" ); Require.that( _chainlinkAggregators.length == _tokenDecimals.length, FILE, "Invalid aggregators length" ); Require.that( _tokenDecimals.length == _tokenPairs.length, FILE, "Invalid decimals length" ); uint256 tokensLength = _tokens.length; for (uint256 i; i < tokensLength; ++i) { _ownerInsertOrUpdateOracleToken( _tokens[i], _tokenDecimals[i], _chainlinkAggregators[i], _tokenPairs[i] ); } _ownerSetStalenessThreshold(36 hours); } // ========================= Admin Functions ========================= function ownerSetStalenessThreshold( uint256 _stalenessThreshold ) external onlyDolomiteMarginOwner(msg.sender) { _ownerSetStalenessThreshold(_stalenessThreshold); } function ownerInsertOrUpdateOracleToken( address _token, uint8 _tokenDecimals, address _chainlinkAggregator, address _tokenPair ) external onlyDolomiteMarginOwner(msg.sender) { _ownerInsertOrUpdateOracleToken( _token, _tokenDecimals, _chainlinkAggregator, _tokenPair ); } // ========================= Public Functions ========================= function getPrice( address _token ) public view returns (Monetary.Price memory) { Require.that( address(_tokenToAggregatorMap[_token]) != address(0), FILE, "Invalid token", _token ); IChainlinkAggregator aggregatorProxy = _tokenToAggregatorMap[_token]; ( /* uint80 roundId */, int256 answer, /* uint256 startedAt */, uint256 updatedAt, /* uint80 answeredInRound */ ) = aggregatorProxy.latestRoundData(); Require.that( block.timestamp.sub(updatedAt) < stalenessThreshold, FILE, "Chainlink price expired", _token ); IChainlinkAccessControlAggregator controlAggregator = aggregatorProxy.aggregator(); Require.that( controlAggregator.minAnswer() < answer, FILE, "Chainlink price too low" ); Require.that( answer < controlAggregator.maxAnswer(), FILE, "Chainlink price too high" ); uint256 chainlinkPrice = uint256(answer); address tokenPair = _tokenToPairingMap[_token]; // standardize the Chainlink price to be the proper number of decimals of (36 - tokenDecimals) uint256 standardizedPrice = standardizeNumberOfDecimals( _tokenToDecimalsMap[_token], chainlinkPrice, aggregatorProxy.decimals() ); if (tokenPair == address(0)) { // The pair has a USD base, we are done. return Monetary.Price({ value: standardizedPrice }); } else { // The price we just got and converted is NOT against USD. So we need to get its pair's price against USD. // We can do so by recursively calling #getPrice using the `tokenPair` as the parameter instead of `token`. uint256 tokenPairPrice = getPrice(tokenPair).value; // Standardize the price to use 36 decimals. uint256 tokenPairWith36Decimals = tokenPairPrice.mul(10 ** uint(_tokenToDecimalsMap[tokenPair])); // Now that the chained price uses 36 decimals (and thus is standardized), we can do easy math. return Monetary.Price({ value: standardizedPrice.mul(tokenPairWith36Decimals).div(ONE_DOLLAR) }); } } /** * Standardizes `value` to have `ONE_DOLLAR.decimals` - `tokenDecimals` number of decimals. */ function standardizeNumberOfDecimals( uint8 _tokenDecimals, uint256 _value, uint8 _valueDecimals ) public pure returns (uint) { uint256 tokenDecimalsFactor = 10 ** uint(_tokenDecimals); uint256 priceFactor = ONE_DOLLAR.div(tokenDecimalsFactor); uint256 valueFactor = 10 ** uint(_valueDecimals); return _value.mul(priceFactor).div(valueFactor); } function getAggregatorByToken(address _token) public view returns (IChainlinkAggregator) { return _tokenToAggregatorMap[_token]; } function getDecimalsByToken(address _token) public view returns (uint8) { return _tokenToDecimalsMap[_token]; } function getTokenPairByToken(address _token) public view returns (address _tokenPair) { return _tokenToPairingMap[_token]; } // ========================= Internal Functions ========================= function _ownerSetStalenessThreshold( uint256 _stalenessThreshold ) internal { Require.that( _stalenessThreshold >= 24 hours, FILE, "Staleness threshold too low", _stalenessThreshold ); Require.that( _stalenessThreshold <= 7 days, FILE, "Staleness threshold too high", _stalenessThreshold ); stalenessThreshold = _stalenessThreshold; emit StalenessDurationUpdated(_stalenessThreshold); } function _ownerInsertOrUpdateOracleToken( address _token, uint8 _tokenDecimals, address _chainlinkAggregator, address _tokenPair ) internal { _tokenToAggregatorMap[_token] = IChainlinkAggregator(_chainlinkAggregator); _tokenToDecimalsMap[_token] = _tokenDecimals; if (_tokenPair != address(0)) { Require.that( address(_tokenToAggregatorMap[_tokenPair]) != address(0), FILE, "Invalid token pair", _tokenPair ); // The aggregator's price is NOT against USD. Therefore, we need to store what it's against as well as the // # of decimals the aggregator's price has. _tokenToPairingMap[_token] = _tokenPair; } emit TokenInsertedOrUpdated(_token, _chainlinkAggregator, _tokenPair); } }
/* Copyright 2019 dYdX Trading Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.7; pragma experimental ABIEncoderV2; import { Require } from "./Require.sol"; /** * @title Bits * @author Dolomite * * Library for caching information about markets */ library Bits { // ============ Constants ============ uint256 internal constant ONE = 1; uint256 internal constant MAX_UINT_BITS = 256; // ============ Functions ============ function createBitmaps(uint256 maxLength) internal pure returns (uint256[] memory) { return new uint256[]((maxLength / MAX_UINT_BITS) + ONE); } function getMarketIdFromBit( uint256 index, uint256 bit ) internal pure returns (uint256) { return (MAX_UINT_BITS * index) + bit; } function setBit( uint256[] memory bitmaps, uint256 marketId ) internal pure { uint256 bucketIndex = marketId / MAX_UINT_BITS; uint256 indexFromRight = marketId % MAX_UINT_BITS; bitmaps[bucketIndex] |= (ONE << indexFromRight); } function hasBit( uint256[] memory bitmaps, uint256 marketId ) internal pure returns (bool) { uint256 bucketIndex = marketId / MAX_UINT_BITS; uint256 indexFromRight = marketId % MAX_UINT_BITS; uint256 bit = bitmaps[bucketIndex] & (ONE << indexFromRight); return bit != 0; } function unsetBit( uint256 bitmap, uint256 bit ) internal pure returns (uint256) { return bitmap & ~(ONE << bit); } // solium-disable security/no-assign-params function getLeastSignificantBit(uint256 x) internal pure returns (uint256) { // gas usage peaks at 350 per call uint256 lsb = 255; if (x & uint128(-1) != 0) { lsb -= 128; } else { x >>= 128; } if (x & uint64(-1) != 0) { lsb -= 64; } else { x >>= 64; } if (x & uint32(-1) != 0) { lsb -= 32; } else { x >>= 32; } if (x & uint16(-1) != 0) { lsb -= 16; } else { x >>= 16; } if (x & uint8(-1) != 0) { lsb -= 8; } else { x >>= 8; } if (x & 0xf != 0) { lsb -= 4; } else { x >>= 4; } if (x & 0x3 != 0) { lsb -= 2; } else { x >>= 2; // solium-enable security/no-assign-params } if (x & 0x1 != 0) { lsb -= 1; } return lsb; } }
/* Copyright 2019 dYdX Trading Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.7; pragma experimental ABIEncoderV2; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { DolomiteMarginMath } from "./DolomiteMarginMath.sol"; /** * @title Types * @author dYdX * * Library for interacting with the basic structs used in DolomiteMargin */ library Types { using DolomiteMarginMath for uint256; // ============ Permission ============ struct OperatorArg { address operator; bool trusted; } // ============ AssetAmount ============ enum AssetDenomination { Wei, // the amount is denominated in wei Par // the amount is denominated in par } enum AssetReference { Delta, // the amount is given as a delta from the current value Target // the amount is given as an exact number to end up at } struct AssetAmount { bool sign; // true if positive AssetDenomination denomination; AssetReference ref; uint256 value; } // ============ Par (Principal Amount) ============ // Total borrow and supply values for a market struct TotalPar { uint128 borrow; uint128 supply; } // Individual principal amount for an account struct Par { bool sign; // true if positive uint128 value; } function zeroPar() internal pure returns (Par memory) { return Par({ sign: false, value: 0 }); } function sub( Par memory a, Par memory b ) internal pure returns (Par memory) { return add(a, negative(b)); } function add( Par memory a, Par memory b ) internal pure returns (Par memory) { Par memory result; if (a.sign == b.sign) { result.sign = a.sign; result.value = SafeMath.add(a.value, b.value).to128(); } else { if (a.value >= b.value) { result.sign = a.sign; result.value = SafeMath.sub(a.value, b.value).to128(); } else { result.sign = b.sign; result.value = SafeMath.sub(b.value, a.value).to128(); } } return result; } function equals( Par memory a, Par memory b ) internal pure returns (bool) { if (a.value == b.value) { if (a.value == 0) { return true; } return a.sign == b.sign; } return false; } function negative( Par memory a ) internal pure returns (Par memory) { return Par({ sign: !a.sign, value: a.value }); } function isNegative( Par memory a ) internal pure returns (bool) { return !a.sign && a.value != 0; } function isPositive( Par memory a ) internal pure returns (bool) { return a.sign && a.value != 0; } function isZero( Par memory a ) internal pure returns (bool) { return a.value == 0; } function isLessThanZero( Par memory a ) internal pure returns (bool) { return a.value != 0 && !a.sign; } function isGreaterThanOrEqualToZero( Par memory a ) internal pure returns (bool) { return isZero(a) || a.sign; } // ============ Wei (Token Amount) ============ struct TotalWei { uint128 borrow; uint128 supply; } // Individual token amount for an account struct Wei { bool sign; // true if positive uint256 value; } function zeroWei() internal pure returns (Wei memory) { return Wei({ sign: false, value: 0 }); } function sub( Wei memory a, Wei memory b ) internal pure returns (Wei memory) { return add(a, negative(b)); } function add( Wei memory a, Wei memory b ) internal pure returns (Wei memory) { Wei memory result; if (a.sign == b.sign) { result.sign = a.sign; result.value = SafeMath.add(a.value, b.value); } else { if (a.value >= b.value) { result.sign = a.sign; result.value = SafeMath.sub(a.value, b.value); } else { result.sign = b.sign; result.value = SafeMath.sub(b.value, a.value); } } return result; } function equals( Wei memory a, Wei memory b ) internal pure returns (bool) { if (a.value == b.value) { if (a.value == 0) { return true; } return a.sign == b.sign; } return false; } function negative( Wei memory a ) internal pure returns (Wei memory) { return Wei({ sign: !a.sign, value: a.value }); } function isNegative( Wei memory a ) internal pure returns (bool) { return !a.sign && a.value != 0; } function isPositive( Wei memory a ) internal pure returns (bool) { return a.sign && a.value != 0; } function isZero( Wei memory a ) internal pure returns (bool) { return a.value == 0; } }
/* Copyright 2019 dYdX Trading Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.7; pragma experimental ABIEncoderV2; import { IERC20Detailed } from "../interfaces/IERC20Detailed.sol"; /** * @title Token * @author dYdX * * This library contains basic functions for interacting with ERC20 tokens. Modified to work with * tokens that don't adhere strictly to the ERC20 standard (for example tokens that don't return a * boolean value on success). */ library Token { // ============ Library Functions ============ function transfer( address token, address to, uint256 amount ) internal { if (amount == 0 || to == address(this)) { return; } _callOptionalReturn( token, abi.encodeWithSelector(IERC20Detailed(token).transfer.selector, to, amount), "Token: transfer failed" ); } function transferFrom( address token, address from, address to, uint256 amount ) internal { if (amount == 0 || to == from) { return; } // solium-disable arg-overflow _callOptionalReturn( token, abi.encodeWithSelector(IERC20Detailed(token).transferFrom.selector, from, to, amount), "Token: transferFrom failed" ); // solium-enable arg-overflow } // ============ Private Functions ============ function _callOptionalReturn(address token, bytes memory data, string memory error) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to contain contract code. Not needed since tokens are manually added // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solium-disable-next-line security/no-low-level-calls (bool success, bytes memory returnData) = token.call(data); require(success, error); if (returnData.length != 0) { // Return data is optional require(abi.decode(returnData, (bool)), error); } } }
/* Copyright 2019 dYdX Trading Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.7; pragma experimental ABIEncoderV2; import { DolomiteMarginMath } from "./DolomiteMarginMath.sol"; /** * @title Time * @author dYdX * * Library for dealing with time, assuming timestamps fit within 32 bits (valid until year 2106) */ library Time { // ============ Library Functions ============ function currentTime() internal view returns (uint32) { return DolomiteMarginMath.to32(block.timestamp); } }
/* Copyright 2019 dYdX Trading Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.7; pragma experimental ABIEncoderV2; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { Account } from "./Account.sol"; import { Bits } from "./Bits.sol"; import { Cache } from "./Cache.sol"; import { Decimal } from "./Decimal.sol"; import { Interest } from "./Interest.sol"; import { EnumerableSet } from "./EnumerableSet.sol"; import { DolomiteMarginMath } from "./DolomiteMarginMath.sol"; import { Monetary } from "./Monetary.sol"; import { Require } from "./Require.sol"; import { Time } from "./Time.sol"; import { Token } from "./Token.sol"; import { Types } from "./Types.sol"; import { IAccountRiskOverrideSetter } from "../interfaces/IAccountRiskOverrideSetter.sol"; import { IERC20Detailed } from "../interfaces/IERC20Detailed.sol"; import { IInterestSetter } from "../interfaces/IInterestSetter.sol"; import { IOracleSentinel } from "../interfaces/IOracleSentinel.sol"; import { IPriceOracle } from "../interfaces/IPriceOracle.sol"; /** * @title Storage * @author dYdX * * Functions for reading, writing, and verifying state in DolomiteMargin */ library Storage { using Cache for Cache.MarketCache; using Storage for Storage.State; using DolomiteMarginMath for uint256; using Types for Types.Par; using Types for Types.Wei; using SafeMath for uint256; using EnumerableSet for EnumerableSet.Set; // ============ Constants ============ bytes32 private constant FILE = "Storage"; // ============ Structs ============ // All information necessary for tracking a market struct Market { // Contract address of the associated ERC20 token address token; // Whether additional borrows are allowed for this market bool isClosing; // Total aggregated supply and borrow amount of the entire market Types.TotalPar totalPar; // Interest index of the market Interest.Index index; // Contract address of the price oracle for this market IPriceOracle priceOracle; // Contract address of the interest setter for this market IInterestSetter interestSetter; // Multiplier on the marginRatio for this market, IE 5% (0.05 * 1e18). This number increases the market's // required collateralization by: reducing the user's supplied value (in terms of dollars) for this market and // increasing its borrowed value. This is done through the following operation: // `suppliedWei = suppliedWei + (assetValueForThisMarket / (1 + marginPremium))` // This number increases the user's borrowed wei by multiplying it by: // `borrowedWei = borrowedWei + (assetValueForThisMarket * (1 + marginPremium))` Decimal.D256 marginPremium; // Multiplier on the liquidationSpread for this market, IE 20% (0.2 * 1e18). This number increases the // `liquidationSpread` using the following formula: // `liquidationSpread = liquidationSpread * (1 + spreadPremium)` // NOTE: This formula is applied up to two times - one for each market whose spreadPremium is greater than 0 // (when performing a liquidation between two markets) Decimal.D256 liquidationSpreadPremium; // The maximum amount that can be held by the protocol. This allows the protocol to cap any additional risk // that is inferred by allowing borrowing against low-cap or assets with increased volatility. Setting this // value to 0 is analogous to having no limit. This value can never be below 0. Types.Wei maxSupplyWei; // The maximum amount that can be borrowed by the protocol. This allows the protocol to cap any additional risk // that is inferred by allowing borrowing against low-cap or assets with increased volatility. Setting this // value to 0 is analogous to having no limit. This value can never be greater than 0. Types.Wei maxBorrowWei; // The percentage of interest paid that is passed along from borrowers to suppliers. Setting this to 0 will // default to RiskParams.earningsRate. Decimal.D256 earningsRateOverride; } // The global risk parameters that govern the health and security of the system struct RiskParams { // Required ratio of over-collateralization Decimal.D256 marginRatio; // Percentage penalty incurred by liquidated accounts Decimal.D256 liquidationSpread; // Percentage of the borrower's interest fee that gets passed to the suppliers Decimal.D256 earningsRate; // The minimum absolute borrow value of an account // There must be sufficient incentivize to liquidate undercollateralized accounts Monetary.Value minBorrowedValue; // The maximum number of markets a user can have a non-zero balance for a given account. uint256 accountMaxNumberOfMarketsWithBalances; // The oracle sentinel used to disable borrowing/liquidations if the sequencer goes down IOracleSentinel oracleSentinel; // The gas limit used for making callbacks via `IExternalCallback::onInternalBalanceChange` to smart contract // wallets. Setting to 0 will effectively disable callbacks; setting it super large is not desired since it // could lead to DOS attacks on the protocol; however, hard coding a max value isn't preferred since some chains // can calculate gas usage differently (like ArbGas before Arbitrum rolled out nitro) uint256 callbackGasLimit; // The default account risk override setter. By default, we ping this for any overrides in risk controls, // if the `accountRiskOverrideSetterMap` resolves to 0x0. If this value is set to `0x0` there is no default. IAccountRiskOverrideSetter defaultAccountRiskOverrideSetter; // Certain addresses are allowed to borrow with different LTV requirements. When an account's risk is overrode, // the global risk parameters are ignored and the account's risk parameters are used instead. mapping(address => IAccountRiskOverrideSetter) accountRiskOverrideSetterMap; } // The maximum RiskParam values that can be set struct RiskLimits { // The highest that the ratio can be for liquidating under-water accounts uint64 marginRatioMax; // The highest that the liquidation rewards can be when a liquidator liquidates an account uint64 liquidationSpreadMax; // The highest that the supply APR can be for a market, as a proportion of the borrow rate. Meaning, a rate of // 100% (1e18) would give suppliers all of the interest that borrowers are paying. A rate of 90% would give // suppliers 90% of the interest that borrowers pay. uint64 earningsRateMax; // The highest min margin ratio premium that can be applied to a particular market. Meaning, a value of 100% // (1e18) would require borrowers to maintain an extra 100% collateral to maintain a healthy margin ratio. This // value works by increasing the debt owed and decreasing the supply held for the particular market by this // amount, plus 1e18 (since a value of 10% needs to be applied as `decimal.plusOne`) uint64 marginPremiumMax; // The highest liquidation reward that can be applied to a particular market. This percentage is applied // in addition to the liquidation spread in `RiskParams`. Meaning a value of 1e18 is 100%. It is calculated as: // `liquidationSpread * Decimal.onePlus(spreadPremium)` uint64 liquidationSpreadPremiumMax; // The highest that the borrow interest rate can ever be. If the rate returned is ever higher, the rate is // capped at this value instead of reverting. The goal is to keep Dolomite operational under all circumstances // instead of inadvertently DOS'ing the protocol. uint96 interestRateMax; // The highest that the minBorrowedValue can be. This is the minimum amount of value that must be borrowed. // Typically a value of $100 (100 * 1e18) is more than sufficient. uint128 minBorrowedValueMax; } // The entire storage state of DolomiteMargin struct State { // number of markets uint256 numMarkets; // marketId => Market mapping (uint256 => Market) markets; // token address => marketId mapping (address => uint256) tokenToMarketId; // owner => account number => Account mapping (address => mapping (uint256 => Account.Storage)) accounts; // Addresses that can control other users accounts mapping (address => mapping (address => uint256)) operators; // Addresses that can control all users accounts mapping (address => uint256) globalOperators; // Addresses of auto traders that can only be called by global operators. IE for expirations mapping (address => uint256) specialAutoTraders; // mutable risk parameters of the system RiskParams riskParams; // immutable risk limits of the system RiskLimits riskLimits; } // ============ Functions ============ function getToken( Storage.State storage state, uint256 marketId ) internal view returns (address) { return state.markets[marketId].token; } function getTotalPar( Storage.State storage state, uint256 marketId ) internal view returns (Types.TotalPar memory) { return state.markets[marketId].totalPar; } function getMaxSupplyWei( Storage.State storage state, uint256 marketId ) internal view returns (Types.Wei memory) { return state.markets[marketId].maxSupplyWei; } function getMaxBorrowWei( Storage.State storage state, uint256 marketId ) internal view returns (Types.Wei memory) { return state.markets[marketId].maxBorrowWei; } function getIndex( Storage.State storage state, uint256 marketId ) internal view returns (Interest.Index memory) { return state.markets[marketId].index; } function getNumExcessTokens( Storage.State storage state, uint256 marketId ) internal view returns (Types.Wei memory) { Interest.Index memory index = state.getIndex(marketId); Types.TotalPar memory totalPar = state.getTotalPar(marketId); address token = state.getToken(marketId); Types.Wei memory balanceWei = Types.Wei({ sign: true, value: IERC20Detailed(token).balanceOf(address(this)) }); ( Types.Wei memory supplyWei, Types.Wei memory borrowWei ) = Interest.totalParToWei(totalPar, index); // borrowWei is negative, so subtracting it makes the value more positive return balanceWei.sub(borrowWei).sub(supplyWei); } function getStatus( Storage.State storage state, Account.Info memory account ) internal view returns (Account.Status) { return state.accounts[account.owner][account.number].status; } function getPar( Storage.State storage state, Account.Info memory account, uint256 marketId ) internal view returns (Types.Par memory) { return state.accounts[account.owner][account.number].balances[marketId]; } function getWei( Storage.State storage state, Account.Info memory account, uint256 marketId, Interest.Index memory index ) internal view returns (Types.Wei memory) { Types.Par memory par = state.getPar(account, marketId); if (par.isZero()) { return Types.zeroWei(); } return Interest.parToWei(par, index); } function getMarketsWithBalances( Storage.State storage state, Account.Info memory account ) internal view returns (uint256[] memory) { return state.accounts[account.owner][account.number].marketsWithNonZeroBalanceSet.values(); } function getAccountMarketWithBalanceAtIndex( Storage.State storage state, Account.Info memory account, uint256 index ) internal view returns (uint256) { return state.accounts[account.owner][account.number].marketsWithNonZeroBalanceSet.getAtIndex(index); } function getNumberOfMarketsWithBalances( Storage.State storage state, Account.Info memory account ) internal view returns (uint256) { return state.accounts[account.owner][account.number].marketsWithNonZeroBalanceSet.length(); } function getAccountNumberOfMarketsWithDebt( Storage.State storage state, Account.Info memory account ) internal view returns (uint256) { return state.accounts[account.owner][account.number].numberOfMarketsWithDebt; } function getLiquidationSpreadForAccountAndPair( Storage.State storage state, Account.Info memory account, uint256 heldMarketId, uint256 owedMarketId ) internal view returns (Decimal.D256 memory) { (, Decimal.D256 memory liquidationSpreadOverride) = getAccountRiskOverride(state, account); if (liquidationSpreadOverride.value != 0) { return liquidationSpreadOverride; } uint256 result = state.riskParams.liquidationSpread.value; result = Decimal.mul(result, Decimal.onePlus(state.markets[heldMarketId].liquidationSpreadPremium)); result = Decimal.mul(result, Decimal.onePlus(state.markets[owedMarketId].liquidationSpreadPremium)); return Decimal.D256({ value: result }); } function fetchNewIndex( Storage.State storage state, uint256 marketId, Interest.Index memory index ) internal view returns (Interest.Index memory) { Interest.Rate memory rate = state.fetchInterestRate(marketId, index); Decimal.D256 memory earningsRate = state.markets[marketId].earningsRateOverride; if (earningsRate.value == 0) { // The earnings rate was not override, fall back to the global one earningsRate = state.riskParams.earningsRate; } return Interest.calculateNewIndex( index, rate, state.getTotalPar(marketId), earningsRate ); } function fetchInterestRate( Storage.State storage state, uint256 marketId, Interest.Index memory index ) internal view returns (Interest.Rate memory) { Types.TotalPar memory totalPar = state.getTotalPar(marketId); ( Types.Wei memory supplyWei, Types.Wei memory borrowWei ) = Interest.totalParToWei(totalPar, index); Interest.Rate memory rate = state.markets[marketId].interestSetter.getInterestRate( state.getToken(marketId), borrowWei.value, supplyWei.value ); if (rate.value > state.riskLimits.interestRateMax) { // Cap the interest rate at the max instead of reverting. We don't want to DOS the protocol rate.value = state.riskLimits.interestRateMax; } return rate; } function fetchPrice( Storage.State storage state, uint256 marketId, address token ) internal view returns (Monetary.Price memory) { IPriceOracle oracle = IPriceOracle(state.markets[marketId].priceOracle); Monetary.Price memory price = oracle.getPrice(token); Require.that( price.value != 0, FILE, "Price cannot be zero", marketId ); return price; } // solium-disable-next-line security/no-assign-params function getAccountValues( Storage.State storage state, Account.Info memory account, Cache.MarketCache memory cache, bool adjustForLiquidity, Decimal.D256 memory marginRatioOverride ) internal view returns (Monetary.Value memory, Monetary.Value memory) { Monetary.Value memory supplyValue; Monetary.Value memory borrowValue; // Only adjust for liquidity if prompted AND if there is no override adjustForLiquidity = adjustForLiquidity && marginRatioOverride.value == 0; uint256 numMarkets = cache.getNumMarkets(); for (uint256 i; i < numMarkets; ++i) { Types.Wei memory userWei = state.getWei(account, cache.getAtIndex(i).marketId, cache.getAtIndex(i).index); if (userWei.isZero()) { continue; } Decimal.D256 memory adjust = Decimal.one(); if (adjustForLiquidity) { adjust = Decimal.onePlus(state.markets[cache.getAtIndex(i).marketId].marginPremium); } uint256 assetValue = userWei.value.mul(cache.getAtIndex(i).price.value); if (userWei.sign) { supplyValue.value = supplyValue.value.add(Decimal.div(assetValue, adjust)); } else { borrowValue.value = borrowValue.value.add(Decimal.mul(assetValue, adjust)); } } return (supplyValue, borrowValue); } function isCollateralized( Storage.State storage state, Account.Info memory account, Cache.MarketCache memory cache, bool requireMinBorrow ) internal view returns (bool) { if (state.getAccountNumberOfMarketsWithDebt(account) == 0) { // The user does not have a balance with a borrow amount, so they must be collateralized return true; } // get account values (adjusted for liquidity, if there isn't a margin ratio override) (Decimal.D256 memory marginRatio,) = getAccountRiskOverride(state, account); ( Monetary.Value memory supplyValue, Monetary.Value memory borrowValue ) = state.getAccountValues( account, cache, /* adjustForLiquidity = */ true, marginRatio ); if (requireMinBorrow) { Require.that( borrowValue.value >= state.riskParams.minBorrowedValue.value, FILE, "Borrow value too low", account.owner, account.number ); } if (marginRatio.value == 0) { marginRatio = state.riskParams.marginRatio; } uint256 requiredMargin = Decimal.mul(borrowValue.value, marginRatio); return supplyValue.value >= borrowValue.value.add(requiredMargin); } function isGlobalOperator( Storage.State storage state, address operator ) internal view returns (bool) { return state.globalOperators[operator] == 1; } function isAutoTraderSpecial( Storage.State storage state, address autoTrader ) internal view returns (bool) { return state.specialAutoTraders[autoTrader] == 1; } function isLocalOperator( Storage.State storage state, address owner, address operator ) internal view returns (bool) { return state.operators[owner][operator] == 1; } function requireIsGlobalOperator( Storage.State storage state, address operator ) internal view { bool isValidOperator = state.isGlobalOperator(operator); Require.that( isValidOperator, FILE, "Unpermissioned global operator", operator ); } function requireIsOperator( Storage.State storage state, Account.Info memory account, address operator ) internal view { bool isValidOperator = operator == account.owner || state.isGlobalOperator(operator) || state.isLocalOperator(account.owner, operator); Require.that( isValidOperator, FILE, "Unpermissioned operator", operator ); } function getAccountRiskOverride( Storage.State storage state, Account.Info memory account ) internal view returns (Decimal.D256 memory marginRatioOverride, Decimal.D256 memory liquidationSpreadOverride) { IAccountRiskOverrideSetter riskOverrideSetter = state.riskParams.accountRiskOverrideSetterMap[account.owner]; if (address(riskOverrideSetter) != address(0)) { (marginRatioOverride, liquidationSpreadOverride) = riskOverrideSetter.getAccountRiskOverride(account); validateAccountRiskOverrideValues(state, marginRatioOverride, liquidationSpreadOverride); return (marginRatioOverride, liquidationSpreadOverride); } riskOverrideSetter = state.riskParams.defaultAccountRiskOverrideSetter; if (address(riskOverrideSetter) != address(0)) { (marginRatioOverride, liquidationSpreadOverride) = riskOverrideSetter.getAccountRiskOverride(account); validateAccountRiskOverrideValues(state, marginRatioOverride, liquidationSpreadOverride); return (marginRatioOverride, liquidationSpreadOverride); } else { marginRatioOverride = Decimal.zero(); liquidationSpreadOverride = Decimal.zero(); return (marginRatioOverride, liquidationSpreadOverride); } } /** * Determine and set an account's balance based on the intended balance change. Return the * equivalent amount in wei */ function getNewParAndDeltaWei( Storage.State storage state, Account.Info memory account, uint256 marketId, Interest.Index memory index, Types.AssetAmount memory amount ) internal view returns (Types.Par memory, Types.Wei memory) { Types.Par memory oldPar = state.getPar(account, marketId); if (amount.value == 0 && amount.ref == Types.AssetReference.Delta) { return (oldPar, Types.zeroWei()); } Types.Wei memory oldWei = Interest.parToWei(oldPar, index); Types.Par memory newPar; Types.Wei memory deltaWei; if (amount.denomination == Types.AssetDenomination.Wei) { deltaWei = Types.Wei({ sign: amount.sign, value: amount.value }); if (amount.ref == Types.AssetReference.Target) { deltaWei = deltaWei.sub(oldWei); } newPar = Interest.weiToPar(oldWei.add(deltaWei), index); } else { // AssetDenomination.Par newPar = Types.Par({ sign: amount.sign, value: amount.value.to128() }); if (amount.ref == Types.AssetReference.Delta) { newPar = oldPar.add(newPar); } deltaWei = Interest.parToWei(newPar, index).sub(oldWei); } return (newPar, deltaWei); } function getNewParAndDeltaWeiForLiquidation( Storage.State storage state, Account.Info memory account, uint256 marketId, Interest.Index memory index, Types.AssetAmount memory amount ) internal view returns (Types.Par memory, Types.Wei memory) { Types.Par memory oldPar = state.getPar(account, marketId); Require.that( !oldPar.isPositive(), FILE, "Owed balance cannot be positive", account.owner, account.number ); ( Types.Par memory newPar, Types.Wei memory deltaWei ) = state.getNewParAndDeltaWei( account, marketId, index, amount ); // if attempting to over-repay the owed asset, bound it by the maximum if (newPar.isPositive()) { newPar = Types.zeroPar(); deltaWei = state.getWei(account, marketId, index).negative(); } Require.that( !deltaWei.isNegative() && oldPar.value >= newPar.value, FILE, "Owed balance cannot increase", account.owner, account.number ); // if not paying back enough wei to repay any par, then bound wei to zero if (oldPar.equals(newPar)) { deltaWei = Types.zeroWei(); } return (newPar, deltaWei); } function isVaporizable( Storage.State storage state, Account.Info memory account, Cache.MarketCache memory cache ) internal view returns (bool) { bool hasNegative = false; uint256 numMarkets = cache.getNumMarkets(); for (uint256 i; i < numMarkets; ++i) { Types.Par memory par = state.getPar(account, cache.getAtIndex(i).marketId); if (par.isZero()) { continue; } else if (par.sign) { return false; } else { hasNegative = true; } } return hasNegative; } function validateAccountRiskOverrideValues( Storage.State storage state, Decimal.D256 memory marginRatioOverride, Decimal.D256 memory liquidationSpreadOverride ) internal view { Require.that( marginRatioOverride.value <= state.riskLimits.marginRatioMax, FILE, "Ratio too high" ); Require.that( liquidationSpreadOverride.value <= state.riskLimits.liquidationSpreadMax, FILE, "Spread too high" ); if (marginRatioOverride.value != 0 && liquidationSpreadOverride.value != 0) { Require.that( liquidationSpreadOverride.value < marginRatioOverride.value, FILE, "Spread cannot be >= ratio" ); } else { Require.that( liquidationSpreadOverride.value == 0 && marginRatioOverride.value == 0, FILE, "Spread and ratio must both be 0" ); } } // =============== Setter Functions =============== function updateIndex( Storage.State storage state, uint256 marketId ) internal returns (Interest.Index memory) { Interest.Index memory index = state.getIndex(marketId); if (index.lastUpdate == Time.currentTime()) { return index; } return state.markets[marketId].index = state.fetchNewIndex(marketId, index); } function setStatus( Storage.State storage state, Account.Info memory account, Account.Status status ) internal { state.accounts[account.owner][account.number].status = status; } function setPar( Storage.State storage state, Account.Info memory account, uint256 marketId, Types.Par memory newPar ) internal { Types.Par memory oldPar = state.getPar(account, marketId); if (Types.equals(oldPar, newPar)) { // GUARD statement return; } // updateTotalPar Types.TotalPar memory totalPar = state.getTotalPar(marketId); // roll-back oldPar if (oldPar.sign) { totalPar.supply = uint256(totalPar.supply).sub(oldPar.value).to128(); } else { totalPar.borrow = uint256(totalPar.borrow).sub(oldPar.value).to128(); } // roll-forward newPar if (newPar.sign) { totalPar.supply = uint256(totalPar.supply).add(newPar.value).to128(); } else { totalPar.borrow = uint256(totalPar.borrow).add(newPar.value).to128(); } if (oldPar.isLessThanZero() && newPar.isGreaterThanOrEqualToZero()) { // user went from borrowing to repaying or positive state.accounts[account.owner][account.number].numberOfMarketsWithDebt -= 1; } else if (oldPar.isGreaterThanOrEqualToZero() && newPar.isLessThanZero()) { // user went from zero or positive to borrowing state.accounts[account.owner][account.number].numberOfMarketsWithDebt += 1; } if (newPar.isZero() && (!oldPar.isZero())) { // User went from a non-zero balance to zero. Remove the market from the set. state.accounts[account.owner][account.number].marketsWithNonZeroBalanceSet.remove(marketId); } else if ((!newPar.isZero()) && oldPar.isZero()) { // User went from zero to non-zero. Add the market to the set. state.accounts[account.owner][account.number].marketsWithNonZeroBalanceSet.add(marketId); } state.markets[marketId].totalPar = totalPar; state.accounts[account.owner][account.number].balances[marketId] = newPar; } /** * Determine and set an account's balance based on a change in wei */ function setParFromDeltaWei( Storage.State storage state, Account.Info memory account, uint256 marketId, Interest.Index memory index, Types.Wei memory deltaWei ) internal { if (deltaWei.isZero()) { return; } Types.Wei memory oldWei = state.getWei(account, marketId, index); Types.Wei memory newWei = oldWei.add(deltaWei); Types.Par memory newPar = Interest.weiToPar(newWei, index); state.setPar( account, marketId, newPar ); } /** * Initializes the cache using the set bits */ function initializeCache( Storage.State storage state, Cache.MarketCache memory cache, bool fetchFreshIndex ) internal view { cache.markets = new Cache.MarketInfo[](cache.marketsLength); // Really neat byproduct of iterating through a bitmap using the least significant bit, where each set flag // represents the marketId, --> the initialized `cache.markets` array is sorted in O(n)! // Meaning, this function call is O(n) where `n` is the number of markets in the cache uint256 marketBitmapsLength = cache.marketBitmaps.length; for (uint256 i; i < marketBitmapsLength; ++i) { uint256 bitmap = cache.marketBitmaps[i]; while (bitmap != 0) { uint256 nextSetBit = Bits.getLeastSignificantBit(bitmap); uint256 marketId = Bits.getMarketIdFromBit(i, nextSetBit); address token = state.getToken(marketId); Types.TotalPar memory totalPar = state.getTotalPar(marketId); Interest.Index memory index = state.getIndex(marketId); cache.markets[cache.counter++] = Cache.MarketInfo({ marketId: marketId, token: token, isClosing: state.markets[marketId].isClosing, borrowPar: totalPar.borrow, supplyPar: totalPar.supply, index: fetchFreshIndex ? state.fetchNewIndex(marketId, index) : index, price: state.fetchPrice(marketId, token) }); // unset the set bit bitmap = Bits.unsetBit(bitmap, nextSetBit); } if (cache.counter == cache.marketsLength) { break; } } assert(cache.marketsLength == cache.counter); } }
/* Copyright 2019 dYdX Trading Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.7; pragma experimental ABIEncoderV2; /** * @title Require * @author dYdX * * Stringifies parameters to pretty-print revert messages. Costs more gas than regular require() */ library Require { // ============ Constants ============ uint256 constant ASCII_ZERO = 48; // '0' uint256 constant ASCII_RELATIVE_ZERO = 87; // 'a' - 10 uint256 constant ASCII_LOWER_EX = 120; // 'x' bytes2 constant COLON = 0x3a20; // ': ' bytes2 constant COMMA = 0x2c20; // ', ' bytes2 constant LPAREN = 0x203c; // ' <' byte constant RPAREN = 0x3e; // '>' uint256 constant FOUR_BIT_MASK = 0xf; // ============ Library Functions ============ function that( bool must, bytes32 file, bytes32 reason ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason) ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, uint256 payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, uint256 payloadA, uint256 payloadB ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA, uint256 payloadB ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA, uint256 payloadB, uint256 payloadC ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), COMMA, stringify(payloadC), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, bytes32 payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, bytes32 payloadA, uint256 payloadB, uint256 payloadC ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), COMMA, stringify(payloadC), RPAREN ) ) ); } } // ============ Private Functions ============ function stringifyTruncated( bytes32 input ) internal pure returns (bytes memory) { // put the input bytes into the result bytes memory result = abi.encodePacked(input); // determine the length of the input by finding the location of the last non-zero byte for (uint256 i = 32; i != 0; ) { // reverse-for-loops with unsigned integer /* solium-disable-next-line security/no-modify-for-iter-var */ i--; // find the last non-zero byte in order to determine the length if (result[i] != 0) { uint256 length = i + 1; /* solium-disable-next-line security/no-inline-assembly */ assembly { mstore(result, length) // r.length = length; } return result; } } // all bytes are zero return new bytes(0); } function stringify( uint256 input ) private pure returns (bytes memory) { if (input == 0) { return "0"; } // get the final string length uint256 j = input; uint256 length; while (j != 0) { ++length; j /= 10; } // allocate the string bytes memory bstr = new bytes(length); // populate the string starting with the least-significant character j = input; for (uint256 i = length; i != 0; ) { // reverse-for-loops with unsigned integer /* solium-disable-next-line security/no-modify-for-iter-var */ i--; // take last decimal digit bstr[i] = byte(uint8(ASCII_ZERO + (j % 10))); // remove the last decimal digit j /= 10; } return bstr; } function stringify( address input ) private pure returns (bytes memory) { uint256 z = uint256(input); // addresses are "0x" followed by 20 bytes of data which take up 2 characters each bytes memory result = new bytes(42); // populate the result with "0x" result[0] = byte(uint8(ASCII_ZERO)); result[1] = byte(uint8(ASCII_LOWER_EX)); // for each byte (starting from the lowest byte), populate the result with two characters for (uint256 i; i < 20; ++i) { // each byte takes two characters uint256 shift = i * 2; // populate the least-significant character result[41 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; // populate the most-significant character result[40 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; } return result; } function stringify( bytes32 input ) private pure returns (bytes memory) { uint256 z = uint256(input); // bytes32 are "0x" followed by 32 bytes of data which take up 2 characters each bytes memory result = new bytes(66); // populate the result with "0x" result[0] = byte(uint8(ASCII_ZERO)); result[1] = byte(uint8(ASCII_LOWER_EX)); // for each byte (starting from the lowest byte), populate the result with two characters for (uint256 i; i < 32; ++i) { // each byte takes two characters uint256 shift = i * 2; // populate the least-significant character result[65 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; // populate the most-significant character result[64 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; } return result; } function char( uint256 input ) private pure returns (byte) { // return ASCII digit (0-9) if (input < 10) { return byte(uint8(input + ASCII_ZERO)); } // return ASCII letter (a-f) return byte(uint8(input + ASCII_RELATIVE_ZERO)); } }
/* Copyright 2019 dYdX Trading Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.7; pragma experimental ABIEncoderV2; /** * @title Monetary * @author dYdX * * Library for types involving money */ library Monetary { /* * The price of a base-unit of an asset. Has `36 - token.decimals` decimals */ struct Price { uint256 value; } /* * Total value of an some amount of an asset. Equal to (price * amount). Has 36 decimals. */ struct Value { uint256 value; } }
/* Copyright 2019 dYdX Trading Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.7; pragma experimental ABIEncoderV2; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { Decimal } from "./Decimal.sol"; import { DolomiteMarginMath } from "./DolomiteMarginMath.sol"; import { Time } from "./Time.sol"; import { Types } from "./Types.sol"; /** * @title Interest * @author dYdX * * Library for managing the interest rate and interest indexes of DolomiteMargin */ library Interest { using DolomiteMarginMath for uint256; using SafeMath for uint256; // ============ Constants ============ bytes32 private constant FILE = "Interest"; uint64 constant BASE = 10**18; // ============ Structs ============ struct Rate { uint256 value; } struct Index { uint112 borrow; uint112 supply; uint32 lastUpdate; } // ============ Library Functions ============ /** * Get a new market Index based on the old index and market interest rate. * Calculate interest for borrowers by using the formula rate * time. Approximates * continuously-compounded interest when called frequently, but is much more * gas-efficient to calculate. For suppliers, the interest rate is adjusted by the earningsRate, * then prorated across all suppliers. * * @param index The old index for a market * @param rate The current interest rate of the market * @param totalPar The total supply and borrow par values of the market * @param earningsRate The portion of the interest that is forwarded to the suppliers * @return The updated index for a market */ function calculateNewIndex( Index memory index, Rate memory rate, Types.TotalPar memory totalPar, Decimal.D256 memory earningsRate ) internal view returns (Index memory) { ( Types.Wei memory supplyWei, Types.Wei memory borrowWei ) = totalParToWei(totalPar, index); // get interest increase for borrowers uint32 currentTime = Time.currentTime(); uint256 borrowInterest = rate.value.mul(uint256(currentTime).sub(index.lastUpdate)); // get interest increase for suppliers uint256 supplyInterest; if (Types.isZero(supplyWei)) { supplyInterest = 0; } else { supplyInterest = Decimal.mul(borrowInterest, earningsRate); if (borrowWei.value < supplyWei.value) { // scale down the interest by the amount being supplied. Why? Because interest is only being paid on // the borrowWei, which means it's split amongst all of the supplyWei. Scaling it down normalizes it // for the suppliers to share what's being paid by borrowers supplyInterest = DolomiteMarginMath.getPartial(supplyInterest, borrowWei.value, supplyWei.value); } } assert(supplyInterest <= borrowInterest); return Index({ borrow: DolomiteMarginMath.getPartial(index.borrow, borrowInterest, BASE).add(index.borrow).to112(), supply: DolomiteMarginMath.getPartial(index.supply, supplyInterest, BASE).add(index.supply).to112(), lastUpdate: currentTime }); } function newIndex() internal view returns (Index memory) { return Index({ borrow: BASE, supply: BASE, lastUpdate: Time.currentTime() }); } /* * Convert a principal amount to a token amount given an index. */ function parToWei( Types.Par memory input, Index memory index ) internal pure returns (Types.Wei memory) { uint256 inputValue = uint256(input.value); if (input.sign) { return Types.Wei({ sign: true, value: inputValue.getPartialRoundHalfUp(index.supply, BASE) }); } else { return Types.Wei({ sign: false, value: inputValue.getPartialRoundHalfUp(index.borrow, BASE) }); } } /* * Convert a token amount to a principal amount given an index. */ function weiToPar( Types.Wei memory input, Index memory index ) internal pure returns (Types.Par memory) { if (input.sign) { return Types.Par({ sign: true, value: input.value.getPartialRoundHalfUp(BASE, index.supply).to128() }); } else { return Types.Par({ sign: false, value: input.value.getPartialRoundHalfUp(BASE, index.borrow).to128() }); } } /* * Convert the total supply and borrow principal amounts of a market to total supply and borrow * token amounts. */ function totalParToWei( Types.TotalPar memory totalPar, Index memory index ) internal pure returns (Types.Wei memory, Types.Wei memory) { Types.Par memory supplyPar = Types.Par({ sign: true, value: totalPar.supply }); Types.Par memory borrowPar = Types.Par({ sign: false, value: totalPar.borrow }); Types.Wei memory supplyWei = parToWei(supplyPar, index); Types.Wei memory borrowWei = parToWei(borrowPar, index); return (supplyWei, borrowWei); } }
/* Copyright 2021 Dolomite. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.7; pragma experimental ABIEncoderV2; library EnumerableSet { struct Set { // Storage of set values uint256[] _values; // Value to the index in `_values` array, plus 1 because index 0 means a value is not in the set. mapping(uint256 => uint256) _valueToIndexMap; } /** * @dev Add a value to a set. O(1). * * @return true if the value was added to the set, that is if it was not already present. */ function add(Set storage set, uint256 value) internal returns (bool) { if (!contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._valueToIndexMap[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * @return true if the value was removed from the set, that is if it was present. */ function remove(Set storage set, uint256 value) internal returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._valueToIndexMap[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { uint256 lastValue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastValue; // Update the index for the moved value set._valueToIndexMap[lastValue] = valueIndex; // Replace lastValue's index to valueIndex } // Delete the slot where the moved value was stored, which is the last index set._values.pop(); // Delete the index for the deleted slot delete set._valueToIndexMap[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Set storage set, uint256 value) internal view returns (bool) { return set._valueToIndexMap[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function length(Set storage set) internal view returns (uint256) { return set._values.length; } /** * @dev Returns the value at the corresponding index. O(1). */ function getAtIndex(Set storage set, uint256 index) internal view returns (uint256) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Set storage set) internal view returns (uint256[] memory) { return set._values; } }
/* Copyright 2019 dYdX Trading Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.7; pragma experimental ABIEncoderV2; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { Require } from "./Require.sol"; /** * @title Math * @author dYdX * * Library for non-standard Math functions */ library DolomiteMarginMath { using SafeMath for uint256; // ============ Constants ============ bytes32 private constant FILE = "Math"; // ============ Library Functions ============ /* * Return target * (numerator / denominator). */ function getPartial( uint256 target, uint256 numerator, uint256 denominator ) internal pure returns (uint256) { return target.mul(numerator).div(denominator); } /* * Return target * (numerator / denominator), but rounded half-up. Meaning, a result of 101.1 rounds to 102 * instead of 101. */ function getPartialRoundUp( uint256 target, uint256 numerator, uint256 denominator ) internal pure returns (uint256) { if (target == 0 || numerator == 0) { // SafeMath will check for zero denominator return SafeMath.div(0, denominator); } return target.mul(numerator).sub(1).div(denominator).add(1); } /* * Return target * (numerator / denominator), but rounded half-up. Meaning, a result of 101.5 rounds to 102 * instead of 101. */ function getPartialRoundHalfUp( uint256 target, uint256 numerator, uint256 denominator ) internal pure returns (uint256) { if (target == 0 || numerator == 0) { // SafeMath will check for zero denominator return SafeMath.div(0, denominator); } uint result = target.mul(numerator); // round the denominator comparator up to ensure a fair comparison is done on the `result`'s modulo. // For example, 51 / 103 == 0; 51 % 103 == 51; ((103 - 1) / 2) + 1 == 52; 51 < 52, therefore no round up return result.div(denominator).add(result.mod(denominator) >= denominator.sub(1).div(2).add(1) ? 1 : 0); } function to128( uint256 number ) internal pure returns (uint128) { uint128 result = uint128(number); Require.that( result == number, FILE, "Unsafe cast to uint128", number ); return result; } function to112( uint256 number ) internal pure returns (uint112) { uint112 result = uint112(number); Require.that( result == number, FILE, "Unsafe cast to uint112", number ); return result; } function to32( uint256 number ) internal pure returns (uint32) { uint32 result = uint32(number); Require.that( result == number, FILE, "Unsafe cast to uint32", number ); return result; } }
/* Copyright 2019 dYdX Trading Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.7; pragma experimental ABIEncoderV2; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { DolomiteMarginMath } from "./DolomiteMarginMath.sol"; /** * @title Decimal * @author dYdX * * Library that defines a fixed-point number with 18 decimal places. */ library Decimal { using SafeMath for uint256; // ============ Constants ============ uint256 constant BASE = 10**18; // ============ Structs ============ struct D256 { uint256 value; } // ============ Functions ============ function zero() internal pure returns (D256 memory) { return D256({ value: 0 }); } function one() internal pure returns (D256 memory) { return D256({ value: BASE }); } function onePlus( D256 memory d ) internal pure returns (D256 memory) { return D256({ value: d.value.add(BASE) }); } function mul( uint256 target, D256 memory d ) internal pure returns (uint256) { return DolomiteMarginMath.getPartial(target, d.value, BASE); } function div( uint256 target, D256 memory d ) internal pure returns (uint256) { return DolomiteMarginMath.getPartial(target, BASE, d.value); } }
/* Copyright 2019 dYdX Trading Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.7; pragma experimental ABIEncoderV2; import { Bits } from "./Bits.sol"; import { Interest } from "./Interest.sol"; import { Monetary } from "./Monetary.sol"; import { Require } from "./Require.sol"; /** * @title Cache * @author dYdX * * Library for caching information about markets */ library Cache { // ============ Constants ============ bytes32 private constant FILE = "Cache"; // ============ Structs ============ struct MarketInfo { uint marketId; address token; bool isClosing; uint128 borrowPar; uint128 supplyPar; Interest.Index index; Monetary.Price price; } struct MarketCache { MarketInfo[] markets; uint256 counter; // used for iterating through the bitmaps and incrementing uint256[] marketBitmaps; uint256 marketsLength; } // ============ Setter Functions ============ /** * Initialize an empty cache for some given number of total markets. */ function create( uint256 numMarkets ) internal pure returns (MarketCache memory) { return MarketCache({ markets: new MarketInfo[](0), counter: 0, marketBitmaps: Bits.createBitmaps(numMarkets), marketsLength: 0 }); } // ============ Getter Functions ============ function getNumMarkets( MarketCache memory cache ) internal pure returns (uint256) { return cache.markets.length; } function hasMarket( MarketCache memory cache, uint256 marketId ) internal pure returns (bool) { return Bits.hasBit(cache.marketBitmaps, marketId); } function get( MarketCache memory cache, uint256 marketId ) internal pure returns (MarketInfo memory) { Require.that( cache.markets.length != 0, FILE, "not initialized" ); return _getInternal( cache.markets, 0, cache.marketsLength, marketId ); } function set( MarketCache memory cache, uint256 marketId ) internal pure { // Devs should not be able to call this function once the `markets` array has been initialized (non-zero length) Require.that( cache.markets.length == 0, FILE, "already initialized" ); Bits.setBit(cache.marketBitmaps, marketId); cache.marketsLength += 1; } function getAtIndex( MarketCache memory cache, uint256 index ) internal pure returns (MarketInfo memory) { Require.that( index < cache.markets.length, FILE, "invalid index", index, cache.markets.length ); return cache.markets[index]; } // ============ Private Functions ============ function _getInternal( MarketInfo[] memory data, uint beginInclusive, uint endExclusive, uint marketId ) private pure returns (MarketInfo memory) { uint len = endExclusive - beginInclusive; // If length equals 0 OR length equals 1 but the item wasn't found, revert assert(!(len == 0 || (len == 1 && data[beginInclusive].marketId != marketId))); uint mid = beginInclusive + (len >> 1); uint midMarketId = data[mid].marketId; if (marketId < midMarketId) { return _getInternal( data, beginInclusive, mid, marketId ); } else if (marketId > midMarketId) { return _getInternal( data, mid + 1, endExclusive, marketId ); } else { return data[mid]; } } }
pragma solidity ^0.5.0; /** * @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) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); 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-contracts/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) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message 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. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); 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) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message 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. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
/* Copyright 2019 dYdX Trading Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.7; pragma experimental ABIEncoderV2; import { Account } from "./Account.sol"; import { Types } from "./Types.sol"; /** * @title Actions * @author dYdX * * Library that defines and parses valid Actions */ library Actions { // ============ Constants ============ bytes32 private constant FILE = "Actions"; // ============ Enums ============ enum ActionType { Deposit, // supply tokens Withdraw, // borrow tokens Transfer, // transfer balance between accounts Buy, // buy an amount of some token (externally) Sell, // sell an amount of some token (externally) Trade, // trade tokens against another account Liquidate, // liquidate an undercollateralized or expiring account Vaporize, // use excess tokens to zero-out a completely negative account Call // send arbitrary data to an address } enum AccountLayout { OnePrimary, TwoPrimary, PrimaryAndSecondary } enum MarketLayout { ZeroMarkets, OneMarket, TwoMarkets } // ============ Structs ============ /* * Arguments that are passed to DolomiteMargin in an ordered list as part of a single operation. * Each ActionArgs has an actionType which specifies which action struct that this data will be * parsed into before being processed. */ struct ActionArgs { ActionType actionType; uint256 accountId; Types.AssetAmount amount; uint256 primaryMarketId; uint256 secondaryMarketId; address otherAddress; uint256 otherAccountId; bytes data; } // ============ Action Types ============ /* * Moves tokens from an address to DolomiteMargin. Can either repay a borrow or provide additional supply. */ struct DepositArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address from; } /* * Moves tokens from DolomiteMargin to another address. Can either borrow tokens or reduce the amount * previously supplied. */ struct WithdrawArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address to; } /* * Transfers balance between two accounts. The msg.sender must be an operator for both accounts. * The amount field applies to accountOne. * This action does not require any token movement since the trade is done internally to DolomiteMargin. */ struct TransferArgs { Types.AssetAmount amount; Account.Info accountOne; Account.Info accountTwo; uint256 market; } /* * Acquires a certain amount of tokens by spending other tokens. Sends takerMarket tokens to the * specified exchangeWrapper contract and expects makerMarket tokens in return. The amount field * applies to the makerMarket. */ struct BuyArgs { Types.AssetAmount amount; Account.Info account; uint256 makerMarket; uint256 takerMarket; address exchangeWrapper; bytes orderData; } /* * Spends a certain amount of tokens to acquire other tokens. Sends takerMarket tokens to the * specified exchangeWrapper and expects makerMarket tokens in return. The amount field applies * to the takerMarket. */ struct SellArgs { Types.AssetAmount amount; Account.Info account; uint256 takerMarket; uint256 makerMarket; address exchangeWrapper; bytes orderData; } /* * Trades balances between two accounts using any external contract that implements the * AutoTrader interface. The AutoTrader contract must be an operator for the makerAccount (for * which it is trading on-behalf-of). The amount field applies to the makerAccount and the * inputMarket. This proposed change to the makerAccount is passed to the AutoTrader which will * quote a change for the makerAccount in the outputMarket (or will disallow the trade). * This action does not require any token movement since the trade is done internally to DolomiteMargin. */ struct TradeArgs { Types.AssetAmount amount; bool calculateAmountWithMakerAccount; Account.Info takerAccount; Account.Info makerAccount; uint256 inputMarket; uint256 outputMarket; address autoTrader; bytes tradeData; } /* * Each account must maintain a certain margin-ratio (specified globally). If the account falls * below this margin-ratio, it can be liquidated by any other account. This allows anyone else * (arbitrageurs) to repay any borrowed asset (owedMarket) of the liquidating account in * exchange for any collateral asset (heldMarket) of the liquidAccount. The ratio is determined * by the price ratio (given by the oracles) plus a spread (specified globally). Liquidating an * account also sets a flag on the account that the account is being liquidated. This allows * anyone to continue liquidating the account until there are no more borrows being taken by the * liquidating account. Liquidators do not have to liquidate the entire account all at once but * can liquidate as much as they choose. The liquidating flag allows liquidators to continue * liquidating the account even if it becomes collateralized through partial liquidation or * price movement. */ struct LiquidateArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info liquidAccount; uint256 owedMarket; uint256 heldMarket; } /* * Similar to liquidate, but vaporAccounts are accounts that have only negative balances remaining. The arbitrageur * pays back the negative asset (owedMarket) of the vaporAccount in exchange for a collateral asset (heldMarket) at * a favorable spread. However, since the liquidAccount has no collateral assets, the collateral must come from * DolomiteMargin's excess tokens. */ struct VaporizeArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info vaporAccount; uint256 owedMarket; uint256 heldMarket; } /* * Passes arbitrary bytes of data to an external contract that implements the Callee interface. * Does not change any asset amounts. This function may be useful for setting certain variables * on layer-two contracts for certain accounts without having to make a separate Ethereum * transaction for doing so. Also, the second-layer contracts can ensure that the call is coming * from an operator of the particular account. */ struct CallArgs { Account.Info account; address callee; bytes data; } // ============ Helper Functions ============ function getMarketLayout( ActionType actionType ) internal pure returns (MarketLayout) { if ( actionType == Actions.ActionType.Deposit || actionType == Actions.ActionType.Withdraw || actionType == Actions.ActionType.Transfer ) { return MarketLayout.OneMarket; } else if (actionType == Actions.ActionType.Call) { return MarketLayout.ZeroMarkets; } return MarketLayout.TwoMarkets; } function getAccountLayout( ActionType actionType ) internal pure returns (AccountLayout) { if ( actionType == Actions.ActionType.Transfer || actionType == Actions.ActionType.Trade ) { return AccountLayout.TwoPrimary; } else if ( actionType == Actions.ActionType.Liquidate || actionType == Actions.ActionType.Vaporize ) { return AccountLayout.PrimaryAndSecondary; } return AccountLayout.OnePrimary; } // ============ Parsing Functions ============ function parseDepositArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (DepositArgs memory) { return DepositArgs({ amount: args.amount, account: accounts[args.accountId], market: args.primaryMarketId, from: args.otherAddress }); } function parseWithdrawArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (WithdrawArgs memory) { return WithdrawArgs({ amount: args.amount, account: accounts[args.accountId], market: args.primaryMarketId, to: args.otherAddress }); } function parseTransferArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (TransferArgs memory) { return TransferArgs({ amount: args.amount, accountOne: accounts[args.accountId], accountTwo: accounts[args.otherAccountId], market: args.primaryMarketId }); } function parseBuyArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (BuyArgs memory) { return BuyArgs({ amount: args.amount, account: accounts[args.accountId], makerMarket: args.primaryMarketId, takerMarket: args.secondaryMarketId, exchangeWrapper: args.otherAddress, orderData: args.data }); } function parseSellArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (SellArgs memory) { return SellArgs({ amount: args.amount, account: accounts[args.accountId], takerMarket: args.primaryMarketId, makerMarket: args.secondaryMarketId, exchangeWrapper: args.otherAddress, orderData: args.data }); } function parseTradeArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (TradeArgs memory) { (bool calculateAmountWithMakerAccount, bytes memory tradeData) = abi.decode(args.data, (bool, bytes)); return TradeArgs({ amount: args.amount, calculateAmountWithMakerAccount: calculateAmountWithMakerAccount, takerAccount: accounts[args.accountId], makerAccount: accounts[args.otherAccountId], inputMarket: args.primaryMarketId, outputMarket: args.secondaryMarketId, autoTrader: args.otherAddress, tradeData: tradeData }); } function parseLiquidateArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (LiquidateArgs memory) { return LiquidateArgs({ amount: args.amount, solidAccount: accounts[args.accountId], liquidAccount: accounts[args.otherAccountId], owedMarket: args.primaryMarketId, heldMarket: args.secondaryMarketId }); } function parseVaporizeArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (VaporizeArgs memory) { return VaporizeArgs({ amount: args.amount, solidAccount: accounts[args.accountId], vaporAccount: accounts[args.otherAccountId], owedMarket: args.primaryMarketId, heldMarket: args.secondaryMarketId }); } function parseCallArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (CallArgs memory) { return CallArgs({ account: accounts[args.accountId], callee: args.otherAddress, data: args.data }); } }
/* Copyright 2019 dYdX Trading Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.7; pragma experimental ABIEncoderV2; import { Types } from "./Types.sol"; import { EnumerableSet } from "./EnumerableSet.sol"; /** * @title Account * @author dYdX * * Library of structs and functions that represent an account */ library Account { // ============ Enums ============ /* * Most-recently-cached account status. * * Normal: Can only be liquidated if the account values are violating the global margin-ratio. * Liquid: Can be liquidated no matter the account values. * Can be vaporized if there are no more positive account values. * Vapor: Has only negative (or zeroed) account values. Can be vaporized. * */ enum Status { Normal, Liquid, Vapor } // ============ Structs ============ // Represents the unique key that specifies an account struct Info { address owner; // The address that owns the account uint256 number; // A nonce that allows a single address to control many accounts } // The complete storage for any account struct Storage { Status status; uint32 numberOfMarketsWithDebt; EnumerableSet.Set marketsWithNonZeroBalanceSet; mapping (uint256 => Types.Par) balances; // Mapping from marketId to principal } // ============ Library Functions ============ function equals( Info memory a, Info memory b ) internal pure returns (bool) { return a.owner == b.owner && a.number == b.number; } }
/* Copyright 2019 dYdX Trading Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.7; pragma experimental ABIEncoderV2; import { Monetary } from "../lib/Monetary.sol"; /** * @title IPriceOracle * @author dYdX * * Interface that Price Oracles for DolomiteMargin must implement in order to report prices. */ contract IPriceOracle { // ============ Constants ============ uint256 public constant ONE_DOLLAR = 10 ** 36; // ============ Public Functions ============ /** * Get the price of a token * * @param token The ERC20 token address of the market * @return The USD price of a base unit of the token, then multiplied by 10^36. * So a USD-stable coin with 18 decimal places would return 10^18. * This is the price of the base unit rather than the price of a "human-readable" * token amount. Every ERC20 may have a different number of decimals. */ function getPrice( address token ) public view returns (Monetary.Price memory); }
/* Copyright 2023 Dolomite Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.7; pragma experimental ABIEncoderV2; /** * @title IOracleSentinel * @author Dolomite * * Interface that Dolomite pings to check if the Blockchain or L2 is alive, if liquidations should be processed, and if * markets should are in size-down only mode. */ contract IOracleSentinel { // ============ Events ============ event GracePeriodSet( uint256 gracePeriod ); // ============ Functions ============ /** * @dev Allows the owner to set the grace period duration, which specifies how long the system will disallow * liquidations after sequencer is back online. Only callable by the owner. * * @param _gracePeriod The new duration of the grace period */ function ownerSetGracePeriod( uint256 _gracePeriod ) external; /** * @return True if new borrows should be allowed, false otherwise */ function isBorrowAllowed() external view returns (bool); /** * @return True if liquidations should be allowed, false otherwise */ function isLiquidationAllowed() external view returns (bool); /** * @return The duration between when the feed comes back online and when the system will allow liquidations to be * processed normally */ function gracePeriod() external view returns (uint256); }
/* Copyright 2019 dYdX Trading Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.7; pragma experimental ABIEncoderV2; import { Interest } from "../lib/Interest.sol"; /** * @title IInterestSetter * @author dYdX * * Interface that Interest Setters for DolomiteMargin must implement in order to report interest rates. */ interface IInterestSetter { // ============ Public Functions ============ /** * Get the interest rate of a token given some borrowed and supplied amounts * * @param token The address of the ERC20 token for the market * @param borrowWei The total borrowed token amount for the market * @param supplyWei The total supplied token amount for the market * @return The interest rate per second */ function getInterestRate( address token, uint256 borrowWei, uint256 supplyWei ) external view returns (Interest.Rate memory); }
/* Copyright 2019 dYdX Trading Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.7; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title IERC20 * @author dYdX * * Interface for using ERC20 Tokens. We have to use a special interface to call ERC20 functions so * that we don't automatically revert when calling non-compliant tokens that have no return value for * transfer(), transferFrom(), or approve(). */ contract IERC20Detailed is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); }
/* Copyright 2021 Dolomite. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity >=0.5.0; pragma experimental ABIEncoderV2; import { IAccountRiskOverrideSetter } from "../interfaces/IAccountRiskOverrideSetter.sol"; import { IInterestSetter } from "../interfaces/IInterestSetter.sol"; import { IOracleSentinel } from "../interfaces/IOracleSentinel.sol"; import { IPriceOracle } from "../interfaces/IPriceOracle.sol"; import { Account } from "../lib/Account.sol"; import { Actions } from "../lib/Actions.sol"; import { Decimal } from "../lib/Decimal.sol"; import { Interest } from "../lib/Interest.sol"; import { Monetary } from "../lib/Monetary.sol"; import { Storage } from "../lib/Storage.sol"; import { Types } from "../lib/Types.sol"; interface IDolomiteMargin { // ============ Getters for Risk Params ============ /** * Get the global minimum margin-ratio that every position must maintain to prevent being * liquidated. * * @return The global margin-ratio */ function getMarginRatio() external view returns (Decimal.D256 memory); /** * Get the global minimum margin-ratio that every position must maintain to prevent being * liquidated. * * @param account The account whose margin ratio is being queried. This is used to determine if there is an * override that supersedes the global minimum. * @return The margin ratio for this account */ function getMarginRatioForAccount(Account.Info calldata account) external view returns (Decimal.D256 memory); /** * Get the global liquidation spread. This is the spread between oracle prices that incentivizes * the liquidation of risky positions. * * @return The global liquidation spread */ function getLiquidationSpread() external view returns (Decimal.D256 memory); /** * Get the adjusted liquidation spread for some market pair. This is equal to the global liquidation spread * multiplied by (1 + spreadPremium) for each of the two markets. * * Assumes the pair is not in e-mode. Backwards compatible with V1. * * @param heldMarketId The market for which the account has collateral * @param owedMarketId The market for which the account has borrowed tokens * @return The adjusted liquidation spread */ function getLiquidationSpreadForPair( uint256 heldMarketId, uint256 owedMarketId ) external view returns (Decimal.D256 memory); /** * Get the adjusted liquidation spread for some market pair. This is equal to the global liquidation spread * multiplied by (1 + spreadPremium) for each of the two markets. * * If the pair is in e-mode and has a liquidation spread override, then the override is used instead. * * @param account The account whose liquidation spread is being queried. This is used to determine if there is * an override in place. * @param heldMarketId The market for which the account has collateral * @param owedMarketId The market for which the account has borrowed tokens * @return The adjusted liquidation spread */ function getLiquidationSpreadForAccountAndPair( Account.Info calldata account, uint256 heldMarketId, uint256 owedMarketId ) external view returns (Decimal.D256 memory); /** * Get the global earnings-rate variable that determines what percentage of the interest paid * by borrowers gets passed-on to suppliers. * * @return The global earnings rate */ function getEarningsRate() external view returns (Decimal.D256 memory); /** * Get the global minimum-borrow value which is the minimum value of any new borrow on DolomiteMargin. * * @return The global minimum borrow value */ function getMinBorrowedValue() external view returns (Monetary.Value memory); /** * Get the maximum number of assets an account owner can hold in an account number. * * @return The maximum number of assets an account owner can hold in an account number. */ function getAccountMaxNumberOfMarketsWithBalances() external view returns (uint256); /** * Gets the oracle sentinel, which is responsible for checking if the Blockchain or L2 is alive, if liquidations * should be processed, and if markets should are in size-down only mode. * * @return The oracle sentinel for DolomiteMargin */ function getOracleSentinel() external view returns (IOracleSentinel); /** * @return True if borrowing is globally allowed according to the Oracle Sentinel or false if it is not */ function getIsBorrowAllowed() external view returns (bool); /** * @return True if liquidations are globally allowed according to the Oracle Sentinel or false if they are not */ function getIsLiquidationAllowed() external view returns (bool); /** * @return The gas limit used for making callbacks via `IExternalCallback::onInternalBalanceChange` to smart * contract wallets. */ function getCallbackGasLimit() external view returns (uint256); /** * Get the account risk override getter for global use. This contract enables e-mode based on the assets held in a * position. * * @return The contract that contains risk override information for any account that does NOT have an account- * specific override. */ function getDefaultAccountRiskOverrideSetter() external view returns (IAccountRiskOverrideSetter); /** * Get the account risk override getter for an account owner. This contract enables e-mode for certain isolation * mode vaults. * * @param accountOwner The address of the account to check if there is a margin ratio override. * @return The contract that contains risk override information for this account. */ function getAccountRiskOverrideSetterByAccountOwner( address accountOwner ) external view returns (IAccountRiskOverrideSetter); /** * Get the margin ratio override for an account owner. Used to enable e-mode for certain isolation mode vaults. * * @param account The account to check if there is a risk override. * @return marginRatioOverride The margin ratio override for an account owner. Defaults to 0 if there's no * override in place. * @return liquidationSpreadOverride The margin ratio override for an account owner. Defaults to 0 if there's no * override in place. */ function getAccountRiskOverrideByAccount( Account.Info calldata account ) external view returns (Decimal.D256 memory marginRatioOverride, Decimal.D256 memory liquidationSpreadOverride); /** * Get the margin ratio override for an account. Used to enable e-mode for certain accounts/positions. * * @param account The account to check if there is a margin ratio override. * @return The margin ratio override for an account owner. Defaults to 0 if there's no override in place. */ function getMarginRatioOverrideByAccount(Account.Info calldata account) external view returns (Decimal.D256 memory); /** * Get the liquidation reward override for an account owner. Used to enable e-mode for certain isolation mode * vaults. * * @param account The account to check if there is a liquidation spread override. * @return The liquidation spread override for an account owner. Defaults to 0 if there's no override in place. */ function getLiquidationSpreadOverrideByAccount( Account.Info calldata account ) external view returns (Decimal.D256 memory); /** * Get all risk parameter limits in a single struct. These are the maximum limits at which the * risk parameters can be set by the admin of DolomiteMargin. * * @return All global risk parameter limits */ function getRiskLimits() external view returns (Storage.RiskLimits memory); // ============ Getters for Markets ============ /** * Get the total number of markets. * * @return The number of markets */ function getNumMarkets() external view returns (uint256); /** * Get the ERC20 token address for a market. * * @param token The token to query * @return The token's marketId if the token is valid */ function getMarketIdByTokenAddress( address token ) external view returns (uint256); /** * Get the ERC20 token address for a market. * * @param marketId The market to query * @return The token address */ function getMarketTokenAddress( uint256 marketId ) external view returns (address); /** * Return true if a particular market is in closing mode. Additional borrows cannot be taken * from a market that is closing. * * @param marketId The market to query * @return True if the market is closing */ function getMarketIsClosing( uint256 marketId ) external view returns (bool); /** * Get the price of the token for a market. * * @param marketId The market to query * @return The price of each atomic unit of the token */ function getMarketPrice( uint256 marketId ) external view returns (Monetary.Price memory); /** * Get the total principal amounts (borrowed and supplied) for a market. * * @param marketId The market to query * @return The total principal amounts */ function getMarketTotalPar( uint256 marketId ) external view returns (Types.TotalPar memory); /** * Get the total principal amounts (borrowed and supplied) for a market. * * @param marketId The market to query * @return The total principal amounts */ function getMarketTotalWei( uint256 marketId ) external view returns (Types.TotalWei memory); /** * Get the most recently cached interest index for a market. * * @param marketId The market to query * @return The most recent index */ function getMarketCachedIndex( uint256 marketId ) external view returns (Interest.Index memory); /** * Get the interest index for a market if it were to be updated right now. * * @param marketId The market to query * @return The estimated current index */ function getMarketCurrentIndex( uint256 marketId ) external view returns (Interest.Index memory); /** * Get the price oracle address for a market. * * @param marketId The market to query * @return The price oracle address */ function getMarketPriceOracle( uint256 marketId ) external view returns (IPriceOracle); /** * Get the interest-setter address for a market. * * @param marketId The market to query * @return The interest-setter address */ function getMarketInterestSetter( uint256 marketId ) external view returns (IInterestSetter); /** * Get the margin premium for a market. A margin premium makes it so that any positions that * include the market require a higher collateralization to avoid being liquidated. * * @param marketId The market to query * @return The market's margin premium */ function getMarketMarginPremium( uint256 marketId ) external view returns (Decimal.D256 memory); /** * Get the spread premium for a market. A spread premium makes it so that any liquidations * that include the market have a higher spread than the global default. * * @param marketId The market to query * @return The market's spread premium */ function getMarketLiquidationSpreadPremium( uint256 marketId ) external view returns (Decimal.D256 memory); /** * Same as getMarketLiquidationSpreadPremium. Added for backwards-compatibility. * * @param marketId The market to query * @return The market's spread premium */ function getMarketSpreadPremium( uint256 marketId ) external view returns (Decimal.D256 memory); /** * Same as getMarketMaxSupplyWei. Added for backwards-compatibility. * * @param marketId The market to query * @return The max amount of the market that can be supplied. Always 0 or positive. */ function getMarketMaxWei( uint256 marketId ) external view returns (Types.Wei memory); /** * Get the max supply amount for a a market. * * @param marketId The market to query * @return The market's max supply amount. Always 0 or positive. */ function getMarketMaxSupplyWei( uint256 marketId ) external view returns (Types.Wei memory); /** * Get the max borrow amount for a a market. * * @param marketId The market to query * @return The market's max borrow amount. Always negative or 0. */ function getMarketMaxBorrowWei( uint256 marketId ) external view returns (Types.Wei memory); /** * Get the market-specific earnings that determines what percentage of the interest paid by borrowers gets passed-on * to suppliers. If the value is set to 0, the override is not set. * * @return The market-specific earnings rate */ function getMarketEarningsRateOverride( uint256 marketId ) external view returns (Decimal.D256 memory); /** * Get the current borrow interest rate for a market. The value is denominated as interest paid per second, and the * number is scaled to have 18 decimals. To get APR, multiply the number returned by 31536000 (seconds in a year). * * @param marketId The market to query * @return The current borrow interest rate */ function getMarketBorrowInterestRatePerSecond( uint256 marketId ) external view returns (Interest.Rate memory); /** * Same as getMarketBorrowInterestRatePerSecond. Added for backwards-compatibility. * * @param marketId The market to query * @return The current borrow interest rate */ function getMarketInterestRate( uint256 marketId ) external view returns (Interest.Rate memory); /** * Get the current borrow interest rate for a market. The value is denominated as interest paid per year, and the * number is scaled to have 18 decimals. * * @param marketId The market to query * @return The current supply interest rate */ function getMarketBorrowInterestRateApr( uint256 marketId ) external view returns (Interest.Rate memory); /** * Get the current supply interest rate for a market. * * @param marketId The market to query * @return The current supply interest rate */ function getMarketSupplyInterestRateApr( uint256 marketId ) external view returns (Interest.Rate memory); /** * Get basic information about a particular market. * * @param marketId The market to query * @return A Storage.Market struct with the current state of the market */ function getMarket( uint256 marketId ) external view returns (Storage.Market memory); /** * Get comprehensive information about a particular market. * * @param marketId The market to query * @return A tuple containing the values: * - A Storage.Market struct with the current state of the market * - The current estimated interest index * - The current token price * - The current market borrow interest rate per second */ function getMarketWithInfo( uint256 marketId ) external view returns ( Storage.Market memory, Interest.Index memory, Monetary.Price memory, Interest.Rate memory ); /** * Get the number of tokens that are owed to the `owner` of DolomiteMargin. The number of excess tokens is * calculated by taking the current number of tokens held in DolomiteMargin, adding the number of tokens owed to * DolomiteMargin by borrowers, and subtracting the number of tokens owed to suppliers by DolomiteMargin. * * @param marketId The market to query * @return The number of excess tokens */ function getNumExcessTokens( uint256 marketId ) external view returns (Types.Wei memory); // ============ Getters for Accounts ============ /** * Get the principal value for a particular account and market. * * @param account The account to query * @param marketId The market to query * @return The principal value */ function getAccountPar( Account.Info calldata account, uint256 marketId ) external view returns (Types.Par memory); /** * Get the token balance for a particular account and market. * * @param account The account to query * @param marketId The market to query * @return The token amount */ function getAccountWei( Account.Info calldata account, uint256 marketId ) external view returns (Types.Wei memory); /** * Get the status of an account (Normal, Liquidating, or Vaporizing). * * @param account The account to query * @return The account's status */ function getAccountStatus( Account.Info calldata account ) external view returns (Account.Status); /** * Get a list of markets that have a non-zero balance for an account * * @param account The account to query * @return The non-sorted marketIds with non-zero balance for the account. */ function getAccountMarketsWithBalances( Account.Info calldata account ) external view returns (uint256[] memory); /** * Get the number of markets that have a non-zero balance for an account * * @param account The account to query * @return The number of markets with a non-zero balance for the account. */ function getAccountNumberOfMarketsWithBalances( Account.Info calldata account ) external view returns (uint256); /** * Get the marketId for an account's market with a non-zero balance at the given index * * @param account The account to query * @return The market ID in the provided index for the account. */ function getAccountMarketWithBalanceAtIndex( Account.Info calldata account, uint256 index ) external view returns (uint256); /** * Get the number of markets with which an account has a negative balance. * * @param account The account to query * @return The number of markets with a negative balance for this account. */ function getAccountNumberOfMarketsWithDebt( Account.Info calldata account ) external view returns (uint256); /** * Get the total supplied and total borrowed value of an account. * * @param account The account to query * @return The following values: * - The supplied value of the account * - The borrowed value of the account */ function getAccountValues( Account.Info calldata account ) external view returns (Monetary.Value memory, Monetary.Value memory); /** * Get the total supplied and total borrowed values of an account adjusted by the marginPremium * of each market. Supplied values are divided by (1 + marginPremium) for each market and * borrowed values are multiplied by (1 + marginPremium) for each market. Comparing these * adjusted values gives the margin-ratio of the account which will be compared to the global * margin-ratio when determining if the account can be liquidated. * * @param account The account to query * @return The following values: * - The supplied value of the account (adjusted for marginPremium) * - The borrowed value of the account (adjusted for marginPremium) */ function getAdjustedAccountValues( Account.Info calldata account ) external view returns (Monetary.Value memory, Monetary.Value memory); /** * Get an account's summary for each market. * * @param account The account to query * @return The following values: * - The market IDs for each market * - The ERC20 token address for each market * - The account's principal value for each market * - The account's (supplied or borrowed) number of tokens for each market */ function getAccountBalances( Account.Info calldata account ) external view returns (uint[] memory, address[] memory, Types.Par[] memory, Types.Wei[] memory); // ============ Getters for Account Permissions ============ /** * Return true if a particular address is approved as an operator for an owner's accounts. * Approved operators can act on the accounts of the owner as if it were the operator's own. * * @param owner The owner of the accounts * @param operator The possible operator * @return True if operator is approved for owner's accounts */ function getIsLocalOperator( address owner, address operator ) external view returns (bool); /** * Return true if a particular address is approved as a global operator. Such an address can * act on any account as if it were the operator's own. * * @param operator The address to query * @return True if operator is a global operator */ function getIsGlobalOperator( address operator ) external view returns (bool); /** * Checks if the autoTrader can only be called invoked by a global operator * * @param autoTrader The trader that should be checked for special call privileges. */ function getIsAutoTraderSpecial(address autoTrader) external view returns (bool); // ============ Write Functions ============ /** * The main entry-point to DolomiteMargin that allows users and contracts to manage accounts. * Take one or more actions on one or more accounts. The msg.sender must be the owner or * operator of all accounts except for those being liquidated, vaporized, or traded with. * One call to operate() is considered a singular "operation". Account collateralization is * ensured only after the completion of the entire operation. * * @param accounts A list of all accounts that will be used in this operation. Cannot contain * duplicates. In each action, the relevant account will be referred-to by its * index in the list. * @param actions An ordered list of all actions that will be taken in this operation. The * actions will be processed in order. */ function operate( Account.Info[] calldata accounts, Actions.ActionArgs[] calldata actions ) external; /** * Approves/disapproves any number of operators. An operator is an external address that has the * same permissions to manipulate an account as the owner of the account. Operators are simply * addresses and therefore may either be externally-owned Ethereum accounts OR smart contracts. * * Operators are also able to act as AutoTrader contracts on behalf of the account owner if the * operator is a smart contract and implements the IAutoTrader interface. * * @param args A list of OperatorArgs which have an address and a boolean. The boolean value * denotes whether to approve (true) or revoke approval (false) for that address. */ function setOperators( Types.OperatorArg[] calldata args ) external; // ========================================= // ============ Owner Functions ============ // ========================================= // ============ Token Functions ============ /** * Withdraw an ERC20 token for which there is an associated market. Only excess tokens can be withdrawn. The number * of excess tokens is calculated by taking the current number of tokens held in DolomiteMargin, adding the number * of tokens owed to DolomiteMargin by borrowers, and subtracting the number of tokens owed to suppliers by * DolomiteMargin. */ function ownerWithdrawExcessTokens( uint256 marketId, address recipient ) external returns (uint256); /** * Withdraw an ERC20 token for which there is no associated market. */ function ownerWithdrawUnsupportedTokens( address token, address recipient ) external returns (uint256); // ============ Market Functions ============ /** * Add a new market to DolomiteMargin. Must be for a previously-unsupported ERC20 token. */ function ownerAddMarket( address token, IPriceOracle priceOracle, IInterestSetter interestSetter, Decimal.D256 calldata marginPremium, Decimal.D256 calldata spreadPremium, uint256 maxSupplyWei, uint256 maxBorrowWei, Decimal.D256 calldata earningsRateOverride, bool isClosing ) external; /** * Set (or unset) the status of a market to "closing". The borrowedValue of a market cannot increase while its * status is "closing". */ function ownerSetIsClosing( uint256 marketId, bool isClosing ) external; /** * Set the price oracle for a market. */ function ownerSetPriceOracle( uint256 marketId, IPriceOracle priceOracle ) external; /** * Set the interest-setter for a market. */ function ownerSetInterestSetter( uint256 marketId, IInterestSetter interestSetter ) external; /** * Set a premium on the minimum margin-ratio for a market. This makes it so that any positions that include this * market require a higher collateralization to avoid being liquidated. */ function ownerSetMarginPremium( uint256 marketId, Decimal.D256 calldata marginPremium ) external; /** * Set a premium on the liquidation spread for a market. This makes it so that any liquidations that include this * market have a higher spread than the global default. */ function ownerSetLiquidationSpreadPremium( uint256 marketId, Decimal.D256 calldata liquidationSpreadPremium ) external; /** * Sets the maximum supply wei for a given `marketId`. */ function ownerSetMaxSupplyWei( uint256 marketId, uint256 maxSupplyWei ) external; /** * Sets the maximum borrow wei for a given `marketId`. */ function ownerSetMaxBorrowWei( uint256 marketId, uint256 maxBorrowWei ) external; /** * Sets the earnings rate override for a given `marketId`. Set it to 0 unset the override. */ function ownerSetEarningsRateOverride( uint256 marketId, Decimal.D256 calldata earningsRateOverride ) external; // ============ Risk Functions ============ /** * Set the global minimum margin-ratio that every position must maintain to prevent being liquidated. */ function ownerSetMarginRatio( Decimal.D256 calldata ratio ) external; /** * Set the global liquidation spread. This is the spread between oracle prices that incentivizes the liquidation of * risky positions. */ function ownerSetLiquidationSpread( Decimal.D256 calldata spread ) external; /** * Set the global earnings-rate variable that determines what percentage of the interest paid by borrowers gets * passed-on to suppliers. */ function ownerSetEarningsRate( Decimal.D256 calldata earningsRate ) external; /** * Set the global minimum-borrow value which is the minimum value of any new borrow on DolomiteMargin. */ function ownerSetMinBorrowedValue( Monetary.Value calldata minBorrowedValue ) external; /** * Sets the number of non-zero balances an account may have within the same `accountIndex`. This ensures a user * cannot DOS the system by filling their account with non-zero balances (which linearly increases gas costs when * checking collateralization) and disallowing themselves to close the position, because the number of gas units * needed to process their transaction exceed the block's gas limit. In turn, this would prevent the user from also * being liquidated, causing the all of the capital to be "stuck" in the position. * * Lowering this number does not "freeze" user accounts that have more than the new limit of balances, because this * variable is enforced by checking the users number of non-zero balances against the max or if it sizes down before * each transaction finishes. */ function ownerSetAccountMaxNumberOfMarketsWithBalances( uint256 accountMaxNumberOfMarketsWithBalances ) external; /** * Sets the current oracle sentinel used to report if borrowing and liquidations are enabled. */ function ownerSetOracleSentinel( IOracleSentinel oracleSentinel ) external; /** * Sets the gas limit that's passed to any of the callback functions */ function ownerSetCallbackGasLimit( uint256 callbackGasLimit ) external; /** * Sets the account risk override setter by default for any account */ function ownerSetDefaultAccountRiskOverride( IAccountRiskOverrideSetter accountRiskOverrideSetter ) external; /** * Sets the account risk override setter for a given wallet */ function ownerSetAccountRiskOverride( address accountOwner, IAccountRiskOverrideSetter accountRiskOverrideSetter ) external; // ============ Global Operator Functions ============ /** * Approve (or disapprove) an address that is permissioned to be an operator for all accounts in DolomiteMargin. * Intended only to approve smart-contracts. */ function ownerSetGlobalOperator( address operator, bool approved ) external; /** * Approve (or disapprove) an auto trader that can only be called by a global operator. IE for expirations */ function ownerSetAutoTraderSpecial( address autoTrader, bool special ) external; // ============ Owner Functions ============ /** * @dev Returns the address of the current owner. */ function owner() external view returns (address); /** * @dev Returns true if the caller is the current owner. */ function isOwner() external view returns (bool); /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() external; /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) external; }
/* Copyright 2023 Dolomite. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity >=0.5.0; pragma experimental ABIEncoderV2; import { Account } from "../lib/Account.sol"; import { Decimal } from "../lib/Decimal.sol"; /** * @title IAccountRiskOverrideSetter * @author Dolomite * * @notice Interface that can be implemented by any contract that needs to implement risk overrides for an account. */ interface IAccountRiskOverrideSetter { /** * @notice Gets the risk overrides for a given account owner. * * @param _account The account whose risk override should be retrieved. * @return marginRatioOverride The margin ratio override for this account. * @return liquidationSpreadOverride The liquidation spread override for this account. */ function getAccountRiskOverride( Account.Info calldata _account ) external view returns ( Decimal.D256 memory marginRatioOverride, Decimal.D256 memory liquidationSpreadOverride ); }
pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
/* Copyright 2020 Dolomite. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.7; pragma experimental ABIEncoderV2; import { IPriceOracle } from "../../protocol/interfaces/IPriceOracle.sol"; import { IChainlinkAggregator } from "../interfaces/IChainlinkAggregator.sol"; /** * @title IChainlinkPriceOracleV1 * @author Dolomite * * An implementation of the IPriceOracle interface that makes Chainlink prices compatible with the protocol. */ contract IChainlinkPriceOracleV1 is IPriceOracle { // ============ Events ============ event StalenessDurationUpdated(uint256 stalenessDuration); event TokenInsertedOrUpdated( address indexed token, address indexed aggregator, address indexed tokenPair ); // ============ Admin Functions ============ /** * @dev Sets the new `stalenessThreshold`. This function can only be called by the owner of DolomiteMargin. * * @param _stalenessThreshold The duration of time that must pass before a price is considered stale from a * Chainlink Aggregator */ function ownerSetStalenessThreshold( uint256 _stalenessThreshold ) external; /** * @dev Insert or update a token in the oracle. This function can only be called by the owner of DolomiteMargin. * * @param _token The token whose Chainlink aggregator should be inserted or updated * @param _tokenDecimals The number of decimals that this token has * @param _chainlinkAggregator The Chainlink aggregator that corresponds with this token * @param _tokenPair The token pair that corresponds with this token. The zero address means USD. */ function ownerInsertOrUpdateOracleToken( address _token, uint8 _tokenDecimals, address _chainlinkAggregator, address _tokenPair ) external; // ============ Getter Functions ============ /** * * @param _token The token whose Chainlink aggregator should be retrieved * @return The aggregator that corresponds with this token */ function getAggregatorByToken(address _token) external view returns (IChainlinkAggregator); /** * @param _token The token whose decimals should be retrieved * @return The number of decimals that this token has */ function getDecimalsByToken(address _token) external view returns (uint8); /** * @param _token The token whose token pair should be retrieved * @return _tokenPair The token pair that corresponds with this token. The zero address means USD. */ function getTokenPairByToken(address _token) external view returns (address _tokenPair); /** * @return The duration of time that must pass before a price is considered stale from a Chainlink Aggregator */ function stalenessThreshold() external view returns (uint256); }
/* Copyright 2020 Dolomite. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.7; pragma experimental ABIEncoderV2; import { IChainlinkAccessControlAggregator } from "./IChainlinkAccessControlAggregator.sol"; /** * @title IChainlinkAggregator * @author Dolomite * * Gets the latest price from the Chainlink Oracle Network. Amount of decimals depends on the base. */ contract IChainlinkAggregator { function aggregator() external view returns (IChainlinkAccessControlAggregator); function decimals() external view returns (uint8); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); }
/* Copyright 2020 Dolomite. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.7; pragma experimental ABIEncoderV2; /** * @title IChainlinkAccessControlAggregator * @author Dolomite * * Gets configuration for an aggregator proxy */ contract IChainlinkAccessControlAggregator { function minAnswer() external view returns (int192); function maxAnswer() external view returns (int192); }
/* Copyright 2022 Dolomite. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.7; pragma experimental ABIEncoderV2; import { IDolomiteMargin } from "../../protocol/interfaces/IDolomiteMargin.sol"; import { Require } from "../../protocol/lib/Require.sol"; /** * @title OnlyDolomiteMargin * @author Dolomite * * Inheritable contract that restricts the calling of certain functions to DolomiteMargin only */ contract OnlyDolomiteMargin { // ============ Constants ============ bytes32 private constant FILE = "OnlyDolomiteMargin"; // ============ Storage ============ IDolomiteMargin public DOLOMITE_MARGIN; // ============ Constructor ============ constructor ( address _dolomiteMargin ) public { DOLOMITE_MARGIN = IDolomiteMargin(_dolomiteMargin); } // ============ Modifiers ============ modifier onlyDolomiteMargin(address _from) { Require.that( _from == address(DOLOMITE_MARGIN), FILE, "Only Dolomite can call function", _from ); _; } modifier onlyDolomiteMarginOwner(address _from) { Require.that( _from == DOLOMITE_MARGIN.owner(), FILE, "Only Dolomite owner can call", _from ); _; } modifier onlyGlobalOperator(address _from) { Require.that( DOLOMITE_MARGIN.getIsGlobalOperator(_from), FILE, "Only global operator can call", _from ); _; } }
{ "remappings": [], "optimizer": { "enabled": true, "runs": 10000 }, "evmVersion": "istanbul", "libraries": {}, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } } }
Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
Contract ABI
API[{"inputs":[{"internalType":"address[]","name":"_tokens","type":"address[]"},{"internalType":"address[]","name":"_chainlinkAggregators","type":"address[]"},{"internalType":"uint8[]","name":"_tokenDecimals","type":"uint8[]"},{"internalType":"address[]","name":"_tokenPairs","type":"address[]"},{"internalType":"address","name":"_dolomiteMargin","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"stalenessDuration","type":"uint256"}],"name":"StalenessDurationUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":true,"internalType":"address","name":"aggregator","type":"address"},{"indexed":true,"internalType":"address","name":"tokenPair","type":"address"}],"name":"TokenInsertedOrUpdated","type":"event"},{"constant":true,"inputs":[],"name":"DOLOMITE_MARGIN","outputs":[{"internalType":"contract IDolomiteMargin","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"ONE_DOLLAR","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_token","type":"address"}],"name":"getAggregatorByToken","outputs":[{"internalType":"contract IChainlinkAggregator","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_token","type":"address"}],"name":"getDecimalsByToken","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_token","type":"address"}],"name":"getPrice","outputs":[{"components":[{"internalType":"uint256","name":"value","type":"uint256"}],"internalType":"struct Monetary.Price","name":"","type":"tuple"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_token","type":"address"}],"name":"getTokenPairByToken","outputs":[{"internalType":"address","name":"_tokenPair","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_token","type":"address"},{"internalType":"uint8","name":"_tokenDecimals","type":"uint8"},{"internalType":"address","name":"_chainlinkAggregator","type":"address"},{"internalType":"address","name":"_tokenPair","type":"address"}],"name":"ownerInsertOrUpdateOracleToken","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"_stalenessThreshold","type":"uint256"}],"name":"ownerSetStalenessThreshold","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"stalenessThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint8","name":"_tokenDecimals","type":"uint8"},{"internalType":"uint256","name":"_value","type":"uint256"},{"internalType":"uint8","name":"_valueDecimals","type":"uint8"}],"name":"standardizeNumberOfDecimals","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"pure","type":"function"}]
Contract Creation Code
60806040523480156200001157600080fd5b5060405162002580380380620025808339810160408190526200003491620008d1565b600080546001600160a01b0319166001600160a01b038316179055835185516200009c9114600080516020620025608339815191527f496e76616c696420746f6b656e73206c656e6774680000000000000000000000620001d1602090811b62000b0217901c565b620000e78351855114600080516020620025608339815191527f496e76616c69642061676772656761746f7273206c656e677468000000000000620001d160201b62000b021760201c565b620001328251845114600080516020620025608339815191527f496e76616c696420646563696d616c73206c656e677468000000000000000000620001d160201b62000b021760201c565b845160005b81811015620001ad57620001a48782815181106200015157fe5b60200260200101518683815181106200016657fe5b60200260200101518884815181106200017b57fe5b60200260200101518785815181106200019057fe5b60200260200101516200024f60201b60201c565b60010162000137565b50620001c56201fa406001600160e01b036200037716565b50505050505062000c3a565b826200024a57620001eb826001600160e01b036200045516565b6101d160f51b62000205836001600160e01b036200045516565b604051602001620002199392919062000a80565b60408051601f198184030181529082905262461bcd60e51b8252620002419160040162000b21565b60405180910390fd5b505050565b6001600160a01b03848116600090815260016020908152604080832080546001600160a01b03191687861617905560029091529020805460ff191660ff861617905581161562000327576001600160a01b03818116600090815260016020908152604090912054620002f8921615159060008051602062002560833981519152907124b73b30b634b2103a37b5b2b7103830b4b960711b908590620009b2620004e2821b17901c565b6001600160a01b03848116600090815260036020526040902080546001600160a01b0319169183169190911790555b806001600160a01b0316826001600160a01b0316856001600160a01b03167ff6dcff57d435662a867049d43b76e51e72ffba006347ec701ce100b59ee6da3760405160405180910390a450505050565b620003c562015180821015600080516020620025608339815191527f5374616c656e657373207468726573686f6c6420746f6f206c6f770000000000846200055260201b6200117e1760201c565b6200041362093a80821115600080516020620025608339815191527f5374616c656e657373207468726573686f6c6420746f6f206869676800000000846200055260201b6200117e1760201c565b60048190556040517f831d03dda5fa6d81b12a8581f2ee8a25cb44b61429b62e96787e0ba64628464e906200044a90839062000b3b565b60405180910390a150565b606080826040516020016200046b919062000a69565b60408051601f19818403018152919052905060205b8015620004c5578151600019909101908290829081106200049d57fe5b01602001516001600160f81b03191615620004bf5760010181529050620004dd565b62000480565b5060408051600080825260208201909252905b509150505b919050565b836200054c57620004fc836001600160e01b036200045516565b6101d160f51b62000516846001600160e01b036200045516565b61080f60f21b62000530856001600160e01b03620005a016565b60405162000219959493929190601f60f91b9060200162000ab7565b50505050565b836200054c576200056c836001600160e01b036200045516565b6101d160f51b62000586846001600160e01b036200045516565b61080f60f21b62000530856001600160e01b03620006c616565b60408051602a80825260608281019093526001600160a01b038416918391602082018180388339019050509050603060f81b81600081518110620005e057fe5b60200101906001600160f81b031916908160001a905350607860f81b816001815181106200060a57fe5b60200101906001600160f81b031916908160001a90535060005b6014811015620004d8576002810262000649600f85166001600160e01b036200078b16565b8382602903815181106200065957fe5b60200101906001600160f81b031916908160001a90535060049390931c926200068e600f85166001600160e01b036200078b16565b8382602803815181106200069e57fe5b60200101906001600160f81b031916908160001a9053505060049290921c9160010162000624565b606081620006ed57506040805180820190915260018152600360fc1b6020820152620004dd565b8160005b81156200070757600101600a82049150620006f1565b6060816040519080825280601f01601f19166020018201604052801562000735576020820181803883390190505b508593509050815b8015620007825760001901600a840660300160f81b8282815181106200075f57fe5b60200101906001600160f81b031916908160001a905350600a840493506200073d565b50949350505050565b6000600a821015620007a557506030810160f81b620004dd565b5060570160f81b90565b8051620007bc8162000c15565b92915050565b600082601f830112620007d457600080fd5b8151620007eb620007e58262000b72565b62000b4b565b915081818352602084019350602081019050838560208402820111156200081157600080fd5b60005b838110156200084157816200082a8882620007af565b845250602092830192919091019060010162000814565b5050505092915050565b600082601f8301126200085d57600080fd5b81516200086e620007e58262000b72565b915081818352602084019350602081019050838560208402820111156200089457600080fd5b60005b83811015620008415781620008ad8882620008c4565b845250602092830192919091019060010162000897565b8051620007bc8162000c2f565b600080600080600060a08688031215620008ea57600080fd5b85516001600160401b038111156200090157600080fd5b6200090f88828901620007c2565b95505060208601516001600160401b038111156200092c57600080fd5b6200093a88828901620007c2565b94505060408601516001600160401b038111156200095757600080fd5b62000965888289016200084b565b93505060608601516001600160401b038111156200098257600080fd5b6200099088828901620007c2565b9250506080620009a388828901620007af565b9150509295509295909350565b620009c5620009bf8262000bad565b62000bc7565b82525050565b620009c5620009bf8262000bba565b620009c5620009bf8262000bc7565b6000620009f68262000b93565b62000a028185620004dd565b935062000a1481856020860162000bdc565b9290920192915050565b600062000a2b8262000b93565b62000a37818562000b97565b935062000a4981856020860162000bdc565b62000a548162000c0b565b9093019392505050565b620009c58162000bc7565b600062000a778284620009da565b50602001919050565b600062000a8e8286620009e9565b915062000a9c8285620009cb565b60028201915062000aae8284620009e9565b95945050505050565b600062000ac58289620009e9565b915062000ad38288620009cb565b60028201915062000ae58287620009e9565b915062000af38286620009cb565b60028201915062000b058285620009e9565b915062000b138284620009b0565b506001019695505050505050565b6020808252810162000b34818462000a1e565b9392505050565b60208101620007bc828462000a5e565b6040518181016001600160401b038111828210171562000b6a57600080fd5b604052919050565b60006001600160401b0382111562000b8957600080fd5b5060209081020190565b5190565b90815260200190565b6000620007bc8262000bca565b6001600160f81b03191690565b6001600160f01b03191690565b90565b6001600160a01b031690565b60ff1690565b60005b8381101562000bf957818101518382015260200162000bdf565b838111156200054c5750506000910152565b601f01601f191690565b62000c208162000ba0565b811462000c2c57600080fd5b50565b62000c208162000bd6565b6119168062000c4a6000396000f3fe608060405234801561001057600080fd5b50600436106100be5760003560e01c806370363ed6116100765780638cfcee811161005b5780638cfcee81146101715780639c489b0b14610191578063a84f6ebb146101a4576100be565b806370363ed61461014b57806378f875b41461015e576100be565b806348f8c5c2116100a757806348f8c5c21461010157806356721d9814610116578063572ca9e714610136576100be565b806315c14a4a146100c357806341976e09146100e1575b600080fd5b6100cb6101ac565b6040516100d8919061173e565b60405180910390f35b6100f46100ef366004611387565b6101c8565b6040516100d8919061176d565b61011461010f366004611468565b610723565b005b610129610124366004611387565b610849565b6040516100d89190611789565b61013e610874565b6040516100d8919061177b565b6100cb610159366004611387565b610887565b61013e61016c366004611519565b6108b2565b61018461017f366004611387565b610903565b6040516100d89190611730565b61011461019f3660046113cb565b61092e565b61013e6109ac565b60005473ffffffffffffffffffffffffffffffffffffffff1681565b6101d0611311565b73ffffffffffffffffffffffffffffffffffffffff828116600090815260016020526040902054610246911615157f436861696e6c696e6b50726963654f7261636c655631000000000000000000007f496e76616c696420746f6b656e00000000000000000000000000000000000000856109b2565b73ffffffffffffffffffffffffffffffffffffffff8083166000908152600160205260408082205481517ffeaf968c00000000000000000000000000000000000000000000000000000000815291519316928291849163feaf968c9160048082019260a092909190829003018186803b1580156102c257600080fd5b505afa1580156102d6573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052506102fa9190810190611486565b5093505092505061036360045461031a8342610ab790919063ffffffff16565b107f436861696e6c696e6b50726963654f7261636c655631000000000000000000007f436861696e6c696e6b2070726963652065787069726564000000000000000000886109b2565b60008373ffffffffffffffffffffffffffffffffffffffff1663245a7bfc6040518163ffffffff1660e01b815260040160206040518083038186803b1580156103ab57600080fd5b505afa1580156103bf573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052506103e3919081019061142c565b90506104b2838273ffffffffffffffffffffffffffffffffffffffff166322adbc786040518163ffffffff1660e01b815260040160206040518083038186803b15801561042f57600080fd5b505afa158015610443573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250610467919081019061144a565b60170b127f436861696e6c696e6b50726963654f7261636c655631000000000000000000007f436861696e6c696e6b20707269636520746f6f206c6f77000000000000000000610b02565b61057f8173ffffffffffffffffffffffffffffffffffffffff166370da2f676040518163ffffffff1660e01b815260040160206040518083038186803b1580156104fb57600080fd5b505afa15801561050f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250610533919081019061144a565b60170b84127f436861696e6c696e6b50726963654f7261636c655631000000000000000000007f436861696e6c696e6b20707269636520746f6f20686967680000000000000000610b02565b73ffffffffffffffffffffffffffffffffffffffff808716600090815260036020908152604080832054600283528184205482517f313ce56700000000000000000000000000000000000000000000000000000000815292518996928316959461064a9460ff909316938893908d169263313ce56792600480840193919291829003018186803b15801561061257600080fd5b505afa158015610626573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525061016c91908101906114fb565b905073ffffffffffffffffffffffffffffffffffffffff82166106845760405180602001604052808281525097505050505050505061071e565b600061068f836101c8565b5173ffffffffffffffffffffffffffffffffffffffff8416600090815260026020526040812054919250906106d190839060ff16600a0a63ffffffff610b5116565b905060405180602001604052806107106ec097ce7bc90715b34b9f10000000006107048588610b5190919063ffffffff16565b9063ffffffff610ba516565b905299505050505050505050505b919050565b3361083c6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16638da5cb5b6040518163ffffffff1660e01b815260040160206040518083038186803b15801561078e57600080fd5b505afa1580156107a2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052506107c691908101906113ad565b73ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff16147f4f6e6c79446f6c6f6d6974654d617267696e00000000000000000000000000007f4f6e6c7920446f6c6f6d697465206f776e65722063616e2063616c6c00000000846109b2565b61084582610be7565b5050565b73ffffffffffffffffffffffffffffffffffffffff1660009081526002602052604090205460ff1690565b6ec097ce7bc90715b34b9f100000000081565b73ffffffffffffffffffffffffffffffffffffffff9081166000908152600160205260409020541690565b600060ff8416600a0a816108db6ec097ce7bc90715b34b9f10000000008363ffffffff610ba516565b905060ff8416600a0a6108f881610704888563ffffffff610b5116565b979650505050505050565b73ffffffffffffffffffffffffffffffffffffffff9081166000908152600360205260409020541690565b336109996000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16638da5cb5b6040518163ffffffff1660e01b815260040160206040518083038186803b15801561078e57600080fd5b6109a585858585610ccb565b5050505050565b60045481565b83610ab1576109c083610e98565b7f3a200000000000000000000000000000000000000000000000000000000000006109ea84610e98565b7f203c000000000000000000000000000000000000000000000000000000000000610a1485610f70565b604051610a4a9594939291907f3e00000000000000000000000000000000000000000000000000000000000000906020016116d2565b604080517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0818403018152908290527f08c379a0000000000000000000000000000000000000000000000000000000008252610aa89160040161174c565b60405180910390fd5b50505050565b6000610af983836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f7700008152506110e7565b90505b92915050565b82610b4c57610b1082610e98565b7f3a20000000000000000000000000000000000000000000000000000000000000610b3a83610e98565b604051602001610a4a939291906116a1565b505050565b600082610b6057506000610afc565b82820282848281610b6d57fe5b0414610af9576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610aa89061175d565b6000610af983836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f00000000000081525061112d565b610c39620151808210157f436861696e6c696e6b50726963654f7261636c655631000000000000000000007f5374616c656e657373207468726573686f6c6420746f6f206c6f7700000000008461117e565b610c8b62093a808211157f436861696e6c696e6b50726963654f7261636c655631000000000000000000007f5374616c656e657373207468726573686f6c6420746f6f2068696768000000008461117e565b60048190556040517f831d03dda5fa6d81b12a8581f2ee8a25cb44b61429b62e96787e0ba64628464e90610cc090839061177b565b60405180910390a150565b73ffffffffffffffffffffffffffffffffffffffff848116600090815260016020908152604080832080547fffffffffffffffffffffffff0000000000000000000000000000000000000000168786161790556002909152902080547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff001660ff8616179055811615610e215773ffffffffffffffffffffffffffffffffffffffff818116600090815260016020526040902054610dcd911615157f436861696e6c696e6b50726963654f7261636c655631000000000000000000007f496e76616c696420746f6b656e20706169720000000000000000000000000000846109b2565b73ffffffffffffffffffffffffffffffffffffffff848116600090815260036020526040902080547fffffffffffffffffffffffff0000000000000000000000000000000000000000169183169190911790555b8073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff168573ffffffffffffffffffffffffffffffffffffffff167ff6dcff57d435662a867049d43b76e51e72ffba006347ec701ce100b59ee6da3760405160405180910390a450505050565b60608082604051602001610eac919061168c565b604080517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0818403018152919052905060205b8015610f555781517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff90910190829082908110610f1857fe5b01602001517fff000000000000000000000000000000000000000000000000000000000000001615610f50576001018152905061071e565b610edf565b5060408051600080825260208201909252905b509392505050565b60408051602a808252606082810190935273ffffffffffffffffffffffffffffffffffffffff8416918391602082018180388339019050509050603060f81b81600081518110610fbc57fe5b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916908160001a905350607860f81b81600181518110610ffd57fe5b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916908160001a90535060005b6014811015610f685760028102611048600f85166111e0565b83826029038151811061105757fe5b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916908160001a905350600484901c9350611099600f85166111e0565b8382602803815181106110a857fe5b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916908160001a9053505060049290921c9160010161102f565b60008184841115611125576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610aa8919061174c565b505050900390565b60008183611168576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610aa8919061174c565b50600083858161117457fe5b0495945050505050565b83610ab15761118c83610e98565b7f3a200000000000000000000000000000000000000000000000000000000000006111b684610e98565b7f203c000000000000000000000000000000000000000000000000000000000000610a1485611202565b6000600a8210156111f857506030810160f81b61071e565b5060570160f81b90565b606081611243575060408051808201909152600181527f3000000000000000000000000000000000000000000000000000000000000000602082015261071e565b8160005b811561125b57600101600a82049150611247565b6060816040519080825280601f01601f191660200182016040528015611288576020820181803883390190505b508593509050815b8015611308577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff01600a840660300160f81b8282815181106112ce57fe5b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916908160001a905350600a84049350611290565b50949350505050565b6040518060200160405280600081525090565b8035610afc8161188f565b8051610afc8161188f565b8051610afc816118a6565b8051610afc816118af565b8051610afc816118b8565b8035610afc816118b8565b8035610afc816118c1565b8051610afc816118ca565b8051610afc816118c1565b60006020828403121561139957600080fd5b60006113a58484611324565b949350505050565b6000602082840312156113bf57600080fd5b60006113a5848461132f565b600080600080608085870312156113e157600080fd5b60006113ed8787611324565b94505060206113fe87828801611366565b935050604061140f87828801611324565b925050606061142087828801611324565b91505092959194509250565b60006020828403121561143e57600080fd5b60006113a5848461133a565b60006020828403121561145c57600080fd5b60006113a58484611345565b60006020828403121561147a57600080fd5b60006113a5848461135b565b600080600080600060a0868803121561149e57600080fd5b60006114aa8888611371565b95505060206114bb88828901611350565b94505060406114cc88828901611350565b93505060606114dd88828901611350565b92505060806114ee88828901611371565b9150509295509295909350565b60006020828403121561150d57600080fd5b60006113a5848461137c565b60008060006060848603121561152e57600080fd5b600061153a8686611366565b935050602061154b8682870161135b565b925050604061155c86828701611366565b9150509250925092565b61156f816117a4565b82525050565b61156f611581826117af565b6117f9565b61156f611581826117d4565b61156f611581826117f9565b60006115a982611797565b6115b3818561071e565b93506115c381856020860161183b565b9290920192915050565b61156f816117fc565b60006115e182611797565b6115eb818561179b565b93506115fb81856020860161183b565b61160481611867565b9093019392505050565b600061161b60218361179b565b7f536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f81527f7700000000000000000000000000000000000000000000000000000000000000602082015260400192915050565b80516020830190610ab184825b61156f816117f9565b61156f81611826565b60006116988284611592565b50602001919050565b60006116ad828661159e565b91506116b98285611586565b6002820191506116c9828461159e565b95945050505050565b60006116de828961159e565b91506116ea8288611586565b6002820191506116fa828761159e565b91506117068286611586565b600282019150611716828561159e565b91506117228284611575565b506001019695505050505050565b60208101610afc8284611566565b60208101610afc82846115cd565b60208082528101610af981846115d6565b60208082528101610afc8161160e565b60208101610afc828461166d565b60208101610afc828461167a565b60208101610afc8284611683565b5190565b90815260200190565b6000610afc8261180d565b7fff000000000000000000000000000000000000000000000000000000000000001690565b7fffff0000000000000000000000000000000000000000000000000000000000001690565b90565b6000610afc826117a4565b60170b90565b73ffffffffffffffffffffffffffffffffffffffff1690565b60ff1690565b69ffffffffffffffffffff1690565b60005b8381101561185657818101518382015260200161183e565b83811115610ab15750506000910152565b601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe01690565b611898816117a4565b81146118a357600080fd5b50565b611898816117fc565b61189881611807565b611898816117f9565b61189881611826565b6118988161182c56fea365627a7a72315820e528b3080966e5a7ce3941a1c2990d54a47a64dbbc9309a52edd24872179706b6c6578706572696d656e74616cf564736f6c63430005100040436861696e6c696e6b50726963654f7261636c6556310000000000000000000000000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000000000e000000000000000000000000000000000000000000000000000000000000001200000000000000000000000000000000000000000000000000000000000000160000000000000000000000000836b557cf9ef29fcf49c776841191782df34e4e500000000000000000000000000000000000000000000000000000000000000010000000000000000000000004f9a0e7fd2bf6067db6994cf12e4495df938e6e9000000000000000000000000000000000000000000000000000000000000000100000000000000000000000097d9f9a00dee0004be8ca0a8fa374d486567ee2d0000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000001200000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000
Deployed Bytecode
0x608060405234801561001057600080fd5b50600436106100be5760003560e01c806370363ed6116100765780638cfcee811161005b5780638cfcee81146101715780639c489b0b14610191578063a84f6ebb146101a4576100be565b806370363ed61461014b57806378f875b41461015e576100be565b806348f8c5c2116100a757806348f8c5c21461010157806356721d9814610116578063572ca9e714610136576100be565b806315c14a4a146100c357806341976e09146100e1575b600080fd5b6100cb6101ac565b6040516100d8919061173e565b60405180910390f35b6100f46100ef366004611387565b6101c8565b6040516100d8919061176d565b61011461010f366004611468565b610723565b005b610129610124366004611387565b610849565b6040516100d89190611789565b61013e610874565b6040516100d8919061177b565b6100cb610159366004611387565b610887565b61013e61016c366004611519565b6108b2565b61018461017f366004611387565b610903565b6040516100d89190611730565b61011461019f3660046113cb565b61092e565b61013e6109ac565b60005473ffffffffffffffffffffffffffffffffffffffff1681565b6101d0611311565b73ffffffffffffffffffffffffffffffffffffffff828116600090815260016020526040902054610246911615157f436861696e6c696e6b50726963654f7261636c655631000000000000000000007f496e76616c696420746f6b656e00000000000000000000000000000000000000856109b2565b73ffffffffffffffffffffffffffffffffffffffff8083166000908152600160205260408082205481517ffeaf968c00000000000000000000000000000000000000000000000000000000815291519316928291849163feaf968c9160048082019260a092909190829003018186803b1580156102c257600080fd5b505afa1580156102d6573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052506102fa9190810190611486565b5093505092505061036360045461031a8342610ab790919063ffffffff16565b107f436861696e6c696e6b50726963654f7261636c655631000000000000000000007f436861696e6c696e6b2070726963652065787069726564000000000000000000886109b2565b60008373ffffffffffffffffffffffffffffffffffffffff1663245a7bfc6040518163ffffffff1660e01b815260040160206040518083038186803b1580156103ab57600080fd5b505afa1580156103bf573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052506103e3919081019061142c565b90506104b2838273ffffffffffffffffffffffffffffffffffffffff166322adbc786040518163ffffffff1660e01b815260040160206040518083038186803b15801561042f57600080fd5b505afa158015610443573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250610467919081019061144a565b60170b127f436861696e6c696e6b50726963654f7261636c655631000000000000000000007f436861696e6c696e6b20707269636520746f6f206c6f77000000000000000000610b02565b61057f8173ffffffffffffffffffffffffffffffffffffffff166370da2f676040518163ffffffff1660e01b815260040160206040518083038186803b1580156104fb57600080fd5b505afa15801561050f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250610533919081019061144a565b60170b84127f436861696e6c696e6b50726963654f7261636c655631000000000000000000007f436861696e6c696e6b20707269636520746f6f20686967680000000000000000610b02565b73ffffffffffffffffffffffffffffffffffffffff808716600090815260036020908152604080832054600283528184205482517f313ce56700000000000000000000000000000000000000000000000000000000815292518996928316959461064a9460ff909316938893908d169263313ce56792600480840193919291829003018186803b15801561061257600080fd5b505afa158015610626573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525061016c91908101906114fb565b905073ffffffffffffffffffffffffffffffffffffffff82166106845760405180602001604052808281525097505050505050505061071e565b600061068f836101c8565b5173ffffffffffffffffffffffffffffffffffffffff8416600090815260026020526040812054919250906106d190839060ff16600a0a63ffffffff610b5116565b905060405180602001604052806107106ec097ce7bc90715b34b9f10000000006107048588610b5190919063ffffffff16565b9063ffffffff610ba516565b905299505050505050505050505b919050565b3361083c6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16638da5cb5b6040518163ffffffff1660e01b815260040160206040518083038186803b15801561078e57600080fd5b505afa1580156107a2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052506107c691908101906113ad565b73ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff16147f4f6e6c79446f6c6f6d6974654d617267696e00000000000000000000000000007f4f6e6c7920446f6c6f6d697465206f776e65722063616e2063616c6c00000000846109b2565b61084582610be7565b5050565b73ffffffffffffffffffffffffffffffffffffffff1660009081526002602052604090205460ff1690565b6ec097ce7bc90715b34b9f100000000081565b73ffffffffffffffffffffffffffffffffffffffff9081166000908152600160205260409020541690565b600060ff8416600a0a816108db6ec097ce7bc90715b34b9f10000000008363ffffffff610ba516565b905060ff8416600a0a6108f881610704888563ffffffff610b5116565b979650505050505050565b73ffffffffffffffffffffffffffffffffffffffff9081166000908152600360205260409020541690565b336109996000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16638da5cb5b6040518163ffffffff1660e01b815260040160206040518083038186803b15801561078e57600080fd5b6109a585858585610ccb565b5050505050565b60045481565b83610ab1576109c083610e98565b7f3a200000000000000000000000000000000000000000000000000000000000006109ea84610e98565b7f203c000000000000000000000000000000000000000000000000000000000000610a1485610f70565b604051610a4a9594939291907f3e00000000000000000000000000000000000000000000000000000000000000906020016116d2565b604080517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0818403018152908290527f08c379a0000000000000000000000000000000000000000000000000000000008252610aa89160040161174c565b60405180910390fd5b50505050565b6000610af983836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f7700008152506110e7565b90505b92915050565b82610b4c57610b1082610e98565b7f3a20000000000000000000000000000000000000000000000000000000000000610b3a83610e98565b604051602001610a4a939291906116a1565b505050565b600082610b6057506000610afc565b82820282848281610b6d57fe5b0414610af9576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610aa89061175d565b6000610af983836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f00000000000081525061112d565b610c39620151808210157f436861696e6c696e6b50726963654f7261636c655631000000000000000000007f5374616c656e657373207468726573686f6c6420746f6f206c6f7700000000008461117e565b610c8b62093a808211157f436861696e6c696e6b50726963654f7261636c655631000000000000000000007f5374616c656e657373207468726573686f6c6420746f6f2068696768000000008461117e565b60048190556040517f831d03dda5fa6d81b12a8581f2ee8a25cb44b61429b62e96787e0ba64628464e90610cc090839061177b565b60405180910390a150565b73ffffffffffffffffffffffffffffffffffffffff848116600090815260016020908152604080832080547fffffffffffffffffffffffff0000000000000000000000000000000000000000168786161790556002909152902080547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff001660ff8616179055811615610e215773ffffffffffffffffffffffffffffffffffffffff818116600090815260016020526040902054610dcd911615157f436861696e6c696e6b50726963654f7261636c655631000000000000000000007f496e76616c696420746f6b656e20706169720000000000000000000000000000846109b2565b73ffffffffffffffffffffffffffffffffffffffff848116600090815260036020526040902080547fffffffffffffffffffffffff0000000000000000000000000000000000000000169183169190911790555b8073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff168573ffffffffffffffffffffffffffffffffffffffff167ff6dcff57d435662a867049d43b76e51e72ffba006347ec701ce100b59ee6da3760405160405180910390a450505050565b60608082604051602001610eac919061168c565b604080517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0818403018152919052905060205b8015610f555781517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff90910190829082908110610f1857fe5b01602001517fff000000000000000000000000000000000000000000000000000000000000001615610f50576001018152905061071e565b610edf565b5060408051600080825260208201909252905b509392505050565b60408051602a808252606082810190935273ffffffffffffffffffffffffffffffffffffffff8416918391602082018180388339019050509050603060f81b81600081518110610fbc57fe5b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916908160001a905350607860f81b81600181518110610ffd57fe5b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916908160001a90535060005b6014811015610f685760028102611048600f85166111e0565b83826029038151811061105757fe5b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916908160001a905350600484901c9350611099600f85166111e0565b8382602803815181106110a857fe5b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916908160001a9053505060049290921c9160010161102f565b60008184841115611125576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610aa8919061174c565b505050900390565b60008183611168576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610aa8919061174c565b50600083858161117457fe5b0495945050505050565b83610ab15761118c83610e98565b7f3a200000000000000000000000000000000000000000000000000000000000006111b684610e98565b7f203c000000000000000000000000000000000000000000000000000000000000610a1485611202565b6000600a8210156111f857506030810160f81b61071e565b5060570160f81b90565b606081611243575060408051808201909152600181527f3000000000000000000000000000000000000000000000000000000000000000602082015261071e565b8160005b811561125b57600101600a82049150611247565b6060816040519080825280601f01601f191660200182016040528015611288576020820181803883390190505b508593509050815b8015611308577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff01600a840660300160f81b8282815181106112ce57fe5b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916908160001a905350600a84049350611290565b50949350505050565b6040518060200160405280600081525090565b8035610afc8161188f565b8051610afc8161188f565b8051610afc816118a6565b8051610afc816118af565b8051610afc816118b8565b8035610afc816118b8565b8035610afc816118c1565b8051610afc816118ca565b8051610afc816118c1565b60006020828403121561139957600080fd5b60006113a58484611324565b949350505050565b6000602082840312156113bf57600080fd5b60006113a5848461132f565b600080600080608085870312156113e157600080fd5b60006113ed8787611324565b94505060206113fe87828801611366565b935050604061140f87828801611324565b925050606061142087828801611324565b91505092959194509250565b60006020828403121561143e57600080fd5b60006113a5848461133a565b60006020828403121561145c57600080fd5b60006113a58484611345565b60006020828403121561147a57600080fd5b60006113a5848461135b565b600080600080600060a0868803121561149e57600080fd5b60006114aa8888611371565b95505060206114bb88828901611350565b94505060406114cc88828901611350565b93505060606114dd88828901611350565b92505060806114ee88828901611371565b9150509295509295909350565b60006020828403121561150d57600080fd5b60006113a5848461137c565b60008060006060848603121561152e57600080fd5b600061153a8686611366565b935050602061154b8682870161135b565b925050604061155c86828701611366565b9150509250925092565b61156f816117a4565b82525050565b61156f611581826117af565b6117f9565b61156f611581826117d4565b61156f611581826117f9565b60006115a982611797565b6115b3818561071e565b93506115c381856020860161183b565b9290920192915050565b61156f816117fc565b60006115e182611797565b6115eb818561179b565b93506115fb81856020860161183b565b61160481611867565b9093019392505050565b600061161b60218361179b565b7f536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f81527f7700000000000000000000000000000000000000000000000000000000000000602082015260400192915050565b80516020830190610ab184825b61156f816117f9565b61156f81611826565b60006116988284611592565b50602001919050565b60006116ad828661159e565b91506116b98285611586565b6002820191506116c9828461159e565b95945050505050565b60006116de828961159e565b91506116ea8288611586565b6002820191506116fa828761159e565b91506117068286611586565b600282019150611716828561159e565b91506117228284611575565b506001019695505050505050565b60208101610afc8284611566565b60208101610afc82846115cd565b60208082528101610af981846115d6565b60208082528101610afc8161160e565b60208101610afc828461166d565b60208101610afc828461167a565b60208101610afc8284611683565b5190565b90815260200190565b6000610afc8261180d565b7fff000000000000000000000000000000000000000000000000000000000000001690565b7fffff0000000000000000000000000000000000000000000000000000000000001690565b90565b6000610afc826117a4565b60170b90565b73ffffffffffffffffffffffffffffffffffffffff1690565b60ff1690565b69ffffffffffffffffffff1690565b60005b8381101561185657818101518382015260200161183e565b83811115610ab15750506000910152565b601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe01690565b611898816117a4565b81146118a357600080fd5b50565b611898816117fc565b61189881611807565b611898816117f9565b61189881611826565b6118988161182c56fea365627a7a72315820e528b3080966e5a7ce3941a1c2990d54a47a64dbbc9309a52edd24872179706b6c6578706572696d656e74616cf564736f6c63430005100040
Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)
00000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000000000e000000000000000000000000000000000000000000000000000000000000001200000000000000000000000000000000000000000000000000000000000000160000000000000000000000000836b557cf9ef29fcf49c776841191782df34e4e500000000000000000000000000000000000000000000000000000000000000010000000000000000000000004f9a0e7fd2bf6067db6994cf12e4495df938e6e9000000000000000000000000000000000000000000000000000000000000000100000000000000000000000097d9f9a00dee0004be8ca0a8fa374d486567ee2d0000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000001200000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000
-----Decoded View---------------
Arg [0] : _tokens (address[]): 0x4F9A0e7FD2Bf6067db6994CF12E4495Df938E6e9
Arg [1] : _chainlinkAggregators (address[]): 0x97d9F9A00dEE0004BE8ca0A8fa374d486567eE2D
Arg [2] : _tokenDecimals (uint8[]): 18
Arg [3] : _tokenPairs (address[]): 0x0000000000000000000000000000000000000000
Arg [4] : _dolomiteMargin (address): 0x836b557Cf9eF29fcF49C776841191782df34e4e5
-----Encoded View---------------
13 Constructor Arguments found :
Arg [0] : 00000000000000000000000000000000000000000000000000000000000000a0
Arg [1] : 00000000000000000000000000000000000000000000000000000000000000e0
Arg [2] : 0000000000000000000000000000000000000000000000000000000000000120
Arg [3] : 0000000000000000000000000000000000000000000000000000000000000160
Arg [4] : 000000000000000000000000836b557cf9ef29fcf49c776841191782df34e4e5
Arg [5] : 0000000000000000000000000000000000000000000000000000000000000001
Arg [6] : 0000000000000000000000004f9a0e7fd2bf6067db6994cf12e4495df938e6e9
Arg [7] : 0000000000000000000000000000000000000000000000000000000000000001
Arg [8] : 00000000000000000000000097d9f9a00dee0004be8ca0a8fa374d486567ee2d
Arg [9] : 0000000000000000000000000000000000000000000000000000000000000001
Arg [10] : 0000000000000000000000000000000000000000000000000000000000000012
Arg [11] : 0000000000000000000000000000000000000000000000000000000000000001
Arg [12] : 0000000000000000000000000000000000000000000000000000000000000000
Loading...
Loading
Loading...
Loading
Multichain Portfolio | 34 Chains
Chain | Token | Portfolio % | Price | Amount | Value |
---|
Loading...
Loading
Loading...
Loading
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.