// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, allowance(owner, spender) + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = allowance(owner, spender);
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(address from, address to, uint256 amount) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
// Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
// decrementing then incrementing.
_balances[to] += amount;
}
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
unchecked {
// Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
_balances[account] += amount;
}
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
// Overflow not possible: amount <= accountBalance <= totalSupply.
_totalSupply -= amount;
}
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `amount`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
}
// SPDX-License-Identifier: GPL-3.0-or-later
/*
Copyright 2023 Dolomite
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
pragma solidity ^0.8.9;
/**
* @title IDolomiteInterestSetter
* @author Dolomite
*
* @notice This interface defines the functions that for an interest setter that can be used to determine the interest
* rate of a market.
*/
interface IDolomiteInterestSetter {
// ============ Enum ============
enum InterestSetterType {
None,
Linear,
DoubleExponential,
Other
}
// ============ Structs ============
struct InterestRate {
uint256 value;
}
// ============ Functions ============
/**
* Get the interest rate of a token given some borrowed and supplied amounts
*
* @param token The address of the ERC20 token for the market
* @param borrowWei The total borrowed token amount for the market
* @param supplyWei The total supplied token amount for the market
* @return The interest rate per second
*/
function getInterestRate(
address token,
uint256 borrowWei,
uint256 supplyWei
)
external
view
returns (InterestRate memory);
function interestSetterType() external pure returns (InterestSetterType);
}
// SPDX-License-Identifier: GPL-3.0-or-later
/*
Copyright 2023 Dolomite
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
pragma solidity ^0.8.9;
import { IDolomiteInterestSetter } from "./IDolomiteInterestSetter.sol";
import { IDolomiteMarginAdmin } from "./IDolomiteMarginAdmin.sol";
import { IDolomitePriceOracle } from "./IDolomitePriceOracle.sol";
/**
* @title IDolomiteMargin
* @author Dolomite
*
* @notice The interface for interacting with the main entry-point to DolomiteMargin
*/
interface IDolomiteMargin is IDolomiteMarginAdmin {
// ==================================================
// ================= Write Functions ================
// ==================================================
/**
* The main entry-point to DolomiteMargin that allows users and contracts to manage accounts.
* Take one or more actions on one or more accounts. The msg.sender must be the owner or
* operator of all accounts except for those being liquidated, vaporized, or traded with.
* One call to operate() is considered a singular "operation". Account collateralization is
* ensured only after the completion of the entire operation.
*
* @param accounts A list of all accounts that will be used in this operation. Cannot contain
* duplicates. In each action, the relevant account will be referred-to by its
* index in the list.
* @param actions An ordered list of all actions that will be taken in this operation. The
* actions will be processed in order.
*/
function operate(
AccountInfo[] calldata accounts,
ActionArgs[] calldata actions
) external;
/**
* Approves/disapproves any number of operators. An operator is an external address that has the
* same permissions to manipulate an account as the owner of the account. Operators are simply
* addresses and therefore may either be externally-owned Ethereum accounts OR smart contracts.
*
* Operators are also able to act as AutoTrader contracts on behalf of the account owner if the
* operator is a smart contract and implements the IAutoTrader interface.
*
* @param args A list of OperatorArgs which have an address and a boolean. The boolean value
* denotes whether to approve (true) or revoke approval (false) for that address.
*/
function setOperators(
OperatorArg[] calldata args
) external;
// ==================================================
// ================= Read Functions ================
// ==================================================
// ============ Getters for Markets ============
/**
* Get the ERC20 token address for a market.
*
* @param token The token to query
* @return The token's marketId if the token is valid
*/
function getMarketIdByTokenAddress(
address token
) external view returns (uint256);
/**
* Get the ERC20 token address for a market.
*
* @param marketId The market to query
* @return The token address
*/
function getMarketTokenAddress(
uint256 marketId
) external view returns (address);
/**
* Return the maximum amount of the market that can be supplied on Dolomite. Always 0 or positive.
*
* @param marketId The market to query
* @return The max amount of the market that can be supplied
*/
function getMarketMaxWei(
uint256 marketId
) external view returns (Wei memory);
/**
* Return true if a particular market is in closing mode. Additional borrows cannot be taken
* from a market that is closing.
*
* @param marketId The market to query
* @return True if the market is closing
*/
function getMarketIsClosing(
uint256 marketId
)
external
view
returns (bool);
/**
* Get the price of the token for a market.
*
* @param marketId The market to query
* @return The price of each atomic unit of the token
*/
function getMarketPrice(
uint256 marketId
) external view returns (MonetaryPrice memory);
/**
* Get the total number of markets.
*
* @return The number of markets
*/
function getNumMarkets() external view returns (uint256);
/**
* Get the total principal amounts (borrowed and supplied) for a market.
*
* @param marketId The market to query
* @return The total principal amounts
*/
function getMarketTotalPar(
uint256 marketId
) external view returns (TotalPar memory);
/**
* Get the most recently cached interest index for a market.
*
* @param marketId The market to query
* @return The most recent index
*/
function getMarketCachedIndex(
uint256 marketId
) external view returns (InterestIndex memory);
/**
* Get the interest index for a market if it were to be updated right now.
*
* @param marketId The market to query
* @return The estimated current index
*/
function getMarketCurrentIndex(
uint256 marketId
) external view returns (InterestIndex memory);
/**
* Get the price oracle address for a market.
*
* @param marketId The market to query
* @return The price oracle address
*/
function getMarketPriceOracle(
uint256 marketId
) external view returns (IDolomitePriceOracle);
/**
* Get the interest-setter address for a market.
*
* @param marketId The market to query
* @return The interest-setter address
*/
function getMarketInterestSetter(
uint256 marketId
) external view returns (IDolomiteInterestSetter);
/**
* Get the margin premium for a market. A margin premium makes it so that any positions that
* include the market require a higher collateralization to avoid being liquidated.
*
* @param marketId The market to query
* @return The market's margin premium
*/
function getMarketMarginPremium(
uint256 marketId
) external view returns (Decimal memory);
/**
* Get the spread premium for a market. A spread premium makes it so that any liquidations
* that include the market have a higher spread than the global default.
*
* @param marketId The market to query
* @return The market's spread premium
*/
function getMarketSpreadPremium(
uint256 marketId
) external view returns (Decimal memory);
/**
* Return true if this market can be removed and its ID can be recycled and reused
*
* @param marketId The market to query
* @return True if the market is recyclable
*/
function getMarketIsRecyclable(
uint256 marketId
) external view returns (bool);
/**
* Gets the recyclable markets, up to `n` length. If `n` is greater than the length of the list, 0's are returned
* for the empty slots.
*
* @param n The number of markets to get, bounded by the linked list being smaller than `n`
* @return The list of recyclable markets, in the same order held by the linked list
*/
function getRecyclableMarkets(
uint256 n
) external view returns (uint[] memory);
/**
* Get the current borrower interest rate for a market.
*
* @param marketId The market to query
* @return The current interest rate
*/
function getMarketInterestRate(
uint256 marketId
) external view returns (IDolomiteInterestSetter.InterestRate memory);
/**
* Get basic information about a particular market.
*
* @param marketId The market to query
* @return A Market struct with the current state of the market
*/
function getMarket(
uint256 marketId
) external view returns (Market memory);
/**
* Get comprehensive information about a particular market.
*
* @param marketId The market to query
* @return A tuple containing the values:
* - A Market struct with the current state of the market
* - The current estimated interest index
* - The current token price
* - The current market interest rate
*/
function getMarketWithInfo(
uint256 marketId
)
external
view
returns (
Market memory,
InterestIndex memory,
MonetaryPrice memory,
IDolomiteInterestSetter.InterestRate memory
);
/**
* Get the number of excess tokens for a market. The number of excess tokens is calculated by taking the current
* number of tokens held in DolomiteMargin, adding the number of tokens owed to DolomiteMargin by borrowers, and
* subtracting the number of tokens owed to suppliers by DolomiteMargin.
*
* @param marketId The market to query
* @return The number of excess tokens
*/
function getNumExcessTokens(
uint256 marketId
) external view returns (Wei memory);
// ============ Getters for Accounts ============
/**
* Get the principal value for a particular account and market.
*
* @param account The account to query
* @param marketId The market to query
* @return The principal value
*/
function getAccountPar(
AccountInfo calldata account,
uint256 marketId
) external view returns (Par memory);
/**
* Get the principal value for a particular account and market, with no check the market is valid. Meaning, markets
* that don't exist return 0.
*
* @param account The account to query
* @param marketId The market to query
* @return The principal value
*/
function getAccountParNoMarketCheck(
AccountInfo calldata account,
uint256 marketId
) external view returns (Par memory);
/**
* Get the token balance for a particular account and market.
*
* @param account The account to query
* @param marketId The market to query
* @return The token amount
*/
function getAccountWei(
AccountInfo calldata account,
uint256 marketId
) external view returns (Wei memory);
/**
* Get the status of an account (Normal, Liquidating, or Vaporizing).
*
* @param account The account to query
* @return The account's status
*/
function getAccountStatus(
AccountInfo calldata account
) external view returns (AccountStatus);
/**
* Get a list of markets that have a non-zero balance for an account
*
* @param account The account to query
* @return The non-sorted marketIds with non-zero balance for the account.
*/
function getAccountMarketsWithBalances(
AccountInfo calldata account
) external view returns (uint256[] memory);
/**
* Get the number of markets that have a non-zero balance for an account
*
* @param account The account to query
* @return The non-sorted marketIds with non-zero balance for the account.
*/
function getAccountNumberOfMarketsWithBalances(
AccountInfo calldata account
) external view returns (uint256);
/**
* Get the marketId for an account's market with a non-zero balance at the given index
*
* @param account The account to query
* @return The non-sorted marketIds with non-zero balance for the account.
*/
function getAccountMarketWithBalanceAtIndex(
AccountInfo calldata account,
uint256 index
) external view returns (uint256);
/**
* Get the number of markets with which an account has a negative balance.
*
* @param account The account to query
* @return The non-sorted marketIds with non-zero balance for the account.
*/
function getAccountNumberOfMarketsWithDebt(
AccountInfo calldata account
) external view returns (uint256);
/**
* Get the total supplied and total borrowed value of an account.
*
* @param account The account to query
* @return The following values:
* - The supplied value of the account
* - The borrowed value of the account
*/
function getAccountValues(
AccountInfo calldata account
) external view returns (MonetaryValue memory, MonetaryValue memory);
/**
* Get the total supplied and total borrowed values of an account adjusted by the marginPremium
* of each market. Supplied values are divided by (1 + marginPremium) for each market and
* borrowed values are multiplied by (1 + marginPremium) for each market. Comparing these
* adjusted values gives the margin-ratio of the account which will be compared to the global
* margin-ratio when determining if the account can be liquidated.
*
* @param account The account to query
* @return The following values:
* - The supplied value of the account (adjusted for marginPremium)
* - The borrowed value of the account (adjusted for marginPremium)
*/
function getAdjustedAccountValues(
AccountInfo calldata account
) external view returns (MonetaryValue memory, MonetaryValue memory);
/**
* Get an account's summary for each market.
*
* @param account The account to query
* @return The following values:
* - The market IDs for each market
* - The ERC20 token address for each market
* - The account's principal value for each market
* - The account's (supplied or borrowed) number of tokens for each market
*/
function getAccountBalances(
AccountInfo calldata account
) external view returns (uint[] memory, address[] memory, Par[] memory, Wei[] memory);
// ============ Getters for Account Permissions ============
/**
* Return true if a particular address is approved as an operator for an owner's accounts.
* Approved operators can act on the accounts of the owner as if it were the operator's own.
*
* @param owner The owner of the accounts
* @param operator The possible operator
* @return True if operator is approved for owner's accounts
*/
function getIsLocalOperator(
address owner,
address operator
) external view returns (bool);
/**
* Return true if a particular address is approved as a global operator. Such an address can
* act on any account as if it were the operator's own.
*
* @param operator The address to query
* @return True if operator is a global operator
*/
function getIsGlobalOperator(
address operator
) external view returns (bool);
/**
* Checks if the autoTrader can only be called invoked by a global operator
*
* @param autoTrader The trader that should be checked for special call privileges.
*/
function getIsAutoTraderSpecial(address autoTrader) external view returns (bool);
/**
* @return The address that owns the DolomiteMargin protocol
*/
function owner() external view returns (address);
// ============ Getters for Risk Params ============
/**
* Get the global minimum margin-ratio that every position must maintain to prevent being
* liquidated.
*
* @return The global margin-ratio
*/
function getMarginRatio() external view returns (Decimal memory);
/**
* Get the global liquidation spread. This is the spread between oracle prices that incentivizes
* the liquidation of risky positions.
*
* @return The global liquidation spread
*/
function getLiquidationSpread() external view returns (Decimal memory);
/**
* Get the adjusted liquidation spread for some market pair. This is equal to the global
* liquidation spread multiplied by (1 + spreadPremium) for each of the two markets.
*
* @param heldMarketId The market for which the account has collateral
* @param owedMarketId The market for which the account has borrowed tokens
* @return The adjusted liquidation spread
*/
function getLiquidationSpreadForPair(
uint256 heldMarketId,
uint256 owedMarketId
) external view returns (Decimal memory);
/**
* Get the global earnings-rate variable that determines what percentage of the interest paid
* by borrowers gets passed-on to suppliers.
*
* @return The global earnings rate
*/
function getEarningsRate() external view returns (Decimal memory);
/**
* Get the global minimum-borrow value which is the minimum value of any new borrow on DolomiteMargin.
*
* @return The global minimum borrow value
*/
function getMinBorrowedValue() external view returns (MonetaryValue memory);
/**
* Get all risk parameters in a single struct.
*
* @return All global risk parameters
*/
function getRiskParams() external view returns (RiskParams memory);
/**
* Get all risk parameter limits in a single struct. These are the maximum limits at which the
* risk parameters can be set by the admin of DolomiteMargin.
*
* @return All global risk parameter limits
*/
function getRiskLimits() external view returns (RiskLimits memory);
}
// SPDX-License-Identifier: GPL-3.0-or-later
/*
Copyright 2023 Dolomite
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
pragma solidity ^0.8.9;
import { IDolomiteInterestSetter } from "./IDolomiteInterestSetter.sol";
import { IDolomitePriceOracle } from "./IDolomitePriceOracle.sol";
import { IDolomiteStructs } from "./IDolomiteStructs.sol";
/**
* @title IDolomiteMarginAdmin
* @author Dolomite
*
* @notice This interface defines the functions that can be called by the owner of DolomiteMargin.
*/
interface IDolomiteMarginAdmin is IDolomiteStructs {
// ============ Token Functions ============
/**
* Withdraw an ERC20 token for which there is an associated market. Only excess tokens can be withdrawn. The number
* of excess tokens is calculated by taking the current number of tokens held in DolomiteMargin, adding the number
* of tokens owed to DolomiteMargin by borrowers, and subtracting the number of tokens owed to suppliers by
* DolomiteMargin.
*/
function ownerWithdrawExcessTokens(
uint256 marketId,
address recipient
)
external
returns (uint256);
/**
* Withdraw an ERC20 token for which there is no associated market.
*/
function ownerWithdrawUnsupportedTokens(
address token,
address recipient
)
external
returns (uint256);
// ============ Market Functions ============
/**
* Sets the number of non-zero balances an account may have within the same `accountIndex`. This ensures a user
* cannot DOS the system by filling their account with non-zero balances (which linearly increases gas costs when
* checking collateralization) and disallowing themselves to close the position, because the number of gas units
* needed to process their transaction exceed the block's gas limit. In turn, this would prevent the user from also
* being liquidated, causing the all of the capital to be "stuck" in the position.
*
* Lowering this number does not "freeze" user accounts that have more than the new limit of balances, because this
* variable is enforced by checking the users number of non-zero balances against the max or if it sizes down before
* each transaction finishes.
*/
function ownerSetAccountMaxNumberOfMarketsWithBalances(
uint256 accountMaxNumberOfMarketsWithBalances
)
external;
/**
* Add a new market to DolomiteMargin. Must be for a previously-unsupported ERC20 token.
*/
function ownerAddMarket(
address token,
IDolomitePriceOracle priceOracle,
IDolomiteInterestSetter interestSetter,
Decimal calldata marginPremium,
Decimal calldata spreadPremium,
uint256 maxWei,
bool isClosing,
bool isRecyclable
)
external;
/**
* Removes a market from DolomiteMargin, sends any remaining tokens in this contract to `salvager` and invokes the
* recyclable callback
*/
function ownerRemoveMarkets(
uint[] calldata marketIds,
address salvager
)
external;
/**
* Set (or unset) the status of a market to "closing". The borrowedValue of a market cannot increase while its
* status is "closing".
*/
function ownerSetIsClosing(
uint256 marketId,
bool isClosing
)
external;
/**
* Set the price oracle for a market.
*/
function ownerSetPriceOracle(
uint256 marketId,
IDolomitePriceOracle priceOracle
)
external;
/**
* Set the interest-setter for a market.
*/
function ownerSetInterestSetter(
uint256 marketId,
IDolomiteInterestSetter interestSetter
)
external;
/**
* Set a premium on the minimum margin-ratio for a market. This makes it so that any positions that include this
* market require a higher collateralization to avoid being liquidated.
*/
function ownerSetMarginPremium(
uint256 marketId,
Decimal calldata marginPremium
)
external;
function ownerSetMaxWei(
uint256 marketId,
uint256 maxWei
)
external;
/**
* Set a premium on the liquidation spread for a market. This makes it so that any liquidations that include this
* market have a higher spread than the global default.
*/
function ownerSetSpreadPremium(
uint256 marketId,
Decimal calldata spreadPremium
)
external;
// ============ Risk Functions ============
/**
* Set the global minimum margin-ratio that every position must maintain to prevent being liquidated.
*/
function ownerSetMarginRatio(
Decimal calldata ratio
)
external;
/**
* Set the global liquidation spread. This is the spread between oracle prices that incentivizes the liquidation of
* risky positions.
*/
function ownerSetLiquidationSpread(
Decimal calldata spread
)
external;
/**
* Set the global earnings-rate variable that determines what percentage of the interest paid by borrowers gets
* passed-on to suppliers.
*/
function ownerSetEarningsRate(
Decimal calldata earningsRate
)
external;
/**
* Set the global minimum-borrow value which is the minimum value of any new borrow on DolomiteMargin.
*/
function ownerSetMinBorrowedValue(
MonetaryValue calldata minBorrowedValue
)
external;
// ============ Global Operator Functions ============
/**
* Approve (or disapprove) an address that is permissioned to be an operator for all accounts in DolomiteMargin.
* Intended only to approve smart-contracts.
*/
function ownerSetGlobalOperator(
address operator,
bool approved
)
external;
/**
* Approve (or disapprove) an auto trader that can only be called by a global operator. IE for expirations
*/
function ownerSetAutoTraderSpecial(
address autoTrader,
bool special
)
external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
/*
Copyright 2023 Dolomite
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
pragma solidity ^0.8.9;
import { IDolomiteStructs } from "./IDolomiteStructs.sol";
/**
* @title IDolomitePriceOracle
* @author Dolomite
*
* @notice Interface that Price Oracles for DolomiteMargin must implement in order to report prices.
*/
interface IDolomitePriceOracle {
// ============ Public Functions ============
/**
* Get the price of a token
*
* @param token The ERC20 token address of the market
* @return The USD price of a base unit of the token, then multiplied by 10^(36 - decimals).
* So a USD-stable coin with 6 decimal places would return `price * 10^30`.
* This is the price of the base unit rather than the price of a "human-readable"
* token amount. Every ERC20 may have a different number of decimals.
*/
function getPrice(
address token
)
external
view
returns (IDolomiteStructs.MonetaryPrice memory);
}
// SPDX-License-Identifier: GPL-3.0-or-later
/*
Copyright 2023 Dolomite
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
pragma solidity ^0.8.9;
import { IDolomiteInterestSetter } from "./IDolomiteInterestSetter.sol";
import { IDolomitePriceOracle } from "./IDolomitePriceOracle.sol";
/**
* @title IDolomiteStructs
* @author Dolomite
*
* @notice This interface defines the structs used by DolomiteMargin
*/
interface IDolomiteStructs {
// ========================= Enums =========================
enum ActionType {
Deposit, // supply tokens
Withdraw, // borrow tokens
Transfer, // transfer balance between accounts
Buy, // buy an amount of some token (externally)
Sell, // sell an amount of some token (externally)
Trade, // trade tokens against another account
Liquidate, // liquidate an undercollateralized or expiring account
Vaporize, // use excess tokens to zero-out a completely negative account
Call // send arbitrary data to an address
}
enum AssetDenomination {
Wei, // the amount is denominated in wei
Par // the amount is denominated in par
}
enum AssetReference {
Delta, // the amount is given as a delta from the current value
Target // the amount is given as an exact number to end up at
}
// ========================= Structs =========================
struct AccountInfo {
address owner; // The address that owns the account
uint256 number; // A nonce that allows a single address to control many accounts
}
/**
* Most-recently-cached account status.
*
* Normal: Can only be liquidated if the account values are violating the global margin-ratio.
* Liquid: Can be liquidated no matter the account values.
* Can be vaporized if there are no more positive account values.
* Vapor: Has only negative (or zeroed) account values. Can be vaporized.
*
*/
enum AccountStatus {
Normal,
Liquid,
Vapor
}
/*
* Arguments that are passed to DolomiteMargin in an ordered list as part of a single operation.
* Each ActionArgs has an actionType which specifies which action struct that this data will be
* parsed into before being processed.
*/
struct ActionArgs {
ActionType actionType;
uint256 accountId;
AssetAmount amount;
uint256 primaryMarketId;
uint256 secondaryMarketId;
address otherAddress;
uint256 otherAccountId;
bytes data;
}
struct AssetAmount {
bool sign; // true if positive
AssetDenomination denomination;
AssetReference ref;
uint256 value;
}
struct Decimal {
uint256 value;
}
struct InterestIndex {
uint96 borrow;
uint96 supply;
uint32 lastUpdate;
}
struct Market {
address token;
// Whether additional borrows are allowed for this market
bool isClosing;
// Whether this market can be removed and its ID can be recycled and reused
bool isRecyclable;
// Total aggregated supply and borrow amount of the entire market
TotalPar totalPar;
// Interest index of the market
InterestIndex index;
// Contract address of the price oracle for this market
IDolomitePriceOracle priceOracle;
// Contract address of the interest setter for this market
IDolomiteInterestSetter interestSetter;
// Multiplier on the marginRatio for this market, IE 5% (0.05 * 1e18). This number increases the market's
// required collateralization by: reducing the user's supplied value (in terms of dollars) for this market and
// increasing its borrowed value. This is done through the following operation:
// `suppliedWei = suppliedWei + (assetValueForThisMarket / (1 + marginPremium))`
// This number increases the user's borrowed wei by multiplying it by:
// `borrowedWei = borrowedWei + (assetValueForThisMarket * (1 + marginPremium))`
Decimal marginPremium;
// Multiplier on the liquidationSpread for this market, IE 20% (0.2 * 1e18). This number increases the
// `liquidationSpread` using the following formula:
// `liquidationSpread = liquidationSpread * (1 + spreadPremium)`
// NOTE: This formula is applied up to two times - one for each market whose spreadPremium is greater than 0
// (when performing a liquidation between two markets)
Decimal spreadPremium;
// The maximum amount that can be held by the external. This allows the external to cap any additional risk
// that is inferred by allowing borrowing against low-cap or assets with increased volatility. Setting this
// value to 0 is analogous to having no limit. This value can never be below 0.
Wei maxWei;
}
/*
* The price of a base-unit of an asset. Has `36 - token.decimals` decimals
*/
struct MonetaryPrice {
uint256 value;
}
struct MonetaryValue {
uint256 value;
}
struct OperatorArg {
address operator;
bool trusted;
}
struct Par {
bool sign;
uint256 value;
}
struct RiskLimits {
// The highest that the ratio can be for liquidating under-water accounts
uint64 marginRatioMax;
// The highest that the liquidation rewards can be when a liquidator liquidates an account
uint64 liquidationSpreadMax;
// The highest that the supply APR can be for a market, as a proportion of the borrow rate. Meaning, a rate of
// 100% (1e18) would give suppliers all of the interest that borrowers are paying. A rate of 90% would give
// suppliers 90% of the interest that borrowers pay.
uint64 earningsRateMax;
// The highest min margin ratio premium that can be applied to a particular market. Meaning, a value of 100%
// (1e18) would require borrowers to maintain an extra 100% collateral to maintain a healthy margin ratio. This
// value works by increasing the debt owed and decreasing the supply held for the particular market by this
// amount, plus 1e18 (since a value of 10% needs to be applied as `decimal.plusOne`)
uint64 marginPremiumMax;
// The highest liquidation reward that can be applied to a particular market. This percentage is applied
// in addition to the liquidation spread in `RiskParams`. Meaning a value of 1e18 is 100%. It is calculated as:
// `liquidationSpread * Decimal.onePlus(spreadPremium)`
uint64 spreadPremiumMax;
uint128 minBorrowedValueMax;
}
struct RiskParams {
// Required ratio of over-collateralization
Decimal marginRatio;
// Percentage penalty incurred by liquidated accounts
Decimal liquidationSpread;
// Percentage of the borrower's interest fee that gets passed to the suppliers
Decimal earningsRate;
// The minimum absolute borrow value of an account
// There must be sufficient incentivize to liquidate undercollateralized accounts
MonetaryValue minBorrowedValue;
// The maximum number of markets a user can have a non-zero balance for a given account.
uint256 accountMaxNumberOfMarketsWithBalances;
}
struct TotalPar {
uint128 borrow;
uint128 supply;
}
struct Wei {
bool sign;
uint256 value;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 amount) external returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: GPL-3.0-or-later
/*
Copyright 2023 Dolomite
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
pragma solidity ^0.8.9;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title IOARB
* @author Dolomite
*
* @notice Interface for oARB token
*/
interface IOARB is IERC20 {
// ======================================================
// ================== External Functions ================
// ======================================================
/**
* @notice Mints the provided amount of oARB tokens. Can only be called by dolomite global operator
*
* @param _amount The amount of tokens to mint
*/
function mint(uint256 _amount) external;
/**
* @notice Burns the provided amount of oARB tokens. Can only be called by dolomite global operator
*
* @param _amount The amount of tokens to burn
*/
function burn(uint256 _amount) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
/*
Copyright 2023 Dolomite
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
pragma solidity ^0.8.9;
import { IDolomiteMargin } from "../../protocol/interfaces/IDolomiteMargin.sol";
/**
* @title IOnlyDolomiteMargin
* @author Dolomite
*
* @notice This interface is for contracts that need to add modifiers for only DolomiteMargin / Owner caller.
*/
interface IOnlyDolomiteMargin {
function DOLOMITE_MARGIN() external view returns (IDolomiteMargin);
}
// SPDX-License-Identifier: GPL-3.0-or-later
/*
Copyright 2023 Dolomite
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
pragma solidity ^0.8.9;
import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import { OnlyDolomiteMargin } from "../helpers/OnlyDolomiteMargin.sol";
import { IOARB } from "../interfaces/liquidityMining/IOARB.sol";
/**
* @title OARB
* @author Dolomite
*
* ERC20 contract for oARB tokens
*/
contract OARB is ERC20, OnlyDolomiteMargin, IOARB {
// ===================================================
// ==================== Constants ====================
// ===================================================
bytes32 private constant _FILE = "oARBToken";
// ==================================================================
// ======================= Constructor =======================
// ==================================================================
constructor(
address _dolomiteMargin
) ERC20("oARB Token", "oARB") OnlyDolomiteMargin(_dolomiteMargin) {} // solhint-disable-line no-empty-blocks
// ==================================================================
// ======================= External Functions =======================
// ==================================================================
function mint(uint256 _amount) external onlyDolomiteMarginGlobalOperator(msg.sender) {
_mint(msg.sender, _amount);
}
function burn(uint256 _amount) external onlyDolomiteMarginGlobalOperator(msg.sender) {
_burn(msg.sender, _amount);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
/*
Copyright 2023 Dolomite
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
pragma solidity ^0.8.9;
import { OnlyDolomiteMarginForUpgradeable } from "./OnlyDolomiteMarginForUpgradeable.sol";
import { IDolomiteMargin } from "../../protocol/interfaces/IDolomiteMargin.sol";
/**
* @title OnlyDolomiteMargin
* @author Dolomite
*
* @notice Inheritable contract that restricts the calling of certain functions to `DolomiteMargin`, the owner of
* `DolomiteMargin` or a `DolomiteMargin` global operator
*/
abstract contract OnlyDolomiteMargin is OnlyDolomiteMarginForUpgradeable {
// ============ Constants ============
bytes32 private constant _FILE = "OnlyDolomiteMargin";
// ============ Storage ============
IDolomiteMargin private immutable _DOLOMITE_MARGIN; // solhint-disable-line var-name-mixedcase
// ============ Constructor ============
constructor (address _dolomiteMargin) {
_DOLOMITE_MARGIN = IDolomiteMargin(_dolomiteMargin);
}
// ============ Functions ============
function DOLOMITE_MARGIN() public override view returns (IDolomiteMargin) {
return _DOLOMITE_MARGIN;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
/*
Copyright 2023 Dolomite
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
pragma solidity ^0.8.9;
import { ProxyContractHelpers } from "./ProxyContractHelpers.sol";
import { IDolomiteMargin } from "../../protocol/interfaces/IDolomiteMargin.sol";
import { Require } from "../../protocol/lib/Require.sol";
import { IOnlyDolomiteMargin } from "../interfaces/IOnlyDolomiteMargin.sol";
/**
* @title OnlyDolomiteMarginForUpgradeable
* @author Dolomite
*
* @notice Inheritable contract that restricts the calling of certain functions to `DolomiteMargin`, the owner of
* `DolomiteMargin` or a `DolomiteMargin` global operator
*/
abstract contract OnlyDolomiteMarginForUpgradeable is IOnlyDolomiteMargin, ProxyContractHelpers {
// ============ Constants ============
bytes32 private constant _FILE = "OnlyDolomiteMargin";
bytes32 private constant _DOLOMITE_MARGIN_SLOT = bytes32(uint256(keccak256("eip1967.proxy.dolomiteMargin")) - 1);
// ============ Modifiers ============
modifier onlyDolomiteMargin(address _from) {
Require.that(
_from == address(DOLOMITE_MARGIN()),
_FILE,
"Only Dolomite can call function",
_from
);
_;
}
modifier onlyDolomiteMarginOwner(address _from) {
Require.that(
_from == DOLOMITE_MARGIN().owner(),
_FILE,
"Caller is not owner of Dolomite",
_from
);
_;
}
modifier onlyDolomiteMarginGlobalOperator(address _from) {
Require.that(
DOLOMITE_MARGIN().getIsGlobalOperator(_from),
_FILE,
"Caller is not a global operator",
_from
);
_;
}
// ============ Functions ============
function DOLOMITE_MARGIN() public virtual view returns (IDolomiteMargin) {
return IDolomiteMargin(_getAddress(_DOLOMITE_MARGIN_SLOT));
}
function _setDolomiteMarginViaSlot(address _dolomiteMargin) internal {
_setAddress(_DOLOMITE_MARGIN_SLOT, _dolomiteMargin);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
/*
Copyright 2023 Dolomite
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
pragma solidity ^0.8.9;
/**
* @title ProxyContractHelpers
* @author Dolomite
*
* @notice Helper functions for upgradeable proxy contracts to use
*/
abstract contract ProxyContractHelpers {
// ================ Internal Functions ==================
function _callImplementation(address _implementation) internal {
// solhint-disable-next-line no-inline-assembly
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), _implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
function _setAddress(bytes32 slot, address _value) internal {
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, _value)
}
}
function _setUint256(bytes32 slot, uint256 _value) internal {
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, _value)
}
}
function _getAddress(bytes32 slot) internal view returns (address value) {
// solhint-disable-next-line no-inline-assembly
assembly {
value := sload(slot)
}
}
function _getUint256(bytes32 slot) internal view returns (uint256 value) {
// solhint-disable-next-line no-inline-assembly
assembly {
value := sload(slot)
}
}
}
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2019 dYdX Trading Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.8.9;
/**
* @title Require
* @author dYdX
*
* @notice Stringifies parameters to pretty-print revert messages. Costs more gas than regular require()
*/
library Require {
// ============ Constants ============
uint256 private constant _ASCII_ZERO = 48; // '0'
uint256 private constant _ASCII_RELATIVE_ZERO = 87; // 'a' - 10
uint256 private constant _ASCII_LOWER_EX = 120; // 'x'
bytes2 private constant _COLON = 0x3a20; // ': '
bytes2 private constant _COMMA = 0x2c20; // ', '
bytes2 private constant _LPAREN = 0x203c; // ' <'
bytes1 private constant _RPAREN = 0x3e; // '>'
uint256 private constant _FOUR_BIT_MASK = 0xf;
// ============ Library Functions ============
function that(
bool must,
bytes32 file,
bytes32 reason
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
_COLON,
stringifyTruncated(reason)
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
uint256 payloadA
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
_COLON,
stringifyTruncated(reason),
_LPAREN,
_stringify(payloadA),
_RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
uint256 payloadA,
uint256 payloadB
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
_COLON,
stringifyTruncated(reason),
_LPAREN,
_stringify(payloadA),
_COMMA,
_stringify(payloadB),
_RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
address payloadA
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
_COLON,
stringifyTruncated(reason),
_LPAREN,
_stringify(payloadA),
_RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
address payloadA,
uint256 payloadB
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
_COLON,
stringifyTruncated(reason),
_LPAREN,
_stringify(payloadA),
_COMMA,
_stringify(payloadB),
_RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
address payloadA,
uint256 payloadB,
uint256 payloadC
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
_COLON,
stringifyTruncated(reason),
_LPAREN,
_stringify(payloadA),
_COMMA,
_stringify(payloadB),
_COMMA,
_stringify(payloadC),
_RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
bytes32 payloadA
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
_COLON,
stringifyTruncated(reason),
_LPAREN,
_stringify(payloadA),
_RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
bytes32 payloadA,
uint256 payloadB,
uint256 payloadC
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
_COLON,
stringifyTruncated(reason),
_LPAREN,
_stringify(payloadA),
_COMMA,
_stringify(payloadB),
_COMMA,
_stringify(payloadC),
_RPAREN
)
)
);
}
}
// ============ Private Functions ============
function stringifyTruncated(
bytes32 input
)
internal
pure
returns (bytes memory)
{
// put the input bytes into the result
bytes memory result = abi.encodePacked(input);
// determine the length of the input by finding the location of the last non-zero byte
for (uint256 i = 32; i > 0; ) {
// reverse-for-loops with unsigned integer
i--;
// find the last non-zero byte in order to determine the length
if (result[i] != 0) {
uint256 length = i + 1;
/* solhint-disable-next-line no-inline-assembly */
assembly {
mstore(result, length) // r.length = length;
}
return result;
}
}
// all bytes are zero
return new bytes(0);
}
function stringifyFunctionSelector(
bytes4 input
)
internal
pure
returns (bytes memory)
{
uint256 z = uint256(bytes32(input) >> 224);
// bytes4 are "0x" followed by 4 bytes of data which take up 2 characters each
bytes memory result = new bytes(10);
// populate the result with "0x"
result[0] = bytes1(uint8(_ASCII_ZERO));
result[1] = bytes1(uint8(_ASCII_LOWER_EX));
// for each byte (starting from the lowest byte), populate the result with two characters
for (uint256 i = 0; i < 4; i++) {
// each byte takes two characters
uint256 shift = i * 2;
// populate the least-significant character
result[9 - shift] = _char(z & _FOUR_BIT_MASK);
z = z >> 4;
// populate the most-significant character
result[8 - shift] = _char(z & _FOUR_BIT_MASK);
z = z >> 4;
}
return result;
}
function _stringify(
uint256 input
)
private
pure
returns (bytes memory)
{
if (input == 0) {
return "0";
}
// get the final string length
uint256 j = input;
uint256 length;
while (j != 0) {
length++;
j /= 10;
}
// allocate the string
bytes memory bstr = new bytes(length);
// populate the string starting with the least-significant character
j = input;
for (uint256 i = length; i > 0; ) {
// reverse-for-loops with unsigned integer
i--;
// take last decimal digit
bstr[i] = bytes1(uint8(_ASCII_ZERO + (j % 10)));
// remove the last decimal digit
j /= 10;
}
return bstr;
}
function _stringify(
address input
)
private
pure
returns (bytes memory)
{
uint256 z = uint256(uint160(input));
// addresses are "0x" followed by 20 bytes of data which take up 2 characters each
bytes memory result = new bytes(42);
// populate the result with "0x"
result[0] = bytes1(uint8(_ASCII_ZERO));
result[1] = bytes1(uint8(_ASCII_LOWER_EX));
// for each byte (starting from the lowest byte), populate the result with two characters
for (uint256 i = 0; i < 20; i++) {
// each byte takes two characters
uint256 shift = i * 2;
// populate the least-significant character
result[41 - shift] = _char(z & _FOUR_BIT_MASK);
z = z >> 4;
// populate the most-significant character
result[40 - shift] = _char(z & _FOUR_BIT_MASK);
z = z >> 4;
}
return result;
}
function _stringify(
bytes32 input
)
private
pure
returns (bytes memory)
{
uint256 z = uint256(input);
// bytes32 are "0x" followed by 32 bytes of data which take up 2 characters each
bytes memory result = new bytes(66);
// populate the result with "0x"
result[0] = bytes1(uint8(_ASCII_ZERO));
result[1] = bytes1(uint8(_ASCII_LOWER_EX));
// for each byte (starting from the lowest byte), populate the result with two characters
for (uint256 i = 0; i < 32; i++) {
// each byte takes two characters
uint256 shift = i * 2;
// populate the least-significant character
result[65 - shift] = _char(z & _FOUR_BIT_MASK);
z = z >> 4;
// populate the most-significant character
result[64 - shift] = _char(z & _FOUR_BIT_MASK);
z = z >> 4;
}
return result;
}
function _char(
uint256 input
)
private
pure
returns (bytes1)
{
// return ASCII digit (0-9)
if (input < 10) {
return bytes1(uint8(input + _ASCII_ZERO));
}
// return ASCII letter (a-f)
return bytes1(uint8(input + _ASCII_RELATIVE_ZERO));
}
}
{
"compilationTarget": {
"contracts/external/liquidityMining/OARB.sol": "OARB"
},
"evmVersion": "london",
"libraries": {},
"metadata": {
"bytecodeHash": "ipfs"
},
"optimizer": {
"details": {
"constantOptimizer": true,
"cse": true,
"deduplicate": true,
"inliner": true,
"jumpdestRemover": true,
"orderLiterals": true,
"peephole": true,
"yul": false
},
"runs": 200
},
"remappings": []
}
[{"inputs":[{"internalType":"address","name":"_dolomiteMargin","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[],"name":"DOLOMITE_MARGIN","outputs":[{"internalType":"contract IDolomiteMargin","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"burn","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"subtractedValue","type":"uint256"}],"name":"decreaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"addedValue","type":"uint256"}],"name":"increaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"mint","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"}]