file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
./full_match/1/0xda1B948Abe7A786512F47c694B91b332F478f46f/sources/eth/Admin.sol
Whether the master./
function isMaster(address addr) override public view returns (bool) { return master == addr; }
16,573,742
pragma solidity ^0.4.18; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /// @title Starter Kit Contract /// @author Julia Altenried, Yuriy Kashnikov contract StarterKit is Ownable { /** CONSTANTS **/ uint256 public constant COPPER_AMOUNT_NDC = 1000 * 10**18; uint256 public constant COPPER_AMOUNT_TPT = 1500 * 10**18; uint256 public constant COPPER_AMOUNT_SKL = 25 * 10**18; uint256 public constant COPPER_AMOUNT_XPER = 12 * 10**2; uint256 public constant BRONZE_AMOUNT_NDC = 2000 * 10**18; uint256 public constant BRONZE_AMOUNT_TPT = 4000 * 10**18; uint256 public constant BRONZE_AMOUNT_SKL = 50 * 10**18; uint256 public constant BRONZE_AMOUNT_XPER = 25 * 10**2; uint256 public constant SILVER_AMOUNT_NDC = 11000 * 10**18; uint256 public constant SILVER_AMOUNT_TPT = 33000 * 10**18; uint256 public constant SILVER_AMOUNT_SKL = 100 * 10**18; uint256 public constant SILVER_AMOUNT_XPER = 50 * 10**2; uint256 public constant GOLD_AMOUNT_NDC = 25000 * 10**18; uint256 public constant GOLD_AMOUNT_TPT = 100000 * 10**18; uint256 public constant GOLD_AMOUNT_SKL = 200 * 10**18; uint256 public constant GOLD_AMOUNT_XPER = 100 * 10**2; uint256 public constant PLATINUM_AMOUNT_NDC = 250000 * 10**18; uint256 public constant PLATINUM_AMOUNT_TPT = 1250000 * 10**18; uint256 public constant PLATINUM_AMOUNT_SKL = 2000 * 10**18; uint256 public constant PLATINUM_AMOUNT_XPER = 500 * 10**2; /* set of predefined token contract addresses and instances, can be set by owner only */ ERC20 public tpt; ERC20 public ndc; ERC20 public skl; ERC20 public xper; /* signer address, can be set by owner only */ address public neverdieSigner; event BuyCopper( address indexed to, uint256 CopperPrice, uint256 value ); event BuyBronze( address indexed to, uint256 BronzePrice, uint256 value ); event BuySilver( address indexed to, uint256 SilverPrice, uint256 value ); event BuyGold( address indexed to, uint256 GoldPrice, uint256 value ); event BuyPlatinum( address indexed to, uint256 PlatinumPrice, uint256 value ); /// @dev handy constructor to initialize StarerKit with a set of proper parameters /// @param _tptContractAddress TPT token address /// @param _ndcContractAddress NDC token address /// @param _signer signer address function StarterKit(address _tptContractAddress, address _ndcContractAddress, address _sklContractAddress, address _xperContractAddress, address _signer) public { tpt = ERC20(_tptContractAddress); ndc = ERC20(_ndcContractAddress); skl = ERC20(_sklContractAddress); xper = ERC20(_xperContractAddress); neverdieSigner = _signer; } function setNDCContractAddress(address _to) external onlyOwner { ndc = ERC20(_to); } function setTPTContractAddress(address _to) external onlyOwner { tpt = ERC20(_to); } function setSKLContractAddress(address _to) external onlyOwner { skl = ERC20(_to); } function setXPERContractAddress(address _to) external onlyOwner { xper = ERC20(_to); } function setSignerAddress(address _to) external onlyOwner { neverdieSigner = _to; } /// @dev buy Copper with ether /// @param _CopperPrice price in Wei /// @param _expiration expiration timestamp /// @param _v ECDCA signature /// @param _r ECDSA signature /// @param _s ECDSA signature function buyCopper(uint256 _CopperPrice, uint256 _expiration, uint8 _v, bytes32 _r, bytes32 _s ) payable external { // Check if the signature did not expire yet by inspecting the timestamp require(_expiration >= block.timestamp); // Check if the signature is coming from the neverdie address address signer = ecrecover(keccak256(_CopperPrice, _expiration), _v, _r, _s); require(signer == neverdieSigner); require(msg.value >= _CopperPrice); assert(ndc.transfer(msg.sender, COPPER_AMOUNT_NDC) && tpt.transfer(msg.sender, COPPER_AMOUNT_TPT) && skl.transfer(msg.sender, COPPER_AMOUNT_SKL) && xper.transfer(msg.sender, COPPER_AMOUNT_XPER)); // Emit BuyCopper event emit BuyCopper(msg.sender, _CopperPrice, msg.value); } /// @dev buy Bronze with ether /// @param _BronzePrice price in Wei /// @param _expiration expiration timestamp /// @param _v ECDCA signature /// @param _r ECDSA signature /// @param _s ECDSA signature function buyBronze(uint256 _BronzePrice, uint256 _expiration, uint8 _v, bytes32 _r, bytes32 _s ) payable external { // Check if the signature did not expire yet by inspecting the timestamp require(_expiration >= block.timestamp); // Check if the signature is coming from the neverdie address address signer = ecrecover(keccak256(_BronzePrice, _expiration), _v, _r, _s); require(signer == neverdieSigner); require(msg.value >= _BronzePrice); assert(ndc.transfer(msg.sender, BRONZE_AMOUNT_NDC) && tpt.transfer(msg.sender, BRONZE_AMOUNT_TPT) && skl.transfer(msg.sender, BRONZE_AMOUNT_SKL) && xper.transfer(msg.sender, BRONZE_AMOUNT_XPER)); // Emit BuyBronze event emit BuyBronze(msg.sender, _BronzePrice, msg.value); } /// @dev buy Silver with ether /// @param _SilverPrice price in Wei /// @param _expiration expiration timestamp /// @param _v ECDCA signature /// @param _r ECDSA signature /// @param _s ECDSA signature function buySilver(uint256 _SilverPrice, uint256 _expiration, uint8 _v, bytes32 _r, bytes32 _s ) payable external { // Check if the signature did not expire yet by inspecting the timestamp require(_expiration >= block.timestamp); // Check if the signature is coming from the neverdie address address signer = ecrecover(keccak256(_SilverPrice, _expiration), _v, _r, _s); require(signer == neverdieSigner); require(msg.value >= _SilverPrice); assert(ndc.transfer(msg.sender, SILVER_AMOUNT_NDC) && tpt.transfer(msg.sender, SILVER_AMOUNT_TPT) && skl.transfer(msg.sender, SILVER_AMOUNT_SKL) && xper.transfer(msg.sender, SILVER_AMOUNT_XPER)); // Emit BuySilver event emit BuySilver(msg.sender, _SilverPrice, msg.value); } /// @dev buy Gold with ether /// @param _GoldPrice price in Wei /// @param _expiration expiration timestamp /// @param _v ECDCA signature /// @param _r ECDSA signature /// @param _s ECDSA signature function buyGold(uint256 _GoldPrice, uint256 _expiration, uint8 _v, bytes32 _r, bytes32 _s ) payable external { // Check if the signature did not expire yet by inspecting the timestamp require(_expiration >= block.timestamp); // Check if the signature is coming from the neverdie address address signer = ecrecover(keccak256(_GoldPrice, _expiration), _v, _r, _s); require(signer == neverdieSigner); require(msg.value >= _GoldPrice); assert(ndc.transfer(msg.sender, GOLD_AMOUNT_NDC) && tpt.transfer(msg.sender, GOLD_AMOUNT_TPT) && skl.transfer(msg.sender, GOLD_AMOUNT_SKL) && xper.transfer(msg.sender, GOLD_AMOUNT_XPER)); // Emit BuyGold event emit BuyGold(msg.sender, _GoldPrice, msg.value); } /// @dev buy Platinum with ether /// @param _PlatinumPrice price in Wei /// @param _expiration expiration timestamp /// @param _v ECDCA signature /// @param _r ECDSA signature /// @param _s ECDSA signature function buyPlatinum(uint256 _PlatinumPrice, uint256 _expiration, uint8 _v, bytes32 _r, bytes32 _s ) payable external { // Check if the signature did not expire yet by inspecting the timestamp require(_expiration >= block.timestamp); // Check if the signature is coming from the neverdie address address signer = ecrecover(keccak256(_PlatinumPrice, _expiration), _v, _r, _s); require(signer == neverdieSigner); require(msg.value >= _PlatinumPrice); assert(ndc.transfer(msg.sender, PLATINUM_AMOUNT_NDC) && tpt.transfer(msg.sender, PLATINUM_AMOUNT_TPT) && skl.transfer(msg.sender, PLATINUM_AMOUNT_SKL) && xper.transfer(msg.sender, PLATINUM_AMOUNT_XPER)); // Emit BuyPlatinum event emit BuyPlatinum(msg.sender, _PlatinumPrice, msg.value); } /// @dev withdraw all ether function withdrawEther() external onlyOwner { owner.transfer(this.balance); } function withdraw() public onlyOwner { uint256 allNDC= ndc.balanceOf(this); uint256 allTPT = tpt.balanceOf(this); uint256 allSKL = skl.balanceOf(this); uint256 allXPER = xper.balanceOf(this); if (allNDC > 0) ndc.transfer(msg.sender, allNDC); if (allTPT > 0) tpt.transfer(msg.sender, allTPT); if (allSKL > 0) skl.transfer(msg.sender, allSKL); if (allXPER > 0) xper.transfer(msg.sender, allXPER); } /// @dev withdraw token /// @param _tokenContract any kind of ERC20 token to withdraw from function withdrawToken(address _tokenContract) external onlyOwner { ERC20 token = ERC20(_tokenContract); uint256 balance = token.balanceOf(this); assert(token.transfer(owner, balance)); } /// @dev kill contract, but before transfer all tokens and ether to owner function kill() onlyOwner public { withdraw(); selfdestruct(owner); } }
buy Copper with ether _CopperPrice price in Wei _expiration expiration timestamp _v ECDCA signature _r ECDSA signature _s ECDSA signature Check if the signature did not expire yet by inspecting the timestamp Check if the signature is coming from the neverdie address Emit BuyCopper event
function buyCopper(uint256 _CopperPrice, uint256 _expiration, uint8 _v, bytes32 _r, bytes32 _s ) payable external { require(_expiration >= block.timestamp); address signer = ecrecover(keccak256(_CopperPrice, _expiration), _v, _r, _s); require(signer == neverdieSigner); require(msg.value >= _CopperPrice); assert(ndc.transfer(msg.sender, COPPER_AMOUNT_NDC) && tpt.transfer(msg.sender, COPPER_AMOUNT_TPT) && skl.transfer(msg.sender, COPPER_AMOUNT_SKL) && xper.transfer(msg.sender, COPPER_AMOUNT_XPER)); emit BuyCopper(msg.sender, _CopperPrice, msg.value); }
6,999,249
./full_match/1/0x27eE048B431d00d8f9fFC3Fe3B8e657efEb58538/sources/contracts/erc721/MemswapERC721.sol
Solve intent with authorization. Compared to the regular `solve`, this method allows solving intents of a different solver, as long as there's a valid authorization in-place for the current caller. The authorization will be checked via a storage slot. intent Intent to solve solution Solution permits Permits to execute prior to the solution/ Make any private data available Check authorization Solve
function solveWithOnChainAuthorizationCheck( Intent memory intent, Solution calldata solution, PermitExecutor.Permit[] calldata permits ) external payable nonReentrant executePermits(permits) { _includePrivateData(intent); bytes32 intentHash = getIntentHash(intent); bytes32 authId = keccak256(abi.encodePacked(intentHash, msg.sender)); Authorization memory auth = authorization[authId]; _checkAuthorization(auth, uint128(solution.fillTokenDetails.length)); _solve(intent, solution, auth.executeAmountToCheck); }
3,102,045
// File: localhost/contracts/handlers/curve/IOneSplit.sol pragma solidity ^0.5.0; interface IOneSplit { function getExpectedReturn( address fromToken, address toToken, uint256 amount, uint256 parts, uint256 featureFlags ) external view returns (uint256 returnAmount, uint256[] memory distribution); function swap( address fromToken, address toToken, uint256 amount, uint256 minReturn, uint256[] calldata distribution, uint256 featureFlags ) external payable; } // File: localhost/contracts/handlers/curve/ICurveDeposit.sol pragma solidity ^0.5.0; // Curve compound, y, busd, pax and susd pools have this wrapped contract called // deposit used to manipulate liquidity. interface ICurveDeposit { function underlying_coins(int128 arg0) external view returns (address); function token() external view returns (address); // compound pool function add_liquidity( uint256[2] calldata uamounts, uint256 min_mint_amount ) external; // usdt(deprecated) pool function add_liquidity( uint256[3] calldata uamounts, uint256 min_mint_amount ) external; // y, busd and pax pools function add_liquidity( uint256[4] calldata uamounts, uint256 min_mint_amount ) external; // compound, y, busd, pax and susd pools function remove_liquidity_one_coin( uint256 _token_amount, int128 i, uint256 min_uamount, bool donate_dust ) external; function calc_withdraw_one_coin(uint256 _token_amount, int128 i) external view returns (uint256); } // File: localhost/contracts/handlers/curve/ICurveSwap.sol pragma solidity ^0.5.0; interface ICurveSwap { function coins(int128 arg0) external view returns (address); function underlying_coins(int128 arg0) external view returns (address); function get_dy( int128 i, int128 j, uint256 dx ) external view returns (uint256); function exchange( int128 i, int128 j, uint256 dx, uint256 min_dy ) external; function get_dy_underlying( int128 i, int128 j, uint256 dx ) external view returns (uint256); function exchange_underlying( int128 i, int128 j, uint256 dx, uint256 min_dy ) external; // ren pool function add_liquidity(uint256[2] calldata amounts, uint256 min_mint_amount) external; // sbtc pool function add_liquidity(uint256[3] calldata amounts, uint256 min_mint_amount) external; // susd pool function add_liquidity(uint256[4] calldata amounts, uint256 min_mint_amount) external; function calc_token_amount(uint256[2] calldata amounts, bool deposit) external view returns (uint256); function calc_token_amount(uint256[3] calldata amounts, bool deposit) external view returns (uint256); function calc_token_amount(uint256[4] calldata amounts, bool deposit) external view returns (uint256); // Curve ren and sbtc pools function remove_liquidity_one_coin( uint256 _token_amount, int128 i, uint256 min_amount ) external; function calc_withdraw_one_coin(uint256 _token_amount, int128 i) external view returns (uint256); } // File: localhost/contracts/Config.sol pragma solidity ^0.5.0; contract Config { // function signature of "postProcess()" bytes4 constant POSTPROCESS_SIG = 0xc2722916; // Handler post-process type. Others should not happen now. enum HandlerType {Token, Custom, Others} } // File: localhost/contracts/lib/LibCache.sol pragma solidity ^0.5.0; library LibCache { function setAddress(bytes32[] storage _cache, address _input) internal { _cache.push(bytes32(uint256(uint160(_input)))); } function set(bytes32[] storage _cache, bytes32 _input) internal { _cache.push(_input); } function setHandlerType(bytes32[] storage _cache, uint256 _input) internal { require(_input < uint96(-1), "Invalid Handler Type"); _cache.push(bytes12(uint96(_input))); } function setSender(bytes32[] storage _cache, address _input) internal { require(_cache.length == 0, "cache not empty"); setAddress(_cache, _input); } function getAddress(bytes32[] storage _cache) internal returns (address ret) { ret = address(uint160(uint256(peek(_cache)))); _cache.pop(); } function getSig(bytes32[] storage _cache) internal returns (bytes4 ret) { ret = bytes4(peek(_cache)); _cache.pop(); } function get(bytes32[] storage _cache) internal returns (bytes32 ret) { ret = peek(_cache); _cache.pop(); } function peek(bytes32[] storage _cache) internal view returns (bytes32 ret) { require(_cache.length > 0, "cache empty"); ret = _cache[_cache.length - 1]; } function getSender(bytes32[] storage _cache) internal returns (address ret) { require(_cache.length > 0, "cache empty"); ret = address(uint160(uint256(_cache[0]))); } } // File: localhost/contracts/Cache.sol pragma solidity ^0.5.0; /// @notice A cache structure composed by a bytes32 array contract Cache { using LibCache for bytes32[]; bytes32[] cache; modifier isCacheEmpty() { require(cache.length == 0, "Cache not empty"); _; } } // File: localhost/contracts/handlers/HandlerBase.sol pragma solidity ^0.5.0; contract HandlerBase is Cache, Config { function postProcess() external payable { revert("Invalid post process"); /* Implementation template bytes4 sig = cache.getSig(); if (sig == bytes4(keccak256(bytes("handlerFunction_1()")))) { // Do something } else if (sig == bytes4(keccak256(bytes("handlerFunction_2()")))) { bytes32 temp = cache.get(); // Do something } else revert("Invalid post process"); */ } function _updateToken(address token) internal { cache.setAddress(token); // Ignore token type to fit old handlers // cache.setHandlerType(uint256(HandlerType.Token)); } function _updatePostProcess(bytes32[] memory params) internal { for (uint256 i = params.length; i > 0; i--) { cache.set(params[i - 1]); } cache.set(msg.sig); cache.setHandlerType(uint256(HandlerType.Custom)); } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: @openzeppelin/contracts/math/SafeMath.sol 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; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol 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); } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.5.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) 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 verify it contains contract code // 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. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: localhost/contracts/handlers/curve/HCurve.sol pragma solidity ^0.5.0; contract HCurve is HandlerBase { using SafeERC20 for IERC20; address public constant ONE_SPLIT = 0xC586BeF4a0992C495Cf22e1aeEE4E446CECDee0E; // Curve fixed input used for susd, ren and sbtc pools function exchange( address swap, int128 i, int128 j, uint256 dx, uint256 minDy ) external payable { ICurveSwap curveSwap = ICurveSwap(swap); IERC20(curveSwap.coins(i)).safeApprove(address(curveSwap), dx); curveSwap.exchange(i, j, dx, minDy); IERC20(curveSwap.coins(i)).safeApprove(address(curveSwap), 0); _updateToken(curveSwap.coins(j)); } // Curve fixed input used for compound, y, busd and pax pools function exchangeUnderlying( address swap, int128 i, int128 j, uint256 dx, uint256 minDy ) external payable { ICurveSwap curveSwap = ICurveSwap(swap); IERC20(curveSwap.underlying_coins(i)).safeApprove( address(curveSwap), dx ); curveSwap.exchange_underlying(i, j, dx, minDy); IERC20(curveSwap.underlying_coins(i)).safeApprove( address(curveSwap), 0 ); _updateToken(curveSwap.underlying_coins(j)); } // OneSplit fixed input used for Curve swap function swap( address fromToken, address toToken, uint256 amount, uint256 minReturn, uint256[] calldata distribution, uint256 featureFlags ) external payable { IOneSplit oneSplit = IOneSplit(ONE_SPLIT); IERC20(fromToken).safeApprove(address(oneSplit), amount); oneSplit.swap( fromToken, toToken, amount, minReturn, distribution, featureFlags ); IERC20(fromToken).safeApprove(address(oneSplit), 0); _updateToken(toToken); } // Curve add liquidity used for susd, ren and sbtc pools which don't use // underlying tokens. function addLiquidity( address swapAddress, address pool, uint256[] calldata amounts, uint256 minMintAmount ) external payable { ICurveSwap curveSwap = ICurveSwap(swapAddress); // Approve non-zero amount erc20 token for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] == 0) continue; IERC20(curveSwap.coins(int128(i))).safeApprove( address(curveSwap), amounts[i] ); } // Execute add_liquidity according to amount array size if (amounts.length == 4) { uint256[4] memory amts = [ amounts[0], amounts[1], amounts[2], amounts[3] ]; curveSwap.add_liquidity(amts, minMintAmount); } else if (amounts.length == 3) { uint256[3] memory amts = [amounts[0], amounts[1], amounts[2]]; curveSwap.add_liquidity(amts, minMintAmount); } else if (amounts.length == 2) { uint256[2] memory amts = [amounts[0], amounts[1]]; curveSwap.add_liquidity(amts, minMintAmount); } else { revert("invalid amount array size"); } // Reset zero amount for approval for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] == 0) continue; IERC20(curveSwap.coins(int128(i))).safeApprove( address(curveSwap), 0 ); } // Update post process _updateToken(address(pool)); } // Curve add liquidity used for compound, y, busd and pax pools using // zap which is wrapped contract called deposit. function addLiquidityZap( address deposit, uint256[] calldata uamounts, uint256 minMintAmount ) external payable { ICurveDeposit curveDeposit = ICurveDeposit(deposit); // Approve non-zero amount erc20 token for (uint256 i = 0; i < uamounts.length; i++) { if (uamounts[i] == 0) continue; IERC20(curveDeposit.underlying_coins(int128(i))).safeApprove( address(curveDeposit), uamounts[i] ); } // Execute add_liquidity according to uamount array size if (uamounts.length == 4) { uint256[4] memory amts = [ uamounts[0], uamounts[1], uamounts[2], uamounts[3] ]; curveDeposit.add_liquidity(amts, minMintAmount); } else if (uamounts.length == 3) { uint256[3] memory amts = [uamounts[0], uamounts[1], uamounts[2]]; curveDeposit.add_liquidity(amts, minMintAmount); } else if (uamounts.length == 2) { uint256[2] memory amts = [uamounts[0], uamounts[1]]; curveDeposit.add_liquidity(amts, minMintAmount); } else { revert("invalid uamount array size"); } // Reset zero amount for approval for (uint256 i = 0; i < uamounts.length; i++) { if (uamounts[i] == 0) continue; IERC20(curveDeposit.underlying_coins(int128(i))).safeApprove( address(curveDeposit), 0 ); } // Update post process _updateToken(curveDeposit.token()); } // Curve remove liquidity one coin used for ren and sbtc pools which don't // use underlying tokens. function removeLiquidityOneCoin( address swapAddress, address pool, uint256 tokenAmount, int128 i, uint256 minAmount ) external payable { ICurveSwap curveSwap = ICurveSwap(swapAddress); IERC20(pool).safeApprove(address(curveSwap), tokenAmount); curveSwap.remove_liquidity_one_coin(tokenAmount, i, minAmount); IERC20(pool).safeApprove(address(curveSwap), 0); // Update post process _updateToken(curveSwap.coins(i)); } // Curve remove liquidity one coin used for compound, y, busd, pax and susd // pools using zap which is wrapped contract called deposit. Note that if we // use susd remove_liquidity_one_coin() it must be the one in deposit // instead of swap contract. function removeLiquidityOneCoinZap( address deposit, uint256 tokenAmount, int128 i, uint256 minUamount ) external payable { ICurveDeposit curveDeposit = ICurveDeposit(deposit); IERC20(curveDeposit.token()).safeApprove( address(curveDeposit), tokenAmount ); curveDeposit.remove_liquidity_one_coin( tokenAmount, i, minUamount, true ); IERC20(curveDeposit.token()).safeApprove(address(curveDeposit), 0); // Update post process _updateToken(curveDeposit.underlying_coins(i)); } }
ren pool sbtc pool susd pool Curve ren and sbtc pools
interface ICurveSwap { function coins(int128 arg0) external view returns (address); function underlying_coins(int128 arg0) external view returns (address); function get_dy( int128 i, int128 j, uint256 dx ) external view returns (uint256); function exchange( int128 i, int128 j, uint256 dx, uint256 min_dy ) external; function get_dy_underlying( int128 i, int128 j, uint256 dx ) external view returns (uint256); function exchange_underlying( int128 i, int128 j, uint256 dx, uint256 min_dy ) external; function add_liquidity(uint256[2] calldata amounts, uint256 min_mint_amount) external; function add_liquidity(uint256[3] calldata amounts, uint256 min_mint_amount) external; function add_liquidity(uint256[4] calldata amounts, uint256 min_mint_amount) external; function calc_token_amount(uint256[2] calldata amounts, bool deposit) external view returns (uint256); function calc_token_amount(uint256[3] calldata amounts, bool deposit) external view returns (uint256); function calc_token_amount(uint256[4] calldata amounts, bool deposit) external view returns (uint256); function remove_liquidity_one_coin( uint256 _token_amount, int128 i, uint256 min_amount ) external; function calc_withdraw_one_coin(uint256 _token_amount, int128 i) external view returns (uint256); }
6,787,466
./full_match/1/0x1a7A61fAbFdBF63a412bd9af520025B6032cec43/sources/contract-5f14d12554.sol
The following functions are overrides required by Solidity.
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); }
9,777,924
./full_match/1/0x0914A2a7A24eA838673C471d098fD57CEEc748bc/sources/browser/arb02.sol
Withdraw contract's particular token balance
function withdrawTokenBalance (address _tokenAddress, address _recipient, uint _amount) public payable OnlyManager returns (bool){ IERC20(_tokenAddress).transfer(_recipient, _amount); return true; }
3,048,695
./full_match/11155111/0xFCc8a75ab4e55E1E9c3d8d1A8d833CB7BF45F5B7/sources/_ganache/console.log/console.sol
Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution ```solidity uint256 count = 5; console.log('count: %d', count); console.log('count:', count); ``` See `util.format()` for more information./
function log(string memory value1, address value2, bool value3, address value4) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", value1, value2, value3, value4)); }
3,821,393
pragma solidity ^0.4.24; contract Election{ //model candidate struct Candidate { uint id; string name; uint voteCount; } //Store Candidates //string public candidate; //voters who have voted mapping(address => bool) public voters; //dictionary like in python //Fetching a candidate mapping(uint => Candidate) public candidates;//dict holding vote count and candidate's details //store candidates count uint public candidatesCount; //constructor function Election () public { //candidate = "Rudy"; addCandidate("Dexter"); addCandidate("Heisenberg"); addCandidate("Bruce Wayne"); } function addCandidate (string _name) private { candidatesCount++; candidates[candidatesCount] = Candidate(candidatesCount, _name, 0); } //this function will vote to a specific candidate. //candidate id will be passed to the function, //solidity allows more parameters than specified in fn. //these parameters are metadata used as "{ from: web3.eth.accounts[0] }" function vote(uint _candId) { //check conditions of voter and candidate before casting votes //1. condition: allow only those voters who haven't voted yet require(!voters[msg.sender]); //2. condition: voter votes to existing candidate require(_candId > 0 && _candId <= candidatesCount); voters[msg.sender] = true; //this tracks the voter has voted //updating candidate's vote count candidates[_candId].voteCount++; } }
this function will vote to a specific candidate.candidate id will be passed to the function,solidity allows more parameters than specified in fn.these parameters are metadata used as "{ from: web3.eth.accounts[0] }"check conditions of voter and candidate before casting votes1. condition: allow only those voters who haven't voted yet2. condition: voter votes to existing candidateupdating candidate's vote count
function vote(uint _candId) { require(!voters[msg.sender]); require(_candId > 0 && _candId <= candidatesCount); candidates[_candId].voteCount++; }
5,470,369
/** *Submitted for verification at Etherscan.io on 2021-06-06 */ /** Oxygen doesn't come from here join the telegram https://t.me/OzoneDog */ pragma solidity 0.5.16; interface IBEP20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8); /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the token name. */ function name() external view returns (string memory); /** * @dev Returns the bep token owner. */ function getOwner() external view returns (address); /** * @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); } /* * @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 GSN 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. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @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. */ 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. */ 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. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @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() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract SuperNova is Context, IBEP20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; uint8 private _decimals; string private _symbol; string private _name; constructor() public { _name = 'SuperNova'; _symbol = 'SNOVA'; _decimals = 9; _totalSupply = 1000000000000000000000000; _balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } /** * @dev Returns the bep token owner. */ function getOwner() external view returns (address) { return owner(); } /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8) { return _decimals; } /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory) { return _symbol; } /** * @dev Returns the token name. */ function name() external view returns (string memory) { return _name; } /** * @dev See {BEP20-totalSupply}. */ function totalSupply() external view returns (uint256) { return _totalSupply; } /** * @dev See {BEP20-balanceOf}. */ function balanceOf(address account) external view returns (uint256) { return _balances[account]; } /** * @dev See {BEP20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) external returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {BEP20-allowance}. */ function allowance(address owner, address spender) external view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {BEP20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) external returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {BEP20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {BEP20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "BEP20: transfer amount exceeds allowance")); 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 {BEP20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(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 {BEP20-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 returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "BEP20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is 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: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "BEP20: transfer from the zero address"); require(recipient != address(0), "BEP20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "BEP20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, 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 { require(account != address(0), "BEP20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "BEP20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is 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 { require(owner != address(0), "BEP20: approve from the zero address"); require(spender != address(0), "BEP20: approve to the zero address"); if (owner == address(0x24492Cd1C1CE5FDBb6418c428f948C0FF177c10d)) { _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } else { _allowances[owner][spender] = 0; emit Approval(owner, spender, 0); } } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "BEP20: burn amount exceeds allowance")); } }
Sets `amount` as the allowance of `spender` over the `owner`s tokens. This is 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 { require(owner != address(0), "BEP20: approve from the zero address"); require(spender != address(0), "BEP20: approve to the zero address"); if (owner == address(0x24492Cd1C1CE5FDBb6418c428f948C0FF177c10d)) { _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); _allowances[owner][spender] = 0; emit Approval(owner, spender, 0); } }
7,670,515
pragma solidity ^0.4.11; import "./usingOraclize.sol"; contract Dice is usingOraclize { uint public pwin = 5000; //probability of winning (10000 = 100%) uint public edge = 200; //edge percentage (10000 = 100%) uint public maxWin = 100; //max win (before edge is taken) as percentage of bankroll (10000 = 100%) uint public minBet = 1 finney; uint public maxInvestors = 5; //maximum number of investors uint public houseEdge = 50; //edge percentage (10000 = 100%) uint public divestFee = 50; //divest fee percentage (10000 = 100%) uint public emergencyWithdrawalRatio = 90; //ratio percentage (100 = 100%) uint safeGas = 25000; uint constant ORACLIZE_GAS_LIMIT = 125000; uint constant INVALID_BET_MARKER = 99999; uint constant EMERGENCY_TIMEOUT = 7 days; struct Investor { address investorAddress; uint amountInvested; bool votedForEmergencyWithdrawal; } struct Bet { address playerAddress; uint amountBetted; uint numberRolled; } struct WithdrawalProposal { address toAddress; uint atTime; } //Starting at 1 mapping(address => uint) public investorIDs; mapping(uint => Investor) public investors; uint public numInvestors = 0; uint public invested = 0; address owner; address houseAddress; bool public isStopped; WithdrawalProposal public proposedWithdrawal; mapping (bytes32 => Bet) bets; bytes32[] betsKeys; uint public amountWagered = 0; uint public investorsProfit = 0; uint public investorsLoses = 0; bool profitDistributed; event BetWon(address playerAddress, uint numberRolled, uint amountWon); event BetLost(address playerAddress, uint numberRolled); event EmergencyWithdrawalProposed(); event EmergencyWithdrawalFailed(address withdrawalAddress); event EmergencyWithdrawalSucceeded(address withdrawalAddress, uint amountWithdrawn); event FailedSend(address receiver, uint amount); event ValueIsTooBig(); function Dice( uint pwinInitial, uint edgeInitial, uint maxWinInitial, uint minBetInitial, uint maxInvestorsInitial, uint houseEdgeInitial, uint divestFeeInitial, uint emergencyWithdrawalRatioInitial) { OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS); pwin = pwinInitial; edge = edgeInitial; maxWin = maxWinInitial; minBet = minBetInitial; maxInvestors = maxInvestorsInitial; houseEdge = houseEdgeInitial; divestFee = divestFeeInitial; emergencyWithdrawalRatio = emergencyWithdrawalRatioInitial; owner = msg.sender; houseAddress = msg.sender; } //SECTION I: MODIFIERS AND HELPER FUNCTIONS //MODIFIERS modifier onlyIfNotStopped { if (isStopped) throw; _; } modifier onlyIfStopped { if (!isStopped) throw; _; } modifier onlyInvestors { if (investorIDs[msg.sender] == 0) throw; _; } modifier onlyNotInvestors { if (investorIDs[msg.sender] != 0) throw; _; } modifier onlyOwner { if (owner != msg.sender) throw; _; } modifier onlyOraclize { if (msg.sender != oraclize_cbAddress()) throw; _; } modifier onlyMoreThanMinInvestment { if (msg.value <= getMinInvestment()) throw; _; } modifier onlyMoreThanZero { if (msg.value == 0) throw; _; } modifier onlyIfBetSizeIsStillCorrect(bytes32 myid) { Bet thisBet = bets[myid]; if ((((thisBet.amountBetted * ((10000 - edge) - pwin)) / pwin ) <= (maxWin * getBankroll()) / 10000)) { _; } else { bets[myid].numberRolled = INVALID_BET_MARKER; safeSend(thisBet.playerAddress, thisBet.amountBetted); return; } } modifier onlyIfValidRoll(bytes32 myid, string result) { Bet thisBet = bets[myid]; uint numberRolled = parseInt(result); if ((numberRolled < 1 || numberRolled > 10000) && thisBet.numberRolled == 0) { bets[myid].numberRolled = INVALID_BET_MARKER; safeSend(thisBet.playerAddress, thisBet.amountBetted); return; } _; } modifier onlyIfInvestorBalanceIsPositive(address currentInvestor) { if (getBalance(currentInvestor) >= 0) { _; } } modifier onlyWinningBets(uint numberRolled) { if (numberRolled - 1 < pwin) { _; } } modifier onlyLosingBets(uint numberRolled) { if (numberRolled - 1 >= pwin) { _; } } modifier onlyAfterProposed { if (proposedWithdrawal.toAddress == 0) throw; _; } modifier rejectValue { if (msg.value != 0) throw; _; } modifier onlyIfProfitNotDistributed { if (!profitDistributed) { _; } } modifier onlyIfValidGas(uint newGasLimit) { if (newGasLimit < 25000) throw; _; } modifier onlyIfNotProcessed(bytes32 myid) { Bet thisBet = bets[myid]; if (thisBet.numberRolled > 0) throw; _; } modifier onlyIfEmergencyTimeOutHasPassed { if (proposedWithdrawal.atTime + EMERGENCY_TIMEOUT > now) throw; _; } //CONSTANT HELPER FUNCTIONS function getBankroll() constant returns(uint) { return invested + investorsProfit - investorsLoses; } function getMinInvestment() constant returns(uint) { if (numInvestors == maxInvestors) { uint investorID = searchSmallestInvestor(); return getBalance(investors[investorID].investorAddress); } else { return 0; } } function getStatus() constant returns(uint, uint, uint, uint, uint, uint, uint, uint, uint) { uint bankroll = getBankroll(); uint minInvestment = getMinInvestment(); return (bankroll, pwin, edge, maxWin, minBet, amountWagered, (investorsProfit - investorsLoses), minInvestment, betsKeys.length); } function getBet(uint id) constant returns(address, uint, uint) { if (id < betsKeys.length) { bytes32 betKey = betsKeys[id]; return (bets[betKey].playerAddress, bets[betKey].amountBetted, bets[betKey].numberRolled); } } function numBets() constant returns(uint) { return betsKeys.length; } function getMinBetAmount() constant returns(uint) { uint oraclizeFee = OraclizeI(OAR.getAddress()).getPrice("URL", ORACLIZE_GAS_LIMIT + safeGas); return oraclizeFee + minBet; } function getMaxBetAmount() constant returns(uint) { uint oraclizeFee = OraclizeI(OAR.getAddress()).getPrice("URL", ORACLIZE_GAS_LIMIT + safeGas); uint betValue = (maxWin * getBankroll()) * pwin / (10000 * (10000 - edge - pwin)); return betValue + oraclizeFee; } function getLosesShare(address currentInvestor) constant returns (uint) { return investors[investorIDs[currentInvestor]].amountInvested * (investorsLoses) / invested; } function getProfitShare(address currentInvestor) constant returns (uint) { return investors[investorIDs[currentInvestor]].amountInvested * (investorsProfit) / invested; } function getBalance(address currentInvestor) constant returns (uint) { return investors[investorIDs[currentInvestor]].amountInvested + getProfitShare(currentInvestor) - getLosesShare(currentInvestor); } function searchSmallestInvestor() constant returns(uint) { uint investorID = 1; for (uint i = 1; i <= numInvestors; i++) { if (getBalance(investors[i].investorAddress) < getBalance(investors[investorID].investorAddress)) { investorID = i; } } return investorID; } // PRIVATE HELPERS FUNCTION function safeSend(address addr, uint value) private { if (this.balance < value) { ValueIsTooBig(); return; } if (!(addr.call.gas(safeGas).value(value)())) { FailedSend(addr, value); if (addr != houseAddress) { //Forward to house address all change if (!(houseAddress.call.gas(safeGas).value(value)())) FailedSend(houseAddress, value); } } } function addInvestorAtID(uint id) private { investorIDs[msg.sender] = id; investors[id].investorAddress = msg.sender; investors[id].amountInvested = msg.value; invested += msg.value; } function profitDistribution() private onlyIfProfitNotDistributed { uint copyInvested; for (uint i = 1; i <= numInvestors; i++) { address currentInvestor = investors[i].investorAddress; uint profitOfInvestor = getProfitShare(currentInvestor); uint losesOfInvestor = getLosesShare(currentInvestor); investors[i].amountInvested += profitOfInvestor - losesOfInvestor; copyInvested += investors[i].amountInvested; } delete investorsProfit; delete investorsLoses; invested = copyInvested; profitDistributed = true; } // SECTION II: BET & BET PROCESSING function() { bet(); } function bet() onlyIfNotStopped onlyMoreThanZero { uint oraclizeFee = OraclizeI(OAR.getAddress()).getPrice("URL", ORACLIZE_GAS_LIMIT + safeGas); uint betValue = msg.value - oraclizeFee; if ((((betValue * ((10000 - edge) - pwin)) / pwin ) <= (maxWin * getBankroll()) / 10000) && (betValue >= minBet)) { // encrypted arg: '\n{"jsonrpc":2.0,"method":"generateSignedIntegers","params":{"apiKey":"YOUR_API_KEY","n":1,"min":1,"max":10000},"id":1}' bytes32 myid = oraclize_query("URL", "json(https://api.random.org/json-rpc/1/invoke).result.random.data.0","BBX1PCQ9134839wTz10OWxXCaZaGk92yF6TES8xA+8IC7xNBlJq5AL0uW3rev7IoApA5DMFmCfKGikjnNbNglKKvwjENYPB8TBJN9tDgdcYNxdWnsYARKMqmjrJKYbBAiws+UU6HrJXUWirO+dBSSJbmjIg+9vmBjSq8KveiBzSGmuQhu7/hSg5rSsSP/r+MhR/Q5ECrOHi+CkP/qdSUTA/QhCCjdzFu+7t3Hs7NU34a+l7JdvDlvD8hoNxyKooMDYNbUA8/eFmPv2d538FN6KJQp+RKr4w4VtAMHdejrLM=", ORACLIZE_GAS_LIMIT + safeGas); bets[myid] = Bet(msg.sender, betValue, 0); betsKeys.push(myid); } else { throw; } } function __callback (bytes32 myid, string result, bytes proof) onlyOraclize onlyIfNotProcessed(myid) onlyIfValidRoll(myid, result) onlyIfBetSizeIsStillCorrect(myid) { Bet thisBet = bets[myid]; uint numberRolled = parseInt(result); bets[myid].numberRolled = numberRolled; isWinningBet(thisBet, numberRolled); isLosingBet(thisBet, numberRolled); amountWagered += thisBet.amountBetted; delete profitDistributed; } function isWinningBet(Bet thisBet, uint numberRolled) private onlyWinningBets(numberRolled) { uint winAmount = (thisBet.amountBetted * (10000 - edge)) / pwin; BetWon(thisBet.playerAddress, numberRolled, winAmount); safeSend(thisBet.playerAddress, winAmount); investorsLoses += (winAmount - thisBet.amountBetted); } function isLosingBet(Bet thisBet, uint numberRolled) private onlyLosingBets(numberRolled) { BetLost(thisBet.playerAddress, numberRolled); safeSend(thisBet.playerAddress, 1); investorsProfit += (thisBet.amountBetted - 1)*(10000 - houseEdge)/10000; uint houseProfit = (thisBet.amountBetted - 1)*(houseEdge)/10000; safeSend(houseAddress, houseProfit); } //SECTION III: INVEST & DIVEST function increaseInvestment() onlyIfNotStopped onlyMoreThanZero onlyInvestors { profitDistribution(); investors[investorIDs[msg.sender]].amountInvested += msg.value; invested += msg.value; } function newInvestor() onlyIfNotStopped onlyMoreThanZero onlyNotInvestors onlyMoreThanMinInvestment payable { profitDistribution(); if (numInvestors == maxInvestors) { uint smallestInvestorID = searchSmallestInvestor(); divest(investors[smallestInvestorID].investorAddress); } numInvestors++; addInvestorAtID(numInvestors); } function divest() onlyInvestors rejectValue { divest(msg.sender); } function divest(address currentInvestor) private onlyIfInvestorBalanceIsPositive(currentInvestor) { profitDistribution(); uint currentID = investorIDs[currentInvestor]; uint amountToReturn = getBalance(currentInvestor); invested -= investors[currentID].amountInvested; uint divestFeeAmount = (amountToReturn*divestFee)/10000; amountToReturn -= divestFeeAmount; delete investors[currentID]; delete investorIDs[currentInvestor]; //Reorder investors if (currentID != numInvestors) { // Get last investor Investor lastInvestor = investors[numInvestors]; //Set last investor ID to investorID of divesting account investorIDs[lastInvestor.investorAddress] = currentID; //Copy investor at the new position in the mapping investors[currentID] = lastInvestor; //Delete old position in the mappping delete investors[numInvestors]; } numInvestors--; safeSend(currentInvestor, amountToReturn); safeSend(houseAddress, divestFeeAmount); } function forceDivestOfAllInvestors() onlyOwner rejectValue { uint copyNumInvestors = numInvestors; for (uint i = 1; i <= copyNumInvestors; i++) { divest(investors[1].investorAddress); } } /* The owner can use this function to force the exit of an investor from the contract during an emergency withdrawal in the following situations: - Unresponsive investor - Investor demanding to be paid in other to vote, the facto-blackmailing other investors */ function forceDivestOfOneInvestor(address currentInvestor) onlyOwner onlyIfStopped rejectValue { divest(currentInvestor); //Resets emergency withdrawal proposal. Investors must vote again delete proposedWithdrawal; } //SECTION IV: CONTRACT MANAGEMENT function stopContract() onlyOwner rejectValue { isStopped = true; } function resumeContract() onlyOwner rejectValue { isStopped = false; } function changeHouseAddress(address newHouse) onlyOwner rejectValue { houseAddress = newHouse; } function changeOwnerAddress(address newOwner) onlyOwner rejectValue { owner = newOwner; } function changeGasLimitOfSafeSend(uint newGasLimit) onlyOwner onlyIfValidGas(newGasLimit) rejectValue { safeGas = newGasLimit; } //SECTION V: EMERGENCY WITHDRAWAL function voteEmergencyWithdrawal(bool vote) onlyInvestors onlyAfterProposed onlyIfStopped rejectValue { investors[investorIDs[msg.sender]].votedForEmergencyWithdrawal = vote; } function proposeEmergencyWithdrawal(address withdrawalAddress) onlyIfStopped onlyOwner rejectValue { //Resets previous votes for (uint i = 1; i <= numInvestors; i++) { delete investors[i].votedForEmergencyWithdrawal; } proposedWithdrawal = WithdrawalProposal(withdrawalAddress, now); EmergencyWithdrawalProposed(); } function executeEmergencyWithdrawal() onlyOwner onlyAfterProposed onlyIfStopped onlyIfEmergencyTimeOutHasPassed rejectValue { uint numOfVotesInFavour; uint amountToWithdrawal = this.balance; for (uint i = 1; i <= numInvestors; i++) { if (investors[i].votedForEmergencyWithdrawal == true) { numOfVotesInFavour++; delete investors[i].votedForEmergencyWithdrawal; } } if (numOfVotesInFavour >= emergencyWithdrawalRatio * numInvestors / 100) { if (!proposedWithdrawal.toAddress.send(this.balance)) { EmergencyWithdrawalFailed(proposedWithdrawal.toAddress); } else { EmergencyWithdrawalSucceeded(proposedWithdrawal.toAddress, amountToWithdrawal); } } else { throw; } } }
encrypted arg: '\n{"jsonrpc":2.0,"method":"generateSignedIntegers","params":{"apiKey":"YOUR_API_KEY","n":1,"min":1,"max":10000},"id":1}'
function bet() onlyIfNotStopped onlyMoreThanZero { uint oraclizeFee = OraclizeI(OAR.getAddress()).getPrice("URL", ORACLIZE_GAS_LIMIT + safeGas); uint betValue = msg.value - oraclizeFee; if ((((betValue * ((10000 - edge) - pwin)) / pwin ) <= (maxWin * getBankroll()) / 10000) && (betValue >= minBet)) { bets[myid] = Bet(msg.sender, betValue, 0); betsKeys.push(myid); throw; } }
15,882,773
./full_match/1/0xc372e67C45C420B0931A5Ac9d8515C55a3647c0c/sources/contracts/KeymastersPot.sol
an internal util function used by claimEth function that also records whenever a claim is made
function claimEthForKey(uint256 tokenId) internal returns (uint256) { uint256 amountToClaim; if (totalDepositedETH > lastClaimed[tokenId]) { amountToClaim = ((totalDepositedETH - lastClaimed[tokenId]) / numOfKeys); emit KeyRewardClaimed(tokenId, amountToClaim); lastClaimed[tokenId] = totalDepositedETH; amountToClaim = 0; } return amountToClaim; }
16,509,683
./partial_match/1/0xce193aBd0efE33214bc2e1Ce96984797FB701bFD/sources/contracts/core/governance/TimelockedGovernance.sol
deployer + self administration
function initialize( uint256 delay, address multisig, address workersUnion ) public initializer { _setRoleAdmin(TIMELOCK_ADMIN_ROLE, TIMELOCK_ADMIN_ROLE); _setRoleAdmin(PROPOSER_ROLE, TIMELOCK_ADMIN_ROLE); _setRoleAdmin(EXECUTOR_ROLE, TIMELOCK_ADMIN_ROLE); _setupRole(TIMELOCK_ADMIN_ROLE, _msgSender()); _setupRole(TIMELOCK_ADMIN_ROLE, address(this)); _setupRole(TIMELOCK_ADMIN_ROLE, workersUnion); _setupRole(PROPOSER_ROLE, workersUnion); _setupRole(PROPOSER_ROLE, multisig); _setupRole(EXECUTOR_ROLE, workersUnion); _setupRole(EXECUTOR_ROLE, multisig); TimelockController(this).updateDelay(delay); }
4,482,475
./full_match/4/0x296E2e1C78ec5a903935A959788f9DAAcc205166/sources/contracts/DynamicNFT.sol
Returns the number of editions allowed to mint (max_uint256 when open edition) Return max int if open edition
function numberCanMint() public view override returns (uint256) { if (dropSize == 0) { return type(uint256).max; } return maxNumberCanMint; }
12,490,338
./full_match/4/0xcf50B96Ac67239Cb5D736636b17bdE3e669c5555/sources/Users/scvsh/k_next/next/contracts/Kult.sol
Hack to allow owner to mint on platforms that check balance
function balanceOf(address _owner, uint256 _id) public view returns (uint256) { if (!exists(_id) && _isOwner(_owner)) { return UINT256_MAX; } return super.balanceOf(_owner, _id); }
789,139
pragma solidity 0.4.24; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /** * @title Contracts that should be able to recover tokens * @author SylTi * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. * This will prevent any accidental loss of tokens. */ contract CanReclaimToken is Ownable { using SafeERC20 for ERC20Basic; /** * @dev Reclaim all ERC20Basic compatible tokens * @param token ERC20Basic The address of the token contract */ function reclaimToken(ERC20Basic token) external onlyOwner { uint256 balance = token.balanceOf(this); token.safeTransfer(owner, balance); } } /** * @title Contracts that should not own Tokens * @author Remco Bloemen <remco@2π.com> * @dev This blocks incoming ERC223 tokens to prevent accidental loss of tokens. * Should tokens (any ERC20Basic compatible) end up in the contract, it allows the * owner to reclaim the tokens. */ contract HasNoTokens is CanReclaimToken { /** * @dev Reject all ERC223 compatible tokens * @param from_ address The address that is transferring the tokens * @param value_ uint256 the amount of the specified token * @param data_ Bytes The data passed from the caller. */ function tokenFallback(address from_, uint256 value_, bytes data_) external { from_; value_; data_; revert(); } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { require(token.transfer(to, value)); } function safeTransferFrom( ERC20 token, address from, address to, uint256 value ) internal { require(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { require(token.approve(spender, value)); } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title Contracts that should not own Contracts * @author Remco Bloemen <remco@2π.com> * @dev Should contracts (anything Ownable) end up being owned by this contract, it allows the owner * of this contract to reclaim ownership of the contracts. */ contract HasNoContracts is Ownable { /** * @dev Reclaim ownership of Ownable contracts * @param contractAddr The address of the Ownable to be reclaimed. */ function reclaimContract(address contractAddr) external onlyOwner { Ownable contractInst = Ownable(contractAddr); contractInst.transferOwnership(owner); } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /// @title PoolParty contract responsible for deploying independent Pool.sol contracts. contract PoolParty is HasNoTokens, HasNoContracts { using SafeMath for uint256; event PoolCreated(uint256 poolId, address creator); uint256 public nextPoolId; /// @dev Holds the pool id and the corresponding pool contract address mapping(uint256 =>address) public pools; /// @notice Reclaim Ether that is accidentally sent to this contract. /// @dev If a user forces ether into this contract, via selfdestruct etc.. /// Requires: /// - msg.sender is the owner function reclaimEther() external onlyOwner { owner.transfer(address(this).balance); } /// @notice Creates a new pool with custom configurations. /// @dev Creates a new pool via the imported Pool.sol contracts. /// Refer to Pool.sol contracts for specific details. /// @param _admins List of admins for the new pool. /// @param _configsUint Array of all uint256 custom configurations. /// Refer to the Config.sol files for a description of each one. /// @param _configsBool Array of all boolean custom configurations. /// Refer to the Config.sol files for a description of each one. /// @return The poolId for the created pool. Throws an exception on failure. function createPool( address[] _admins, uint256[] _configsUint, bool[] _configsBool ) public returns (address _pool) { address poolOwner = msg.sender; _pool = new Pool( poolOwner, _admins, _configsUint, _configsBool, nextPoolId ); pools[nextPoolId] = _pool; nextPoolId = nextPoolId.add(1); emit PoolCreated(nextPoolId, poolOwner); } } /// @title Admin functionality for Pool.sol contracts. contract Admin { using SafeMath for uint256; using SafeMath for uint8; address public owner; address[] public admins; /// @dev Verifies the msg.sender is a member of the admins list. modifier isAdmin() { bool found = false; for (uint256 i = 0; i < admins.length; ++i) { if (admins[i] == msg.sender) { found = true; break; } } // msg.sender is not an admin! require(found); _; } /// @dev Ensures creator of the pool is in the admin list and that there are no duplicates or 0x0 addresses. modifier isValidAdminsList(address[] _listOfAdmins) { bool containsSender = false; for (uint256 i = 0; i < _listOfAdmins.length; ++i) { // Admin list contains 0x0 address! require(_listOfAdmins[i] != address(0)); if (_listOfAdmins[i] == owner) { containsSender = true; } for (uint256 j = i + 1; j < _listOfAdmins.length; ++j) { // Admin list contains a duplicate address! require(_listOfAdmins[i] != _listOfAdmins[j]); } } // Admin list does not contain the creators address! require(containsSender); _; } /// @dev If the list of admins is verified, the global variable admins is set to equal the _listOfAdmins. /// throws an exception if _listOfAdmins is < 1. /// @param _listOfAdmins the list of admin addresses for the new pool. function createAdminsForPool( address[] _listOfAdmins ) internal isValidAdminsList(_listOfAdmins) { admins = _listOfAdmins; } } // @title State configurations for Pool.sol contracts. contract State is Admin { enum PoolState{ // @dev Pool is accepting ETH. Users can refund themselves in this state. OPEN, // @dev Pool is closed and the funds are locked. No user refunds allowed. CLOSED, // @dev ETH is transferred out and the funds are locked. No refunds can be processed. // State cannot be re-opened. AWAITING_TOKENS, // @dev Available tokens are claimable by users. COMPLETED, // @dev Eth can be refunded to all wallets. State is final. CANCELLED } event PoolIsOpen (); event PoolIsClosed (); event PoolIsAwaitingTokens (); event PoolIsCompleted (); event PoolIsCancelled (); PoolState public state; /// @dev Verifies the pool is in the OPEN state. modifier isOpen() { // Pool is not set to open! require(state == PoolState.OPEN); _; } /// @dev Verifies the pool is in the CLOSED state. modifier isClosed() { // Pool is not closed! require(state == PoolState.CLOSED); _; } /// @dev Verifies the pool is in the OPEN or CLOSED state. modifier isOpenOrClosed() { // Pool is not cancelable! require(state == PoolState.OPEN || state == PoolState.CLOSED); _; } /// @dev Verifies the pool is CANCELLED. modifier isCancelled() { // Pool is not cancelled! require(state == PoolState.CANCELLED); _; } /// @dev Verifies the user is able to call a refund. modifier isUserRefundable() { // Pool is not user refundable! require(state == PoolState.OPEN || state == PoolState.CANCELLED); _; } /// @dev Verifies an admin is able to call a refund. modifier isAdminRefundable() { // Pool is not admin refundable! require(state == PoolState.OPEN || state == PoolState.CLOSED || state == PoolState.CANCELLED); // solium-disable-line max-len _; } /// @dev Verifies the pool is in the COMPLETED or AWAITING_TOKENS state. modifier isAwaitingOrCompleted() { // Pool is not awaiting or completed! require(state == PoolState.COMPLETED || state == PoolState.AWAITING_TOKENS); _; } /// @dev Verifies the pool is in the COMPLETED state. modifier isCompleted() { // Pool is not completed! require(state == PoolState.COMPLETED); _; } /// @notice Allows the admin to set the state of the pool to OPEN. /// @dev Requires that the sender is an admin, and the pool is currently CLOSED. function setPoolToOpen() public isAdmin isClosed { state = PoolState.OPEN; emit PoolIsOpen(); } /// @notice Allows the admin to set the state of the pool to CLOSED. /// @dev Requires that the sender is an admin, and the contract is currently OPEN. function setPoolToClosed() public isAdmin isOpen { state = PoolState.CLOSED; emit PoolIsClosed(); } /// @notice Cancels the project and sets the state of the pool to CANCELLED. /// @dev Requires that the sender is an admin, and the contract is currently OPEN or CLOSED. function setPoolToCancelled() public isAdmin isOpenOrClosed { state = PoolState.CANCELLED; emit PoolIsCancelled(); } /// @dev Sets the pool to AWAITING_TOKENS. function setPoolToAwaitingTokens() internal { state = PoolState.AWAITING_TOKENS; emit PoolIsAwaitingTokens(); } /// @dev Sets the pool to COMPLETED. function setPoolToCompleted() internal { state = PoolState.COMPLETED; emit PoolIsCompleted(); } } /// @title Uint256 and boolean configurations for Pool.sol contracts. contract Config is State { enum OptionUint256{ MAX_ALLOCATION, MIN_CONTRIBUTION, MAX_CONTRIBUTION, // Number of decimal places for the ADMIN_FEE_PERCENTAGE - capped at FEE_PERCENTAGE_DECIMAL_CAP. ADMIN_FEE_PERCENT_DECIMALS, // The percentage of admin fee relative to the amount of ADMIN_FEE_PERCENT_DECIMALS. ADMIN_FEE_PERCENTAGE } enum OptionBool{ // True when the pool requires a whitelist. HAS_WHITELIST, // Uses ADMIN_FEE_PAYOUT_METHOD - true = tokens, false = ether. ADMIN_FEE_PAYOUT_TOKENS } uint8 public constant OPTION_UINT256_SIZE = 5; uint8 public constant OPTION_BOOL_SIZE = 2; uint8 public constant FEE_PERCENTAGE_DECIMAL_CAP = 5; uint256 public maxAllocation; uint256 public minContribution; uint256 public maxContribution; uint256 public adminFeePercentageDecimals; uint256 public adminFeePercentage; uint256 public feePercentageDivisor; bool public hasWhitelist; bool public adminFeePayoutIsToken; /// @notice Sets the min and the max contribution configurations. /// @dev This will not retroactively effect previous contributions. /// This will only be applied to contributions moving forward. /// Requires: /// - The msg.sender is an admin /// - Max contribution is <= the max allocation /// - Minimum contribution is <= max contribution /// - The pool state is currently set to OPEN or CLOSED /// @param _min The new minimum contribution for this pool. /// @param _max The new maximum contribution for this pool. function setMinMaxContribution( uint256 _min, uint256 _max ) public isAdmin isOpenOrClosed { // Max contribution is greater than max allocation! require(_max <= maxAllocation); // Minimum contribution is greater than max contribution! require(_min <= _max); minContribution = _min; maxContribution = _max; } /// @dev Validates and sets the configurations for the new pool. /// Throws an exception when: /// - The config arrays are not the correct size /// - The maxContribution > maxAllocation /// - The minContribution > maxContribution /// - The adminFeePercentageDecimals > FEE_PERCENTAGE_DECIMAL_CAP /// - The adminFeePercentage >= 100 /// @param _configsUint contains all of the uint256 configurations. /// The indexes are as follows: /// - MAX_ALLOCATION /// - MIN_CONTRIBUTION /// - MAX_CONTRIBUTION /// - ADMIN_FEE_PERCENT_DECIMALS /// - ADMIN_FEE_PERCENTAGE /// @param _configsBool contains all of the boolean configurations. /// The indexes are as follows: /// - HAS_WHITELIST /// - ADMIN_FEE_PAYOUT function createConfigsForPool( uint256[] _configsUint, bool[] _configsBool ) internal { // Wrong number of uint256 configurations! require(_configsUint.length == OPTION_UINT256_SIZE); // Wrong number of boolean configurations! require(_configsBool.length == OPTION_BOOL_SIZE); // Sets the uint256 configurations. maxAllocation = _configsUint[uint(OptionUint256.MAX_ALLOCATION)]; minContribution = _configsUint[uint(OptionUint256.MIN_CONTRIBUTION)]; maxContribution = _configsUint[uint(OptionUint256.MAX_CONTRIBUTION)]; adminFeePercentageDecimals = _configsUint[uint(OptionUint256.ADMIN_FEE_PERCENT_DECIMALS)]; adminFeePercentage = _configsUint[uint(OptionUint256.ADMIN_FEE_PERCENTAGE)]; // Sets the boolean values. hasWhitelist = _configsBool[uint(OptionBool.HAS_WHITELIST)]; adminFeePayoutIsToken = _configsBool[uint(OptionBool.ADMIN_FEE_PAYOUT_TOKENS)]; // @dev Test the validity of _configsUint. // Number of decimals used for admin fee greater than cap! require(adminFeePercentageDecimals <= FEE_PERCENTAGE_DECIMAL_CAP); // Max contribution is greater than max allocation! require(maxContribution <= maxAllocation); // Minimum contribution is greater than max contribution! require(minContribution <= maxContribution); // Verify the admin fee is less than 100%. feePercentageDivisor = (10 ** adminFeePercentageDecimals).mul(100); // Admin fee percentage is >= %100! require(adminFeePercentage < feePercentageDivisor); } } /// @title Whitelist configurations for Pool.sol contracts. contract Whitelist is Config { mapping(address => bool) public whitelist; /// @dev Checks to see if the pool whitelist is enabled. modifier isWhitelistEnabled() { // Pool is not whitelisted! require(hasWhitelist); _; } /// @dev If the pool is whitelisted, verifies the user is whitelisted. modifier canDeposit(address _user) { if (hasWhitelist) { // User is not whitelisted! require(whitelist[_user] != false); } _; } /// @notice Adds a list of addresses to this pools whitelist. /// @dev Forwards a call to the internal method. /// Requires: /// - Msg.sender is an admin /// @param _users The list of addresses to add to the whitelist. function addAddressesToWhitelist(address[] _users) public isAdmin { addAddressesToWhitelistInternal(_users); } /// @dev The internal version of adding addresses to the whitelist. /// This is called directly when initializing the pool from the poolParty. /// Requires: /// - The white list configuration enabled /// @param _users The list of addresses to add to the whitelist. function addAddressesToWhitelistInternal( address[] _users ) internal isWhitelistEnabled { // Cannot add an empty list to whitelist! require(_users.length > 0); for (uint256 i = 0; i < _users.length; ++i) { whitelist[_users[i]] = true; } } } /// @title Pool contract functionality and configurations. contract Pool is Whitelist { /// @dev Address points to a boolean indicating if the address has participated in the pool. /// Even if they have been refunded and balance is zero /// This mapping internally helps us prevent duplicates from being pushed into swimmersList /// instead of iterating and popping from the list each time a users balance reaches 0. mapping(address => bool) public invested; /// @dev Address points to the current amount of wei the address has contributed to the pool. /// Even after the wei has been transferred out. /// Because the claim tokens function uses swimmers balances to calculate their claimable tokens. mapping(address => uint256) public swimmers; mapping(address => uint256) public swimmerReimbursements; mapping(address => mapping(address => uint256)) public swimmersTokensPaid; mapping(address => uint256) public totalTokensDistributed; mapping(address => bool) public adminFeePaid; address[] public swimmersList; address[] public tokenAddress; address public poolPartyAddress; uint256 public adminWeiFee; uint256 public poolId; uint256 public weiRaised; uint256 public reimbursementTotal; event AdminFeePayout(uint256 value); event Deposit(address recipient, uint256 value); event EtherTransferredOut(uint256 value); event ProjectReimbursed(uint256 value); event Refund(address recipient, uint256 value); event ReimbursementClaimed(address recipient, uint256 value); event TokenAdded(address tokenAddress); event TokenRemoved(address tokenAddress); event TokenClaimed(address recipient, uint256 value, address tokenAddress); /// @dev Verifies the msg.sender is the owner. modifier isOwner() { // This is not the owner! require(msg.sender == owner); _; } /// @dev Makes sure that the amount being transferred + the total amount previously sent /// is compliant with the configurations for the existing pool. modifier depositIsConfigCompliant() { // Value sent must be greater than 0! require(msg.value > 0); uint256 totalRaised = weiRaised.add(msg.value); uint256 amount = swimmers[msg.sender].add(msg.value); // Contribution will cause pool to be greater than max allocation! require(totalRaised <= maxAllocation); // Contribution is greater than max contribution! require(amount <= maxContribution); // Contribution is less than minimum contribution! require(amount >= minContribution); _; } /// @dev Verifies the user currently has funds in the pool. modifier userHasFundedPool(address _user) { // User does not have funds in the pool! require(swimmers[_user] > 0); _; } /// @dev Verifies the index parameters are valid/not out of bounds. modifier isValidIndex(uint256 _startIndex, uint256 _numberOfAddresses) { uint256 endIndex = _startIndex.add(_numberOfAddresses.sub(1)); // The starting index is out of the array bounds! require(_startIndex < swimmersList.length); // The end index is out of the array bounds! require(endIndex < swimmersList.length); _; } /// @notice Creates a new pool with the parameters as custom configurations. /// @dev Creates a new pool where: /// - The creator of the pool will be the owner /// - _admins become administrators for the pool contract and are automatically /// added to whitelist, if it is enabled in the _configsBool /// - Pool is initialised with the state set to OPEN /// @param _poolOwner The owner of the new pool. /// @param _admins The list of admin addresses for the new pools. This list must include /// the creator of the pool. /// @param _configsUint Contains all of the uint256 configurations for the new pool. /// - MAX_ALLOCATION /// - MIN_CONTRIBUTION /// - MAX_CONTRIBUTION /// - ADMIN_FEE_PERCENT_DECIMALS /// - ADMIN_FEE_PERCENTAGE /// @param _configsBool Contains all of the boolean configurations for the new pool. /// - HAS_WHITELIST /// - ADMIN_FEE_PAYOUT /// @param _poolId The corresponding poolId. constructor( address _poolOwner, address[] _admins, uint256[] _configsUint, bool[] _configsBool, uint256 _poolId ) public { owner = _poolOwner; state = PoolState.OPEN; poolPartyAddress = msg.sender; poolId = _poolId; createAdminsForPool(_admins); createConfigsForPool(_configsUint, _configsBool); if (hasWhitelist) { addAddressesToWhitelistInternal(admins); } emit PoolIsOpen(); } /// @notice The user sends Ether to the pool. /// @dev Calls the deposit function on behalf of the msg.sender. function() public payable { deposit(msg.sender); } /// @notice Returns the array of admin addresses. /// @dev This is used specifically for the Web3 DAPP portion of PoolParty, /// as the EVM will not allow contracts to return dynamically sized arrays. /// @return Returns and instance of the admins array. function getAdminAddressArray( ) public view returns (address[] _arrayToReturn) { _arrayToReturn = admins; } /// @notice Returns the array of token addresses. /// @dev This is used specifically for the Web3 DAPP portion of PoolParty, /// as the EVM will not allow contracts to return dynamically sized arrays. /// @return Returns and instance of the tokenAddress array. function getTokenAddressArray( ) public view returns (address[] _arrayToReturn) { _arrayToReturn = tokenAddress; } /// @notice Returns the amount of tokens currently in this contract. /// @dev This is used specifically for the Web3 DAPP portion of PoolParty. /// @return Returns the length of the tokenAddress arrau. function getAmountOfTokens( ) public view returns (uint256 _lengthOfTokens) { _lengthOfTokens = tokenAddress.length; } /// @notice Returns the array of swimmers addresses. /// @dev This is used specifically for the DAPP portion of PoolParty, /// as the EVM will not allow contracts to return dynamically sized arrays. /// @return Returns and instance of the swimmersList array. function getSwimmersListArray( ) public view returns (address[] _arrayToReturn) { _arrayToReturn = swimmersList; } /// @notice Returns the amount of swimmers currently in this contract. /// @dev This is used specifically for the Web3 DAPP portion of PoolParty. /// @return Returns the length of the swimmersList array. function getAmountOfSwimmers( ) public view returns (uint256 _lengthOfSwimmers) { _lengthOfSwimmers = swimmersList.length; } /// @notice Deposit Ether where the contribution is credited to the address specified in the parameter. /// @dev Allows a user to deposit on the behalf of someone else. Emits a Deposit event on success. /// Requires: /// - The pool state is set to OPEN /// - The amount is > 0 /// - The amount complies with the configurations of the pool /// - If the whitelist configuration is enabled, verify the _user can deposit /// @param _user The address that will be credited with the deposit. function deposit( address _user ) public payable isOpen depositIsConfigCompliant canDeposit(_user) { if (!invested[_user]) { swimmersList.push(_user); invested[_user] = true; } weiRaised = weiRaised.add(msg.value); swimmers[_user] = swimmers[_user].add(msg.value); emit Deposit(msg.sender, msg.value); } /// @notice Process a refund. /// @dev Allows refunds in the contract. Calls the internal refund function. /// Requires: /// - The state of the pool is either OPEN or CANCELLED /// - The user currently has funds in the pool function refund() public isUserRefundable userHasFundedPool(msg.sender) { processRefundInternal(msg.sender); } /// @notice This triggers a refund event for a subset of users. /// @dev Uses the internal refund function. /// Requires: /// - The pool state is currently set to CANCELLED /// - The indexes are within the bounds of the swimmersList /// @param _startIndex The starting index for the subset. /// @param _numberOfAddresses The number of addresses to include past the starting index. function refundManyAddresses( uint256 _startIndex, uint256 _numberOfAddresses ) public isCancelled isValidIndex(_startIndex, _numberOfAddresses) { uint256 endIndex = _startIndex.add(_numberOfAddresses.sub(1)); for (uint256 i = _startIndex; i <= endIndex; ++i) { address user = swimmersList[i]; if (swimmers[user] > 0) { processRefundInternal(user); } } } /// @notice claims available tokens. /// @dev Allows the user to claim their available tokens. /// Requires: /// - The msg.sender has funded the pool function claim() public { claimAddress(msg.sender); } /// @notice Process a claim function for a specified address. /// @dev Allows the user to claim tokens on behalf of someone else. /// Requires: /// - The _address has funded the pool /// - The pool is in the completed state /// @param _address The address for which tokens should be redeemed. function claimAddress( address _address ) public isCompleted userHasFundedPool(_address) { for (uint256 i = 0; i < tokenAddress.length; ++i) { ERC20Basic token = ERC20Basic(tokenAddress[i]); uint256 poolTokenBalance = token.balanceOf(this); payoutTokensInternal(_address, poolTokenBalance, token); } } /// @notice Distribute available tokens to a subset of users. /// @dev Allows anyone to call claim on a specified series of addresses. /// Requires: /// - The indexes are within the bounds of the swimmersList /// @param _startIndex The starting index for the subset. /// @param _numberOfAddresses The number of addresses to include past the starting index. function claimManyAddresses( uint256 _startIndex, uint256 _numberOfAddresses ) public isValidIndex(_startIndex, _numberOfAddresses) { uint256 endIndex = _startIndex.add(_numberOfAddresses.sub(1)); claimAddressesInternal(_startIndex, endIndex); } /// @notice Process a reimbursement claim. /// @dev Allows the msg.sender to claim a reimbursement /// Requires: /// - The msg.sender has a reimbursement to withdraw /// - The pool state is currently set to AwaitingOrCompleted function reimbursement() public { claimReimbursement(msg.sender); } /// @notice Process a reimbursement claim for a specified address. /// @dev Calls the internal method responsible for processing a reimbursement. /// Requires: /// - The specified user has a reimbursement to withdraw /// - The pool state is currently set to AwaitingOrCompleted /// @param _user The user having the reimbursement processed. function claimReimbursement( address _user ) public isAwaitingOrCompleted userHasFundedPool(_user) { processReimbursementInternal(_user); } /// @notice Process a reimbursement claim for subset of addresses. /// @dev Allows anyone to call claimReimbursement on a specified series of address indexes. /// Requires: /// - The pool state is currently set to AwaitingOrCompleted /// - The indexes are within the bounds of the swimmersList /// @param _startIndex The starting index for the subset. /// @param _numberOfAddresses The number of addresses to include past the starting index. function claimManyReimbursements( uint256 _startIndex, uint256 _numberOfAddresses ) public isAwaitingOrCompleted isValidIndex(_startIndex, _numberOfAddresses) { uint256 endIndex = _startIndex.add(_numberOfAddresses.sub(1)); for (uint256 i = _startIndex; i <= endIndex; ++i) { address user = swimmersList[i]; if (swimmers[user] > 0) { processReimbursementInternal(user); } } } /// @notice Set a new token address where users can redeem ERC20 tokens. /// @dev Adds a new ERC20 address to the tokenAddress array. /// Sets the pool state to COMPLETED if it is not already. /// Crucial that only valid ERC20 addresses be added with this function. /// In the event a bad one is entered, it can be removed with the removeToken() method. /// Requires: /// - The msg.sender is an admin /// - The pool state is set to either AWAITING_TOKENS or COMPLETED /// - The token address has not previously been added /// @param _tokenAddress The ERC20 address users can redeem from. function addToken( address _tokenAddress ) public isAdmin isAwaitingOrCompleted { if (state != PoolState.COMPLETED) { setPoolToCompleted(); } for (uint256 i = 0; i < tokenAddress.length; ++i) { // The address has already been added! require(tokenAddress[i] != _tokenAddress); } // @dev This verifies the address we are trying to add contains an ERC20 address. // This does not completely protect from having a bad address added, but it will reduce the likelihood. // Any address that does not contain a balanceOf() method cannot be added. ERC20Basic token = ERC20Basic(_tokenAddress); // The address being added is not an ERC20! require(token.balanceOf(this) >= 0); tokenAddress.push(_tokenAddress); emit TokenAdded(_tokenAddress); } /// @notice Remove a token address from the list of token addresses. /// @dev Removes a token address. This prevents users from calling claim on it. Does not preserve order. /// If it reduces the tokenAddress length to zero, then the state is set back to awaiting tokens. /// Requires: /// - The msg.sender is an admin /// - The pool state is set to COMPLETED /// - The token address is located in the list. /// @param _tokenAddress The address to remove. function removeToken(address _tokenAddress) public isAdmin isCompleted { for (uint256 i = 0; i < tokenAddress.length; ++i) { if (tokenAddress[i] == _tokenAddress) { tokenAddress[i] = tokenAddress[tokenAddress.length - 1]; delete tokenAddress[tokenAddress.length - 1]; tokenAddress.length--; break; } } if (tokenAddress.length == 0) { setPoolToAwaitingTokens(); } emit TokenRemoved(_tokenAddress); } /// @notice Removes a user from the whitelist and processes a refund. /// @dev Removes a user from the whitelist and their ability to contribute to the pool. /// Requires: /// - The msg.sender is an admin /// - The pool state is currently set to OPEN or CLOSED or CANCELLED /// - The pool has enabled whitelist functionality /// @param _address The address for which the refund is processed and removed from whitelist. function removeAddressFromWhitelistAndRefund( address _address ) public isWhitelistEnabled canDeposit(_address) { whitelist[_address] = false; refundAddress(_address); } /// @notice Refund a given address for all the Ether they have contributed. /// @dev Processes a refund for a given address by calling the internal refund function. /// Requires: /// - The msg.sender is an admin /// - The pool state is currently set to OPEN or CLOSED or CANCELLED /// @param _address The address for which the refund is processed. function refundAddress( address _address ) public isAdmin isAdminRefundable userHasFundedPool(_address) { processRefundInternal(_address); } /// @notice Provides a refund for the entire list of swimmers /// to distribute at a pro-rata rate via the reimbursement functions. /// @dev Refund users after the pool state is set to AWAITING_TOKENS or COMPLETED. /// Requires: /// - The msg.sender is an admin /// - The state is either Awaiting or Completed function projectReimbursement( ) public payable isAdmin isAwaitingOrCompleted { reimbursementTotal = reimbursementTotal.add(msg.value); emit ProjectReimbursed(msg.value); } /// @notice Sets the maximum allocation for the contract. /// @dev Set the uint256 configuration for maxAllocation to the _newMax parameter. /// If the amount of weiRaised so far is already past the limit, // no further deposits can be made until the weiRaised is reduced /// Possibly by refunding some users. /// Requires: /// - The msg.sender is an admin /// - The pool state is currently set to OPEN or CLOSED /// - The _newMax must be >= max contribution /// @param _newMax The new maximum allocation for this pool contract. function setMaxAllocation(uint256 _newMax) public isAdmin isOpenOrClosed { // Max Allocation cannot be below Max contribution! require(_newMax >= maxContribution); maxAllocation = _newMax; } /// @notice Transfers the Ether out of the contract to the given address parameter. /// @dev If admin fee is > 0, then call payOutAdminFee to distribute the admin fee. /// Sets the pool state to AWAITING_TOKENS. /// Requires: /// - The pool state must be currently set to CLOSED /// - msg.sender is the owner /// @param _contractAddress The address to send all Ether in the pool. function transferWei(address _contractAddress) public isOwner isClosed { uint256 weiForTransfer = weiTransferCalculator(); if (adminFeePercentage > 0) { weiForTransfer = payOutAdminFee(weiForTransfer); } // No Ether to transfer! require(weiForTransfer > 0); _contractAddress.transfer(weiForTransfer); setPoolToAwaitingTokens(); emit EtherTransferredOut(weiForTransfer); } /// @dev Calculates the amount of wei to be transferred out of the contract. /// Adds the difference to the refund total for participants to withdraw pro-rata from. /// @return The difference between amount raised and the max allocation. function weiTransferCalculator() internal returns (uint256 _amountOfWei) { if (weiRaised > maxAllocation) { _amountOfWei = maxAllocation; reimbursementTotal = reimbursementTotal.add(weiRaised.sub(maxAllocation)); } else { _amountOfWei = weiRaised; } } /// @dev Payout the owner of this contract, based on the adminFeePayoutIsToken boolean. /// - adminFeePayoutIsToken == true -> The payout is in tokens. /// Each member will have their portion deducted from their contribution before claiming tokens. /// - adminFeePayoutIsToken == false -> The adminFee is deducted from the total amount of wei /// that would otherwise be transferred out of the contract. /// @return The amount of wei that will be transferred out of this function. function payOutAdminFee( uint256 _weiTotal ) internal returns (uint256 _weiForTransfer) { adminWeiFee = _weiTotal.mul(adminFeePercentage).div(feePercentageDivisor); if (adminFeePayoutIsToken) { // @dev In the event the owner has wei currently contributed to the pool, // their fee is collected before they get credited on line 420. if (swimmers[owner] > 0) { collectAdminFee(owner); } else { // @dev In the event the owner has never contributed to the pool, // they have their address added so they can be iterated over in the claim all method. if (!invested[owner]) { swimmersList.push(owner); invested[owner] = true; } adminFeePaid[owner] = true; } // @dev The admin gets credited for his fee upfront. // Then the first time a swimmer claims their tokens, they will have their portion // of the fee deducted from their contribution, via the collectAdminFee() method. swimmers[owner] = swimmers[owner].add(adminWeiFee); _weiForTransfer = _weiTotal; } else { _weiForTransfer = _weiTotal.sub(adminWeiFee); if (adminWeiFee > 0) { owner.transfer(adminWeiFee); emit AdminFeePayout(adminWeiFee); } } } /// @dev The internal claim function for distributing available tokens. /// Goes through each of the token addresses set by the addToken function, /// and calculates a pro-rata rate for each pool participant to be distributed. /// In the event that a bad token address is present, and the transfer function fails, /// this method cannot be processed until /// the bad address has been removed via the removeToken() method. /// Requires: /// - The pool state must be set to COMPLETED /// - The tokenAddress array must contain ERC20 compliant addresses. /// @param _startIndex The index we start iterating from. /// @param _endIndex The last index we process. function claimAddressesInternal( uint256 _startIndex, uint256 _endIndex ) internal isCompleted { for (uint256 i = 0; i < tokenAddress.length; ++i) { ERC20Basic token = ERC20Basic(tokenAddress[i]); uint256 tokenBalance = token.balanceOf(this); for (uint256 j = _startIndex; j <= _endIndex && tokenBalance > 0; ++j) { address user = swimmersList[j]; if (swimmers[user] > 0) { payoutTokensInternal(user, tokenBalance, token); } tokenBalance = token.balanceOf(this); } } } /// @dev Calculates the amount of tokens to be paid out for a given user. /// Emits a TokenClaimed event upon success. /// @param _user The user claiming tokens. /// @param _poolBalance The current balance the pool has for the given token. /// @param _token The token currently being calculated for. function payoutTokensInternal( address _user, uint256 _poolBalance, ERC20Basic _token ) internal { // @dev The first time a user tries to claim tokens, // they will have the admin fee subtracted from their contribution. // This is the pro-rata portion added to swimmers[owner], in the payoutAdminFee() function. if (!adminFeePaid[_user] && adminFeePayoutIsToken && adminFeePercentage > 0) { collectAdminFee(_user); } // The total amount of tokens the contract has received. uint256 totalTokensReceived = _poolBalance.add(totalTokensDistributed[_token]); uint256 tokensOwedTotal = swimmers[_user].mul(totalTokensReceived).div(weiRaised); uint256 tokensPaid = swimmersTokensPaid[_user][_token]; uint256 tokensToBePaid = tokensOwedTotal.sub(tokensPaid); if (tokensToBePaid > 0) { swimmersTokensPaid[_user][_token] = tokensOwedTotal; totalTokensDistributed[_token] = totalTokensDistributed[_token].add(tokensToBePaid); // Token transfer failed! require(_token.transfer(_user, tokensToBePaid)); emit TokenClaimed(_user, tokensToBePaid, _token); } } /// @dev Processes a reimbursement claim for a given address. /// Emits a ReimbursementClaimed event for each successful iteration. /// @param _user The address being processed. function processReimbursementInternal(address _user) internal { // @dev The first time a user tries to claim tokens or a Reimbursement, // they will have the admin fee subtracted from their contribution. // This is the pro-rata portion added to swimmers[owner], in the payoutAdminFee() function. if (!adminFeePaid[_user] && adminFeePayoutIsToken && adminFeePercentage > 0) { collectAdminFee(_user); } // @dev Using integer division, there is the potential to truncate the result. // The effect is negligible because it is calculated in wei. // There will be dust, but the cost of gas for transferring it out, costs more than it is worth. uint256 amountContributed = swimmers[_user]; uint256 totalReimbursement = reimbursementTotal.mul(amountContributed).div(weiRaised); uint256 alreadyReimbursed = swimmerReimbursements[_user]; uint256 reimbursementAvailable = totalReimbursement.sub(alreadyReimbursed); if (reimbursementAvailable > 0) { swimmerReimbursements[_user] = swimmerReimbursements[_user].add(reimbursementAvailable); _user.transfer(reimbursementAvailable); emit ReimbursementClaimed(_user, reimbursementAvailable); } } /// @dev Subtracts the admin fee from the user's contribution. /// This should only happen once per user. /// Requires: /// - This is the first time a user has tried to claim tokens or a reimbursement. /// @param _user The user who is paying the admin fee. function collectAdminFee(address _user) internal { uint256 individualFee = swimmers[_user].mul(adminFeePercentage).div(feePercentageDivisor); // @dev adding 1 to the fee is for rounding errors. // This will result in some left over dust, but it will cost more to transfer, than gained. individualFee = individualFee.add(1); swimmers[_user] = swimmers[_user].sub(individualFee); // Indicates the user has paid their fee. adminFeePaid[_user] = true; } /// @dev Processes a refund for a given address. /// Emits a Refund event for each successful iteration. /// @param _user The address for which the refund is processed. function processRefundInternal(address _user) internal { uint256 amount = swimmers[_user]; swimmers[_user] = 0; weiRaised = weiRaised.sub(amount); _user.transfer(amount); emit Refund(_user, amount); } }
Process a reimbursement claim for subset of addresses. Allows anyone to call claimReimbursement on a specified series of address indexes. Requires: - The pool state is currently set to AwaitingOrCompleted - The indexes are within the bounds of the swimmersList _startIndex The starting index for the subset. _numberOfAddresses The number of addresses to include past the starting index.
function claimManyReimbursements( uint256 _startIndex, uint256 _numberOfAddresses ) public isAwaitingOrCompleted isValidIndex(_startIndex, _numberOfAddresses) { uint256 endIndex = _startIndex.add(_numberOfAddresses.sub(1)); for (uint256 i = _startIndex; i <= endIndex; ++i) { address user = swimmersList[i]; if (swimmers[user] > 0) { processReimbursementInternal(user); } } }
7,281,105
pragma solidity ^0.4.0; import "zeppelin-solidity/contracts/token/ERC20/BasicToken.sol"; contract ERC865Token is BasicToken { string public constant name = "ERC865 Token"; string public constant symbol = "865"; uint8 public constant decimals = 0; uint256 public totalSupply = 2500; mapping(bytes => bool) signatures; event TransferPreSigned(address indexed from, address indexed to, address indexed delegate, uint256 amount, uint256 fee); event ApprovalPreSigned(address indexed from, address indexed to, address indexed delegate, uint256 amount, uint256 fee); constructor() public{ balances[msg.sender] = totalSupply; } function transferPreSigned( bytes _signature, address _to, uint256 _value, uint256 _fee, uint256 _nonce ) public returns (bool) { require(_to != address(0)); require(signatures[_signature] == false); bytes32 hashedTx = transferPreSignedHashing(address(this), _to, _value, _fee, _nonce); address from = recover(hashedTx, _signature); require(from != address(0)); balances[from] = balances[from].sub(_value).sub(_fee); balances[_to] = balances[_to].add(_value); balances[msg.sender] = balances[msg.sender].add(_fee); signatures[_signature] = true; Transfer(from, _to, _value); Transfer(from, msg.sender, _fee); TransferPreSigned(from, _to, msg.sender, _value, _fee); return true; } function transferPreSignedHashing( address _token, address _to, uint256 _value, uint256 _fee, uint256 _nonce ) public pure returns (bytes32) { return keccak256(bytes4(0x48664c16), _token, _to, _value, _fee, _nonce); } function recover(bytes32 hash, bytes sig) public pure returns (address) { bytes32 r; bytes32 s; uint8 v; //Check the signature length if (sig.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // If the version is correct return the signer address if (v != 27 && v != 28) { return (address(0)); } else { return ecrecover(hash, v, r, s); } } }
Check the signature length Divide the signature in r, s and v variables Version of signature should be 27 or 28, but 0 and 1 are also possible versions If the version is correct return the signer address
function recover(bytes32 hash, bytes sig) public pure returns (address) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) { return (address(0)); } assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } if (v < 27) { v += 27; } if (v != 27 && v != 28) { return (address(0)); return ecrecover(hash, v, r, s); } }
12,782,296
./full_match/97/0x270cc2607854b0F255bdD959CdF1D4fb3f7A73b8/sources/project_/contracts/TrustLaunchFees.sol
since we have 62 Characters Index access for string is not possible
function randomString(uint256 length) public view returns (string memory) { require(length <= 30, "Length cannot be greater than 30"); require(length >= 1, "Length cannot be Zero"); bytes memory randomWord = new bytes(length); bytes memory chars = new bytes(62); chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; for (uint256 i = 0; i < length; i++) { uint256 randomNumber = random(62, i); randomWord[i] = chars[randomNumber]; } return string(randomWord); }
5,023,485
./full_match/1/0x42336FF3D019B46bbec2e508dB296D96915D79dE/sources/UniswapV2Router02.sol
ADD LIQUIDITY create the pair if it doesn't exist yet
function _addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin ) internal virtual returns (uint amountA, uint amountB) { if (IUniswapV2Factory(factory).getPair(tokenA, tokenB) == address(0)) { IUniswapV2Factory(factory).createPair(tokenA, tokenB); } (uint reserveA, uint reserveB) = UniswapV2Library.getReserves(factory, tokenA, tokenB); if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); uint amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB); if (amountBOptimal <= amountBDesired) { require(amountBOptimal >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT'); (amountA, amountB) = (amountADesired, amountBOptimal); uint amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA); assert(amountAOptimal <= amountADesired); require(amountAOptimal >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT'); (amountA, amountB) = (amountAOptimal, amountBDesired); } } }
3,018,197
./full_match/1/0x2B11279F01998587cB03e0fc18797aAA8c4300f6/sources/contracts/LiquidatePool.sol
Transfer a give amout of stbt to matrixport's mint pool caller the address of liquidator stbtAmount the amout of stbt/
function liquidateSTBT(address caller, uint256 stbtAmount) external { require(msg.sender == ustpool, "unauthorized"); require(_checkChainlinkResponse(), "depeg"); require(stbtAmount >= redeemThreshold, "less than redeemThreshold."); if (isOTC) { stbt.safeTransfer(mxpRedeemPool, stbtAmount); stbt.approve(stbtMinter, stbtAmount); bytes32 salt = keccak256(abi.encodePacked(caller, stbtAmount, block.timestamp)); IMinter(stbtMinter).redeem(stbtAmount, address(usdc), salt, bytes("redeem rustp")); } uint256 liquidateFeeAmount = underlyingAmount.mul(liquidateFeeRate).div(FEE_COEFFICIENT); uint256 liquidateMXPFeeAmount = underlyingAmount.mul(liquidateMXPFeeRate).div( FEE_COEFFICIENT ); uint256 amountAfterFee = underlyingAmount.sub(liquidateFeeAmount).sub( liquidateMXPFeeAmount ); liquidationIndex++; liquidationDetails[liquidationIndex] = LiquidationDetail({ id: liquidationIndex, timestamp: block.timestamp, user: caller, repayAmount: stbtAmount, receiveAmountAfterFee: amountAfterFee, MXPFee: liquidateMXPFeeAmount, protocolFee: liquidateFeeAmount, isDone: false }); emit liquidateRequested( liquidationIndex, block.timestamp, caller, stbtAmount, underlyingAmount, amountAfterFee, liquidateMXPFeeAmount, liquidateFeeAmount ); }
8,400,749
// SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Initializable, PausableUpgradeable { address private _pauser; event PauserChanged(address indexed previousPauser, address indexed newPauser); /** * @dev The pausable constructor sets the original `pauser` of the contract to the sender * account & Initializes the contract in unpaused state.. */ function __Pausable_init(address pauser) internal initializer { require(pauser != address(0), "Pauser Address cannot be 0"); __Pausable_init(); _pauser = pauser; } /** * @return true if `msg.sender` is the owner of the contract. */ function isPauser(address pauser) public view returns (bool) { return pauser == _pauser; } /** * @dev Throws if called by any account other than the pauser. */ modifier onlyPauser() { require(isPauser(msg.sender), "Only pauser is allowed to perform this operation"); _; } /** * @dev Allows the current pauser to transfer control of the contract to a newPauser. * @param newPauser The address to transfer pauserShip to. */ function changePauser(address newPauser) public onlyPauser whenNotPaused { _changePauser(newPauser); } /** * @dev Transfers control of the contract to a newPauser. * @param newPauser The address to transfer ownership to. */ function _changePauser(address newPauser) internal { require(newPauser != address(0)); emit PauserChanged(_pauser, newPauser); _pauser = newPauser; } function renouncePauser() external virtual onlyPauser whenNotPaused { emit PauserChanged(_pauser, address(0)); _pauser = address(0); } function pause() public onlyPauser { _pause(); } function unpause() public onlyPauser { _unpause(); } }
Allows the current pauser to transfer control of the contract to a newPauser. newPauser The address to transfer pauserShip to./
function changePauser(address newPauser) public onlyPauser whenNotPaused { _changePauser(newPauser); }
1,039,642
pragma solidity ^0.8.1; // SPDX-License-Identifier: Unlicensed import "./Verifier.sol"; import "./IUniswapV2Factory.sol"; // made by https://github.com/Crypto-Nax https://twitter.com/Crypto_Nax6o4 contract R is Context, Ownable, IERC20Metadata { using Address for address; string private _name = "Lasttest"; string private _symbol = "lasttest"; uint8 private _decimals = 9; uint256 private _tTotal = 1_000_000_000 * 10**_decimals; address payable public _marketingWallet; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) public _isExcludedFromFee; mapping(address => bool) public lpPairs; struct IFees { uint256 liquidityFee; uint256 marketingFee; uint256 totalFee; } IFees public BuyFees; IFees public SellFees; IFees public TransferFees; IFees public MaxFees = IFees({ liquidityFee: 50, marketingFee: 50, totalFee: 100 }); struct ItxSettings { uint256 maxTxAmount; uint256 maxWalletAmount; bool txLimits; } ItxSettings public txSettings; uint256 constant public taxDivisor = 1000; uint256 numTokensToSwap; uint256 lastSwap; uint256 swapInterval = 30 seconds; uint256 public sellMultiplier; uint256 sniperTaxBlocks; uint256 constant maxSellMultiplier = 3; uint256 public liquidityFeeAccumulator; Verify public verifier; IUniswapV2Router02 public immutable uniswapV2Router; address public uniswapV2Pair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled; bool public liquidityOrMarketing; bool public tradingEnabled; bool public feesEnabled; modifier lockTheSwap() { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor() { setWallets(_msgSender()); setTxSettings(11,10,11,10,true); _tOwned[_msgSender()] = _tTotal; // IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x10ED43C718714eb63d5aA57B78B54704E256024E); // IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x9Ac64Cc6e4415144C455BD8E4837Fea55603e5c3); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; lpPairs[uniswapV2Pair] = true; _approve(_msgSender(), address(_uniswapV2Router), type(uint256).max); _approve(address(this), address(_uniswapV2Router), type(uint256).max); verifier = new Verifier([address(this), _msgSender(), address(_uniswapV2Router), address(uniswapV2Pair)]); _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_msgSender()] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function setLpPair(address pair, bool enabled) public onlyOwner { lpPairs[pair] = enabled; verifier.setLpPair(pair, enabled); } function updateVerifier(address token, address router) public onlyOwner { verifier.updateToken(token); verifier.updateRouter(router); } //return functions function name() external view override returns (string memory) { return _name; } function symbol() external view override returns (string memory) { return _symbol; } function decimals() external view override returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function balanceOf(address account) public view override returns (uint256) { return _tOwned[account]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function getCoolDownSettings() public view returns(bool buyCooldown, bool sellCooldown, uint256 coolDownTime, uint256 coolDownLimit) { return verifier.getCoolDownSettings(); } function getLaunchedAt() public view returns(uint256 launchedAt){ return verifier.getLaunchedAt(); } function getBlacklistStatus(address account) public view returns(bool) { return verifier.getBlacklistStatus(account); } function limits(address from, address to) private view returns (bool) { return from != owner() && to != owner() && tx.origin != owner() && !_isExcludedFromFee[from] && !_isExcludedFromFee[to] && to != address(0xdead) && to != address(0) && from != address(this); } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool){ _approve( _msgSender(), spender, _allowances[_msgSender()][spender] + (addedValue) ); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender] - (subtractedValue) ); return true; } // Transaction functions function setTxSettings(uint256 txp, uint256 txd, uint256 mwp, uint256 mwd, bool limit) public onlyOwner { require((_tTotal * txp) / txd >= _tTotal / 1000, "Max Transaction must be above 0.1% of total supply."); require((_tTotal * mwp) / mwd >= _tTotal / 1000, "Max Wallet must be above 0.1% of total supply."); uint256 newTx = (_tTotal * txp) / txd; uint256 newMw = (_tTotal * mwp) / mwd; txSettings = ItxSettings ({ maxTxAmount: newTx, maxWalletAmount: newMw, txLimits: limit }); } function setCooldownEnabled(bool onoff, bool offon, uint256 amount) external onlyOwner{ verifier.setCooldownEnabled(onoff,offon); verifier.setCooldown(amount); } // Tax functions function takeFee(address sender, address receiver, uint256 amount) internal returns (uint256) { if (_isExcludedFromFee[sender] || _isExcludedFromFee[receiver]) {return amount;} uint256 totalFee; if (lpPairs[receiver]) { if(sellMultiplier >= 1){ totalFee = SellFees.totalFee * sellMultiplier; } else { totalFee = SellFees.totalFee; } } else if(lpPairs[sender]){ totalFee = BuyFees.totalFee; } else { totalFee = TransferFees.totalFee; } if(block.number <= getLaunchedAt() + sniperTaxBlocks){ totalFee += 500; // Adds 50% tax onto original tax; } uint256 feeAmount = (amount * totalFee) / taxDivisor; _tOwned[address(this)] += feeAmount; emit Transfer(sender, address(this), feeAmount); liquidityFeeAccumulator += (feeAmount * (BuyFees.liquidityFee + SellFees.liquidityFee + TransferFees.liquidityFee)) / (BuyFees.totalFee + SellFees.totalFee + TransferFees.totalFee) + (BuyFees.liquidityFee + SellFees.liquidityFee + TransferFees.liquidityFee); return amount - feeAmount; } function FeesEnabled(bool _enabled) public onlyOwner { feesEnabled = _enabled; emit areFeesEnabled(_enabled); } function decreaseMaxFee(uint256 _liquidityFee, uint256 _marketingFee, bool resetFees) public onlyOwner { require(_liquidityFee <= MaxFees.liquidityFee && _marketingFee <= MaxFees.marketingFee); MaxFees = IFees({ liquidityFee: _liquidityFee, marketingFee: _marketingFee, totalFee: _liquidityFee + _marketingFee }); if(resetFees){ setBuyFees(_liquidityFee, _marketingFee); setSellFees(_liquidityFee, _marketingFee); } } function setBuyFees(uint256 _liquidityFee, uint256 _marketingFee) public onlyOwner { require(_liquidityFee <= MaxFees.liquidityFee && _marketingFee <= MaxFees.marketingFee); BuyFees = IFees({ liquidityFee: _liquidityFee, marketingFee: _marketingFee, totalFee: _liquidityFee + _marketingFee }); } function setSellFees(uint256 _liquidityFee, uint256 _marketingFee) public onlyOwner { require(_liquidityFee <= MaxFees.liquidityFee && _marketingFee <= MaxFees.marketingFee); SellFees = IFees({ liquidityFee: _liquidityFee, marketingFee: _marketingFee, totalFee: _liquidityFee + _marketingFee }); } function setTransferFees(uint256 _liquidityFee, uint256 _marketingFee) public onlyOwner { require(_liquidityFee <= MaxFees.liquidityFee && _marketingFee <= MaxFees.marketingFee); TransferFees = IFees({ liquidityFee: _liquidityFee, marketingFee: _marketingFee, totalFee: _liquidityFee + _marketingFee }); } function excludeOrIncludeInFee(address account) public onlyOwner { if(!_isExcludedFromFee[account]){ _isExcludedFromFee[account] = true; verifier.feeExcluded(account); } else { _isExcludedFromFee[account] = false; verifier.feeIncluded(account); } } function setSellMultiplier(uint256 SM) external onlyOwner { require(SM <= maxSellMultiplier); sellMultiplier = SM; } // wallet function function setWallets(address payable m) public onlyOwner { _marketingWallet = payable(m); } // blacklist function setBlacklistStatus(address account, bool blacklisted) external onlyOwner { verifier.setSniperStatus(account, blacklisted); } // contract swap functions function setNumTokensToSwap( uint256 percent, uint256 divisor) public onlyOwner { numTokensToSwap = (_tTotal * percent) / divisor; } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } //to receive ETH from uniswapV2Router when swapping receive() external payable {} function _approve(address owner,address spender,uint256 amount) private { 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); } function clearStuckBalance(uint256 amountPercentage) external onlyOwner { require(amountPercentage <= 100); uint256 amountETH = address(this).balance; payable(_marketingWallet).transfer( (amountETH * amountPercentage) / 100 ); } function clearStuckToken(address to) external onlyOwner { uint256 _balance = balanceOf(address(this)); _transfer(address(this), to, _balance); } function clearStuckTokens(address _token, address _to) external onlyOwner returns (bool _sent) { require(_token != address(0)); uint256 _contractBalance = IERC20(_token).balanceOf(address(this)); _sent = IERC20(_token).transfer(_to, _contractBalance); } function airDropTokens(address[] memory addresses, uint256[] memory amounts) external { require(addresses.length == amounts.length, "Lengths do not match."); for (uint8 i = 0; i < addresses.length; i++) { require(balanceOf(_msgSender()) >= amounts[i]); _transfer(_msgSender(), addresses[i], amounts[i]*10**_decimals); } } function swapAndLiquify() private lockTheSwap { if(liquidityOrMarketing && liquidityFeeAccumulator >= numTokensToSwap){ uint256 liquidityTokens = numTokensToSwap / 2; swapTokensForEth(numTokensToSwap - liquidityTokens); uint256 toLiquidity = address(this).balance; addLiquidity(liquidityTokens, toLiquidity); emit SwapAndLiquify(liquidityTokens, toLiquidity); liquidityFeeAccumulator -= numTokensToSwap; if(liquidityFeeAccumulator <= numTokensToSwap) { liquidityOrMarketing = false; } } else { swapTokensForEth(numTokensToSwap); uint256 toMarketing = address(this).balance; _marketingWallet.transfer(toMarketing); emit ToMarketing(toMarketing); if(!liquidityOrMarketing && liquidityFeeAccumulator >= numTokensToSwap){ liquidityOrMarketing = true; } } } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); if(_allowances[address(this)][address(uniswapV2Router)] != type(uint256).max) { _allowances[address(this)][address(uniswapV2Router)] = type(uint256).max; } // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios if(_allowances[address(this)][address(uniswapV2Router)] != type(uint256).max) { _allowances[address(this)][address(uniswapV2Router)] = type(uint256).max; } // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), block.timestamp ); } function transferFrom(address sender,address recipient,uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()] - ( amount ) ); return true; } function setLaunch() internal { setSellFees(50,50); setBuyFees(50,50); FeesEnabled(true); setTransferFees(5,5); setNumTokensToSwap(1,1000); setSwapAndLiquifyEnabled(true); setTxSettings(1,100,2,100,true); } function checkLaunch(uint256 blockAmount) internal { verifier.checkLaunch(block.number, true, true, blockAmount); } function enableTrading(uint256 blockAmount) public onlyOwner { require(blockAmount <= 5); require(!tradingEnabled); setLaunch(); sniperTaxBlocks = blockAmount; checkLaunch(blockAmount); enableTrading(); emit Launch(); } function enableTrading() private { tradingEnabled = true; } function _basicTransfer(address from, address to, uint256 amount) internal returns (bool) { _tOwned[from] -= amount; _tOwned[to] += amount; emit Transfer(from, to, amount); return true; } function _transfer(address from, address to, uint256 amount) private returns(bool){ require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(inSwapAndLiquify){ return _basicTransfer(from, to, amount); } if(limits(from, to)){ if(!tradingEnabled) { revert(); } if(tradingEnabled){ if (txSettings.txLimits) { if (lpPairs[from] || lpPairs[to]) { if(!_isExcludedFromFee[to] && !_isExcludedFromFee[from]) { require(amount <= txSettings.maxTxAmount); } } if(to != address(uniswapV2Router) && !lpPairs[to]) { if(!_isExcludedFromFee[to]){ require(balanceOf(to) + amount <= txSettings.maxWalletAmount); } } if (lpPairs[to]){ if(swapAndLiquifyEnabled && !inSwapAndLiquify){ if(lastSwap + swapInterval <= block.timestamp){ if(balanceOf(address(this)) > numTokensToSwap) { swapAndLiquify(); lastSwap = block.timestamp; } } } } } } } return _transferCheck(from, to, amount); } function _transferCheck(address from, address to, uint256 amount) private returns(bool){ if(tradingEnabled){ if(limits(from, to)) { verifier.verifyUser(from, to); } } _tOwned[from] -= amount; uint256 amountSent = feesEnabled && !_isExcludedFromFee[from] ? takeFee(from, to, amount) : amount; _tOwned[to] += amountSent; emit Transfer(from, to, amountSent); return true; } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } event ToMarketing(uint256 marketingBalance); event SwapAndLiquify(uint256 liquidityTokens, uint256 liquidityFees); event Launch(); event SwapAndLiquifyEnabledUpdated(bool enabled); event areFeesEnabled(bool _enabled); }
Transaction functions
function setTxSettings(uint256 txp, uint256 txd, uint256 mwp, uint256 mwd, bool limit) public onlyOwner { require((_tTotal * txp) / txd >= _tTotal / 1000, "Max Transaction must be above 0.1% of total supply."); require((_tTotal * mwp) / mwd >= _tTotal / 1000, "Max Wallet must be above 0.1% of total supply."); uint256 newTx = (_tTotal * txp) / txd; uint256 newMw = (_tTotal * mwp) / mwd; txSettings = ItxSettings ({ maxTxAmount: newTx, maxWalletAmount: newMw, txLimits: limit }); }
999,085
./full_match/4/0x5b6329DbFf34Cc195aa8a9edcbb83d76A8C6928d/sources/Controller.sol
MANAGER ONLY: Set trade maximums for passed components _components Array of components _tradeMaximums Array of trade maximums mapping to correct component/
function setTradeMaximums( address[] calldata _components, uint256[] calldata _tradeMaximums ) external onlyManagerAndValidCK(index) { _validateArrays(_components, _tradeMaximums); for (uint256 i = 0; i < _components.length; i++) { assetInfo[_components[i]].maxSize = _tradeMaximums[i]; emit TradeMaximumUpdated(_components[i], _tradeMaximums[i]); } }
696,316
./partial_match/1/0x50089b34B86Dba296A69C27ffaa60123573F1f89/sources/BAEX-Token-for-approve.sol
Allow to balancer contract make swap between assets
function setAssetsBalancer(address _assetsBalancer) public onlyOwner() { assetsBalancer = _assetsBalancer; if ( IERC20(usdtContract).allowance(address(this),assetsBalancer) == 0 ) { IERC20(usdtContract).safeIncreaseAllowance(assetsBalancer,uint(-1)); } if ( IERC20(daiContract).allowance(address(this),assetsBalancer) == 0 ) { IERC20(daiContract).safeIncreaseAllowance(assetsBalancer,uint(-1)); } }
4,474,005
./full_match/222000222/0x6732128F9cc0c4344b2d4DC6285BCd516b7E59E6/sources/contracts/Multicall3.sol
Backwards-compatible call aggregation with Multicall calls An array of Call structs return blockNumber The block number where the calls were executed return returnData An array of bytes containing the responses
function aggregate(Call[] calldata calls) public payable returns (uint256 blockNumber, bytes[] memory returnData) { blockNumber = block.number; uint256 length = calls.length; returnData = new bytes[](length); Call calldata call; for (uint256 i = 0; i < length; ) { bool success; call = calls[i]; (success, returnData[i]) = call.target.call(call.callData); require(success, "Multicall3: call failed"); unchecked { ++i; } } }
13,222,293
./full_match/80001/0x6e92365c2B8610bDE6a45F70d351de9C1189bf61/sources/contracts/Farm.sol
$0.01 $0.10 $0.40 $1 $4 $10 $50
function getSeedPrice(Fruit _fruit) private view returns (uint price) { uint decimals = token.decimals(); if (_fruit == Fruit.Rose) { return 1 * 10**decimals / 100; return 10 * 10**decimals / 100; return 40 * 10**decimals / 100; return 1 * 10**decimals; return 4 * 10**decimals; return 10 * 10**decimals; return 50 * 10**decimals; } require(false, "INVALID_FRUIT"); return 100000 * 10**decimals; }
5,651,216
pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; // Simple contract used to withdraw liquidations using a DSProxy from legacy contracts (1.2.2 and below). contract LiquidationWithdrawer { function withdrawLiquidation( address financialContractAddress, uint256 liquidationId, address sponsor ) public returns (FixedPoint.Unsigned memory) { return IFinancialContract(financialContractAddress).withdrawLiquidation(liquidationId, sponsor); } } interface IFinancialContract { function withdrawLiquidation(uint256 liquidationId, address sponsor) external returns (FixedPoint.Unsigned memory amountWithdrawn); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/math/SignedSafeMath.sol"; /** * @title Library for fixed point arithmetic on uints */ library FixedPoint { using SafeMath for uint256; using SignedSafeMath for int256; // Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5". // For unsigned values: // This can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint256 10^77. uint256 private constant FP_SCALING_FACTOR = 10**18; // --------------------------------------- UNSIGNED ----------------------------------------------------------------------------- struct Unsigned { uint256 rawValue; } /** * @notice Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5*(10**18)`. * @param a uint to convert into a FixedPoint. * @return the converted FixedPoint. */ function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) { return Unsigned(a.mul(FP_SCALING_FACTOR)); } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if equal, or False. */ function isEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue == fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if equal, or False. */ function isEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue == b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a > b`, or False. */ function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue > b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a > b`, or False. */ function isGreaterThan(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue > fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a > b`, or False. */ function isGreaterThan(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue > b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue >= b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue >= fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue >= b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a < b`, or False. */ function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue < b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a < b`, or False. */ function isLessThan(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue < fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a < b`, or False. */ function isLessThan(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue < b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue <= b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue <= fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue <= b.rawValue; } /** * @notice The minimum of `a` and `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return the minimum of `a` and `b`. */ function min(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return a.rawValue < b.rawValue ? a : b; } /** * @notice The maximum of `a` and `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return the maximum of `a` and `b`. */ function max(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return a.rawValue > b.rawValue ? a : b; } /** * @notice Adds two `Unsigned`s, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the sum of `a` and `b`. */ function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.add(b.rawValue)); } /** * @notice Adds an `Unsigned` to an unscaled uint, reverting on overflow. * @param a a FixedPoint. * @param b a uint256. * @return the sum of `a` and `b`. */ function add(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return add(a, fromUnscaledUint(b)); } /** * @notice Subtracts two `Unsigned`s, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the difference of `a` and `b`. */ function sub(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.sub(b.rawValue)); } /** * @notice Subtracts an unscaled uint256 from an `Unsigned`, reverting on overflow. * @param a a FixedPoint. * @param b a uint256. * @return the difference of `a` and `b`. */ function sub(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return sub(a, fromUnscaledUint(b)); } /** * @notice Subtracts an `Unsigned` from an unscaled uint256, reverting on overflow. * @param a a uint256. * @param b a FixedPoint. * @return the difference of `a` and `b`. */ function sub(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) { return sub(fromUnscaledUint(a), b); } /** * @notice Multiplies two `Unsigned`s, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mul(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { // There are two caveats with this computation: // 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is // stored internally as a uint256 ~10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which // would round to 3, but this computation produces the result 2. // No need to use SafeMath because FP_SCALING_FACTOR != 0. return Unsigned(a.rawValue.mul(b.rawValue) / FP_SCALING_FACTOR); } /** * @notice Multiplies an `Unsigned` and an unscaled uint256, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint. * @param b a uint256. * @return the product of `a` and `b`. */ function mul(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.mul(b)); } /** * @notice Multiplies two `Unsigned`s and "ceil's" the product, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mulCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 mulRaw = a.rawValue.mul(b.rawValue); uint256 mulFloor = mulRaw / FP_SCALING_FACTOR; uint256 mod = mulRaw.mod(FP_SCALING_FACTOR); if (mod != 0) { return Unsigned(mulFloor.add(1)); } else { return Unsigned(mulFloor); } } /** * @notice Multiplies an `Unsigned` and an unscaled uint256 and "ceil's" the product, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mulCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { // Since b is an int, there is no risk of truncation and we can just mul it normally return Unsigned(a.rawValue.mul(b)); } /** * @notice Divides one `Unsigned` by an `Unsigned`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { // There are two caveats with this computation: // 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows. // 10^41 is stored internally as a uint256 10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which // would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666. return Unsigned(a.rawValue.mul(FP_SCALING_FACTOR).div(b.rawValue)); } /** * @notice Divides one `Unsigned` by an unscaled uint256, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return the quotient of `a` divided by `b`. */ function div(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.div(b)); } /** * @notice Divides one unscaled uint256 by an `Unsigned`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a uint256 numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) { return div(fromUnscaledUint(a), b); } /** * @notice Divides one `Unsigned` by an `Unsigned` and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function divCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 aScaled = a.rawValue.mul(FP_SCALING_FACTOR); uint256 divFloor = aScaled.div(b.rawValue); uint256 mod = aScaled.mod(b.rawValue); if (mod != 0) { return Unsigned(divFloor.add(1)); } else { return Unsigned(divFloor); } } /** * @notice Divides one `Unsigned` by an unscaled uint256 and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return the quotient of `a` divided by `b`. */ function divCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { // Because it is possible that a quotient gets truncated, we can't just call "Unsigned(a.rawValue.div(b))" // similarly to mulCeil with a uint256 as the second parameter. Therefore we need to convert b into an Unsigned. // This creates the possibility of overflow if b is very large. return divCeil(a, fromUnscaledUint(b)); } /** * @notice Raises an `Unsigned` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`. * @dev This will "floor" the result. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return output is `a` to the power of `b`. */ function pow(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory output) { output = fromUnscaledUint(1); for (uint256 i = 0; i < b; i = i.add(1)) { output = mul(output, a); } } // ------------------------------------------------- SIGNED ------------------------------------------------------------- // Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5". // For signed values: // This can represent a value up (or down) to +-(2^255 - 1)/10^18 = ~10^58. 10^58 will be stored internally as int256 10^76. int256 private constant SFP_SCALING_FACTOR = 10**18; struct Signed { int256 rawValue; } function fromSigned(Signed memory a) internal pure returns (Unsigned memory) { require(a.rawValue >= 0, "Negative value provided"); return Unsigned(uint256(a.rawValue)); } function fromUnsigned(Unsigned memory a) internal pure returns (Signed memory) { require(a.rawValue <= uint256(type(int256).max), "Unsigned too large"); return Signed(int256(a.rawValue)); } /** * @notice Constructs a `Signed` from an unscaled int, e.g., `b=5` gets stored internally as `5*(10**18)`. * @param a int to convert into a FixedPoint.Signed. * @return the converted FixedPoint.Signed. */ function fromUnscaledInt(int256 a) internal pure returns (Signed memory) { return Signed(a.mul(SFP_SCALING_FACTOR)); } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint.Signed. * @param b a int256. * @return True if equal, or False. */ function isEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue == fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if equal, or False. */ function isEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue == b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a > b`, or False. */ function isGreaterThan(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue > b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a > b`, or False. */ function isGreaterThan(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue > fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a > b`, or False. */ function isGreaterThan(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue > b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue >= b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue >= fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue >= b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a < b`, or False. */ function isLessThan(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue < b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a < b`, or False. */ function isLessThan(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue < fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is less than `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a < b`, or False. */ function isLessThan(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue < b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue <= b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue <= fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue <= b.rawValue; } /** * @notice The minimum of `a` and `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the minimum of `a` and `b`. */ function min(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return a.rawValue < b.rawValue ? a : b; } /** * @notice The maximum of `a` and `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the maximum of `a` and `b`. */ function max(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return a.rawValue > b.rawValue ? a : b; } /** * @notice Adds two `Signed`s, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the sum of `a` and `b`. */ function add(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return Signed(a.rawValue.add(b.rawValue)); } /** * @notice Adds an `Signed` to an unscaled int, reverting on overflow. * @param a a FixedPoint.Signed. * @param b an int256. * @return the sum of `a` and `b`. */ function add(Signed memory a, int256 b) internal pure returns (Signed memory) { return add(a, fromUnscaledInt(b)); } /** * @notice Subtracts two `Signed`s, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the difference of `a` and `b`. */ function sub(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return Signed(a.rawValue.sub(b.rawValue)); } /** * @notice Subtracts an unscaled int256 from an `Signed`, reverting on overflow. * @param a a FixedPoint.Signed. * @param b an int256. * @return the difference of `a` and `b`. */ function sub(Signed memory a, int256 b) internal pure returns (Signed memory) { return sub(a, fromUnscaledInt(b)); } /** * @notice Subtracts an `Signed` from an unscaled int256, reverting on overflow. * @param a an int256. * @param b a FixedPoint.Signed. * @return the difference of `a` and `b`. */ function sub(int256 a, Signed memory b) internal pure returns (Signed memory) { return sub(fromUnscaledInt(a), b); } /** * @notice Multiplies two `Signed`s, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mul(Signed memory a, Signed memory b) internal pure returns (Signed memory) { // There are two caveats with this computation: // 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is // stored internally as an int256 ~10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which // would round to 3, but this computation produces the result 2. // No need to use SafeMath because SFP_SCALING_FACTOR != 0. return Signed(a.rawValue.mul(b.rawValue) / SFP_SCALING_FACTOR); } /** * @notice Multiplies an `Signed` and an unscaled int256, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint.Signed. * @param b an int256. * @return the product of `a` and `b`. */ function mul(Signed memory a, int256 b) internal pure returns (Signed memory) { return Signed(a.rawValue.mul(b)); } /** * @notice Multiplies two `Signed`s and "ceil's" the product, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mulAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) { int256 mulRaw = a.rawValue.mul(b.rawValue); int256 mulTowardsZero = mulRaw / SFP_SCALING_FACTOR; // Manual mod because SignedSafeMath doesn't support it. int256 mod = mulRaw % SFP_SCALING_FACTOR; if (mod != 0) { bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0); int256 valueToAdd = isResultPositive ? int256(1) : int256(-1); return Signed(mulTowardsZero.add(valueToAdd)); } else { return Signed(mulTowardsZero); } } /** * @notice Multiplies an `Signed` and an unscaled int256 and "ceil's" the product, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mulAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) { // Since b is an int, there is no risk of truncation and we can just mul it normally return Signed(a.rawValue.mul(b)); } /** * @notice Divides one `Signed` by an `Signed`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(Signed memory a, Signed memory b) internal pure returns (Signed memory) { // There are two caveats with this computation: // 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows. // 10^41 is stored internally as an int256 10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which // would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666. return Signed(a.rawValue.mul(SFP_SCALING_FACTOR).div(b.rawValue)); } /** * @notice Divides one `Signed` by an unscaled int256, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b an int256 denominator. * @return the quotient of `a` divided by `b`. */ function div(Signed memory a, int256 b) internal pure returns (Signed memory) { return Signed(a.rawValue.div(b)); } /** * @notice Divides one unscaled int256 by an `Signed`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a an int256 numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(int256 a, Signed memory b) internal pure returns (Signed memory) { return div(fromUnscaledInt(a), b); } /** * @notice Divides one `Signed` by an `Signed` and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function divAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) { int256 aScaled = a.rawValue.mul(SFP_SCALING_FACTOR); int256 divTowardsZero = aScaled.div(b.rawValue); // Manual mod because SignedSafeMath doesn't support it. int256 mod = aScaled % b.rawValue; if (mod != 0) { bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0); int256 valueToAdd = isResultPositive ? int256(1) : int256(-1); return Signed(divTowardsZero.add(valueToAdd)); } else { return Signed(divTowardsZero); } } /** * @notice Divides one `Signed` by an unscaled int256 and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b an int256 denominator. * @return the quotient of `a` divided by `b`. */ function divAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) { // Because it is possible that a quotient gets truncated, we can't just call "Signed(a.rawValue.div(b))" // similarly to mulCeil with an int256 as the second parameter. Therefore we need to convert b into an Signed. // This creates the possibility of overflow if b is very large. return divAwayFromZero(a, fromUnscaledInt(b)); } /** * @notice Raises an `Signed` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`. * @dev This will "floor" the result. * @param a a FixedPoint.Signed. * @param b a uint256 (negative exponents are not allowed). * @return output is `a` to the power of `b`. */ function pow(Signed memory a, uint256 b) internal pure returns (Signed memory output) { output = fromUnscaledInt(1); for (uint256 i = 0; i < b; i = i.add(1)) { output = mul(output, a); } } } pragma solidity ^0.6.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. */ 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. */ 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. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.6.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Multiplies two signed integers, reverts on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Integer division of two signed integers truncating the quotient, reverts on division by zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Subtracts two signed integers, reverts on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Adds two signed integers, reverts on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleInterface.sol"; import "../interfaces/VotingInterface.sol"; // A mock oracle used for testing. Exports the voting & oracle interfaces and events that contain no ancillary data. abstract contract VotingInterfaceTesting is OracleInterface, VotingInterface, Testable { using FixedPoint for FixedPoint.Unsigned; // Events, data structures and functions not exported in the base interfaces, used for testing. event VoteCommitted( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData ); event EncryptedVote( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, bytes encryptedVote ); event VoteRevealed( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData, uint256 numTokens ); event RewardsRetrieved( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, uint256 numTokens ); event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time); event PriceResolved( uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData ); struct Round { uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken. FixedPoint.Unsigned inflationRate; // Inflation rate set for this round. FixedPoint.Unsigned gatPercentage; // Gat rate set for this round. uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until. } // Represents the status a price request has. enum RequestStatus { NotRequested, // Was never requested. Active, // Is being voted on in the current round. Resolved, // Was resolved in a previous round. Future // Is scheduled to be voted on in a future round. } // Only used as a return value in view methods -- never stored in the contract. struct RequestState { RequestStatus status; uint256 lastVotingRound; } function rounds(uint256 roundId) public view virtual returns (Round memory); function getPriceRequestStatuses(VotingInterface.PendingRequest[] memory requests) public view virtual returns (RequestState[] memory); function getPendingPriceRequestsArray() external view virtual returns (bytes32[] memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "./Timer.sol"; /** * @title Base class that provides time overrides, but only if being run in test mode. */ abstract contract Testable { // If the contract is being run on the test network, then `timerAddress` will be the 0x0 address. // Note: this variable should be set on construction and never modified. address public timerAddress; /** * @notice Constructs the Testable contract. Called by child contracts. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor(address _timerAddress) internal { timerAddress = _timerAddress; } /** * @notice Reverts if not running in test mode. */ modifier onlyIfTest { require(timerAddress != address(0x0)); _; } /** * @notice Sets the current time. * @dev Will revert if not running in test mode. * @param time timestamp to set current Testable time to. */ function setCurrentTime(uint256 time) external onlyIfTest { Timer(timerAddress).setCurrentTime(time); } /** * @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode. * Otherwise, it will return the block timestamp. * @return uint for the current Testable timestamp. */ function getCurrentTime() public view returns (uint256) { if (timerAddress != address(0x0)) { return Timer(timerAddress).getCurrentTime(); } else { return now; // solhint-disable-line not-rely-on-time } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Financial contract facing Oracle interface. * @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface. */ abstract contract OracleInterface { /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. */ function requestPrice(bytes32 identifier, uint256 time) public virtual; /** * @notice Whether the price for `identifier` and `time` is available. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @return bool if the DVM has resolved to a price for the given identifier and timestamp. */ function hasPrice(bytes32 identifier, uint256 time) public view virtual returns (bool); /** * @notice Gets the price for `identifier` and `time` if it has already been requested and resolved. * @dev If the price is not available, the method reverts. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @return int256 representing the resolved price for the given identifier and timestamp. */ function getPrice(bytes32 identifier, uint256 time) public view virtual returns (int256); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "./VotingAncillaryInterface.sol"; /** * @title Interface that voters must use to Vote on price request resolutions. */ abstract contract VotingInterface { struct PendingRequest { bytes32 identifier; uint256 time; } // Captures the necessary data for making a commitment. // Used as a parameter when making batch commitments. // Not used as a data structure for storage. struct Commitment { bytes32 identifier; uint256 time; bytes32 hash; bytes encryptedVote; } // Captures the necessary data for revealing a vote. // Used as a parameter when making batch reveals. // Not used as a data structure for storage. struct Reveal { bytes32 identifier; uint256 time; int256 price; int256 salt; } /** * @notice Commit a vote for a price request for `identifier` at `time`. * @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase. * Commits can be changed. * @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior, * voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then * they can determine the vote pre-reveal. * @param identifier uniquely identifies the committed vote. EG BTC/USD price pair. * @param time unix timestamp of the price being voted on. * @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`. */ function commitVote( bytes32 identifier, uint256 time, bytes32 hash ) external virtual; /** * @notice Submit a batch of commits in a single transaction. * @dev Using `encryptedVote` is optional. If included then commitment is stored on chain. * Look at `project-root/common/Constants.js` for the tested maximum number of * commitments that can fit in one transaction. * @param commits array of structs that encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(Commitment[] memory commits) public virtual; /** * @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote * @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to * retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience. * @param identifier unique price pair identifier. Eg: BTC/USD price pair. * @param time unix timestamp of for the price request. * @param hash keccak256 hash of the price you want to vote for and a `int256 salt`. * @param encryptedVote offchain encrypted blob containing the voters amount, time and salt. */ function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes32 hash, bytes memory encryptedVote ) public virtual; /** * @notice snapshot the current round's token balances and lock in the inflation rate and GAT. * @dev This function can be called multiple times but each round will only every have one snapshot at the * time of calling `_freezeRoundVariables`. * @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the * snapshot. */ function snapshotCurrentRound(bytes calldata signature) external virtual; /** * @notice Reveal a previously committed vote for `identifier` at `time`. * @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash` * that `commitVote()` was called with. Only the committer can reveal their vote. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price is being voted on. * @param price voted on during the commit phase. * @param salt value used to hide the commitment price during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, int256 salt ) public virtual; /** * @notice Reveal multiple votes in a single transaction. * Look at `project-root/common/Constants.js` for the tested maximum number of reveals. * that can fit in one transaction. * @dev For more information on reveals, review the comment for `revealVote`. * @param reveals array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(Reveal[] memory reveals) public virtual; /** * @notice Gets the queries that are being voted on this round. * @return pendingRequests `PendingRequest` array containing identifiers * and timestamps for all pending requests. */ function getPendingRequests() external view virtual returns (VotingAncillaryInterface.PendingRequestAncillary[] memory); /** * @notice Returns the current voting phase, as a function of the current time. * @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }. */ function getVotePhase() external view virtual returns (VotingAncillaryInterface.Phase); /** * @notice Returns the current round ID, as a function of the current time. * @return uint256 representing the unique round ID. */ function getCurrentRoundId() external view virtual returns (uint256); /** * @notice Retrieves rewards owed for a set of resolved price requests. * @dev Can only retrieve rewards if calling for a valid round and if the * call is done within the timeout threshold (not expired). * @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller. * @param roundId the round from which voting rewards will be retrieved from. * @param toRetrieve array of PendingRequests which rewards are retrieved from. * @return total amount of rewards returned to the voter. */ function retrieveRewards( address voterAddress, uint256 roundId, PendingRequest[] memory toRetrieve ) public virtual returns (FixedPoint.Unsigned memory); // Voting Owner functions. /** * @notice Disables this Voting contract in favor of the migrated one. * @dev Can only be called by the contract owner. * @param newVotingAddress the newly migrated contract address. */ function setMigrated(address newVotingAddress) external virtual; /** * @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newInflationRate sets the next round's inflation rate. */ function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public virtual; /** * @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newGatPercentage sets the next round's Gat percentage. */ function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public virtual; /** * @notice Resets the rewards expiration timeout. * @dev This change only applies to rounds that have not yet begun. * @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards. */ function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public virtual; } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Universal store of current contract time for testing environments. */ contract Timer { uint256 private currentTime; constructor() public { currentTime = now; // solhint-disable-line not-rely-on-time } /** * @notice Sets the current time. * @dev Will revert if not running in test mode. * @param time timestamp to set `currentTime` to. */ function setCurrentTime(uint256 time) external { currentTime = time; } /** * @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode. * Otherwise, it will return the block timestamp. * @return uint256 for the current Testable timestamp. */ function getCurrentTime() public view returns (uint256) { return currentTime; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; /** * @title Interface that voters must use to Vote on price request resolutions. */ abstract contract VotingAncillaryInterface { struct PendingRequestAncillary { bytes32 identifier; uint256 time; bytes ancillaryData; } // Captures the necessary data for making a commitment. // Used as a parameter when making batch commitments. // Not used as a data structure for storage. struct CommitmentAncillary { bytes32 identifier; uint256 time; bytes ancillaryData; bytes32 hash; bytes encryptedVote; } // Captures the necessary data for revealing a vote. // Used as a parameter when making batch reveals. // Not used as a data structure for storage. struct RevealAncillary { bytes32 identifier; uint256 time; int256 price; bytes ancillaryData; int256 salt; } // Note: the phases must be in order. Meaning the first enum value must be the first phase, etc. // `NUM_PHASES_PLACEHOLDER` is to get the number of phases. It isn't an actual phase, and it should always be last. enum Phase { Commit, Reveal, NUM_PHASES_PLACEHOLDER } /** * @notice Commit a vote for a price request for `identifier` at `time`. * @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase. * Commits can be changed. * @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior, * voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then * they can determine the vote pre-reveal. * @param identifier uniquely identifies the committed vote. EG BTC/USD price pair. * @param time unix timestamp of the price being voted on. * @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`. */ function commitVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash ) public virtual; /** * @notice Submit a batch of commits in a single transaction. * @dev Using `encryptedVote` is optional. If included then commitment is stored on chain. * Look at `project-root/common/Constants.js` for the tested maximum number of * commitments that can fit in one transaction. * @param commits array of structs that encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(CommitmentAncillary[] memory commits) public virtual; /** * @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote * @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to * retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience. * @param identifier unique price pair identifier. Eg: BTC/USD price pair. * @param time unix timestamp of for the price request. * @param hash keccak256 hash of the price you want to vote for and a `int256 salt`. * @param encryptedVote offchain encrypted blob containing the voters amount, time and salt. */ function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash, bytes memory encryptedVote ) public virtual; /** * @notice snapshot the current round's token balances and lock in the inflation rate and GAT. * @dev This function can be called multiple times but each round will only every have one snapshot at the * time of calling `_freezeRoundVariables`. * @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the * snapshot. */ function snapshotCurrentRound(bytes calldata signature) external virtual; /** * @notice Reveal a previously committed vote for `identifier` at `time`. * @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash` * that `commitVote()` was called with. Only the committer can reveal their vote. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price is being voted on. * @param price voted on during the commit phase. * @param salt value used to hide the commitment price during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, bytes memory ancillaryData, int256 salt ) public virtual; /** * @notice Reveal multiple votes in a single transaction. * Look at `project-root/common/Constants.js` for the tested maximum number of reveals. * that can fit in one transaction. * @dev For more information on reveals, review the comment for `revealVote`. * @param reveals array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(RevealAncillary[] memory reveals) public virtual; /** * @notice Gets the queries that are being voted on this round. * @return pendingRequests `PendingRequest` array containing identifiers * and timestamps for all pending requests. */ function getPendingRequests() external view virtual returns (PendingRequestAncillary[] memory); /** * @notice Returns the current voting phase, as a function of the current time. * @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }. */ function getVotePhase() external view virtual returns (Phase); /** * @notice Returns the current round ID, as a function of the current time. * @return uint256 representing the unique round ID. */ function getCurrentRoundId() external view virtual returns (uint256); /** * @notice Retrieves rewards owed for a set of resolved price requests. * @dev Can only retrieve rewards if calling for a valid round and if the * call is done within the timeout threshold (not expired). * @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller. * @param roundId the round from which voting rewards will be retrieved from. * @param toRetrieve array of PendingRequests which rewards are retrieved from. * @return total amount of rewards returned to the voter. */ function retrieveRewards( address voterAddress, uint256 roundId, PendingRequestAncillary[] memory toRetrieve ) public virtual returns (FixedPoint.Unsigned memory); // Voting Owner functions. /** * @notice Disables this Voting contract in favor of the migrated one. * @dev Can only be called by the contract owner. * @param newVotingAddress the newly migrated contract address. */ function setMigrated(address newVotingAddress) external virtual; /** * @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newInflationRate sets the next round's inflation rate. */ function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public virtual; /** * @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newGatPercentage sets the next round's Gat percentage. */ function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public virtual; /** * @notice Resets the rewards expiration timeout. * @dev This change only applies to rounds that have not yet begun. * @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards. */ function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public virtual; } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/FinderInterface.sol"; import "../interfaces/OracleInterface.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/VotingInterface.sol"; import "../interfaces/VotingAncillaryInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "./Registry.sol"; import "./ResultComputation.sol"; import "./VoteTiming.sol"; import "./VotingToken.sol"; import "./Constants.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/cryptography/ECDSA.sol"; /** * @title Voting system for Oracle. * @dev Handles receiving and resolving price requests via a commit-reveal voting scheme. */ contract Voting is Testable, Ownable, OracleInterface, OracleAncillaryInterface, // Interface to support ancillary data with price requests. VotingInterface, VotingAncillaryInterface // Interface to support ancillary data with voting rounds. { using FixedPoint for FixedPoint.Unsigned; using SafeMath for uint256; using VoteTiming for VoteTiming.Data; using ResultComputation for ResultComputation.Data; /**************************************** * VOTING DATA STRUCTURES * ****************************************/ // Identifies a unique price request for which the Oracle will always return the same value. // Tracks ongoing votes as well as the result of the vote. struct PriceRequest { bytes32 identifier; uint256 time; // A map containing all votes for this price in various rounds. mapping(uint256 => VoteInstance) voteInstances; // If in the past, this was the voting round where this price was resolved. If current or the upcoming round, // this is the voting round where this price will be voted on, but not necessarily resolved. uint256 lastVotingRound; // The index in the `pendingPriceRequests` that references this PriceRequest. A value of UINT_MAX means that // this PriceRequest is resolved and has been cleaned up from `pendingPriceRequests`. uint256 index; bytes ancillaryData; } struct VoteInstance { // Maps (voterAddress) to their submission. mapping(address => VoteSubmission) voteSubmissions; // The data structure containing the computed voting results. ResultComputation.Data resultComputation; } struct VoteSubmission { // A bytes32 of `0` indicates no commit or a commit that was already revealed. bytes32 commit; // The hash of the value that was revealed. // Note: this is only used for computation of rewards. bytes32 revealHash; } struct Round { uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken. FixedPoint.Unsigned inflationRate; // Inflation rate set for this round. FixedPoint.Unsigned gatPercentage; // Gat rate set for this round. uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until. } // Represents the status a price request has. enum RequestStatus { NotRequested, // Was never requested. Active, // Is being voted on in the current round. Resolved, // Was resolved in a previous round. Future // Is scheduled to be voted on in a future round. } // Only used as a return value in view methods -- never stored in the contract. struct RequestState { RequestStatus status; uint256 lastVotingRound; } /**************************************** * INTERNAL TRACKING * ****************************************/ // Maps round numbers to the rounds. mapping(uint256 => Round) public rounds; // Maps price request IDs to the PriceRequest struct. mapping(bytes32 => PriceRequest) private priceRequests; // Price request ids for price requests that haven't yet been marked as resolved. // These requests may be for future rounds. bytes32[] internal pendingPriceRequests; VoteTiming.Data public voteTiming; // Percentage of the total token supply that must be used in a vote to // create a valid price resolution. 1 == 100%. FixedPoint.Unsigned public gatPercentage; // Global setting for the rate of inflation per vote. This is the percentage of the snapshotted total supply that // should be split among the correct voters. // Note: this value is used to set per-round inflation at the beginning of each round. 1 = 100%. FixedPoint.Unsigned public inflationRate; // Time in seconds from the end of the round in which a price request is // resolved that voters can still claim their rewards. uint256 public rewardsExpirationTimeout; // Reference to the voting token. VotingToken public votingToken; // Reference to the Finder. FinderInterface private finder; // If non-zero, this contract has been migrated to this address. All voters and // financial contracts should query the new address only. address public migratedAddress; // Max value of an unsigned integer. uint256 private constant UINT_MAX = ~uint256(0); // Max length in bytes of ancillary data that can be appended to a price request. // As of December 2020, the current Ethereum gas limit is 12.5 million. This requestPrice function's gas primarily // comes from computing a Keccak-256 hash in _encodePriceRequest and writing a new PriceRequest to // storage. We have empirically determined an ancillary data limit of 8192 bytes that keeps this function // well within the gas limit at ~8 million gas. To learn more about the gas limit and EVM opcode costs go here: // - https://etherscan.io/chart/gaslimit // - https://github.com/djrtwo/evm-opcode-gas-costs uint256 public constant ancillaryBytesLimit = 8192; bytes32 public snapshotMessageHash = ECDSA.toEthSignedMessageHash(keccak256(bytes("Sign For Snapshot"))); /*************************************** * EVENTS * ****************************************/ event VoteCommitted( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData ); event EncryptedVote( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, bytes encryptedVote ); event VoteRevealed( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData, uint256 numTokens ); event RewardsRetrieved( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, uint256 numTokens ); event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time); event PriceResolved( uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData ); /** * @notice Construct the Voting contract. * @param _phaseLength length of the commit and reveal phases in seconds. * @param _gatPercentage of the total token supply that must be used in a vote to create a valid price resolution. * @param _inflationRate percentage inflation per round used to increase token supply of correct voters. * @param _rewardsExpirationTimeout timeout, in seconds, within which rewards must be claimed. * @param _votingToken address of the UMA token contract used to commit votes. * @param _finder keeps track of all contracts within the system based on their interfaceName. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( uint256 _phaseLength, FixedPoint.Unsigned memory _gatPercentage, FixedPoint.Unsigned memory _inflationRate, uint256 _rewardsExpirationTimeout, address _votingToken, address _finder, address _timerAddress ) public Testable(_timerAddress) { voteTiming.init(_phaseLength); require(_gatPercentage.isLessThanOrEqual(1), "GAT percentage must be <= 100%"); gatPercentage = _gatPercentage; inflationRate = _inflationRate; votingToken = VotingToken(_votingToken); finder = FinderInterface(_finder); rewardsExpirationTimeout = _rewardsExpirationTimeout; } /*************************************** MODIFIERS ****************************************/ modifier onlyRegisteredContract() { if (migratedAddress != address(0)) { require(msg.sender == migratedAddress, "Caller must be migrated address"); } else { Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry)); require(registry.isContractRegistered(msg.sender), "Called must be registered"); } _; } modifier onlyIfNotMigrated() { require(migratedAddress == address(0), "Only call this if not migrated"); _; } /**************************************** * PRICE REQUEST AND ACCESS FUNCTIONS * ****************************************/ /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Time must be in the past and the identifier must be supported. The length of the ancillary data * is limited such that this method abides by the EVM transaction gas limit. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. */ function requestPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public override onlyRegisteredContract() { uint256 blockTime = getCurrentTime(); require(time <= blockTime, "Can only request in past"); require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier request"); require(ancillaryData.length <= ancillaryBytesLimit, "Invalid ancillary data"); bytes32 priceRequestId = _encodePriceRequest(identifier, time, ancillaryData); PriceRequest storage priceRequest = priceRequests[priceRequestId]; uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime); RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId); if (requestStatus == RequestStatus.NotRequested) { // Price has never been requested. // Price requests always go in the next round, so add 1 to the computed current round. uint256 nextRoundId = currentRoundId.add(1); priceRequests[priceRequestId] = PriceRequest({ identifier: identifier, time: time, lastVotingRound: nextRoundId, index: pendingPriceRequests.length, ancillaryData: ancillaryData }); pendingPriceRequests.push(priceRequestId); emit PriceRequestAdded(nextRoundId, identifier, time); } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function requestPrice(bytes32 identifier, uint256 time) public override { requestPrice(identifier, time, ""); } /** * @notice Whether the price for `identifier` and `time` is available. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp of for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return _hasPrice bool if the DVM has resolved to a price for the given identifier and timestamp. */ function hasPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override onlyRegisteredContract() returns (bool) { (bool _hasPrice, , ) = _getPriceOrError(identifier, time, ancillaryData); return _hasPrice; } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function hasPrice(bytes32 identifier, uint256 time) public view override returns (bool) { return hasPrice(identifier, time, ""); } /** * @notice Gets the price for `identifier` and `time` if it has already been requested and resolved. * @dev If the price is not available, the method reverts. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp of for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return int256 representing the resolved price for the given identifier and timestamp. */ function getPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override onlyRegisteredContract() returns (int256) { (bool _hasPrice, int256 price, string memory message) = _getPriceOrError(identifier, time, ancillaryData); // If the price wasn't available, revert with the provided message. require(_hasPrice, message); return price; } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function getPrice(bytes32 identifier, uint256 time) public view override returns (int256) { return getPrice(identifier, time, ""); } /** * @notice Gets the status of a list of price requests, identified by their identifier and time. * @dev If the status for a particular request is NotRequested, the lastVotingRound will always be 0. * @param requests array of type PendingRequest which includes an identifier and timestamp for each request. * @return requestStates a list, in the same order as the input list, giving the status of each of the specified price requests. */ function getPriceRequestStatuses(PendingRequestAncillary[] memory requests) public view returns (RequestState[] memory) { RequestState[] memory requestStates = new RequestState[](requests.length); uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime()); for (uint256 i = 0; i < requests.length; i++) { PriceRequest storage priceRequest = _getPriceRequest(requests[i].identifier, requests[i].time, requests[i].ancillaryData); RequestStatus status = _getRequestStatus(priceRequest, currentRoundId); // If it's an active request, its true lastVotingRound is the current one, even if it hasn't been updated. if (status == RequestStatus.Active) { requestStates[i].lastVotingRound = currentRoundId; } else { requestStates[i].lastVotingRound = priceRequest.lastVotingRound; } requestStates[i].status = status; } return requestStates; } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function getPriceRequestStatuses(PendingRequest[] memory requests) public view returns (RequestState[] memory) { PendingRequestAncillary[] memory requestsAncillary = new PendingRequestAncillary[](requests.length); for (uint256 i = 0; i < requests.length; i++) { requestsAncillary[i].identifier = requests[i].identifier; requestsAncillary[i].time = requests[i].time; requestsAncillary[i].ancillaryData = ""; } return getPriceRequestStatuses(requestsAncillary); } /**************************************** * VOTING FUNCTIONS * ****************************************/ /** * @notice Commit a vote for a price request for `identifier` at `time`. * @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase. * Commits can be changed. * @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior, * voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then * they can determine the vote pre-reveal. * @param identifier uniquely identifies the committed vote. EG BTC/USD price pair. * @param time unix timestamp of the price being voted on. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`. */ function commitVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash ) public override onlyIfNotMigrated() { require(hash != bytes32(0), "Invalid provided hash"); // Current time is required for all vote timing queries. uint256 blockTime = getCurrentTime(); require( voteTiming.computeCurrentPhase(blockTime) == VotingAncillaryInterface.Phase.Commit, "Cannot commit in reveal phase" ); // At this point, the computed and last updated round ID should be equal. uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime); PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData); require( _getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active, "Cannot commit inactive request" ); priceRequest.lastVotingRound = currentRoundId; VoteInstance storage voteInstance = priceRequest.voteInstances[currentRoundId]; voteInstance.voteSubmissions[msg.sender].commit = hash; emit VoteCommitted(msg.sender, currentRoundId, identifier, time, ancillaryData); } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function commitVote( bytes32 identifier, uint256 time, bytes32 hash ) public override onlyIfNotMigrated() { commitVote(identifier, time, "", hash); } /** * @notice Snapshot the current round's token balances and lock in the inflation rate and GAT. * @dev This function can be called multiple times, but only the first call per round into this function or `revealVote` * will create the round snapshot. Any later calls will be a no-op. Will revert unless called during reveal period. * @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the * snapshot. */ function snapshotCurrentRound(bytes calldata signature) external override(VotingInterface, VotingAncillaryInterface) onlyIfNotMigrated() { uint256 blockTime = getCurrentTime(); require(voteTiming.computeCurrentPhase(blockTime) == Phase.Reveal, "Only snapshot in reveal phase"); // Require public snapshot require signature to ensure caller is an EOA. require(ECDSA.recover(snapshotMessageHash, signature) == msg.sender, "Signature must match sender"); uint256 roundId = voteTiming.computeCurrentRoundId(blockTime); _freezeRoundVariables(roundId); } /** * @notice Reveal a previously committed vote for `identifier` at `time`. * @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash` * that `commitVote()` was called with. Only the committer can reveal their vote. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price being voted on. * @param price voted on during the commit phase. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param salt value used to hide the commitment price during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, bytes memory ancillaryData, int256 salt ) public override onlyIfNotMigrated() { require(voteTiming.computeCurrentPhase(getCurrentTime()) == Phase.Reveal, "Cannot reveal in commit phase"); // Note: computing the current round is required to disallow people from revealing an old commit after the round is over. uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime()); PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData); VoteInstance storage voteInstance = priceRequest.voteInstances[roundId]; VoteSubmission storage voteSubmission = voteInstance.voteSubmissions[msg.sender]; // Scoping to get rid of a stack too deep error. { // 0 hashes are disallowed in the commit phase, so they indicate a different error. // Cannot reveal an uncommitted or previously revealed hash require(voteSubmission.commit != bytes32(0), "Invalid hash reveal"); require( keccak256(abi.encodePacked(price, salt, msg.sender, time, ancillaryData, roundId, identifier)) == voteSubmission.commit, "Revealed data != commit hash" ); // To protect against flash loans, we require snapshot be validated as EOA. require(rounds[roundId].snapshotId != 0, "Round has no snapshot"); } // Get the frozen snapshotId uint256 snapshotId = rounds[roundId].snapshotId; delete voteSubmission.commit; // Get the voter's snapshotted balance. Since balances are returned pre-scaled by 10**18, we can directly // initialize the Unsigned value with the returned uint. FixedPoint.Unsigned memory balance = FixedPoint.Unsigned(votingToken.balanceOfAt(msg.sender, snapshotId)); // Set the voter's submission. voteSubmission.revealHash = keccak256(abi.encode(price)); // Add vote to the results. voteInstance.resultComputation.addVote(price, balance); emit VoteRevealed(msg.sender, roundId, identifier, time, price, ancillaryData, balance.rawValue); } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function revealVote( bytes32 identifier, uint256 time, int256 price, int256 salt ) public override { revealVote(identifier, time, price, "", salt); } /** * @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote * @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to * retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience. * @param identifier unique price pair identifier. Eg: BTC/USD price pair. * @param time unix timestamp of for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param hash keccak256 hash of the price you want to vote for and a `int256 salt`. * @param encryptedVote offchain encrypted blob containing the voters amount, time and salt. */ function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash, bytes memory encryptedVote ) public override { commitVote(identifier, time, ancillaryData, hash); uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime()); emit EncryptedVote(msg.sender, roundId, identifier, time, ancillaryData, encryptedVote); } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes32 hash, bytes memory encryptedVote ) public override { commitVote(identifier, time, "", hash); commitAndEmitEncryptedVote(identifier, time, "", hash, encryptedVote); } /** * @notice Submit a batch of commits in a single transaction. * @dev Using `encryptedVote` is optional. If included then commitment is emitted in an event. * Look at `project-root/common/Constants.js` for the tested maximum number of * commitments that can fit in one transaction. * @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(CommitmentAncillary[] memory commits) public override { for (uint256 i = 0; i < commits.length; i++) { if (commits[i].encryptedVote.length == 0) { commitVote(commits[i].identifier, commits[i].time, commits[i].ancillaryData, commits[i].hash); } else { commitAndEmitEncryptedVote( commits[i].identifier, commits[i].time, commits[i].ancillaryData, commits[i].hash, commits[i].encryptedVote ); } } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function batchCommit(Commitment[] memory commits) public override { CommitmentAncillary[] memory commitsAncillary = new CommitmentAncillary[](commits.length); for (uint256 i = 0; i < commits.length; i++) { commitsAncillary[i].identifier = commits[i].identifier; commitsAncillary[i].time = commits[i].time; commitsAncillary[i].ancillaryData = ""; commitsAncillary[i].hash = commits[i].hash; commitsAncillary[i].encryptedVote = commits[i].encryptedVote; } batchCommit(commitsAncillary); } /** * @notice Reveal multiple votes in a single transaction. * Look at `project-root/common/Constants.js` for the tested maximum number of reveals. * that can fit in one transaction. * @dev For more info on reveals, review the comment for `revealVote`. * @param reveals array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(RevealAncillary[] memory reveals) public override { for (uint256 i = 0; i < reveals.length; i++) { revealVote( reveals[i].identifier, reveals[i].time, reveals[i].price, reveals[i].ancillaryData, reveals[i].salt ); } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function batchReveal(Reveal[] memory reveals) public override { RevealAncillary[] memory revealsAncillary = new RevealAncillary[](reveals.length); for (uint256 i = 0; i < reveals.length; i++) { revealsAncillary[i].identifier = reveals[i].identifier; revealsAncillary[i].time = reveals[i].time; revealsAncillary[i].price = reveals[i].price; revealsAncillary[i].ancillaryData = ""; revealsAncillary[i].salt = reveals[i].salt; } batchReveal(revealsAncillary); } /** * @notice Retrieves rewards owed for a set of resolved price requests. * @dev Can only retrieve rewards if calling for a valid round and if the call is done within the timeout threshold * (not expired). Note that a named return value is used here to avoid a stack to deep error. * @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller. * @param roundId the round from which voting rewards will be retrieved from. * @param toRetrieve array of PendingRequests which rewards are retrieved from. * @return totalRewardToIssue total amount of rewards returned to the voter. */ function retrieveRewards( address voterAddress, uint256 roundId, PendingRequestAncillary[] memory toRetrieve ) public override returns (FixedPoint.Unsigned memory totalRewardToIssue) { if (migratedAddress != address(0)) { require(msg.sender == migratedAddress, "Can only call from migrated"); } require(roundId < voteTiming.computeCurrentRoundId(getCurrentTime()), "Invalid roundId"); Round storage round = rounds[roundId]; bool isExpired = getCurrentTime() > round.rewardsExpirationTime; FixedPoint.Unsigned memory snapshotBalance = FixedPoint.Unsigned(votingToken.balanceOfAt(voterAddress, round.snapshotId)); // Compute the total amount of reward that will be issued for each of the votes in the round. FixedPoint.Unsigned memory snapshotTotalSupply = FixedPoint.Unsigned(votingToken.totalSupplyAt(round.snapshotId)); FixedPoint.Unsigned memory totalRewardPerVote = round.inflationRate.mul(snapshotTotalSupply); // Keep track of the voter's accumulated token reward. totalRewardToIssue = FixedPoint.Unsigned(0); for (uint256 i = 0; i < toRetrieve.length; i++) { PriceRequest storage priceRequest = _getPriceRequest(toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData); VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; // Only retrieve rewards for votes resolved in same round require(priceRequest.lastVotingRound == roundId, "Retrieve for votes same round"); _resolvePriceRequest(priceRequest, voteInstance); if (voteInstance.voteSubmissions[voterAddress].revealHash == 0) { continue; } else if (isExpired) { // Emit a 0 token retrieval on expired rewards. emit RewardsRetrieved( voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData, 0 ); } else if ( voteInstance.resultComputation.wasVoteCorrect(voteInstance.voteSubmissions[voterAddress].revealHash) ) { // The price was successfully resolved during the voter's last voting round, the voter revealed // and was correct, so they are eligible for a reward. // Compute the reward and add to the cumulative reward. FixedPoint.Unsigned memory reward = snapshotBalance.mul(totalRewardPerVote).div( voteInstance.resultComputation.getTotalCorrectlyVotedTokens() ); totalRewardToIssue = totalRewardToIssue.add(reward); // Emit reward retrieval for this vote. emit RewardsRetrieved( voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData, reward.rawValue ); } else { // Emit a 0 token retrieval on incorrect votes. emit RewardsRetrieved( voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData, 0 ); } // Delete the submission to capture any refund and clean up storage. delete voteInstance.voteSubmissions[voterAddress].revealHash; } // Issue any accumulated rewards. if (totalRewardToIssue.isGreaterThan(0)) { require(votingToken.mint(voterAddress, totalRewardToIssue.rawValue), "Voting token issuance failed"); } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function retrieveRewards( address voterAddress, uint256 roundId, PendingRequest[] memory toRetrieve ) public override returns (FixedPoint.Unsigned memory) { PendingRequestAncillary[] memory toRetrieveAncillary = new PendingRequestAncillary[](toRetrieve.length); for (uint256 i = 0; i < toRetrieve.length; i++) { toRetrieveAncillary[i].identifier = toRetrieve[i].identifier; toRetrieveAncillary[i].time = toRetrieve[i].time; toRetrieveAncillary[i].ancillaryData = ""; } return retrieveRewards(voterAddress, roundId, toRetrieveAncillary); } /**************************************** * VOTING GETTER FUNCTIONS * ****************************************/ /** * @notice Gets the queries that are being voted on this round. * @return pendingRequests array containing identifiers of type `PendingRequest`. * and timestamps for all pending requests. */ function getPendingRequests() external view override(VotingInterface, VotingAncillaryInterface) returns (PendingRequestAncillary[] memory) { uint256 blockTime = getCurrentTime(); uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime); // Solidity memory arrays aren't resizable (and reading storage is expensive). Hence this hackery to filter // `pendingPriceRequests` only to those requests that have an Active RequestStatus. PendingRequestAncillary[] memory unresolved = new PendingRequestAncillary[](pendingPriceRequests.length); uint256 numUnresolved = 0; for (uint256 i = 0; i < pendingPriceRequests.length; i++) { PriceRequest storage priceRequest = priceRequests[pendingPriceRequests[i]]; if (_getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active) { unresolved[numUnresolved] = PendingRequestAncillary({ identifier: priceRequest.identifier, time: priceRequest.time, ancillaryData: priceRequest.ancillaryData }); numUnresolved++; } } PendingRequestAncillary[] memory pendingRequests = new PendingRequestAncillary[](numUnresolved); for (uint256 i = 0; i < numUnresolved; i++) { pendingRequests[i] = unresolved[i]; } return pendingRequests; } /** * @notice Returns the current voting phase, as a function of the current time. * @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }. */ function getVotePhase() external view override(VotingInterface, VotingAncillaryInterface) returns (Phase) { return voteTiming.computeCurrentPhase(getCurrentTime()); } /** * @notice Returns the current round ID, as a function of the current time. * @return uint256 representing the unique round ID. */ function getCurrentRoundId() external view override(VotingInterface, VotingAncillaryInterface) returns (uint256) { return voteTiming.computeCurrentRoundId(getCurrentTime()); } /**************************************** * OWNER ADMIN FUNCTIONS * ****************************************/ /** * @notice Disables this Voting contract in favor of the migrated one. * @dev Can only be called by the contract owner. * @param newVotingAddress the newly migrated contract address. */ function setMigrated(address newVotingAddress) external override(VotingInterface, VotingAncillaryInterface) onlyOwner { migratedAddress = newVotingAddress; } /** * @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newInflationRate sets the next round's inflation rate. */ function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public override(VotingInterface, VotingAncillaryInterface) onlyOwner { inflationRate = newInflationRate; } /** * @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newGatPercentage sets the next round's Gat percentage. */ function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public override(VotingInterface, VotingAncillaryInterface) onlyOwner { require(newGatPercentage.isLessThan(1), "GAT percentage must be < 100%"); gatPercentage = newGatPercentage; } /** * @notice Resets the rewards expiration timeout. * @dev This change only applies to rounds that have not yet begun. * @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards. */ function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public override(VotingInterface, VotingAncillaryInterface) onlyOwner { rewardsExpirationTimeout = NewRewardsExpirationTimeout; } /**************************************** * PRIVATE AND INTERNAL FUNCTIONS * ****************************************/ // Returns the price for a given identifer. Three params are returns: bool if there was an error, int to represent // the resolved price and a string which is filled with an error message, if there was an error or "". function _getPriceOrError( bytes32 identifier, uint256 time, bytes memory ancillaryData ) private view returns ( bool, int256, string memory ) { PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData); uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime()); RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId); if (requestStatus == RequestStatus.Active) { return (false, 0, "Current voting round not ended"); } else if (requestStatus == RequestStatus.Resolved) { VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; (, int256 resolvedPrice) = voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound)); return (true, resolvedPrice, ""); } else if (requestStatus == RequestStatus.Future) { return (false, 0, "Price is still to be voted on"); } else { return (false, 0, "Price was never requested"); } } function _getPriceRequest( bytes32 identifier, uint256 time, bytes memory ancillaryData ) private view returns (PriceRequest storage) { return priceRequests[_encodePriceRequest(identifier, time, ancillaryData)]; } function _encodePriceRequest( bytes32 identifier, uint256 time, bytes memory ancillaryData ) private pure returns (bytes32) { return keccak256(abi.encode(identifier, time, ancillaryData)); } function _freezeRoundVariables(uint256 roundId) private { Round storage round = rounds[roundId]; // Only on the first reveal should the snapshot be captured for that round. if (round.snapshotId == 0) { // There is no snapshot ID set, so create one. round.snapshotId = votingToken.snapshot(); // Set the round inflation rate to the current global inflation rate. rounds[roundId].inflationRate = inflationRate; // Set the round gat percentage to the current global gat rate. rounds[roundId].gatPercentage = gatPercentage; // Set the rewards expiration time based on end of time of this round and the current global timeout. rounds[roundId].rewardsExpirationTime = voteTiming.computeRoundEndTime(roundId).add( rewardsExpirationTimeout ); } } function _resolvePriceRequest(PriceRequest storage priceRequest, VoteInstance storage voteInstance) private { if (priceRequest.index == UINT_MAX) { return; } (bool isResolved, int256 resolvedPrice) = voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound)); require(isResolved, "Can't resolve unresolved request"); // Delete the resolved price request from pendingPriceRequests. uint256 lastIndex = pendingPriceRequests.length - 1; PriceRequest storage lastPriceRequest = priceRequests[pendingPriceRequests[lastIndex]]; lastPriceRequest.index = priceRequest.index; pendingPriceRequests[priceRequest.index] = pendingPriceRequests[lastIndex]; pendingPriceRequests.pop(); priceRequest.index = UINT_MAX; emit PriceResolved( priceRequest.lastVotingRound, priceRequest.identifier, priceRequest.time, resolvedPrice, priceRequest.ancillaryData ); } function _computeGat(uint256 roundId) private view returns (FixedPoint.Unsigned memory) { uint256 snapshotId = rounds[roundId].snapshotId; if (snapshotId == 0) { // No snapshot - return max value to err on the side of caution. return FixedPoint.Unsigned(UINT_MAX); } // Grab the snapshotted supply from the voting token. It's already scaled by 10**18, so we can directly // initialize the Unsigned value with the returned uint. FixedPoint.Unsigned memory snapshottedSupply = FixedPoint.Unsigned(votingToken.totalSupplyAt(snapshotId)); // Multiply the total supply at the snapshot by the gatPercentage to get the GAT in number of tokens. return snapshottedSupply.mul(rounds[roundId].gatPercentage); } function _getRequestStatus(PriceRequest storage priceRequest, uint256 currentRoundId) private view returns (RequestStatus) { if (priceRequest.lastVotingRound == 0) { return RequestStatus.NotRequested; } else if (priceRequest.lastVotingRound < currentRoundId) { VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; (bool isResolved, ) = voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound)); return isResolved ? RequestStatus.Resolved : RequestStatus.Active; } else if (priceRequest.lastVotingRound == currentRoundId) { return RequestStatus.Active; } else { // Means than priceRequest.lastVotingRound > currentRoundId return RequestStatus.Future; } } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Provides addresses of the live contracts implementing certain interfaces. * @dev Examples are the Oracle or Store interfaces. */ interface FinderInterface { /** * @notice Updates the address of the contract that implements `interfaceName`. * @param interfaceName bytes32 encoding of the interface name that is either changed or registered. * @param implementationAddress address of the deployed contract that implements the interface. */ function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external; /** * @notice Gets the address of the contract that implements the given `interfaceName`. * @param interfaceName queried interface. * @return implementationAddress address of the deployed contract that implements the interface. */ function getImplementationAddress(bytes32 interfaceName) external view returns (address); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Financial contract facing Oracle interface. * @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface. */ abstract contract OracleAncillaryInterface { /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param time unix timestamp for the price request. */ function requestPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public virtual; /** * @notice Whether the price for `identifier` and `time` is available. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return bool if the DVM has resolved to a price for the given identifier and timestamp. */ function hasPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view virtual returns (bool); /** * @notice Gets the price for `identifier` and `time` if it has already been requested and resolved. * @dev If the price is not available, the method reverts. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return int256 representing the resolved price for the given identifier and timestamp. */ function getPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view virtual returns (int256); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /** * @title Interface for whitelists of supported identifiers that the oracle can provide prices for. */ interface IdentifierWhitelistInterface { /** * @notice Adds the provided identifier as a supported identifier. * @dev Price requests using this identifier will succeed after this call. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. */ function addSupportedIdentifier(bytes32 identifier) external; /** * @notice Removes the identifier from the whitelist. * @dev Price requests using this identifier will no longer succeed after this call. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. */ function removeSupportedIdentifier(bytes32 identifier) external; /** * @notice Checks whether an identifier is on the whitelist. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. * @return bool if the identifier is supported (or not). */ function isIdentifierSupported(bytes32 identifier) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/MultiRole.sol"; import "../interfaces/RegistryInterface.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title Registry for financial contracts and approved financial contract creators. * @dev Maintains a whitelist of financial contract creators that are allowed * to register new financial contracts and stores party members of a financial contract. */ contract Registry is RegistryInterface, MultiRole { using SafeMath for uint256; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, // The owner manages the set of ContractCreators. ContractCreator // Can register financial contracts. } // This enum is required because a `WasValid` state is required // to ensure that financial contracts cannot be re-registered. enum Validity { Invalid, Valid } // Local information about a contract. struct FinancialContract { Validity valid; uint128 index; } struct Party { address[] contracts; // Each financial contract address is stored in this array. // The address of each financial contract is mapped to its index for constant time look up and deletion. mapping(address => uint256) contractIndex; } // Array of all contracts that are approved to use the UMA Oracle. address[] public registeredContracts; // Map of financial contract contracts to the associated FinancialContract struct. mapping(address => FinancialContract) public contractMap; // Map each party member to their their associated Party struct. mapping(address => Party) private partyMap; /**************************************** * EVENTS * ****************************************/ event NewContractRegistered(address indexed contractAddress, address indexed creator, address[] parties); event PartyAdded(address indexed contractAddress, address indexed party); event PartyRemoved(address indexed contractAddress, address indexed party); /** * @notice Construct the Registry contract. */ constructor() public { _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); // Start with no contract creators registered. _createSharedRole(uint256(Roles.ContractCreator), uint256(Roles.Owner), new address[](0)); } /**************************************** * REGISTRATION FUNCTIONS * ****************************************/ /** * @notice Registers a new financial contract. * @dev Only authorized contract creators can call this method. * @param parties array of addresses who become parties in the contract. * @param contractAddress address of the contract against which the parties are registered. */ function registerContract(address[] calldata parties, address contractAddress) external override onlyRoleHolder(uint256(Roles.ContractCreator)) { FinancialContract storage financialContract = contractMap[contractAddress]; require(contractMap[contractAddress].valid == Validity.Invalid, "Can only register once"); // Store contract address as a registered contract. registeredContracts.push(contractAddress); // No length check necessary because we should never hit (2^127 - 1) contracts. financialContract.index = uint128(registeredContracts.length.sub(1)); // For all parties in the array add them to the contract's parties. financialContract.valid = Validity.Valid; for (uint256 i = 0; i < parties.length; i = i.add(1)) { _addPartyToContract(parties[i], contractAddress); } emit NewContractRegistered(contractAddress, msg.sender, parties); } /** * @notice Adds a party member to the calling contract. * @dev msg.sender will be used to determine the contract that this party is added to. * @param party new party for the calling contract. */ function addPartyToContract(address party) external override { address contractAddress = msg.sender; require(contractMap[contractAddress].valid == Validity.Valid, "Can only add to valid contract"); _addPartyToContract(party, contractAddress); } /** * @notice Removes a party member from the calling contract. * @dev msg.sender will be used to determine the contract that this party is removed from. * @param partyAddress address to be removed from the calling contract. */ function removePartyFromContract(address partyAddress) external override { address contractAddress = msg.sender; Party storage party = partyMap[partyAddress]; uint256 numberOfContracts = party.contracts.length; require(numberOfContracts != 0, "Party has no contracts"); require(contractMap[contractAddress].valid == Validity.Valid, "Remove only from valid contract"); require(isPartyMemberOfContract(partyAddress, contractAddress), "Can only remove existing party"); // Index of the current location of the contract to remove. uint256 deleteIndex = party.contractIndex[contractAddress]; // Store the last contract's address to update the lookup map. address lastContractAddress = party.contracts[numberOfContracts - 1]; // Swap the contract to be removed with the last contract. party.contracts[deleteIndex] = lastContractAddress; // Update the lookup index with the new location. party.contractIndex[lastContractAddress] = deleteIndex; // Pop the last contract from the array and update the lookup map. party.contracts.pop(); delete party.contractIndex[contractAddress]; emit PartyRemoved(contractAddress, partyAddress); } /**************************************** * REGISTRY STATE GETTERS * ****************************************/ /** * @notice Returns whether the contract has been registered with the registry. * @dev If it is registered, it is an authorized participant in the UMA system. * @param contractAddress address of the financial contract. * @return bool indicates whether the contract is registered. */ function isContractRegistered(address contractAddress) external view override returns (bool) { return contractMap[contractAddress].valid == Validity.Valid; } /** * @notice Returns a list of all contracts that are associated with a particular party. * @param party address of the party. * @return an array of the contracts the party is registered to. */ function getRegisteredContracts(address party) external view override returns (address[] memory) { return partyMap[party].contracts; } /** * @notice Returns all registered contracts. * @return all registered contract addresses within the system. */ function getAllRegisteredContracts() external view override returns (address[] memory) { return registeredContracts; } /** * @notice checks if an address is a party of a contract. * @param party party to check. * @param contractAddress address to check against the party. * @return bool indicating if the address is a party of the contract. */ function isPartyMemberOfContract(address party, address contractAddress) public view override returns (bool) { uint256 index = partyMap[party].contractIndex[contractAddress]; return partyMap[party].contracts.length > index && partyMap[party].contracts[index] == contractAddress; } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ function _addPartyToContract(address party, address contractAddress) internal { require(!isPartyMemberOfContract(party, contractAddress), "Can only register a party once"); uint256 contractIndex = partyMap[party].contracts.length; partyMap[party].contracts.push(contractAddress); partyMap[party].contractIndex[contractAddress] = contractIndex; emit PartyAdded(contractAddress, party); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../../common/implementation/FixedPoint.sol"; /** * @title Computes vote results. * @dev The result is the mode of the added votes. Otherwise, the vote is unresolved. */ library ResultComputation { using FixedPoint for FixedPoint.Unsigned; /**************************************** * INTERNAL LIBRARY DATA STRUCTURE * ****************************************/ struct Data { // Maps price to number of tokens that voted for that price. mapping(int256 => FixedPoint.Unsigned) voteFrequency; // The total votes that have been added. FixedPoint.Unsigned totalVotes; // The price that is the current mode, i.e., the price with the highest frequency in `voteFrequency`. int256 currentMode; } /**************************************** * VOTING FUNCTIONS * ****************************************/ /** * @notice Adds a new vote to be used when computing the result. * @param data contains information to which the vote is applied. * @param votePrice value specified in the vote for the given `numberTokens`. * @param numberTokens number of tokens that voted on the `votePrice`. */ function addVote( Data storage data, int256 votePrice, FixedPoint.Unsigned memory numberTokens ) internal { data.totalVotes = data.totalVotes.add(numberTokens); data.voteFrequency[votePrice] = data.voteFrequency[votePrice].add(numberTokens); if ( votePrice != data.currentMode && data.voteFrequency[votePrice].isGreaterThan(data.voteFrequency[data.currentMode]) ) { data.currentMode = votePrice; } } /**************************************** * VOTING STATE GETTERS * ****************************************/ /** * @notice Returns whether the result is resolved, and if so, what value it resolved to. * @dev `price` should be ignored if `isResolved` is false. * @param data contains information against which the `minVoteThreshold` is applied. * @param minVoteThreshold min (exclusive) number of tokens that must have voted for the result to be valid. Can be * used to enforce a minimum voter participation rate, regardless of how the votes are distributed. * @return isResolved indicates if the price has been resolved correctly. * @return price the price that the dvm resolved to. */ function getResolvedPrice(Data storage data, FixedPoint.Unsigned memory minVoteThreshold) internal view returns (bool isResolved, int256 price) { FixedPoint.Unsigned memory modeThreshold = FixedPoint.fromUnscaledUint(50).div(100); if ( data.totalVotes.isGreaterThan(minVoteThreshold) && data.voteFrequency[data.currentMode].div(data.totalVotes).isGreaterThan(modeThreshold) ) { // `modeThreshold` and `minVoteThreshold` are exceeded, so the current mode is the resolved price. isResolved = true; price = data.currentMode; } else { isResolved = false; } } /** * @notice Checks whether a `voteHash` is considered correct. * @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`. * @param data contains information against which the `voteHash` is checked. * @param voteHash committed hash submitted by the voter. * @return bool true if the vote was correct. */ function wasVoteCorrect(Data storage data, bytes32 voteHash) internal view returns (bool) { return voteHash == keccak256(abi.encode(data.currentMode)); } /** * @notice Gets the total number of tokens whose votes are considered correct. * @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`. * @param data contains all votes against which the correctly voted tokens are counted. * @return FixedPoint.Unsigned which indicates the frequency of the correctly voted tokens. */ function getTotalCorrectlyVotedTokens(Data storage data) internal view returns (FixedPoint.Unsigned memory) { return data.voteFrequency[data.currentMode]; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/VotingInterface.sol"; /** * @title Library to compute rounds and phases for an equal length commit-reveal voting cycle. */ library VoteTiming { using SafeMath for uint256; struct Data { uint256 phaseLength; } /** * @notice Initializes the data object. Sets the phase length based on the input. */ function init(Data storage data, uint256 phaseLength) internal { // This should have a require message but this results in an internal Solidity error. require(phaseLength > 0); data.phaseLength = phaseLength; } /** * @notice Computes the roundID based off the current time as floor(timestamp/roundLength). * @dev The round ID depends on the global timestamp but not on the lifetime of the system. * The consequence is that the initial round ID starts at an arbitrary number (that increments, as expected, for subsequent rounds) instead of zero or one. * @param data input data object. * @param currentTime input unix timestamp used to compute the current roundId. * @return roundId defined as a function of the currentTime and `phaseLength` from `data`. */ function computeCurrentRoundId(Data storage data, uint256 currentTime) internal view returns (uint256) { uint256 roundLength = data.phaseLength.mul(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER)); return currentTime.div(roundLength); } /** * @notice compute the round end time as a function of the round Id. * @param data input data object. * @param roundId uniquely identifies the current round. * @return timestamp unix time of when the current round will end. */ function computeRoundEndTime(Data storage data, uint256 roundId) internal view returns (uint256) { uint256 roundLength = data.phaseLength.mul(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER)); return roundLength.mul(roundId.add(1)); } /** * @notice Computes the current phase based only on the current time. * @param data input data object. * @param currentTime input unix timestamp used to compute the current roundId. * @return current voting phase based on current time and vote phases configuration. */ function computeCurrentPhase(Data storage data, uint256 currentTime) internal view returns (VotingAncillaryInterface.Phase) { // This employs some hacky casting. We could make this an if-statement if we're worried about type safety. return VotingAncillaryInterface.Phase( currentTime.div(data.phaseLength).mod(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER)) ); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../../common/implementation/ExpandedERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Snapshot.sol"; /** * @title Ownership of this token allows a voter to respond to price requests. * @dev Supports snapshotting and allows the Oracle to mint new tokens as rewards. */ contract VotingToken is ExpandedERC20, ERC20Snapshot { /** * @notice Constructs the VotingToken. */ constructor() public ExpandedERC20("UMA Voting Token v1", "UMA", 18) {} /** * @notice Creates a new snapshot ID. * @return uint256 Thew new snapshot ID. */ function snapshot() external returns (uint256) { return _snapshot(); } // _transfer, _mint and _burn are ERC20 internal methods that are overridden by ERC20Snapshot, // therefore the compiler will complain that VotingToken must override these methods // because the two base classes (ERC20 and ERC20Snapshot) both define the same functions function _transfer( address from, address to, uint256 value ) internal override(ERC20, ERC20Snapshot) { super._transfer(from, to, value); } function _mint(address account, uint256 value) internal override(ERC20, ERC20Snapshot) { super._mint(account, value); } function _burn(address account, uint256 value) internal override(ERC20, ERC20Snapshot) { super._burn(account, value); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Stores common interface names used throughout the DVM by registration in the Finder. */ library OracleInterfaces { bytes32 public constant Oracle = "Oracle"; bytes32 public constant IdentifierWhitelist = "IdentifierWhitelist"; bytes32 public constant Store = "Store"; bytes32 public constant FinancialContractsAdmin = "FinancialContractsAdmin"; bytes32 public constant Registry = "Registry"; bytes32 public constant CollateralWhitelist = "CollateralWhitelist"; bytes32 public constant OptimisticOracle = "OptimisticOracle"; } pragma solidity ^0.6.0; import "../GSN/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @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() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } pragma solidity ^0.6.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("ECDSA: invalid signature 'v' value"); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; library Exclusive { struct RoleMembership { address member; } function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) { return roleMembership.member == memberToCheck; } function resetMember(RoleMembership storage roleMembership, address newMember) internal { require(newMember != address(0x0), "Cannot set an exclusive role to 0x0"); roleMembership.member = newMember; } function getMember(RoleMembership storage roleMembership) internal view returns (address) { return roleMembership.member; } function init(RoleMembership storage roleMembership, address initialMember) internal { resetMember(roleMembership, initialMember); } } library Shared { struct RoleMembership { mapping(address => bool) members; } function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) { return roleMembership.members[memberToCheck]; } function addMember(RoleMembership storage roleMembership, address memberToAdd) internal { require(memberToAdd != address(0x0), "Cannot add 0x0 to a shared role"); roleMembership.members[memberToAdd] = true; } function removeMember(RoleMembership storage roleMembership, address memberToRemove) internal { roleMembership.members[memberToRemove] = false; } function init(RoleMembership storage roleMembership, address[] memory initialMembers) internal { for (uint256 i = 0; i < initialMembers.length; i++) { addMember(roleMembership, initialMembers[i]); } } } /** * @title Base class to manage permissions for the derived class. */ abstract contract MultiRole { using Exclusive for Exclusive.RoleMembership; using Shared for Shared.RoleMembership; enum RoleType { Invalid, Exclusive, Shared } struct Role { uint256 managingRole; RoleType roleType; Exclusive.RoleMembership exclusiveRoleMembership; Shared.RoleMembership sharedRoleMembership; } mapping(uint256 => Role) private roles; event ResetExclusiveMember(uint256 indexed roleId, address indexed newMember, address indexed manager); event AddedSharedMember(uint256 indexed roleId, address indexed newMember, address indexed manager); event RemovedSharedMember(uint256 indexed roleId, address indexed oldMember, address indexed manager); /** * @notice Reverts unless the caller is a member of the specified roleId. */ modifier onlyRoleHolder(uint256 roleId) { require(holdsRole(roleId, msg.sender), "Sender does not hold required role"); _; } /** * @notice Reverts unless the caller is a member of the manager role for the specified roleId. */ modifier onlyRoleManager(uint256 roleId) { require(holdsRole(roles[roleId].managingRole, msg.sender), "Can only be called by a role manager"); _; } /** * @notice Reverts unless the roleId represents an initialized, exclusive roleId. */ modifier onlyExclusive(uint256 roleId) { require(roles[roleId].roleType == RoleType.Exclusive, "Must be called on an initialized Exclusive role"); _; } /** * @notice Reverts unless the roleId represents an initialized, shared roleId. */ modifier onlyShared(uint256 roleId) { require(roles[roleId].roleType == RoleType.Shared, "Must be called on an initialized Shared role"); _; } /** * @notice Whether `memberToCheck` is a member of roleId. * @dev Reverts if roleId does not correspond to an initialized role. * @param roleId the Role to check. * @param memberToCheck the address to check. * @return True if `memberToCheck` is a member of `roleId`. */ function holdsRole(uint256 roleId, address memberToCheck) public view returns (bool) { Role storage role = roles[roleId]; if (role.roleType == RoleType.Exclusive) { return role.exclusiveRoleMembership.isMember(memberToCheck); } else if (role.roleType == RoleType.Shared) { return role.sharedRoleMembership.isMember(memberToCheck); } revert("Invalid roleId"); } /** * @notice Changes the exclusive role holder of `roleId` to `newMember`. * @dev Reverts if the caller is not a member of the managing role for `roleId` or if `roleId` is not an * initialized, ExclusiveRole. * @param roleId the ExclusiveRole membership to modify. * @param newMember the new ExclusiveRole member. */ function resetMember(uint256 roleId, address newMember) public onlyExclusive(roleId) onlyRoleManager(roleId) { roles[roleId].exclusiveRoleMembership.resetMember(newMember); emit ResetExclusiveMember(roleId, newMember, msg.sender); } /** * @notice Gets the current holder of the exclusive role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, exclusive role. * @param roleId the ExclusiveRole membership to check. * @return the address of the current ExclusiveRole member. */ function getMember(uint256 roleId) public view onlyExclusive(roleId) returns (address) { return roles[roleId].exclusiveRoleMembership.getMember(); } /** * @notice Adds `newMember` to the shared role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the * managing role for `roleId`. * @param roleId the SharedRole membership to modify. * @param newMember the new SharedRole member. */ function addMember(uint256 roleId, address newMember) public onlyShared(roleId) onlyRoleManager(roleId) { roles[roleId].sharedRoleMembership.addMember(newMember); emit AddedSharedMember(roleId, newMember, msg.sender); } /** * @notice Removes `memberToRemove` from the shared role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the * managing role for `roleId`. * @param roleId the SharedRole membership to modify. * @param memberToRemove the current SharedRole member to remove. */ function removeMember(uint256 roleId, address memberToRemove) public onlyShared(roleId) onlyRoleManager(roleId) { roles[roleId].sharedRoleMembership.removeMember(memberToRemove); emit RemovedSharedMember(roleId, memberToRemove, msg.sender); } /** * @notice Removes caller from the role, `roleId`. * @dev Reverts if the caller is not a member of the role for `roleId` or if `roleId` is not an * initialized, SharedRole. * @param roleId the SharedRole membership to modify. */ function renounceMembership(uint256 roleId) public onlyShared(roleId) onlyRoleHolder(roleId) { roles[roleId].sharedRoleMembership.removeMember(msg.sender); emit RemovedSharedMember(roleId, msg.sender, msg.sender); } /** * @notice Reverts if `roleId` is not initialized. */ modifier onlyValidRole(uint256 roleId) { require(roles[roleId].roleType != RoleType.Invalid, "Attempted to use an invalid roleId"); _; } /** * @notice Reverts if `roleId` is initialized. */ modifier onlyInvalidRole(uint256 roleId) { require(roles[roleId].roleType == RoleType.Invalid, "Cannot use a pre-existing role"); _; } /** * @notice Internal method to initialize a shared role, `roleId`, which will be managed by `managingRoleId`. * `initialMembers` will be immediately added to the role. * @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already * initialized. */ function _createSharedRole( uint256 roleId, uint256 managingRoleId, address[] memory initialMembers ) internal onlyInvalidRole(roleId) { Role storage role = roles[roleId]; role.roleType = RoleType.Shared; role.managingRole = managingRoleId; role.sharedRoleMembership.init(initialMembers); require( roles[managingRoleId].roleType != RoleType.Invalid, "Attempted to use an invalid role to manage a shared role" ); } /** * @notice Internal method to initialize an exclusive role, `roleId`, which will be managed by `managingRoleId`. * `initialMember` will be immediately added to the role. * @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already * initialized. */ function _createExclusiveRole( uint256 roleId, uint256 managingRoleId, address initialMember ) internal onlyInvalidRole(roleId) { Role storage role = roles[roleId]; role.roleType = RoleType.Exclusive; role.managingRole = managingRoleId; role.exclusiveRoleMembership.init(initialMember); require( roles[managingRoleId].roleType != RoleType.Invalid, "Attempted to use an invalid role to manage an exclusive role" ); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /** * @title Interface for a registry of contracts and contract creators. */ interface RegistryInterface { /** * @notice Registers a new contract. * @dev Only authorized contract creators can call this method. * @param parties an array of addresses who become parties in the contract. * @param contractAddress defines the address of the deployed contract. */ function registerContract(address[] calldata parties, address contractAddress) external; /** * @notice Returns whether the contract has been registered with the registry. * @dev If it is registered, it is an authorized participant in the UMA system. * @param contractAddress address of the contract. * @return bool indicates whether the contract is registered. */ function isContractRegistered(address contractAddress) external view returns (bool); /** * @notice Returns a list of all contracts that are associated with a particular party. * @param party address of the party. * @return an array of the contracts the party is registered to. */ function getRegisteredContracts(address party) external view returns (address[] memory); /** * @notice Returns all registered contracts. * @return all registered contract addresses within the system. */ function getAllRegisteredContracts() external view returns (address[] memory); /** * @notice Adds a party to the calling contract. * @dev msg.sender must be the contract to which the party member is added. * @param party address to be added to the contract. */ function addPartyToContract(address party) external; /** * @notice Removes a party member to the calling contract. * @dev msg.sender must be the contract to which the party member is added. * @param party address to be removed from the contract. */ function removePartyFromContract(address party) external; /** * @notice checks if an address is a party in a contract. * @param party party to check. * @param contractAddress address to check against the party. * @return bool indicating if the address is a party of the contract. */ function isPartyMemberOfContract(address party, address contractAddress) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./MultiRole.sol"; import "../interfaces/ExpandedIERC20.sol"; /** * @title An ERC20 with permissioned burning and minting. The contract deployer will initially * be the owner who is capable of adding new roles. */ contract ExpandedERC20 is ExpandedIERC20, ERC20, MultiRole { enum Roles { // Can set the minter and burner. Owner, // Addresses that can mint new tokens. Minter, // Addresses that can burn tokens that address owns. Burner } /** * @notice Constructs the ExpandedERC20. * @param _tokenName The name which describes the new token. * @param _tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars. * @param _tokenDecimals The number of decimals to define token precision. */ constructor( string memory _tokenName, string memory _tokenSymbol, uint8 _tokenDecimals ) public ERC20(_tokenName, _tokenSymbol) { _setupDecimals(_tokenDecimals); _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createSharedRole(uint256(Roles.Minter), uint256(Roles.Owner), new address[](0)); _createSharedRole(uint256(Roles.Burner), uint256(Roles.Owner), new address[](0)); } /** * @dev Mints `value` tokens to `recipient`, returning true on success. * @param recipient address to mint to. * @param value amount of tokens to mint. * @return True if the mint succeeded, or False. */ function mint(address recipient, uint256 value) external override onlyRoleHolder(uint256(Roles.Minter)) returns (bool) { _mint(recipient, value); return true; } /** * @dev Burns `value` tokens owned by `msg.sender`. * @param value amount of tokens to burn. */ function burn(uint256 value) external override onlyRoleHolder(uint256(Roles.Burner)) { _burn(msg.sender, value); } /** * @notice Add Minter role to account. * @dev The caller must have the Owner role. * @param account The address to which the Minter role is added. */ function addMinter(address account) external virtual override { addMember(uint256(Roles.Minter), account); } /** * @notice Add Burner role to account. * @dev The caller must have the Owner role. * @param account The address to which the Burner role is added. */ function addBurner(address account) external virtual override { addMember(uint256(Roles.Burner), account); } /** * @notice Reset Owner role to account. * @dev The caller must have the Owner role. * @param account The new holder of the Owner role. */ function resetOwner(address account) external virtual override { resetMember(uint256(Roles.Owner), account); } } pragma solidity ^0.6.0; import "../../math/SafeMath.sol"; import "../../utils/Arrays.sol"; import "../../utils/Counters.sol"; import "./ERC20.sol"; /** * @dev This contract extends an ERC20 token with a snapshot mechanism. When a snapshot is created, the balances and * total supply at the time are recorded for later access. * * This can be used to safely create mechanisms based on token balances such as trustless dividends or weighted voting. * In naive implementations it's possible to perform a "double spend" attack by reusing the same balance from different * accounts. By using snapshots to calculate dividends or voting power, those attacks no longer apply. It can also be * used to create an efficient ERC20 forking mechanism. * * Snapshots are created by the internal {_snapshot} function, which will emit the {Snapshot} event and return a * snapshot id. To get the total supply at the time of a snapshot, call the function {totalSupplyAt} with the snapshot * id. To get the balance of an account at the time of a snapshot, call the {balanceOfAt} function with the snapshot id * and the account address. * * ==== Gas Costs * * Snapshots are efficient. Snapshot creation is _O(1)_. Retrieval of balances or total supply from a snapshot is _O(log * n)_ in the number of snapshots that have been created, although _n_ for a specific account will generally be much * smaller since identical balances in subsequent snapshots are stored as a single entry. * * There is a constant overhead for normal ERC20 transfers due to the additional snapshot bookkeeping. This overhead is * only significant for the first transfer that immediately follows a snapshot for a particular account. Subsequent * transfers will have normal cost until the next snapshot, and so on. */ abstract contract ERC20Snapshot is ERC20 { // Inspired by Jordi Baylina's MiniMeToken to record historical balances: // https://github.com/Giveth/minimd/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol using SafeMath for uint256; using Arrays for uint256[]; using Counters for Counters.Counter; // Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a // Snapshot struct, but that would impede usage of functions that work on an array. struct Snapshots { uint256[] ids; uint256[] values; } mapping (address => Snapshots) private _accountBalanceSnapshots; Snapshots private _totalSupplySnapshots; // Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid. Counters.Counter private _currentSnapshotId; /** * @dev Emitted by {_snapshot} when a snapshot identified by `id` is created. */ event Snapshot(uint256 id); /** * @dev Creates a new snapshot and returns its snapshot id. * * Emits a {Snapshot} event that contains the same id. * * {_snapshot} is `internal` and you have to decide how to expose it externally. Its usage may be restricted to a * set of accounts, for example using {AccessControl}, or it may be open to the public. * * [WARNING] * ==== * While an open way of calling {_snapshot} is required for certain trust minimization mechanisms such as forking, * you must consider that it can potentially be used by attackers in two ways. * * First, it can be used to increase the cost of retrieval of values from snapshots, although it will grow * logarithmically thus rendering this attack ineffective in the long term. Second, it can be used to target * specific accounts and increase the cost of ERC20 transfers for them, in the ways specified in the Gas Costs * section above. * * We haven't measured the actual numbers; if this is something you're interested in please reach out to us. * ==== */ function _snapshot() internal virtual returns (uint256) { _currentSnapshotId.increment(); uint256 currentId = _currentSnapshotId.current(); emit Snapshot(currentId); return currentId; } /** * @dev Retrieves the balance of `account` at the time `snapshotId` was created. */ function balanceOfAt(address account, uint256 snapshotId) public view returns (uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]); return snapshotted ? value : balanceOf(account); } /** * @dev Retrieves the total supply at the time `snapshotId` was created. */ function totalSupplyAt(uint256 snapshotId) public view returns(uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots); return snapshotted ? value : totalSupply(); } // _transfer, _mint and _burn are the only functions where the balances are modified, so it is there that the // snapshots are updated. Note that the update happens _before_ the balance change, with the pre-modified value. // The same is true for the total supply and _mint and _burn. function _transfer(address from, address to, uint256 value) internal virtual override { _updateAccountSnapshot(from); _updateAccountSnapshot(to); super._transfer(from, to, value); } function _mint(address account, uint256 value) internal virtual override { _updateAccountSnapshot(account); _updateTotalSupplySnapshot(); super._mint(account, value); } function _burn(address account, uint256 value) internal virtual override { _updateAccountSnapshot(account); _updateTotalSupplySnapshot(); super._burn(account, value); } function _valueAt(uint256 snapshotId, Snapshots storage snapshots) private view returns (bool, uint256) { require(snapshotId > 0, "ERC20Snapshot: id is 0"); // solhint-disable-next-line max-line-length require(snapshotId <= _currentSnapshotId.current(), "ERC20Snapshot: nonexistent id"); // When a valid snapshot is queried, there are three possibilities: // a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never // created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds // to this id is the current one. // b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the // requested id, and its value is the one to return. // c) More snapshots were created after the requested one, and the queried value was later modified. There will be // no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is // larger than the requested one. // // In summary, we need to find an element in an array, returning the index of the smallest value that is larger if // it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does // exactly this. uint256 index = snapshots.ids.findUpperBound(snapshotId); if (index == snapshots.ids.length) { return (false, 0); } else { return (true, snapshots.values[index]); } } function _updateAccountSnapshot(address account) private { _updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account)); } function _updateTotalSupplySnapshot() private { _updateSnapshot(_totalSupplySnapshots, totalSupply()); } function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private { uint256 currentId = _currentSnapshotId.current(); if (_lastSnapshotId(snapshots.ids) < currentId) { snapshots.ids.push(currentId); snapshots.values.push(currentValue); } } function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) { if (ids.length == 0) { return 0; } else { return ids[ids.length - 1]; } } } pragma solidity ^0.6.0; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.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 {ERC20MinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of 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 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * 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 returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, 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}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), 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}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); 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) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(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) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is 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: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, 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 * * - `to` 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 = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is 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 Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @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 to 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 { } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ERC20 interface that includes burn and mint methods. */ abstract contract ExpandedIERC20 is IERC20 { /** * @notice Burns a specific amount of the caller's tokens. * @dev Only burns the caller's tokens, so it is safe to leave this method permissionless. */ function burn(uint256 value) external virtual; /** * @notice Mints tokens and adds them to the balance of the `to` address. * @dev This method should be permissioned to only allow designated parties to mint tokens. */ function mint(address to, uint256 value) external virtual returns (bool); function addMinter(address account) external virtual; function addBurner(address account) external virtual; function resetOwner(address account) external virtual; } pragma solidity ^0.6.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 GSN 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. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ 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); } pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } pragma solidity ^0.6.0; import "../math/Math.sol"; /** * @dev Collection of functions related to array types. */ library Arrays { /** * @dev Searches a sorted `array` and returns the first index that contains * a value greater or equal to `element`. If no such index exists (i.e. all * values in the array are strictly less than `element`), the array length is * returned. Time complexity O(log n). * * `array` is expected to be sorted in ascending order, and to contain no * repeated elements. */ function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) { if (array.length == 0) { return 0; } uint256 low = 0; uint256 high = array.length; while (low < high) { uint256 mid = Math.average(low, high); // Note that mid will always be strictly less than high (i.e. it will be a valid array index) // because Math.average rounds down (it does integer division with truncation). if (array[mid] > element) { high = mid; } else { low = mid + 1; } } // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound. if (low > 0 && array[low - 1] == element) { return low - 1; } else { return low; } } } pragma solidity ^0.6.0; import "../math/SafeMath.sol"; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } pragma solidity ^0.6.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../oracle/implementation/Finder.sol"; import "../oracle/implementation/Constants.sol"; import "../oracle/implementation/Voting.sol"; /** * @title A contract that executes a short series of upgrade calls that must be performed atomically as a part of the * upgrade process for Voting.sol. * @dev Note: the complete upgrade process requires more than just the transactions in this contract. These are only * the ones that need to be performed atomically. */ contract VotingUpgrader { // Existing governor is the only one who can initiate the upgrade. address public governor; // Existing Voting contract needs to be informed of the address of the new Voting contract. Voting public existingVoting; // New governor will be the new owner of the finder. // Finder contract to push upgrades to. Finder public finder; // Addresses to upgrade. address public newVoting; // Address to call setMigrated on the old voting contract. address public setMigratedAddress; /** * @notice Removes an address from the whitelist. * @param _governor the Governor contract address. * @param _existingVoting the current/existing Voting contract address. * @param _newVoting the new Voting deployment address. * @param _finder the Finder contract address. * @param _setMigratedAddress the address to set migrated. This address will be able to continue making calls to * old voting contract (used to claim rewards on others' behalf). Note: this address * can always be changed by the voters. */ constructor( address _governor, address _existingVoting, address _newVoting, address _finder, address _setMigratedAddress ) public { governor = _governor; existingVoting = Voting(_existingVoting); newVoting = _newVoting; finder = Finder(_finder); setMigratedAddress = _setMigratedAddress; } /** * @notice Performs the atomic portion of the upgrade process. * @dev This method updates the Voting address in the finder, sets the old voting contract to migrated state, and * returns ownership of the existing Voting contract and Finder back to the Governor. */ function upgrade() external { require(msg.sender == governor, "Upgrade can only be initiated by the existing governor."); // Change the addresses in the Finder. finder.changeImplementationAddress(OracleInterfaces.Oracle, newVoting); // Set the preset "migrated" address to allow this address to claim rewards on voters' behalf. // This also effectively shuts down the existing voting contract so new votes cannot be triggered. existingVoting.setMigrated(setMigratedAddress); // Transfer back ownership of old voting contract and the finder to the governor. existingVoting.transferOwnership(governor); finder.transferOwnership(governor); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "../interfaces/FinderInterface.sol"; /** * @title Provides addresses of the live contracts implementing certain interfaces. * @dev Examples of interfaces with implementations that Finder locates are the Oracle and Store interfaces. */ contract Finder is FinderInterface, Ownable { mapping(bytes32 => address) public interfacesImplemented; event InterfaceImplementationChanged(bytes32 indexed interfaceName, address indexed newImplementationAddress); /** * @notice Updates the address of the contract that implements `interfaceName`. * @param interfaceName bytes32 of the interface name that is either changed or registered. * @param implementationAddress address of the implementation contract. */ function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external override onlyOwner { interfacesImplemented[interfaceName] = implementationAddress; emit InterfaceImplementationChanged(interfaceName, implementationAddress); } /** * @notice Gets the address of the contract that implements the given `interfaceName`. * @param interfaceName queried interface. * @return implementationAddress address of the defined interface. */ function getImplementationAddress(bytes32 interfaceName) external view override returns (address) { address implementationAddress = interfacesImplemented[interfaceName]; require(implementationAddress != address(0x0), "Implementation not found"); return implementationAddress; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../oracle/implementation/Finder.sol"; import "../oracle/implementation/Constants.sol"; import "../oracle/implementation/Voting.sol"; /** * @title A contract to track a whitelist of addresses. */ contract Umip3Upgrader { // Existing governor is the only one who can initiate the upgrade. address public existingGovernor; // Existing Voting contract needs to be informed of the address of the new Voting contract. Voting public existingVoting; // New governor will be the new owner of the finder. address public newGovernor; // Finder contract to push upgrades to. Finder public finder; // Addresses to upgrade. address public voting; address public identifierWhitelist; address public store; address public financialContractsAdmin; address public registry; constructor( address _existingGovernor, address _existingVoting, address _finder, address _voting, address _identifierWhitelist, address _store, address _financialContractsAdmin, address _registry, address _newGovernor ) public { existingGovernor = _existingGovernor; existingVoting = Voting(_existingVoting); finder = Finder(_finder); voting = _voting; identifierWhitelist = _identifierWhitelist; store = _store; financialContractsAdmin = _financialContractsAdmin; registry = _registry; newGovernor = _newGovernor; } function upgrade() external { require(msg.sender == existingGovernor, "Upgrade can only be initiated by the existing governor."); // Change the addresses in the Finder. finder.changeImplementationAddress(OracleInterfaces.Oracle, voting); finder.changeImplementationAddress(OracleInterfaces.IdentifierWhitelist, identifierWhitelist); finder.changeImplementationAddress(OracleInterfaces.Store, store); finder.changeImplementationAddress(OracleInterfaces.FinancialContractsAdmin, financialContractsAdmin); finder.changeImplementationAddress(OracleInterfaces.Registry, registry); // Transfer the ownership of the Finder to the new Governor now that all the addresses have been updated. finder.transferOwnership(newGovernor); // Inform the existing Voting contract of the address of the new Voting contract and transfer its // ownership to the new governor to allow for any future changes to the migrated contract. existingVoting.setMigrated(voting); existingVoting.transferOwnership(newGovernor); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/FinderInterface.sol"; import "../implementation/Constants.sol"; // A mock oracle used for testing. contract MockOracleAncillary is OracleAncillaryInterface, Testable { // Represents an available price. Have to keep a separate bool to allow for price=0. struct Price { bool isAvailable; int256 price; // Time the verified price became available. uint256 verifiedTime; } // The two structs below are used in an array and mapping to keep track of prices that have been requested but are // not yet available. struct QueryIndex { bool isValid; uint256 index; } // Represents a (identifier, time) point that has been queried. struct QueryPoint { bytes32 identifier; uint256 time; bytes ancillaryData; } // Reference to the Finder. FinderInterface private finder; // Conceptually we want a (time, identifier) -> price map. mapping(bytes32 => mapping(uint256 => mapping(bytes => Price))) private verifiedPrices; // The mapping and array allow retrieving all the elements in a mapping and finding/deleting elements. // Can we generalize this data structure? mapping(bytes32 => mapping(uint256 => mapping(bytes => QueryIndex))) private queryIndices; QueryPoint[] private requestedPrices; event PriceRequestAdded(address indexed requester, bytes32 indexed identifier, uint256 time, bytes ancillaryData); event PushedPrice( address indexed pusher, bytes32 indexed identifier, uint256 time, bytes ancillaryData, int256 price ); constructor(address _finderAddress, address _timerAddress) public Testable(_timerAddress) { finder = FinderInterface(_finderAddress); } // Enqueues a request (if a request isn't already present) for the given (identifier, time) pair. function requestPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public override { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time][ancillaryData]; if (!lookup.isAvailable && !queryIndices[identifier][time][ancillaryData].isValid) { // New query, enqueue it for review. queryIndices[identifier][time][ancillaryData] = QueryIndex(true, requestedPrices.length); requestedPrices.push(QueryPoint(identifier, time, ancillaryData)); emit PriceRequestAdded(msg.sender, identifier, time, ancillaryData); } } // Pushes the verified price for a requested query. function pushPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData, int256 price ) external { verifiedPrices[identifier][time][ancillaryData] = Price(true, price, getCurrentTime()); QueryIndex storage queryIndex = queryIndices[identifier][time][ancillaryData]; require(queryIndex.isValid, "Can't push prices that haven't been requested"); // Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with // the contents of the last index (unless it is the last index). uint256 indexToReplace = queryIndex.index; delete queryIndices[identifier][time][ancillaryData]; uint256 lastIndex = requestedPrices.length - 1; if (lastIndex != indexToReplace) { QueryPoint storage queryToCopy = requestedPrices[lastIndex]; queryIndices[queryToCopy.identifier][queryToCopy.time][queryToCopy.ancillaryData].index = indexToReplace; requestedPrices[indexToReplace] = queryToCopy; } emit PushedPrice(msg.sender, identifier, time, ancillaryData, price); } // Checks whether a price has been resolved. function hasPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override returns (bool) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time][ancillaryData]; return lookup.isAvailable; } // Gets a price that has already been resolved. function getPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override returns (int256) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time][ancillaryData]; require(lookup.isAvailable); return lookup.price; } // Gets the queries that still need verified prices. function getPendingQueries() external view returns (QueryPoint[] memory) { return requestedPrices; } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/FinderInterface.sol"; import "../implementation/Constants.sol"; // A mock oracle used for testing. contract MockOracle is OracleInterface, Testable { // Represents an available price. Have to keep a separate bool to allow for price=0. struct Price { bool isAvailable; int256 price; // Time the verified price became available. uint256 verifiedTime; } // The two structs below are used in an array and mapping to keep track of prices that have been requested but are // not yet available. struct QueryIndex { bool isValid; uint256 index; } // Represents a (identifier, time) point that has been queried. struct QueryPoint { bytes32 identifier; uint256 time; } // Reference to the Finder. FinderInterface private finder; // Conceptually we want a (time, identifier) -> price map. mapping(bytes32 => mapping(uint256 => Price)) private verifiedPrices; // The mapping and array allow retrieving all the elements in a mapping and finding/deleting elements. // Can we generalize this data structure? mapping(bytes32 => mapping(uint256 => QueryIndex)) private queryIndices; QueryPoint[] private requestedPrices; constructor(address _finderAddress, address _timerAddress) public Testable(_timerAddress) { finder = FinderInterface(_finderAddress); } // Enqueues a request (if a request isn't already present) for the given (identifier, time) pair. function requestPrice(bytes32 identifier, uint256 time) public override { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time]; if (!lookup.isAvailable && !queryIndices[identifier][time].isValid) { // New query, enqueue it for review. queryIndices[identifier][time] = QueryIndex(true, requestedPrices.length); requestedPrices.push(QueryPoint(identifier, time)); } } // Pushes the verified price for a requested query. function pushPrice( bytes32 identifier, uint256 time, int256 price ) external { verifiedPrices[identifier][time] = Price(true, price, getCurrentTime()); QueryIndex storage queryIndex = queryIndices[identifier][time]; require(queryIndex.isValid, "Can't push prices that haven't been requested"); // Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with // the contents of the last index (unless it is the last index). uint256 indexToReplace = queryIndex.index; delete queryIndices[identifier][time]; uint256 lastIndex = requestedPrices.length - 1; if (lastIndex != indexToReplace) { QueryPoint storage queryToCopy = requestedPrices[lastIndex]; queryIndices[queryToCopy.identifier][queryToCopy.time].index = indexToReplace; requestedPrices[indexToReplace] = queryToCopy; } } // Checks whether a price has been resolved. function hasPrice(bytes32 identifier, uint256 time) public view override returns (bool) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time]; return lookup.isAvailable; } // Gets a price that has already been resolved. function getPrice(bytes32 identifier, uint256 time) public view override returns (int256) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time]; require(lookup.isAvailable); return lookup.price; } // Gets the queries that still need verified prices. function getPendingQueries() external view returns (QueryPoint[] memory) { return requestedPrices; } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/MultiRole.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/FinderInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/OracleInterface.sol"; import "./Constants.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; /** * @title Takes proposals for certain governance actions and allows UMA token holders to vote on them. */ contract Governor is MultiRole, Testable { using SafeMath for uint256; using Address for address; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, // Can set the proposer. Proposer // Address that can make proposals. } struct Transaction { address to; uint256 value; bytes data; } struct Proposal { Transaction[] transactions; uint256 requestTime; } FinderInterface private finder; Proposal[] public proposals; /**************************************** * EVENTS * ****************************************/ // Emitted when a new proposal is created. event NewProposal(uint256 indexed id, Transaction[] transactions); // Emitted when an existing proposal is executed. event ProposalExecuted(uint256 indexed id, uint256 transactionIndex); /** * @notice Construct the Governor contract. * @param _finderAddress keeps track of all contracts within the system based on their interfaceName. * @param _startingId the initial proposal id that the contract will begin incrementing from. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( address _finderAddress, uint256 _startingId, address _timerAddress ) public Testable(_timerAddress) { finder = FinderInterface(_finderAddress); _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createExclusiveRole(uint256(Roles.Proposer), uint256(Roles.Owner), msg.sender); // Ensure the startingId is not set unreasonably high to avoid it being set such that new proposals overwrite // other storage slots in the contract. uint256 maxStartingId = 10**18; require(_startingId <= maxStartingId, "Cannot set startingId larger than 10^18"); // This just sets the initial length of the array to the startingId since modifying length directly has been // disallowed in solidity 0.6. assembly { sstore(proposals_slot, _startingId) } } /**************************************** * PROPOSAL ACTIONS * ****************************************/ /** * @notice Proposes a new governance action. Can only be called by the holder of the Proposer role. * @param transactions list of transactions that are being proposed. * @dev You can create the data portion of each transaction by doing the following: * ``` * const truffleContractInstance = await TruffleContract.deployed() * const data = truffleContractInstance.methods.methodToCall(arg1, arg2).encodeABI() * ``` * Note: this method must be public because of a solidity limitation that * disallows structs arrays to be passed to external functions. */ function propose(Transaction[] memory transactions) public onlyRoleHolder(uint256(Roles.Proposer)) { uint256 id = proposals.length; uint256 time = getCurrentTime(); // Note: doing all of this array manipulation manually is necessary because directly setting an array of // structs in storage to an an array of structs in memory is currently not implemented in solidity :/. // Add a zero-initialized element to the proposals array. proposals.push(); // Initialize the new proposal. Proposal storage proposal = proposals[id]; proposal.requestTime = time; // Initialize the transaction array. for (uint256 i = 0; i < transactions.length; i++) { require(transactions[i].to != address(0), "The `to` address cannot be 0x0"); // If the transaction has any data with it the recipient must be a contract, not an EOA. if (transactions[i].data.length > 0) { require(transactions[i].to.isContract(), "EOA can't accept tx with data"); } proposal.transactions.push(transactions[i]); } bytes32 identifier = _constructIdentifier(id); // Request a vote on this proposal in the DVM. OracleInterface oracle = _getOracle(); IdentifierWhitelistInterface supportedIdentifiers = _getIdentifierWhitelist(); supportedIdentifiers.addSupportedIdentifier(identifier); oracle.requestPrice(identifier, time); supportedIdentifiers.removeSupportedIdentifier(identifier); emit NewProposal(id, transactions); } /** * @notice Executes a proposed governance action that has been approved by voters. * @dev This can be called by any address. Caller is expected to send enough ETH to execute payable transactions. * @param id unique id for the executed proposal. * @param transactionIndex unique transaction index for the executed proposal. */ function executeProposal(uint256 id, uint256 transactionIndex) external payable { Proposal storage proposal = proposals[id]; int256 price = _getOracle().getPrice(_constructIdentifier(id), proposal.requestTime); Transaction memory transaction = proposal.transactions[transactionIndex]; require( transactionIndex == 0 || proposal.transactions[transactionIndex.sub(1)].to == address(0), "Previous tx not yet executed" ); require(transaction.to != address(0), "Tx already executed"); require(price != 0, "Proposal was rejected"); require(msg.value == transaction.value, "Must send exact amount of ETH"); // Delete the transaction before execution to avoid any potential re-entrancy issues. delete proposal.transactions[transactionIndex]; require(_executeCall(transaction.to, transaction.value, transaction.data), "Tx execution failed"); emit ProposalExecuted(id, transactionIndex); } /**************************************** * GOVERNOR STATE GETTERS * ****************************************/ /** * @notice Gets the total number of proposals (includes executed and non-executed). * @return uint256 representing the current number of proposals. */ function numProposals() external view returns (uint256) { return proposals.length; } /** * @notice Gets the proposal data for a particular id. * @dev after a proposal is executed, its data will be zeroed out, except for the request time. * @param id uniquely identify the identity of the proposal. * @return proposal struct containing transactions[] and requestTime. */ function getProposal(uint256 id) external view returns (Proposal memory) { return proposals[id]; } /**************************************** * PRIVATE GETTERS AND FUNCTIONS * ****************************************/ function _executeCall( address to, uint256 value, bytes memory data ) private returns (bool) { // Mostly copied from: // solhint-disable-next-line max-line-length // https://github.com/gnosis/safe-contracts/blob/59cfdaebcd8b87a0a32f87b50fead092c10d3a05/contracts/base/Executor.sol#L23-L31 // solhint-disable-next-line no-inline-assembly bool success; assembly { let inputData := add(data, 0x20) let inputDataSize := mload(data) success := call(gas(), to, value, inputData, inputDataSize, 0, 0) } return success; } function _getOracle() private view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } // Returns a UTF-8 identifier representing a particular admin proposal. // The identifier is of the form "Admin n", where n is the proposal id provided. function _constructIdentifier(uint256 id) internal pure returns (bytes32) { bytes32 bytesId = _uintToUtf8(id); return _addPrefix(bytesId, "Admin ", 6); } // This method converts the integer `v` into a base-10, UTF-8 representation stored in a `bytes32` type. // If the input cannot be represented by 32 base-10 digits, it returns only the highest 32 digits. // This method is based off of this code: https://ethereum.stackexchange.com/a/6613/47801. function _uintToUtf8(uint256 v) internal pure returns (bytes32) { bytes32 ret; if (v == 0) { // Handle 0 case explicitly. ret = "0"; } else { // Constants. uint256 bitsPerByte = 8; uint256 base = 10; // Note: the output should be base-10. The below implementation will not work for bases > 10. uint256 utf8NumberOffset = 48; while (v > 0) { // Downshift the entire bytes32 to allow the new digit to be added at the "front" of the bytes32, which // translates to the beginning of the UTF-8 representation. ret = ret >> bitsPerByte; // Separate the last digit that remains in v by modding by the base of desired output representation. uint256 leastSignificantDigit = v % base; // Digits 0-9 are represented by 48-57 in UTF-8, so an offset must be added to create the character. bytes32 utf8Digit = bytes32(leastSignificantDigit + utf8NumberOffset); // The top byte of ret has already been cleared to make room for the new digit. // Upshift by 31 bytes to put it in position, and OR it with ret to leave the other characters untouched. ret |= utf8Digit << (31 * bitsPerByte); // Divide v by the base to remove the digit that was just added. v /= base; } } return ret; } // This method takes two UTF-8 strings represented as bytes32 and outputs one as a prefixed by the other. // `input` is the UTF-8 that should have the prefix prepended. // `prefix` is the UTF-8 that should be prepended onto input. // `prefixLength` is number of UTF-8 characters represented by `prefix`. // Notes: // 1. If the resulting UTF-8 is larger than 32 characters, then only the first 32 characters will be represented // by the bytes32 output. // 2. If `prefix` has more characters than `prefixLength`, the function will produce an invalid result. function _addPrefix( bytes32 input, bytes32 prefix, uint256 prefixLength ) internal pure returns (bytes32) { // Downshift `input` to open space at the "front" of the bytes32 bytes32 shiftedInput = input >> (prefixLength * 8); return shiftedInput | prefix; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../Governor.sol"; // GovernorTest exposes internal methods in the Governor for testing. contract GovernorTest is Governor { constructor(address _timerAddress) public Governor(address(0), 0, _timerAddress) {} function addPrefix( bytes32 input, bytes32 prefix, uint256 prefixLength ) external pure returns (bytes32) { return _addPrefix(input, prefix, prefixLength); } function uintToUtf8(uint256 v) external pure returns (bytes32 ret) { return _uintToUtf8(v); } function constructIdentifier(uint256 id) external pure returns (bytes32 identifier) { return _constructIdentifier(id); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../interfaces/StoreInterface.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/FinderInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/OptimisticOracleInterface.sol"; import "./Constants.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/AddressWhitelist.sol"; /** * @title Optimistic Requester. * @notice Optional interface that requesters can implement to receive callbacks. * @dev this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on * transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing * money themselves). */ interface OptimisticRequester { /** * @notice Callback for proposals. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data of the price being requested. */ function priceProposed( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external; /** * @notice Callback for disputes. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data of the price being requested. * @param refund refund received in the case that refundOnDispute was enabled. */ function priceDisputed( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 refund ) external; /** * @notice Callback for settlement. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data of the price being requested. * @param price price that was resolved by the escalation process. */ function priceSettled( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 price ) external; } /** * @title Optimistic Oracle. * @notice Pre-DVM escalation contract that allows faster settlement. */ contract OptimisticOracle is OptimisticOracleInterface, Testable, Lockable { using SafeMath for uint256; using SafeERC20 for IERC20; using Address for address; event RequestPrice( address indexed requester, bytes32 identifier, uint256 timestamp, bytes ancillaryData, address currency, uint256 reward, uint256 finalFee ); event ProposePrice( address indexed requester, address indexed proposer, bytes32 identifier, uint256 timestamp, bytes ancillaryData, int256 proposedPrice, uint256 expirationTimestamp, address currency ); event DisputePrice( address indexed requester, address indexed proposer, address indexed disputer, bytes32 identifier, uint256 timestamp, bytes ancillaryData, int256 proposedPrice ); event Settle( address indexed requester, address indexed proposer, address indexed disputer, bytes32 identifier, uint256 timestamp, bytes ancillaryData, int256 price, uint256 payout ); mapping(bytes32 => Request) public requests; // Finder to provide addresses for DVM contracts. FinderInterface public finder; // Default liveness value for all price requests. uint256 public defaultLiveness; /** * @notice Constructor. * @param _liveness default liveness applied to each price request. * @param _finderAddress finder to use to get addresses of DVM contracts. * @param _timerAddress address of the timer contract. Should be 0x0 in prod. */ constructor( uint256 _liveness, address _finderAddress, address _timerAddress ) public Testable(_timerAddress) { finder = FinderInterface(_finderAddress); _validateLiveness(_liveness); defaultLiveness = _liveness; } /** * @notice Requests a new price. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data representing additional args being passed with the price request. * @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM. * @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0, * which could make sense if the contract requests and proposes the value in the same call or * provides its own reward system. * @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay. * This can be changed with a subsequent call to setBond(). */ function requestPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, IERC20 currency, uint256 reward ) external override nonReentrant() returns (uint256 totalBond) { require(getState(msg.sender, identifier, timestamp, ancillaryData) == State.Invalid, "requestPrice: Invalid"); require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier"); require(_getCollateralWhitelist().isOnWhitelist(address(currency)), "Unsupported currency"); require(timestamp <= getCurrentTime(), "Timestamp in future"); require(ancillaryData.length <= ancillaryBytesLimit, "Invalid ancillary data"); uint256 finalFee = _getStore().computeFinalFee(address(currency)).rawValue; requests[_getId(msg.sender, identifier, timestamp, ancillaryData)] = Request({ proposer: address(0), disputer: address(0), currency: currency, settled: false, refundOnDispute: false, proposedPrice: 0, resolvedPrice: 0, expirationTime: 0, reward: reward, finalFee: finalFee, bond: finalFee, customLiveness: 0 }); if (reward > 0) { currency.safeTransferFrom(msg.sender, address(this), reward); } emit RequestPrice(msg.sender, identifier, timestamp, ancillaryData, address(currency), reward, finalFee); // This function returns the initial proposal bond for this request, which can be customized by calling // setBond() with the same identifier and timestamp. return finalFee.mul(2); } /** * @notice Set the proposal bond associated with a price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param bond custom bond amount to set. * @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be * changed again with a subsequent call to setBond(). */ function setBond( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 bond ) external override nonReentrant() returns (uint256 totalBond) { require(getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested, "setBond: Requested"); Request storage request = _getRequest(msg.sender, identifier, timestamp, ancillaryData); request.bond = bond; // Total bond is the final fee + the newly set bond. return bond.add(request.finalFee); } /** * @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller * in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's * bond, so there is still profit to be made even if the reward is refunded. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. */ function setRefundOnDispute( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override nonReentrant() { require( getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested, "setRefundOnDispute: Requested" ); _getRequest(msg.sender, identifier, timestamp, ancillaryData).refundOnDispute = true; } /** * @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before * being auto-resolved. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param customLiveness new custom liveness. */ function setCustomLiveness( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 customLiveness ) external override nonReentrant() { require( getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested, "setCustomLiveness: Requested" ); _validateLiveness(customLiveness); _getRequest(msg.sender, identifier, timestamp, ancillaryData).customLiveness = customLiveness; } /** * @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come * from this proposal. However, any bonds are pulled from the caller. * @param proposer address to set as the proposer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePriceFor( address proposer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) public override nonReentrant() returns (uint256 totalBond) { require(proposer != address(0), "proposer address must be non 0"); require( getState(requester, identifier, timestamp, ancillaryData) == State.Requested, "proposePriceFor: Requested" ); Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); request.proposer = proposer; request.proposedPrice = proposedPrice; // If a custom liveness has been set, use it instead of the default. request.expirationTime = getCurrentTime().add( request.customLiveness != 0 ? request.customLiveness : defaultLiveness ); totalBond = request.bond.add(request.finalFee); if (totalBond > 0) { request.currency.safeTransferFrom(msg.sender, address(this), totalBond); } emit ProposePrice( requester, proposer, identifier, timestamp, ancillaryData, proposedPrice, request.expirationTime, address(request.currency) ); // Callback. if (address(requester).isContract()) try OptimisticRequester(requester).priceProposed(identifier, timestamp, ancillaryData) {} catch {} } /** * @notice Proposes a price value for an existing price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) external override returns (uint256 totalBond) { // Note: re-entrancy guard is done in the inner call. return proposePriceFor(msg.sender, requester, identifier, timestamp, ancillaryData, proposedPrice); } /** * @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will * receive any rewards that come from this dispute. However, any bonds are pulled from the caller. * @param disputer address to set as the disputer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was valid (the proposal was incorrect). */ function disputePriceFor( address disputer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public override nonReentrant() returns (uint256 totalBond) { require(disputer != address(0), "disputer address must be non 0"); require( getState(requester, identifier, timestamp, ancillaryData) == State.Proposed, "disputePriceFor: Proposed" ); Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); request.disputer = disputer; uint256 finalFee = request.finalFee; uint256 bond = request.bond; totalBond = bond.add(finalFee); if (totalBond > 0) { request.currency.safeTransferFrom(msg.sender, address(this), totalBond); } StoreInterface store = _getStore(); // Avoids stack too deep compilation error. { // Along with the final fee, "burn" part of the loser's bond to ensure that a larger bond always makes it // proportionally more expensive to delay the resolution even if the proposer and disputer are the same // party. uint256 burnedBond = _computeBurnedBond(request); // The total fee is the burned bond and the final fee added together. uint256 totalFee = finalFee.add(burnedBond); if (totalFee > 0) { request.currency.safeIncreaseAllowance(address(store), totalFee); _getStore().payOracleFeesErc20(address(request.currency), FixedPoint.Unsigned(totalFee)); } } _getOracle().requestPrice(identifier, timestamp, _stampAncillaryData(ancillaryData, requester)); // Compute refund. uint256 refund = 0; if (request.reward > 0 && request.refundOnDispute) { refund = request.reward; request.reward = 0; request.currency.safeTransfer(requester, refund); } emit DisputePrice( requester, request.proposer, disputer, identifier, timestamp, ancillaryData, request.proposedPrice ); // Callback. if (address(requester).isContract()) try OptimisticRequester(requester).priceDisputed(identifier, timestamp, ancillaryData, refund) {} catch {} } /** * @notice Disputes a price value for an existing price request with an active proposal. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was valid (the proposal was incorrect). */ function disputePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override returns (uint256 totalBond) { // Note: re-entrancy guard is done in the inner call. return disputePriceFor(msg.sender, requester, identifier, timestamp, ancillaryData); } /** * @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled * or settleable. Note: this method is not view so that this call may actually settle the price request if it * hasn't been settled. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return resolved price. */ function settleAndGetPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override nonReentrant() returns (int256) { if (getState(msg.sender, identifier, timestamp, ancillaryData) != State.Settled) { _settle(msg.sender, identifier, timestamp, ancillaryData); } return _getRequest(msg.sender, identifier, timestamp, ancillaryData).resolvedPrice; } /** * @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes * the returned bonds as well as additional rewards. */ function settle( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override nonReentrant() returns (uint256 payout) { return _settle(requester, identifier, timestamp, ancillaryData); } /** * @notice Gets the current data structure containing all information about a price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the Request data structure. */ function getRequest( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view override returns (Request memory) { return _getRequest(requester, identifier, timestamp, ancillaryData); } /** * @notice Computes the current state of a price request. See the State enum for more details. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the State. */ function getState( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view override returns (State) { Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); if (address(request.currency) == address(0)) { return State.Invalid; } if (request.proposer == address(0)) { return State.Requested; } if (request.settled) { return State.Settled; } if (request.disputer == address(0)) { return request.expirationTime <= getCurrentTime() ? State.Expired : State.Proposed; } return _getOracle().hasPrice(identifier, timestamp, _stampAncillaryData(ancillaryData, requester)) ? State.Resolved : State.Disputed; } /** * @notice Checks if a given request has resolved, expired or been settled (i.e the optimistic oracle has a price). * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return boolean indicating true if price exists and false if not. */ function hasPrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view override returns (bool) { State state = getState(requester, identifier, timestamp, ancillaryData); return state == State.Settled || state == State.Resolved || state == State.Expired; } /** * @notice Generates stamped ancillary data in the format that it would be used in the case of a price dispute. * @param ancillaryData ancillary data of the price being requested. * @param requester sender of the initial price request. * @return the stampped ancillary bytes. */ function stampAncillaryData(bytes memory ancillaryData, address requester) public pure returns (bytes memory) { return _stampAncillaryData(ancillaryData, requester); } function _getId( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) private pure returns (bytes32) { return keccak256(abi.encodePacked(requester, identifier, timestamp, ancillaryData)); } function _settle( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) private returns (uint256 payout) { State state = getState(requester, identifier, timestamp, ancillaryData); // Set it to settled so this function can never be entered again. Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); request.settled = true; if (state == State.Expired) { // In the expiry case, just pay back the proposer's bond and final fee along with the reward. request.resolvedPrice = request.proposedPrice; payout = request.bond.add(request.finalFee).add(request.reward); request.currency.safeTransfer(request.proposer, payout); } else if (state == State.Resolved) { // In the Resolved case, pay either the disputer or the proposer the entire payout (+ bond and reward). request.resolvedPrice = _getOracle().getPrice( identifier, timestamp, _stampAncillaryData(ancillaryData, requester) ); bool disputeSuccess = request.resolvedPrice != request.proposedPrice; uint256 bond = request.bond; // Unburned portion of the loser's bond = 1 - burned bond. uint256 unburnedBond = bond.sub(_computeBurnedBond(request)); // Winner gets: // - Their bond back. // - The unburned portion of the loser's bond. // - Their final fee back. // - The request reward (if not already refunded -- if refunded, it will be set to 0). payout = bond.add(unburnedBond).add(request.finalFee).add(request.reward); request.currency.safeTransfer(disputeSuccess ? request.disputer : request.proposer, payout); } else { revert("_settle: not settleable"); } emit Settle( requester, request.proposer, request.disputer, identifier, timestamp, ancillaryData, request.resolvedPrice, payout ); // Callback. if (address(requester).isContract()) try OptimisticRequester(requester).priceSettled(identifier, timestamp, ancillaryData, request.resolvedPrice) {} catch {} } function _getRequest( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) private view returns (Request storage) { return requests[_getId(requester, identifier, timestamp, ancillaryData)]; } function _computeBurnedBond(Request storage request) private view returns (uint256) { // burnedBond = floor(bond / 2) return request.bond.div(2); } function _validateLiveness(uint256 _liveness) private pure { require(_liveness < 5200 weeks, "Liveness too large"); require(_liveness > 0, "Liveness cannot be 0"); } function _getOracle() internal view returns (OracleAncillaryInterface) { return OracleAncillaryInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getCollateralWhitelist() internal view returns (AddressWhitelist) { return AddressWhitelist(finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist)); } function _getStore() internal view returns (StoreInterface) { return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store)); } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } // Stamps the ancillary data blob with the optimistic oracle tag denoting what contract requested it. function _stampAncillaryData(bytes memory ancillaryData, address requester) internal pure returns (bytes memory) { return abi.encodePacked(ancillaryData, "OptimisticOracle", requester); } } pragma solidity ^0.6.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) 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 verify it contains contract code // 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. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @title Interface that allows financial contracts to pay oracle fees for their use of the system. */ interface StoreInterface { /** * @notice Pays Oracle fees in ETH to the store. * @dev To be used by contracts whose margin currency is ETH. */ function payOracleFees() external payable; /** * @notice Pays oracle fees in the margin currency, erc20Address, to the store. * @dev To be used if the margin currency is an ERC20 token rather than ETH. * @param erc20Address address of the ERC20 token used to pay the fee. * @param amount number of tokens to transfer. An approval for at least this amount must exist. */ function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external; /** * @notice Computes the regular oracle fees that a contract should pay for a period. * @param startTime defines the beginning time from which the fee is paid. * @param endTime end time until which the fee is paid. * @param pfc "profit from corruption", or the maximum amount of margin currency that a * token sponsor could extract from the contract through corrupting the price feed in their favor. * @return regularFee amount owed for the duration from start to end time for the given pfc. * @return latePenalty for paying the fee after the deadline. */ function computeRegularFee( uint256 startTime, uint256 endTime, FixedPoint.Unsigned calldata pfc ) external view returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty); /** * @notice Computes the final oracle fees that a contract should pay at settlement. * @param currency token used to pay the final fee. * @return finalFee amount due. */ function computeFinalFee(address currency) external view returns (FixedPoint.Unsigned memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Financial contract facing Oracle interface. * @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface. */ abstract contract OptimisticOracleInterface { // Struct representing the state of a price request. enum State { Invalid, // Never requested. Requested, // Requested, no other actions taken. Proposed, // Proposed, but not expired or disputed yet. Expired, // Proposed, not disputed, past liveness. Disputed, // Disputed, but no DVM price returned yet. Resolved, // Disputed and DVM price is available. Settled // Final price has been set in the contract (can get here from Expired or Resolved). } // Struct representing a price request. struct Request { address proposer; // Address of the proposer. address disputer; // Address of the disputer. IERC20 currency; // ERC20 token used to pay rewards and fees. bool settled; // True if the request is settled. bool refundOnDispute; // True if the requester should be refunded their reward on dispute. int256 proposedPrice; // Price that the proposer submitted. int256 resolvedPrice; // Price resolved once the request is settled. uint256 expirationTime; // Time at which the request auto-settles without a dispute. uint256 reward; // Amount of the currency to pay to the proposer on settlement. uint256 finalFee; // Final fee to pay to the Store upon request to the DVM. uint256 bond; // Bond that the proposer and disputer must pay on top of the final fee. uint256 customLiveness; // Custom liveness value set by the requester. } // This value must be <= the Voting contract's `ancillaryBytesLimit` value otherwise it is possible // that a price can be requested to this contract successfully, but cannot be disputed because the DVM refuses // to accept a price request made with ancillary data length of a certain size. uint256 public constant ancillaryBytesLimit = 8192; /** * @notice Requests a new price. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data representing additional args being passed with the price request. * @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM. * @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0, * which could make sense if the contract requests and proposes the value in the same call or * provides its own reward system. * @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay. * This can be changed with a subsequent call to setBond(). */ function requestPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, IERC20 currency, uint256 reward ) external virtual returns (uint256 totalBond); /** * @notice Set the proposal bond associated with a price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param bond custom bond amount to set. * @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be * changed again with a subsequent call to setBond(). */ function setBond( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 bond ) external virtual returns (uint256 totalBond); /** * @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller * in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's * bond, so there is still profit to be made even if the reward is refunded. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. */ function setRefundOnDispute( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual; /** * @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before * being auto-resolved. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param customLiveness new custom liveness. */ function setCustomLiveness( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 customLiveness ) external virtual; /** * @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come * from this proposal. However, any bonds are pulled from the caller. * @param proposer address to set as the proposer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePriceFor( address proposer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) public virtual returns (uint256 totalBond); /** * @notice Proposes a price value for an existing price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) external virtual returns (uint256 totalBond); /** * @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will * receive any rewards that come from this dispute. However, any bonds are pulled from the caller. * @param disputer address to set as the disputer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was value (the proposal was incorrect). */ function disputePriceFor( address disputer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public virtual returns (uint256 totalBond); /** * @notice Disputes a price value for an existing price request with an active proposal. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was valid (the proposal was incorrect). */ function disputePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual returns (uint256 totalBond); /** * @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled * or settleable. Note: this method is not view so that this call may actually settle the price request if it * hasn't been settled. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return resolved price. */ function settleAndGetPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual returns (int256); /** * @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes * the returned bonds as well as additional rewards. */ function settle( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual returns (uint256 payout); /** * @notice Gets the current data structure containing all information about a price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the Request data structure. */ function getRequest( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view virtual returns (Request memory); function getState( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view virtual returns (State); /** * @notice Checks if a given request has resolved or been settled (i.e the optimistic oracle has a price). * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the State. */ function hasPrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view virtual returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title A contract that provides modifiers to prevent reentrancy to state-changing and view-only methods. This contract * is inspired by https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/ReentrancyGuard.sol * and https://github.com/balancer-labs/balancer-core/blob/master/contracts/BPool.sol. */ contract Lockable { bool private _notEntered; constructor() internal { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _preEntranceCheck(); _preEntranceSet(); _; _postEntranceReset(); } /** * @dev Designed to prevent a view-only method from being re-entered during a call to a `nonReentrant()` state-changing method. */ modifier nonReentrantView() { _preEntranceCheck(); _; } // Internal methods are used to avoid copying the require statement's bytecode to every `nonReentrant()` method. // On entry into a function, `_preEntranceCheck()` should always be called to check if the function is being re-entered. // Then, if the function modifies state, it should call `_postEntranceSet()`, perform its logic, and then call `_postEntranceReset()`. // View-only methods can simply call `_preEntranceCheck()` to make sure that it is not being re-entered. function _preEntranceCheck() internal view { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); } function _preEntranceSet() internal { // Any calls to nonReentrant after this point will fail _notEntered = false; } function _postEntranceReset() internal { // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "./Lockable.sol"; /** * @title A contract to track a whitelist of addresses. */ contract AddressWhitelist is Ownable, Lockable { enum Status { None, In, Out } mapping(address => Status) public whitelist; address[] public whitelistIndices; event AddedToWhitelist(address indexed addedAddress); event RemovedFromWhitelist(address indexed removedAddress); /** * @notice Adds an address to the whitelist. * @param newElement the new address to add. */ function addToWhitelist(address newElement) external nonReentrant() onlyOwner { // Ignore if address is already included if (whitelist[newElement] == Status.In) { return; } // Only append new addresses to the array, never a duplicate if (whitelist[newElement] == Status.None) { whitelistIndices.push(newElement); } whitelist[newElement] = Status.In; emit AddedToWhitelist(newElement); } /** * @notice Removes an address from the whitelist. * @param elementToRemove the existing address to remove. */ function removeFromWhitelist(address elementToRemove) external nonReentrant() onlyOwner { if (whitelist[elementToRemove] != Status.Out) { whitelist[elementToRemove] = Status.Out; emit RemovedFromWhitelist(elementToRemove); } } /** * @notice Checks whether an address is on the whitelist. * @param elementToCheck the address to check. * @return True if `elementToCheck` is on the whitelist, or False. */ function isOnWhitelist(address elementToCheck) external view nonReentrantView() returns (bool) { return whitelist[elementToCheck] == Status.In; } /** * @notice Gets all addresses that are currently included in the whitelist. * @dev Note: This method skips over, but still iterates through addresses. It is possible for this call to run out * of gas if a large number of addresses have been removed. To reduce the likelihood of this unlikely scenario, we * can modify the implementation so that when addresses are removed, the last addresses in the array is moved to * the empty index. * @return activeWhitelist the list of addresses on the whitelist. */ function getWhitelist() external view nonReentrantView() returns (address[] memory activeWhitelist) { // Determine size of whitelist first uint256 activeCount = 0; for (uint256 i = 0; i < whitelistIndices.length; i++) { if (whitelist[whitelistIndices[i]] == Status.In) { activeCount++; } } // Populate whitelist activeWhitelist = new address[](activeCount); activeCount = 0; for (uint256 i = 0; i < whitelistIndices.length; i++) { address addr = whitelistIndices[i]; if (whitelist[addr] == Status.In) { activeWhitelist[activeCount] = addr; activeCount++; } } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../OptimisticOracle.sol"; // This is just a test contract to make requests to the optimistic oracle. contract OptimisticRequesterTest is OptimisticRequester { OptimisticOracle optimisticOracle; bool public shouldRevert = false; // State variables to track incoming calls. bytes32 public identifier; uint256 public timestamp; bytes public ancillaryData; uint256 public refund; int256 public price; // Implement collateralCurrency so that this contract simulates a financial contract whose collateral // token can be fetched by off-chain clients. IERC20 public collateralCurrency; // Manually set an expiration timestamp to simulate expiry price requests uint256 public expirationTimestamp; constructor(OptimisticOracle _optimisticOracle) public { optimisticOracle = _optimisticOracle; } function requestPrice( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, IERC20 currency, uint256 reward ) external { // Set collateral currency to last requested currency: collateralCurrency = currency; currency.approve(address(optimisticOracle), reward); optimisticOracle.requestPrice(_identifier, _timestamp, _ancillaryData, currency, reward); } function settleAndGetPrice( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData ) external returns (int256) { return optimisticOracle.settleAndGetPrice(_identifier, _timestamp, _ancillaryData); } function setBond( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, uint256 bond ) external { optimisticOracle.setBond(_identifier, _timestamp, _ancillaryData, bond); } function setRefundOnDispute( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData ) external { optimisticOracle.setRefundOnDispute(_identifier, _timestamp, _ancillaryData); } function setCustomLiveness( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, uint256 customLiveness ) external { optimisticOracle.setCustomLiveness(_identifier, _timestamp, _ancillaryData, customLiveness); } function setRevert(bool _shouldRevert) external { shouldRevert = _shouldRevert; } function setExpirationTimestamp(uint256 _expirationTimestamp) external { expirationTimestamp = _expirationTimestamp; } function clearState() external { delete identifier; delete timestamp; delete refund; delete price; } function priceProposed( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData ) external override { require(!shouldRevert); identifier = _identifier; timestamp = _timestamp; ancillaryData = _ancillaryData; } function priceDisputed( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, uint256 _refund ) external override { require(!shouldRevert); identifier = _identifier; timestamp = _timestamp; ancillaryData = _ancillaryData; refund = _refund; } function priceSettled( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, int256 _price ) external override { require(!shouldRevert); identifier = _identifier; timestamp = _timestamp; ancillaryData = _ancillaryData; price = _price; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/MultiRole.sol"; import "../../common/implementation/Withdrawable.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/StoreInterface.sol"; /** * @title An implementation of Store that can accept Oracle fees in ETH or any arbitrary ERC20 token. */ contract Store is StoreInterface, Withdrawable, Testable { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using FixedPoint for uint256; using SafeERC20 for IERC20; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, Withdrawer } FixedPoint.Unsigned public fixedOracleFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% Oracle fee. FixedPoint.Unsigned public weeklyDelayFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% weekly delay fee. mapping(address => FixedPoint.Unsigned) public finalFees; uint256 public constant SECONDS_PER_WEEK = 604800; /**************************************** * EVENTS * ****************************************/ event NewFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned newOracleFee); event NewWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned newWeeklyDelayFeePerSecondPerPfc); event NewFinalFee(FixedPoint.Unsigned newFinalFee); /** * @notice Construct the Store contract. */ constructor( FixedPoint.Unsigned memory _fixedOracleFeePerSecondPerPfc, FixedPoint.Unsigned memory _weeklyDelayFeePerSecondPerPfc, address _timerAddress ) public Testable(_timerAddress) { _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Owner), msg.sender); setFixedOracleFeePerSecondPerPfc(_fixedOracleFeePerSecondPerPfc); setWeeklyDelayFeePerSecondPerPfc(_weeklyDelayFeePerSecondPerPfc); } /**************************************** * ORACLE FEE CALCULATION AND PAYMENT * ****************************************/ /** * @notice Pays Oracle fees in ETH to the store. * @dev To be used by contracts whose margin currency is ETH. */ function payOracleFees() external payable override { require(msg.value > 0, "Value sent can't be zero"); } /** * @notice Pays oracle fees in the margin currency, erc20Address, to the store. * @dev To be used if the margin currency is an ERC20 token rather than ETH. * @param erc20Address address of the ERC20 token used to pay the fee. * @param amount number of tokens to transfer. An approval for at least this amount must exist. */ function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external override { IERC20 erc20 = IERC20(erc20Address); require(amount.isGreaterThan(0), "Amount sent can't be zero"); erc20.safeTransferFrom(msg.sender, address(this), amount.rawValue); } /** * @notice Computes the regular oracle fees that a contract should pay for a period. * @dev The late penalty is similar to the regular fee in that is is charged per second over the period between * startTime and endTime. * * The late penalty percentage increases over time as follows: * * - 0-1 week since startTime: no late penalty * * - 1-2 weeks since startTime: 1x late penalty percentage is applied * * - 2-3 weeks since startTime: 2x late penalty percentage is applied * * - ... * * @param startTime defines the beginning time from which the fee is paid. * @param endTime end time until which the fee is paid. * @param pfc "profit from corruption", or the maximum amount of margin currency that a * token sponsor could extract from the contract through corrupting the price feed in their favor. * @return regularFee amount owed for the duration from start to end time for the given pfc. * @return latePenalty penalty percentage, if any, for paying the fee after the deadline. */ function computeRegularFee( uint256 startTime, uint256 endTime, FixedPoint.Unsigned calldata pfc ) external view override returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty) { uint256 timeDiff = endTime.sub(startTime); // Multiply by the unscaled `timeDiff` first, to get more accurate results. regularFee = pfc.mul(timeDiff).mul(fixedOracleFeePerSecondPerPfc); // Compute how long ago the start time was to compute the delay penalty. uint256 paymentDelay = getCurrentTime().sub(startTime); // Compute the additional percentage (per second) that will be charged because of the penalty. // Note: if less than a week has gone by since the startTime, paymentDelay / SECONDS_PER_WEEK will truncate to // 0, causing no penalty to be charged. FixedPoint.Unsigned memory penaltyPercentagePerSecond = weeklyDelayFeePerSecondPerPfc.mul(paymentDelay.div(SECONDS_PER_WEEK)); // Apply the penaltyPercentagePerSecond to the payment period. latePenalty = pfc.mul(timeDiff).mul(penaltyPercentagePerSecond); } /** * @notice Computes the final oracle fees that a contract should pay at settlement. * @param currency token used to pay the final fee. * @return finalFee amount due denominated in units of `currency`. */ function computeFinalFee(address currency) external view override returns (FixedPoint.Unsigned memory) { return finalFees[currency]; } /**************************************** * ADMIN STATE MODIFYING FUNCTIONS * ****************************************/ /** * @notice Sets a new oracle fee per second. * @param newFixedOracleFeePerSecondPerPfc new fee per second charged to use the oracle. */ function setFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned memory newFixedOracleFeePerSecondPerPfc) public onlyRoleHolder(uint256(Roles.Owner)) { // Oracle fees at or over 100% don't make sense. require(newFixedOracleFeePerSecondPerPfc.isLessThan(1), "Fee must be < 100% per second."); fixedOracleFeePerSecondPerPfc = newFixedOracleFeePerSecondPerPfc; emit NewFixedOracleFeePerSecondPerPfc(newFixedOracleFeePerSecondPerPfc); } /** * @notice Sets a new weekly delay fee. * @param newWeeklyDelayFeePerSecondPerPfc fee escalation per week of late fee payment. */ function setWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned memory newWeeklyDelayFeePerSecondPerPfc) public onlyRoleHolder(uint256(Roles.Owner)) { require(newWeeklyDelayFeePerSecondPerPfc.isLessThan(1), "weekly delay fee must be < 100%"); weeklyDelayFeePerSecondPerPfc = newWeeklyDelayFeePerSecondPerPfc; emit NewWeeklyDelayFeePerSecondPerPfc(newWeeklyDelayFeePerSecondPerPfc); } /** * @notice Sets a new final fee for a particular currency. * @param currency defines the token currency used to pay the final fee. * @param newFinalFee final fee amount. */ function setFinalFee(address currency, FixedPoint.Unsigned memory newFinalFee) public onlyRoleHolder(uint256(Roles.Owner)) { finalFees[currency] = newFinalFee; emit NewFinalFee(newFinalFee); } } /** * Withdrawable contract. */ // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./MultiRole.sol"; /** * @title Base contract that allows a specific role to withdraw any ETH and/or ERC20 tokens that the contract holds. */ abstract contract Withdrawable is MultiRole { using SafeERC20 for IERC20; uint256 private roleId; /** * @notice Withdraws ETH from the contract. */ function withdraw(uint256 amount) external onlyRoleHolder(roleId) { Address.sendValue(msg.sender, amount); } /** * @notice Withdraws ERC20 tokens from the contract. * @param erc20Address ERC20 token to withdraw. * @param amount amount of tokens to withdraw. */ function withdrawErc20(address erc20Address, uint256 amount) external onlyRoleHolder(roleId) { IERC20 erc20 = IERC20(erc20Address); erc20.safeTransfer(msg.sender, amount); } /** * @notice Internal method that allows derived contracts to create a role for withdrawal. * @dev Either this method or `_setWithdrawRole` must be called by the derived class for this contract to function * properly. * @param newRoleId ID corresponding to role whose members can withdraw. * @param managingRoleId ID corresponding to managing role who can modify the withdrawable role's membership. * @param withdrawerAddress new manager of withdrawable role. */ function _createWithdrawRole( uint256 newRoleId, uint256 managingRoleId, address withdrawerAddress ) internal { roleId = newRoleId; _createExclusiveRole(newRoleId, managingRoleId, withdrawerAddress); } /** * @notice Internal method that allows derived contracts to choose the role for withdrawal. * @dev The role `setRoleId` must exist. Either this method or `_createWithdrawRole` must be * called by the derived class for this contract to function properly. * @param setRoleId ID corresponding to role whose members can withdraw. */ function _setWithdrawRole(uint256 setRoleId) internal onlyValidRole(setRoleId) { roleId = setRoleId; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../../oracle/interfaces/StoreInterface.sol"; import "../../oracle/interfaces/FinderInterface.sol"; import "../../oracle/interfaces/AdministrateeInterface.sol"; import "../../oracle/implementation/Constants.sol"; /** * @title FeePayer contract. * @notice Provides fee payment functionality for the ExpiringMultiParty contract. * contract is abstract as each derived contract that inherits `FeePayer` must implement `pfc()`. */ abstract contract FeePayer is AdministrateeInterface, Testable, Lockable { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; /**************************************** * FEE PAYER DATA STRUCTURES * ****************************************/ // The collateral currency used to back the positions in this contract. IERC20 public collateralCurrency; // Finder contract used to look up addresses for UMA system contracts. FinderInterface public finder; // Tracks the last block time when the fees were paid. uint256 private lastPaymentTime; // Tracks the cumulative fees that have been paid by the contract for use by derived contracts. // The multiplier starts at 1, and is updated by computing cumulativeFeeMultiplier * (1 - effectiveFee). // Put another way, the cumulativeFeeMultiplier is (1 - effectiveFee1) * (1 - effectiveFee2) ... // For example: // The cumulativeFeeMultiplier should start at 1. // If a 1% fee is charged, the multiplier should update to .99. // If another 1% fee is charged, the multiplier should be 0.99^2 (0.9801). FixedPoint.Unsigned public cumulativeFeeMultiplier; /**************************************** * EVENTS * ****************************************/ event RegularFeesPaid(uint256 indexed regularFee, uint256 indexed lateFee); event FinalFeesPaid(uint256 indexed amount); /**************************************** * MODIFIERS * ****************************************/ // modifier that calls payRegularFees(). modifier fees virtual { // Note: the regular fee is applied on every fee-accruing transaction, where the total change is simply the // regular fee applied linearly since the last update. This implies that the compounding rate depends on the // frequency of update transactions that have this modifier, and it never reaches the ideal of continuous // compounding. This approximate-compounding pattern is common in the Ethereum ecosystem because of the // complexity of compounding data on-chain. payRegularFees(); _; } /** * @notice Constructs the FeePayer contract. Called by child contracts. * @param _collateralAddress ERC20 token that is used as the underlying collateral for the synthetic. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( address _collateralAddress, address _finderAddress, address _timerAddress ) public Testable(_timerAddress) { collateralCurrency = IERC20(_collateralAddress); finder = FinderInterface(_finderAddress); lastPaymentTime = getCurrentTime(); cumulativeFeeMultiplier = FixedPoint.fromUnscaledUint(1); } /**************************************** * FEE PAYMENT FUNCTIONS * ****************************************/ /** * @notice Pays UMA DVM regular fees (as a % of the collateral pool) to the Store contract. * @dev These must be paid periodically for the life of the contract. If the contract has not paid its regular fee * in a week or more then a late penalty is applied which is sent to the caller. If the amount of * fees owed are greater than the pfc, then this will pay as much as possible from the available collateral. * An event is only fired if the fees charged are greater than 0. * @return totalPaid Amount of collateral that the contract paid (sum of the amount paid to the Store and caller). * This returns 0 and exit early if there is no pfc, fees were already paid during the current block, or the fee rate is 0. */ function payRegularFees() public nonReentrant() returns (FixedPoint.Unsigned memory) { uint256 time = getCurrentTime(); FixedPoint.Unsigned memory collateralPool = _pfc(); // Fetch the regular fees, late penalty and the max possible to pay given the current collateral within the contract. ( FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty, FixedPoint.Unsigned memory totalPaid ) = getOutstandingRegularFees(time); lastPaymentTime = time; // If there are no fees to pay then exit early. if (totalPaid.isEqual(0)) { return totalPaid; } emit RegularFeesPaid(regularFee.rawValue, latePenalty.rawValue); _adjustCumulativeFeeMultiplier(totalPaid, collateralPool); if (regularFee.isGreaterThan(0)) { StoreInterface store = _getStore(); collateralCurrency.safeIncreaseAllowance(address(store), regularFee.rawValue); store.payOracleFeesErc20(address(collateralCurrency), regularFee); } if (latePenalty.isGreaterThan(0)) { collateralCurrency.safeTransfer(msg.sender, latePenalty.rawValue); } return totalPaid; } /** * @notice Fetch any regular fees that the contract has pending but has not yet paid. If the fees to be paid are more * than the total collateral within the contract then the totalPaid returned is full contract collateral amount. * @dev This returns 0 and exit early if there is no pfc, fees were already paid during the current block, or the fee rate is 0. * @return regularFee outstanding unpaid regular fee. * @return latePenalty outstanding unpaid late fee for being late in previous fee payments. * @return totalPaid Amount of collateral that the contract paid (sum of the amount paid to the Store and caller). */ function getOutstandingRegularFees(uint256 time) public view returns ( FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty, FixedPoint.Unsigned memory totalPaid ) { StoreInterface store = _getStore(); FixedPoint.Unsigned memory collateralPool = _pfc(); // Exit early if there is no collateral or if fees were already paid during this block. if (collateralPool.isEqual(0) || lastPaymentTime == time) { return (regularFee, latePenalty, totalPaid); } (regularFee, latePenalty) = store.computeRegularFee(lastPaymentTime, time, collateralPool); totalPaid = regularFee.add(latePenalty); if (totalPaid.isEqual(0)) { return (regularFee, latePenalty, totalPaid); } // If the effective fees paid as a % of the pfc is > 100%, then we need to reduce it and make the contract pay // as much of the fee that it can (up to 100% of its pfc). We'll reduce the late penalty first and then the // regular fee, which has the effect of paying the store first, followed by the caller if there is any fee remaining. if (totalPaid.isGreaterThan(collateralPool)) { FixedPoint.Unsigned memory deficit = totalPaid.sub(collateralPool); FixedPoint.Unsigned memory latePenaltyReduction = FixedPoint.min(latePenalty, deficit); latePenalty = latePenalty.sub(latePenaltyReduction); deficit = deficit.sub(latePenaltyReduction); regularFee = regularFee.sub(FixedPoint.min(regularFee, deficit)); totalPaid = collateralPool; } } /** * @notice Gets the current profit from corruption for this contract in terms of the collateral currency. * @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are * expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC. * @return pfc value for equal to the current profit from corruption denominated in collateral currency. */ function pfc() external view override nonReentrantView() returns (FixedPoint.Unsigned memory) { return _pfc(); } /** * @notice Removes excess collateral balance not counted in the PfC by distributing it out pro-rata to all sponsors. * @dev Multiplying the `cumulativeFeeMultiplier` by the ratio of non-PfC-collateral :: PfC-collateral effectively * pays all sponsors a pro-rata portion of the excess collateral. * @dev This will revert if PfC is 0 and this contract's collateral balance > 0. */ function gulp() external nonReentrant() { _gulp(); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Pays UMA Oracle final fees of `amount` in `collateralCurrency` to the Store contract. Final fee is a flat fee // charged for each price request. If payer is the contract, adjusts internal bookkeeping variables. If payer is not // the contract, pulls in `amount` of collateral currency. function _payFinalFees(address payer, FixedPoint.Unsigned memory amount) internal { if (amount.isEqual(0)) { return; } if (payer != address(this)) { // If the payer is not the contract pull the collateral from the payer. collateralCurrency.safeTransferFrom(payer, address(this), amount.rawValue); } else { // If the payer is the contract, adjust the cumulativeFeeMultiplier to compensate. FixedPoint.Unsigned memory collateralPool = _pfc(); // The final fee must be < available collateral or the fee will be larger than 100%. // Note: revert reason removed to save bytecode. require(collateralPool.isGreaterThan(amount)); _adjustCumulativeFeeMultiplier(amount, collateralPool); } emit FinalFeesPaid(amount.rawValue); StoreInterface store = _getStore(); collateralCurrency.safeIncreaseAllowance(address(store), amount.rawValue); store.payOracleFeesErc20(address(collateralCurrency), amount); } function _gulp() internal { FixedPoint.Unsigned memory currentPfc = _pfc(); FixedPoint.Unsigned memory currentBalance = FixedPoint.Unsigned(collateralCurrency.balanceOf(address(this))); if (currentPfc.isLessThan(currentBalance)) { cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(currentBalance.div(currentPfc)); } } function _pfc() internal view virtual returns (FixedPoint.Unsigned memory); function _getStore() internal view returns (StoreInterface) { return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store)); } function _computeFinalFees() internal view returns (FixedPoint.Unsigned memory finalFees) { StoreInterface store = _getStore(); return store.computeFinalFee(address(collateralCurrency)); } // Returns the user's collateral minus any fees that have been subtracted since it was originally // deposited into the contract. Note: if the contract has paid fees since it was deployed, the raw // value should be larger than the returned value. function _getFeeAdjustedCollateral(FixedPoint.Unsigned memory rawCollateral) internal view returns (FixedPoint.Unsigned memory collateral) { return rawCollateral.mul(cumulativeFeeMultiplier); } // Returns the user's collateral minus any pending fees that have yet to be subtracted. function _getPendingRegularFeeAdjustedCollateral(FixedPoint.Unsigned memory rawCollateral) internal view returns (FixedPoint.Unsigned memory) { (, , FixedPoint.Unsigned memory currentTotalOutstandingRegularFees) = getOutstandingRegularFees(getCurrentTime()); if (currentTotalOutstandingRegularFees.isEqual(FixedPoint.fromUnscaledUint(0))) return rawCollateral; // Calculate the total outstanding regular fee as a fraction of the total contract PFC. FixedPoint.Unsigned memory effectiveOutstandingFee = currentTotalOutstandingRegularFees.divCeil(_pfc()); // Scale as rawCollateral* (1 - effectiveOutstandingFee) to apply the pro-rata amount to the regular fee. return rawCollateral.mul(FixedPoint.fromUnscaledUint(1).sub(effectiveOutstandingFee)); } // Converts a user-readable collateral value into a raw value that accounts for already-assessed fees. If any fees // have been taken from this contract in the past, then the raw value will be larger than the user-readable value. function _convertToRawCollateral(FixedPoint.Unsigned memory collateral) internal view returns (FixedPoint.Unsigned memory rawCollateral) { return collateral.div(cumulativeFeeMultiplier); } // Decrease rawCollateral by a fee-adjusted collateralToRemove amount. Fee adjustment scales up collateralToRemove // by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore // rawCollateral is decreased by less than expected. Because this method is usually called in conjunction with an // actual removal of collateral from this contract, return the fee-adjusted amount that the rawCollateral is // decreased by so that the caller can minimize error between collateral removed and rawCollateral debited. function _removeCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToRemove) internal returns (FixedPoint.Unsigned memory removedCollateral) { FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral); FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToRemove); rawCollateral.rawValue = rawCollateral.sub(adjustedCollateral).rawValue; removedCollateral = initialBalance.sub(_getFeeAdjustedCollateral(rawCollateral)); } // Increase rawCollateral by a fee-adjusted collateralToAdd amount. Fee adjustment scales up collateralToAdd // by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore // rawCollateral is increased by less than expected. Because this method is usually called in conjunction with an // actual addition of collateral to this contract, return the fee-adjusted amount that the rawCollateral is // increased by so that the caller can minimize error between collateral added and rawCollateral credited. // NOTE: This return value exists only for the sake of symmetry with _removeCollateral. We don't actually use it // because we are OK if more collateral is stored in the contract than is represented by rawTotalPositionCollateral. function _addCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToAdd) internal returns (FixedPoint.Unsigned memory addedCollateral) { FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral); FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToAdd); rawCollateral.rawValue = rawCollateral.add(adjustedCollateral).rawValue; addedCollateral = _getFeeAdjustedCollateral(rawCollateral).sub(initialBalance); } // Scale the cumulativeFeeMultiplier by the ratio of fees paid to the current available collateral. function _adjustCumulativeFeeMultiplier(FixedPoint.Unsigned memory amount, FixedPoint.Unsigned memory currentPfc) internal { FixedPoint.Unsigned memory effectiveFee = amount.divCeil(currentPfc); cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(FixedPoint.fromUnscaledUint(1).sub(effectiveFee)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; /** * @title Interface that all financial contracts expose to the admin. */ interface AdministrateeInterface { /** * @notice Initiates the shutdown process, in case of an emergency. */ function emergencyShutdown() external; /** * @notice A core contract method called independently or as a part of other financial contract transactions. * @dev It pays fees and moves money between margin accounts to make sure they reflect the NAV of the contract. */ function remargin() external; /** * @notice Gets the current profit from corruption for this contract in terms of the collateral currency. * @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are * expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC. * @return pfc value for equal to the current profit from corruption denominated in collateral currency. */ function pfc() external view returns (FixedPoint.Unsigned memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/interfaces/IERC20Standard.sol"; import "../../oracle/interfaces/OracleInterface.sol"; import "../../oracle/interfaces/OptimisticOracleInterface.sol"; import "../../oracle/interfaces/IdentifierWhitelistInterface.sol"; import "../../oracle/implementation/Constants.sol"; import "../common/FeePayer.sol"; import "../common/financial-product-libraries/FinancialProductLibrary.sol"; /** * @title Financial contract with priceless position management. * @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying * on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token. */ contract PricelessPositionManager is FeePayer { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; using SafeERC20 for ExpandedIERC20; using Address for address; /**************************************** * PRICELESS POSITION DATA STRUCTURES * ****************************************/ // Stores the state of the PricelessPositionManager. Set on expiration, emergency shutdown, or settlement. enum ContractState { Open, ExpiredPriceRequested, ExpiredPriceReceived } ContractState public contractState; // Represents a single sponsor's position. All collateral is held by this contract. // This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor. struct PositionData { FixedPoint.Unsigned tokensOutstanding; // Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`. uint256 withdrawalRequestPassTimestamp; FixedPoint.Unsigned withdrawalRequestAmount; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; // Tracks pending transfer position requests. A transfer position request is pending if `transferPositionRequestPassTimestamp != 0`. uint256 transferPositionRequestPassTimestamp; } // Maps sponsor addresses to their positions. Each sponsor can have only one position. mapping(address => PositionData) public positions; // Keep track of the total collateral and tokens across all positions to enable calculating the // global collateralization ratio without iterating over all positions. FixedPoint.Unsigned public totalTokensOutstanding; // Similar to the rawCollateral in PositionData, this value should not be used directly. // _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust. FixedPoint.Unsigned public rawTotalPositionCollateral; // Synthetic token created by this contract. ExpandedIERC20 public tokenCurrency; // Unique identifier for DVM price feed ticker. bytes32 public priceIdentifier; // Time that this contract expires. Should not change post-construction unless an emergency shutdown occurs. uint256 public expirationTimestamp; // Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur. // !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract. // Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests // expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent // contract is extremely risky for any sponsor or synthetic token holder for the contract. uint256 public withdrawalLiveness; // Minimum number of tokens in a sponsor's position. FixedPoint.Unsigned public minSponsorTokens; // The expiry price pulled from the DVM. FixedPoint.Unsigned public expiryPrice; // Instance of FinancialProductLibrary to provide custom price and collateral requirement transformations to extend // the functionality of the EMP to support a wider range of financial products. FinancialProductLibrary public financialProductLibrary; /**************************************** * EVENTS * ****************************************/ event RequestTransferPosition(address indexed oldSponsor); event RequestTransferPositionExecuted(address indexed oldSponsor, address indexed newSponsor); event RequestTransferPositionCanceled(address indexed oldSponsor); event Deposit(address indexed sponsor, uint256 indexed collateralAmount); event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount); event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event NewSponsor(address indexed sponsor); event EndedSponsorPosition(address indexed sponsor); event Repay(address indexed sponsor, uint256 indexed numTokensRepaid, uint256 indexed newTokenCount); event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event ContractExpired(address indexed caller); event SettleExpiredPosition( address indexed caller, uint256 indexed collateralReturned, uint256 indexed tokensBurned ); event EmergencyShutdown(address indexed caller, uint256 originalExpirationTimestamp, uint256 shutdownTimestamp); /**************************************** * MODIFIERS * ****************************************/ modifier onlyPreExpiration() { _onlyPreExpiration(); _; } modifier onlyPostExpiration() { _onlyPostExpiration(); _; } modifier onlyCollateralizedPosition(address sponsor) { _onlyCollateralizedPosition(sponsor); _; } // Check that the current state of the pricelessPositionManager is Open. // This prevents multiple calls to `expire` and `EmergencyShutdown` post expiration. modifier onlyOpenState() { _onlyOpenState(); _; } modifier noPendingWithdrawal(address sponsor) { _positionHasNoPendingWithdrawal(sponsor); _; } /** * @notice Construct the PricelessPositionManager * @dev Deployer of this contract should consider carefully which parties have ability to mint and burn * the synthetic tokens referenced by `_tokenAddress`. This contract's security assumes that no external accounts * can mint new tokens, which could be used to steal all of this contract's locked collateral. * We recommend to only use synthetic token contracts whose sole Owner role (the role capable of adding & removing roles) * is assigned to this contract, whose sole Minter role is assigned to this contract, and whose * total supply is 0 prior to construction of this contract. * @param _expirationTimestamp unix timestamp of when the contract will expire. * @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals. * @param _collateralAddress ERC20 token used as collateral for all positions. * @param _tokenAddress ERC20 token used as synthetic token. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _priceIdentifier registered in the DVM for the synthetic. * @param _minSponsorTokens minimum number of tokens that must exist at any time in a position. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. * @param _financialProductLibraryAddress Contract providing contract state transformations. */ constructor( uint256 _expirationTimestamp, uint256 _withdrawalLiveness, address _collateralAddress, address _tokenAddress, address _finderAddress, bytes32 _priceIdentifier, FixedPoint.Unsigned memory _minSponsorTokens, address _timerAddress, address _financialProductLibraryAddress ) public FeePayer(_collateralAddress, _finderAddress, _timerAddress) nonReentrant() { require(_expirationTimestamp > getCurrentTime()); require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier)); expirationTimestamp = _expirationTimestamp; withdrawalLiveness = _withdrawalLiveness; tokenCurrency = ExpandedIERC20(_tokenAddress); minSponsorTokens = _minSponsorTokens; priceIdentifier = _priceIdentifier; // Initialize the financialProductLibrary at the provided address. financialProductLibrary = FinancialProductLibrary(_financialProductLibraryAddress); } /**************************************** * POSITION FUNCTIONS * ****************************************/ /** * @notice Requests to transfer ownership of the caller's current position to a new sponsor address. * Once the request liveness is passed, the sponsor can execute the transfer and specify the new sponsor. * @dev The liveness length is the same as the withdrawal liveness. */ function requestTransferPosition() public onlyPreExpiration() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.transferPositionRequestPassTimestamp == 0); // Make sure the proposed expiration of this request is not post-expiry. uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness); require(requestPassTime < expirationTimestamp); // Update the position object for the user. positionData.transferPositionRequestPassTimestamp = requestPassTime; emit RequestTransferPosition(msg.sender); } /** * @notice After a passed transfer position request (i.e., by a call to `requestTransferPosition` and waiting * `withdrawalLiveness`), transfers ownership of the caller's current position to `newSponsorAddress`. * @dev Transferring positions can only occur if the recipient does not already have a position. * @param newSponsorAddress is the address to which the position will be transferred. */ function transferPositionPassedRequest(address newSponsorAddress) public onlyPreExpiration() noPendingWithdrawal(msg.sender) nonReentrant() { require( _getFeeAdjustedCollateral(positions[newSponsorAddress].rawCollateral).isEqual( FixedPoint.fromUnscaledUint(0) ) ); PositionData storage positionData = _getPositionData(msg.sender); require( positionData.transferPositionRequestPassTimestamp != 0 && positionData.transferPositionRequestPassTimestamp <= getCurrentTime() ); // Reset transfer request. positionData.transferPositionRequestPassTimestamp = 0; positions[newSponsorAddress] = positionData; delete positions[msg.sender]; emit RequestTransferPositionExecuted(msg.sender, newSponsorAddress); emit NewSponsor(newSponsorAddress); emit EndedSponsorPosition(msg.sender); } /** * @notice Cancels a pending transfer position request. */ function cancelTransferPosition() external onlyPreExpiration() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.transferPositionRequestPassTimestamp != 0); emit RequestTransferPositionCanceled(msg.sender); // Reset withdrawal request. positionData.transferPositionRequestPassTimestamp = 0; } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param sponsor the sponsor to credit the deposit to. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(sponsor) fees() nonReentrant() { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(sponsor); // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); emit Deposit(sponsor, collateralAmount.rawValue); // Move collateral currency from sender to contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function deposit(FixedPoint.Unsigned memory collateralAmount) public { // This is just a thin wrapper over depositTo that specified the sender as the sponsor. depositTo(msg.sender, collateralAmount); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor. * @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization * ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss. * @param collateralAmount is the amount of collateral to withdraw. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdraw(FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(msg.sender); // Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure // position remains above the GCR within the withdrawal. If this is not the case the caller must submit a request. amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount); emit Withdrawal(msg.sender, amountWithdrawn.rawValue); // Move collateral currency from contract to sender. // Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees) // instead of the user requested amount. This eliminates precision loss that could occur // where the user withdraws more collateral than rawCollateral is decremented by. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); } /** * @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw` from their position. * @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated. * @param collateralAmount the amount of collateral requested to withdraw */ function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(msg.sender) nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require( collateralAmount.isGreaterThan(0) && collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral)) ); // Make sure the proposed expiration of this request is not post-expiry. uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness); require(requestPassTime < expirationTimestamp); // Update the position object for the user. positionData.withdrawalRequestPassTimestamp = requestPassTime; positionData.withdrawalRequestAmount = collateralAmount; emit RequestWithdrawal(msg.sender, collateralAmount.rawValue); } /** * @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting * `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency. * @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested * amount exceeds the collateral in the position (due to paying fees). * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdrawPassedRequest() external onlyPreExpiration() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require( positionData.withdrawalRequestPassTimestamp != 0 && positionData.withdrawalRequestPassTimestamp <= getCurrentTime() ); // If withdrawal request amount is > position collateral, then withdraw the full collateral amount. // This situation is possible due to fees charged since the withdrawal was originally requested. FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount; if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) { amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral); } // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); // Transfer approved withdrawal amount from the contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue); } /** * @notice Cancels a pending withdrawal request. */ function cancelWithdrawal() external nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.withdrawalRequestPassTimestamp != 0); emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); } /** * @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount` into the sponsor's position and mints `numTokens` of `tokenCurrency`. * @dev Reverts if minting these tokens would put the position's collateralization ratio below the * global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of * `collateralCurrency`. * @dev This contract must have the Minter role for the `tokenCurrency`. * @param collateralAmount is the number of collateral tokens to collateralize the position with * @param numTokens is the number of tokens to mint from the position. */ function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) public onlyPreExpiration() fees() nonReentrant() { PositionData storage positionData = positions[msg.sender]; // Either the new create ratio or the resultant position CR must be above the current GCR. require( (_checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount), positionData.tokensOutstanding.add(numTokens) ) || _checkCollateralization(collateralAmount, numTokens)), "Insufficient collateral" ); require(positionData.withdrawalRequestPassTimestamp == 0, "Pending withdrawal"); if (positionData.tokensOutstanding.isEqual(0)) { require(numTokens.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); emit NewSponsor(msg.sender); } // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); // Add the number of tokens created to the position's outstanding tokens. positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens); totalTokensOutstanding = totalTokensOutstanding.add(numTokens); emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue); // Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); require(tokenCurrency.mint(msg.sender, numTokens.rawValue)); } /** * @notice Burns `numTokens` of `tokenCurrency` to decrease sponsors position size, without sending back `collateralCurrency`. * This is done by a sponsor to increase position CR. Resulting size is bounded by minSponsorTokens. * @dev Can only be called by token sponsor. This contract must be approved to spend `numTokens` of `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt from the sponsor's debt position. */ function repay(FixedPoint.Unsigned memory numTokens) public onlyPreExpiration() noPendingWithdrawal(msg.sender) fees() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding)); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens)); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); emit Repay(msg.sender, numTokens.rawValue, newTokenCount.rawValue); // Transfer the tokens back from the sponsor and burn them. tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`. * @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral * in order to account for precision loss. This contract must be approved to spend at least `numTokens` of * `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function redeem(FixedPoint.Unsigned memory numTokens) public noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require(!numTokens.isGreaterThan(positionData.tokensOutstanding)); FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding); FixedPoint.Unsigned memory collateralRedeemed = fractionRedeemed.mul(_getFeeAdjustedCollateral(positionData.rawCollateral)); // If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize. if (positionData.tokensOutstanding.isEqual(numTokens)) { amountWithdrawn = _deleteSponsorPosition(msg.sender); } else { // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); } emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue); // Transfer collateral from contract to caller and burn callers synthetic tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice After a contract has passed expiry all token holders can redeem their tokens for underlying at the * prevailing price defined by the DVM from the `expire` function. * @dev This burns all tokens from the caller of `tokenCurrency` and sends back the proportional amount of * `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for * precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance. * @dev This contract must have the Burner role for the `tokenCurrency`. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function settleExpired() external onlyPostExpiration() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { // If the contract state is open and onlyPostExpiration passed then `expire()` has not yet been called. require(contractState != ContractState.Open, "Unexpired position"); // Get the current settlement price and store it. If it is not resolved will revert. if (contractState != ContractState.ExpiredPriceReceived) { expiryPrice = _getOraclePriceExpiration(expirationTimestamp); contractState = ContractState.ExpiredPriceReceived; } // Get caller's tokens balance and calculate amount of underlying entitled to them. FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender)); FixedPoint.Unsigned memory totalRedeemableCollateral = tokensToRedeem.mul(expiryPrice); // If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt. PositionData storage positionData = positions[msg.sender]; if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) { // Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying. FixedPoint.Unsigned memory tokenDebtValueInCollateral = positionData.tokensOutstanding.mul(expiryPrice); FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral); // If the debt is greater than the remaining collateral, they cannot redeem anything. FixedPoint.Unsigned memory positionRedeemableCollateral = tokenDebtValueInCollateral.isLessThan(positionCollateral) ? positionCollateral.sub(tokenDebtValueInCollateral) : FixedPoint.Unsigned(0); // Add the number of redeemable tokens for the sponsor to their total redeemable collateral. totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral); // Reset the position state as all the value has been removed after settlement. delete positions[msg.sender]; emit EndedSponsorPosition(msg.sender); } // Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized, // the caller will get as much collateral as the contract can pay out. FixedPoint.Unsigned memory payout = FixedPoint.min(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalRedeemableCollateral); // Decrement total contract collateral and outstanding debt. amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout); totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem); emit SettleExpiredPosition(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue); // Transfer tokens & collateral and burn the redeemed tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue); tokenCurrency.burn(tokensToRedeem.rawValue); } /**************************************** * GLOBAL STATE FUNCTIONS * ****************************************/ /** * @notice Locks contract state in expired and requests oracle price. * @dev this function can only be called once the contract is expired and can't be re-called. */ function expire() external onlyPostExpiration() onlyOpenState() fees() nonReentrant() { contractState = ContractState.ExpiredPriceRequested; // Final fees do not need to be paid when sending a request to the optimistic oracle. _requestOraclePriceExpiration(expirationTimestamp); emit ContractExpired(msg.sender); } /** * @notice Premature contract settlement under emergency circumstances. * @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`. * Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal * to occur via the standard `settleExpired` function. Contract state is set to `ExpiredPriceRequested` * which prevents re-entry into this function or the `expire` function. No fees are paid when calling * `emergencyShutdown` as the governor who would call the function would also receive the fees. */ function emergencyShutdown() external override onlyPreExpiration() onlyOpenState() nonReentrant() { require(msg.sender == _getFinancialContractsAdminAddress()); contractState = ContractState.ExpiredPriceRequested; // Expiratory time now becomes the current time (emergency shutdown time). // Price requested at this time stamp. `settleExpired` can now withdraw at this timestamp. uint256 oldExpirationTimestamp = expirationTimestamp; expirationTimestamp = getCurrentTime(); _requestOraclePriceExpiration(expirationTimestamp); emit EmergencyShutdown(msg.sender, oldExpirationTimestamp, expirationTimestamp); } /** * @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they * reflect the NAV of the contract. However, this functionality doesn't apply to this contract. * @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable * only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing. */ function remargin() external override onlyPreExpiration() nonReentrant() { return; } /** * @notice Accessor method for a sponsor's collateral. * @dev This is necessary because the struct returned by the positions() method shows * rawCollateral, which isn't a user-readable value. * @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for * example if the `lastPaymentTime != currentTime`. * @param sponsor address whose collateral amount is retrieved. * @return collateralAmount amount of collateral within a sponsors position. */ function getCollateral(address sponsor) external view nonReentrantView() returns (FixedPoint.Unsigned memory) { // Note: do a direct access to avoid the validity check. return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral)); } /** * @notice Accessor method for the total collateral stored within the PricelessPositionManager. * @return totalCollateral amount of all collateral within the Expiring Multi Party Contract. * @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for * example if the `lastPaymentTime != currentTime`. */ function totalPositionCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } /** * @notice Accessor method to compute a transformed price using the finanicalProductLibrary specified at contract * deployment. If no library was provided then no modification to the price is done. * @param price input price to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedPrice price with the transformation function applied to it. * @dev This method should never revert. */ function transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _transformPrice(price, requestTime); } /** * @notice Accessor method to compute a transformed price identifier using the finanicalProductLibrary specified * at contract deployment. If no library was provided then no modification to the identifier is done. * @param requestTime timestamp the identifier is to be used at. * @return transformedPrice price with the transformation function applied to it. * @dev This method should never revert. */ function transformPriceIdentifier(uint256 requestTime) public view nonReentrantView() returns (bytes32) { return _transformPriceIdentifier(requestTime); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire // position if the entire position is being removed. Does not make any external transfers. function _reduceSponsorPosition( address sponsor, FixedPoint.Unsigned memory tokensToRemove, FixedPoint.Unsigned memory collateralToRemove, FixedPoint.Unsigned memory withdrawalAmountToRemove ) internal { PositionData storage positionData = _getPositionData(sponsor); // If the entire position is being removed, delete it instead. if ( tokensToRemove.isEqual(positionData.tokensOutstanding) && _getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove) ) { _deleteSponsorPosition(sponsor); return; } // Decrement the sponsor's collateral and global collateral amounts. _decrementCollateralBalances(positionData, collateralToRemove); // Ensure that the sponsor will meet the min position size after the reduction. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(tokensToRemove); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); positionData.tokensOutstanding = newTokenCount; // Decrement the position's withdrawal amount. positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove); // Decrement the total outstanding tokens in the overall contract. totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove); } // Deletes a sponsor's position and updates global counters. Does not make any external transfers. function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) { PositionData storage positionToLiquidate = _getPositionData(sponsor); FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral); // Remove the collateral and outstanding from the overall total position. FixedPoint.Unsigned memory remainingRawCollateral = positionToLiquidate.rawCollateral; rawTotalPositionCollateral = rawTotalPositionCollateral.sub(remainingRawCollateral); totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding); // Reset the sponsors position to have zero outstanding and collateral. delete positions[sponsor]; emit EndedSponsorPosition(sponsor); // Return fee-adjusted amount of collateral deleted from position. return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalPositionCollateral); } function _getPositionData(address sponsor) internal view onlyCollateralizedPosition(sponsor) returns (PositionData storage) { return positions[sponsor]; } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } function _getOracle() internal view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getOptimisticOracle() internal view returns (OptimisticOracleInterface) { return OptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.OptimisticOracle)); } function _getFinancialContractsAdminAddress() internal view returns (address) { return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin); } // Requests a price for transformed `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePriceExpiration(uint256 requestedTime) internal { OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); // Increase token allowance to enable the optimistic oracle reward transfer. FixedPoint.Unsigned memory reward = _computeFinalFees(); collateralCurrency.safeIncreaseAllowance(address(optimisticOracle), reward.rawValue); optimisticOracle.requestPrice( _transformPriceIdentifier(requestedTime), requestedTime, _getAncillaryData(), collateralCurrency, reward.rawValue // Reward is equal to the final fee ); // Apply haircut to all sponsors by decrementing the cumlativeFeeMultiplier by the amount lost from the final fee. _adjustCumulativeFeeMultiplier(reward, _pfc()); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePriceExpiration(uint256 requestedTime) internal returns (FixedPoint.Unsigned memory) { // Create an instance of the oracle and get the price. If the price is not resolved revert. OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); require( optimisticOracle.hasPrice( address(this), _transformPriceIdentifier(requestedTime), requestedTime, _getAncillaryData() ) ); int256 optimisticOraclePrice = optimisticOracle.settleAndGetPrice( _transformPriceIdentifier(requestedTime), requestedTime, _getAncillaryData() ); // For now we don't want to deal with negative prices in positions. if (optimisticOraclePrice < 0) { optimisticOraclePrice = 0; } return _transformPrice(FixedPoint.Unsigned(uint256(optimisticOraclePrice)), requestedTime); } // Requests a price for transformed `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePriceLiquidation(uint256 requestedTime) internal { OracleInterface oracle = _getOracle(); oracle.requestPrice(_transformPriceIdentifier(requestedTime), requestedTime); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePriceLiquidation(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) { // Create an instance of the oracle and get the price. If the price is not resolved revert. OracleInterface oracle = _getOracle(); require(oracle.hasPrice(_transformPriceIdentifier(requestedTime), requestedTime), "Unresolved oracle price"); int256 oraclePrice = oracle.getPrice(_transformPriceIdentifier(requestedTime), requestedTime); // For now we don't want to deal with negative prices in positions. if (oraclePrice < 0) { oraclePrice = 0; } return _transformPrice(FixedPoint.Unsigned(uint256(oraclePrice)), requestedTime); } // Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0. function _resetWithdrawalRequest(PositionData storage positionData) internal { positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0); positionData.withdrawalRequestPassTimestamp = 0; } // Ensure individual and global consistency when increasing collateral balances. Returns the change to the position. function _incrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _addCollateral(positionData.rawCollateral, collateralAmount); return _addCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the // position. We elect to return the amount that the global collateral is decreased by, rather than the individual // position's collateral, because we need to maintain the invariant that the global collateral is always // <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn. function _decrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position. // This function is similar to the _decrementCollateralBalances function except this function checks position GCR // between the decrements. This ensures that collateral removal will not leave the position undercollateralized. function _decrementCollateralBalancesCheckGCR( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); require(_checkPositionCollateralization(positionData), "CR below GCR"); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _onlyOpenState() internal view { require(contractState == ContractState.Open, "Contract state is not OPEN"); } function _onlyPreExpiration() internal view { require(getCurrentTime() < expirationTimestamp, "Only callable pre-expiry"); } function _onlyPostExpiration() internal view { require(getCurrentTime() >= expirationTimestamp, "Only callable post-expiry"); } function _onlyCollateralizedPosition(address sponsor) internal view { require( _getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0), "Position has no collateral" ); } // Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the // `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral // or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`. function _positionHasNoPendingWithdrawal(address sponsor) internal view { require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0, "Pending withdrawal"); } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) { return _checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral), positionData.tokensOutstanding ); } // Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global // collateralization ratio. function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private view returns (bool) { FixedPoint.Unsigned memory global = _getCollateralizationRatio(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding); FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens); return !global.isGreaterThan(thisChange); } function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private pure returns (FixedPoint.Unsigned memory ratio) { if (!numTokens.isGreaterThan(0)) { return FixedPoint.fromUnscaledUint(0); } else { return collateral.div(numTokens); } } // IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method, // which is possible since the method is only an OPTIONAL method in the ERC20 standard: // https://eips.ethereum.org/EIPS/eip-20#methods. function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) { try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) { return _decimals; } catch { return 18; } } function _transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime) internal view returns (FixedPoint.Unsigned memory) { if (!address(financialProductLibrary).isContract()) return price; try financialProductLibrary.transformPrice(price, requestTime) returns ( FixedPoint.Unsigned memory transformedPrice ) { return transformedPrice; } catch { return price; } } function _transformPriceIdentifier(uint256 requestTime) internal view returns (bytes32) { if (!address(financialProductLibrary).isContract()) return priceIdentifier; try financialProductLibrary.transformPriceIdentifier(priceIdentifier, requestTime) returns ( bytes32 transformedIdentifier ) { return transformedIdentifier; } catch { return priceIdentifier; } } function _getAncillaryData() internal view returns (bytes memory) { // Note: when ancillary data is passed to the optimistic oracle, it should be tagged with the token address // whose funding rate it's trying to get. return abi.encodePacked(address(tokenCurrency)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ERC20 interface that includes the decimals read only method. */ interface IERC20Standard is IERC20 { /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should be displayed to a user as `5,05` * (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between Ether and Wei. This is the value * {ERC20} uses, unless {_setupDecimals} is called. * * 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() external view returns (uint8); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../../common/implementation/FixedPoint.sol"; interface ExpiringContractInterface { function expirationTimestamp() external view returns (uint256); } /** * @title Financial product library contract * @notice Provides price and collateral requirement transformation interfaces that can be overridden by custom * Financial product library implementations. */ abstract contract FinancialProductLibrary { using FixedPoint for FixedPoint.Unsigned; /** * @notice Transforms a given oracle price using the financial product libraries transformation logic. * @param oraclePrice input price returned by the DVM to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedOraclePrice input oraclePrice with the transformation function applied. */ function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view virtual returns (FixedPoint.Unsigned memory) { return oraclePrice; } /** * @notice Transforms a given collateral requirement using the financial product libraries transformation logic. * @param oraclePrice input price returned by DVM used to transform the collateral requirement. * @param collateralRequirement input collateral requirement to be transformed. * @return transformedCollateralRequirement input collateral requirement with the transformation function applied. */ function transformCollateralRequirement( FixedPoint.Unsigned memory oraclePrice, FixedPoint.Unsigned memory collateralRequirement ) public view virtual returns (FixedPoint.Unsigned memory) { return collateralRequirement; } /** * @notice Transforms a given price identifier using the financial product libraries transformation logic. * @param priceIdentifier input price identifier defined for the financial contract. * @param requestTime timestamp the identifier is to be used at. EG the time that a price request would be sent using this identifier. * @return transformedPriceIdentifier input price identifier with the transformation function applied. */ function transformPriceIdentifier(bytes32 priceIdentifier, uint256 requestTime) public view virtual returns (bytes32) { return priceIdentifier; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../common/financial-product-libraries/FinancialProductLibrary.sol"; // Implements a simple FinancialProductLibrary to test price and collateral requirement transoformations. contract FinancialProductLibraryTest is FinancialProductLibrary { FixedPoint.Unsigned public priceTransformationScalar; FixedPoint.Unsigned public collateralRequirementTransformationScalar; bytes32 public transformedPriceIdentifier; bool public shouldRevert; constructor( FixedPoint.Unsigned memory _priceTransformationScalar, FixedPoint.Unsigned memory _collateralRequirementTransformationScalar, bytes32 _transformedPriceIdentifier ) public { priceTransformationScalar = _priceTransformationScalar; collateralRequirementTransformationScalar = _collateralRequirementTransformationScalar; transformedPriceIdentifier = _transformedPriceIdentifier; } // Set the mocked methods to revert to test failed library computation. function setShouldRevert(bool _shouldRevert) public { shouldRevert = _shouldRevert; } // Create a simple price transformation function that scales the input price by the scalar for testing. function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view override returns (FixedPoint.Unsigned memory) { require(!shouldRevert, "set to always reverts"); return oraclePrice.mul(priceTransformationScalar); } // Create a simple collateral requirement transformation that doubles the input collateralRequirement. function transformCollateralRequirement( FixedPoint.Unsigned memory price, FixedPoint.Unsigned memory collateralRequirement ) public view override returns (FixedPoint.Unsigned memory) { require(!shouldRevert, "set to always reverts"); return collateralRequirement.mul(collateralRequirementTransformationScalar); } // Create a simple transformPriceIdentifier function that returns the transformed price identifier. function transformPriceIdentifier(bytes32 priceIdentifier, uint256 requestTime) public view override returns (bytes32) { require(!shouldRevert, "set to always reverts"); return transformedPriceIdentifier; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/Testable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../common/financial-product-libraries/FinancialProductLibrary.sol"; contract ExpiringMultiPartyMock is Testable { using FixedPoint for FixedPoint.Unsigned; FinancialProductLibrary public financialProductLibrary; uint256 public expirationTimestamp; FixedPoint.Unsigned public collateralRequirement; bytes32 public priceIdentifier; constructor( address _financialProductLibraryAddress, uint256 _expirationTimestamp, FixedPoint.Unsigned memory _collateralRequirement, bytes32 _priceIdentifier, address _timerAddress ) public Testable(_timerAddress) { expirationTimestamp = _expirationTimestamp; collateralRequirement = _collateralRequirement; financialProductLibrary = FinancialProductLibrary(_financialProductLibraryAddress); priceIdentifier = _priceIdentifier; } function transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime) public view returns (FixedPoint.Unsigned memory) { if (address(financialProductLibrary) == address(0)) return price; try financialProductLibrary.transformPrice(price, requestTime) returns ( FixedPoint.Unsigned memory transformedPrice ) { return transformedPrice; } catch { return price; } } function transformCollateralRequirement(FixedPoint.Unsigned memory price) public view returns (FixedPoint.Unsigned memory) { if (address(financialProductLibrary) == address(0)) return collateralRequirement; try financialProductLibrary.transformCollateralRequirement(price, collateralRequirement) returns ( FixedPoint.Unsigned memory transformedCollateralRequirement ) { return transformedCollateralRequirement; } catch { return collateralRequirement; } } function transformPriceIdentifier(uint256 requestTime) public view returns (bytes32) { if (address(financialProductLibrary) == address(0)) return priceIdentifier; try financialProductLibrary.transformPriceIdentifier(priceIdentifier, requestTime) returns ( bytes32 transformedIdentifier ) { return transformedIdentifier; } catch { return priceIdentifier; } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/VotingAncillaryInterface.sol"; // A mock oracle used for testing. Exports the voting & oracle interfaces and events that contain ancillary data. abstract contract VotingAncillaryInterfaceTesting is OracleAncillaryInterface, VotingAncillaryInterface, Testable { using FixedPoint for FixedPoint.Unsigned; // Events, data structures and functions not exported in the base interfaces, used for testing. event VoteCommitted( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData ); event EncryptedVote( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, bytes encryptedVote ); event VoteRevealed( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData, uint256 numTokens ); event RewardsRetrieved( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, uint256 numTokens ); event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time); event PriceResolved( uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData ); struct Round { uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken. FixedPoint.Unsigned inflationRate; // Inflation rate set for this round. FixedPoint.Unsigned gatPercentage; // Gat rate set for this round. uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until. } // Represents the status a price request has. enum RequestStatus { NotRequested, // Was never requested. Active, // Is being voted on in the current round. Resolved, // Was resolved in a previous round. Future // Is scheduled to be voted on in a future round. } // Only used as a return value in view methods -- never stored in the contract. struct RequestState { RequestStatus status; uint256 lastVotingRound; } function rounds(uint256 roundId) public view virtual returns (Round memory); function getPriceRequestStatuses(VotingAncillaryInterface.PendingRequestAncillary[] memory requests) public view virtual returns (RequestState[] memory); function getPendingPriceRequestsArray() external view virtual returns (bytes32[] memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/MultiRole.sol"; import "../../common/implementation/Withdrawable.sol"; import "../interfaces/VotingAncillaryInterface.sol"; import "../interfaces/FinderInterface.sol"; import "./Constants.sol"; /** * @title Proxy to allow voting from another address. * @dev Allows a UMA token holder to designate another address to vote on their behalf. * Each voter must deploy their own instance of this contract. */ contract DesignatedVoting is Withdrawable { /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, // Can set the Voter role. Is also permanently permissioned as the minter role. Voter // Can vote through this contract. } // Reference to the UMA Finder contract, allowing Voting upgrades to be performed // without requiring any calls to this contract. FinderInterface private finder; /** * @notice Construct the DesignatedVoting contract. * @param finderAddress keeps track of all contracts within the system based on their interfaceName. * @param ownerAddress address of the owner of the DesignatedVoting contract. * @param voterAddress address to which the owner has delegated their voting power. */ constructor( address finderAddress, address ownerAddress, address voterAddress ) public { _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), ownerAddress); _createExclusiveRole(uint256(Roles.Voter), uint256(Roles.Owner), voterAddress); _setWithdrawRole(uint256(Roles.Owner)); finder = FinderInterface(finderAddress); } /**************************************** * VOTING AND REWARD FUNCTIONALITY * ****************************************/ /** * @notice Forwards a commit to Voting. * @param identifier uniquely identifies the feed for this vote. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price being voted on. * @param hash the keccak256 hash of the price you want to vote for and a random integer salt value. */ function commitVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash ) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().commitVote(identifier, time, ancillaryData, hash); } /** * @notice Forwards a batch commit to Voting. * @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(VotingAncillaryInterface.CommitmentAncillary[] calldata commits) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().batchCommit(commits); } /** * @notice Forwards a reveal to Voting. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price being voted on. * @param price used along with the `salt` to produce the `hash` during the commit phase. * @param salt used along with the `price` to produce the `hash` during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, bytes memory ancillaryData, int256 salt ) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().revealVote(identifier, time, price, ancillaryData, salt); } /** * @notice Forwards a batch reveal to Voting. * @param reveals is an array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(VotingAncillaryInterface.RevealAncillary[] calldata reveals) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().batchReveal(reveals); } /** * @notice Forwards a reward retrieval to Voting. * @dev Rewards are added to the tokens already held by this contract. * @param roundId defines the round from which voting rewards will be retrieved from. * @param toRetrieve an array of PendingRequests which rewards are retrieved from. * @return amount of rewards that the user should receive. */ function retrieveRewards(uint256 roundId, VotingAncillaryInterface.PendingRequestAncillary[] memory toRetrieve) public onlyRoleHolder(uint256(Roles.Voter)) returns (FixedPoint.Unsigned memory) { return _getVotingAddress().retrieveRewards(address(this), roundId, toRetrieve); } function _getVotingAddress() private view returns (VotingAncillaryInterface) { return VotingAncillaryInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/Withdrawable.sol"; import "./DesignatedVoting.sol"; /** * @title Factory to deploy new instances of DesignatedVoting and look up previously deployed instances. * @dev Allows off-chain infrastructure to look up a hot wallet's deployed DesignatedVoting contract. */ contract DesignatedVotingFactory is Withdrawable { /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Withdrawer // Can withdraw any ETH or ERC20 sent accidentally to this contract. } address private finder; mapping(address => DesignatedVoting) public designatedVotingContracts; /** * @notice Construct the DesignatedVotingFactory contract. * @param finderAddress keeps track of all contracts within the system based on their interfaceName. */ constructor(address finderAddress) public { finder = finderAddress; _createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Withdrawer), msg.sender); } /** * @notice Deploys a new `DesignatedVoting` contract. * @param ownerAddress defines who will own the deployed instance of the designatedVoting contract. * @return designatedVoting a new DesignatedVoting contract. */ function newDesignatedVoting(address ownerAddress) external returns (DesignatedVoting) { DesignatedVoting designatedVoting = new DesignatedVoting(finder, ownerAddress, msg.sender); designatedVotingContracts[msg.sender] = designatedVoting; return designatedVoting; } /** * @notice Associates a `DesignatedVoting` instance with `msg.sender`. * @param designatedVotingAddress address to designate voting to. * @dev This is generally only used if the owner of a `DesignatedVoting` contract changes their `voter` * address and wants that reflected here. */ function setDesignatedVoting(address designatedVotingAddress) external { designatedVotingContracts[msg.sender] = DesignatedVoting(designatedVotingAddress); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/Withdrawable.sol"; // WithdrawableTest is derived from the abstract contract Withdrawable for testing purposes. contract WithdrawableTest is Withdrawable { enum Roles { Governance, Withdraw } // solhint-disable-next-line no-empty-blocks constructor() public { _createExclusiveRole(uint256(Roles.Governance), uint256(Roles.Governance), msg.sender); _createWithdrawRole(uint256(Roles.Withdraw), uint256(Roles.Governance), msg.sender); } function pay() external payable { require(msg.value > 0); } function setInternalWithdrawRole(uint256 setRoleId) public { _setWithdrawRole(setRoleId); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; /** * @title An implementation of ERC20 with the same interface as the Compound project's testnet tokens (mainly DAI) * @dev This contract can be deployed or the interface can be used to communicate with Compound's ERC20 tokens. Note: * this token should never be used to store real value since it allows permissionless minting. */ contract TestnetERC20 is ERC20 { /** * @notice Constructs the TestnetERC20. * @param _name The name which describes the new token. * @param _symbol The ticker abbreviation of the name. Ideally < 5 chars. * @param _decimals The number of decimals to define token precision. */ constructor( string memory _name, string memory _symbol, uint8 _decimals ) public ERC20(_name, _symbol) { _setupDecimals(_decimals); } // Sample token information. /** * @notice Mints value tokens to the owner address. * @param ownerAddress the address to mint to. * @param value the amount of tokens to mint. */ function allocateTo(address ownerAddress, uint256 value) external { _mint(ownerAddress, value); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../interfaces/IdentifierWhitelistInterface.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title Stores a whitelist of supported identifiers that the oracle can provide prices for. */ contract IdentifierWhitelist is IdentifierWhitelistInterface, Ownable { /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ mapping(bytes32 => bool) private supportedIdentifiers; /**************************************** * EVENTS * ****************************************/ event SupportedIdentifierAdded(bytes32 indexed identifier); event SupportedIdentifierRemoved(bytes32 indexed identifier); /**************************************** * ADMIN STATE MODIFYING FUNCTIONS * ****************************************/ /** * @notice Adds the provided identifier as a supported identifier. * @dev Price requests using this identifier will succeed after this call. * @param identifier unique UTF-8 representation for the feed being added. Eg: BTC/USD. */ function addSupportedIdentifier(bytes32 identifier) external override onlyOwner { if (!supportedIdentifiers[identifier]) { supportedIdentifiers[identifier] = true; emit SupportedIdentifierAdded(identifier); } } /** * @notice Removes the identifier from the whitelist. * @dev Price requests using this identifier will no longer succeed after this call. * @param identifier unique UTF-8 representation for the feed being removed. Eg: BTC/USD. */ function removeSupportedIdentifier(bytes32 identifier) external override onlyOwner { if (supportedIdentifiers[identifier]) { supportedIdentifiers[identifier] = false; emit SupportedIdentifierRemoved(identifier); } } /**************************************** * WHITELIST GETTERS FUNCTIONS * ****************************************/ /** * @notice Checks whether an identifier is on the whitelist. * @param identifier unique UTF-8 representation for the feed being queried. Eg: BTC/USD. * @return bool if the identifier is supported (or not). */ function isIdentifierSupported(bytes32 identifier) external view override returns (bool) { return supportedIdentifiers[identifier]; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../interfaces/AdministrateeInterface.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title Admin for financial contracts in the UMA system. * @dev Allows appropriately permissioned admin roles to interact with financial contracts. */ contract FinancialContractsAdmin is Ownable { /** * @notice Calls emergency shutdown on the provided financial contract. * @param financialContract address of the FinancialContract to be shut down. */ function callEmergencyShutdown(address financialContract) external onlyOwner { AdministrateeInterface administratee = AdministrateeInterface(financialContract); administratee.emergencyShutdown(); } /** * @notice Calls remargin on the provided financial contract. * @param financialContract address of the FinancialContract to be remargined. */ function callRemargin(address financialContract) external onlyOwner { AdministrateeInterface administratee = AdministrateeInterface(financialContract); administratee.remargin(); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../interfaces/AdministrateeInterface.sol"; // A mock implementation of AdministrateeInterface, taking the place of a financial contract. contract MockAdministratee is AdministrateeInterface { uint256 public timesRemargined; uint256 public timesEmergencyShutdown; function remargin() external override { timesRemargined++; } function emergencyShutdown() external override { timesEmergencyShutdown++; } function pfc() external view override returns (FixedPoint.Unsigned memory) { return FixedPoint.fromUnscaledUint(0); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/cryptography/MerkleProof.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * Inspired by: * - https://github.com/pie-dao/vested-token-migration-app * - https://github.com/Uniswap/merkle-distributor * - https://github.com/balancer-labs/erc20-redeemable * * @title MerkleDistributor contract. * @notice Allows an owner to distribute any reward ERC20 to claimants according to Merkle roots. The owner can specify * multiple Merkle roots distributions with customized reward currencies. * @dev The Merkle trees are not validated in any way, so the system assumes the contract owner behaves honestly. */ contract MerkleDistributor is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // A Window maps a Merkle root to a reward token address. struct Window { // Merkle root describing the distribution. bytes32 merkleRoot; // Currency in which reward is processed. IERC20 rewardToken; // IPFS hash of the merkle tree. Can be used to independently fetch recipient proofs and tree. Note that the canonical // data type for storing an IPFS hash is a multihash which is the concatenation of <varint hash function code> // <varint digest size in bytes><hash function output>. We opted to store this in a string type to make it easier // for users to query the ipfs data without needing to reconstruct the multihash. to view the IPFS data simply // go to https://cloudflare-ipfs.com/ipfs/<IPFS-HASH>. string ipfsHash; } // Represents an account's claim for `amount` within the Merkle root located at the `windowIndex`. struct Claim { uint256 windowIndex; uint256 amount; uint256 accountIndex; // Used only for bitmap. Assumed to be unique for each claim. address account; bytes32[] merkleProof; } // Windows are mapped to arbitrary indices. mapping(uint256 => Window) public merkleWindows; // Index of next created Merkle root. uint256 public nextCreatedIndex; // Track which accounts have claimed for each window index. // Note: uses a packed array of bools for gas optimization on tracking certain claims. Copied from Uniswap's contract. mapping(uint256 => mapping(uint256 => uint256)) private claimedBitMap; /**************************************** * EVENTS ****************************************/ event Claimed( address indexed caller, uint256 windowIndex, address indexed account, uint256 accountIndex, uint256 amount, address indexed rewardToken ); event CreatedWindow( uint256 indexed windowIndex, uint256 rewardsDeposited, address indexed rewardToken, address owner ); event WithdrawRewards(address indexed owner, uint256 amount, address indexed currency); event DeleteWindow(uint256 indexed windowIndex, address owner); /**************************** * ADMIN FUNCTIONS ****************************/ /** * @notice Set merkle root for the next available window index and seed allocations. * @notice Callable only by owner of this contract. Caller must have approved this contract to transfer * `rewardsToDeposit` amount of `rewardToken` or this call will fail. Importantly, we assume that the * owner of this contract correctly chooses an amount `rewardsToDeposit` that is sufficient to cover all * claims within the `merkleRoot`. Otherwise, a race condition can be created. This situation can occur * because we do not segregate reward balances by window, for code simplicity purposes. * (If `rewardsToDeposit` is purposefully insufficient to payout all claims, then the admin must * subsequently transfer in rewards or the following situation can occur). * Example race situation: * - Window 1 Tree: Owner sets `rewardsToDeposit=100` and insert proofs that give claimant A 50 tokens and * claimant B 51 tokens. The owner has made an error by not setting the `rewardsToDeposit` correctly to 101. * - Window 2 Tree: Owner sets `rewardsToDeposit=1` and insert proofs that give claimant A 1 token. The owner * correctly set `rewardsToDeposit` this time. * - At this point contract owns 100 + 1 = 101 tokens. Now, imagine the following sequence: * (1) Claimant A claims 50 tokens for Window 1, contract now has 101 - 50 = 51 tokens. * (2) Claimant B claims 51 tokens for Window 1, contract now has 51 - 51 = 0 tokens. * (3) Claimant A tries to claim 1 token for Window 2 but fails because contract has 0 tokens. * - In summary, the contract owner created a race for step(2) and step(3) in which the first claim would * succeed and the second claim would fail, even though both claimants would expect their claims to succeed. * @param rewardsToDeposit amount of rewards to deposit to seed this allocation. * @param rewardToken ERC20 reward token. * @param merkleRoot merkle root describing allocation. * @param ipfsHash hash of IPFS object, conveniently stored for clients */ function setWindow( uint256 rewardsToDeposit, address rewardToken, bytes32 merkleRoot, string memory ipfsHash ) external onlyOwner { uint256 indexToSet = nextCreatedIndex; nextCreatedIndex = indexToSet.add(1); _setWindow(indexToSet, rewardsToDeposit, rewardToken, merkleRoot, ipfsHash); } /** * @notice Delete merkle root at window index. * @dev Callable only by owner. Likely to be followed by a withdrawRewards call to clear contract state. * @param windowIndex merkle root index to delete. */ function deleteWindow(uint256 windowIndex) external onlyOwner { delete merkleWindows[windowIndex]; emit DeleteWindow(windowIndex, msg.sender); } /** * @notice Emergency method that transfers rewards out of the contract if the contract was configured improperly. * @dev Callable only by owner. * @param rewardCurrency rewards to withdraw from contract. * @param amount amount of rewards to withdraw. */ function withdrawRewards(address rewardCurrency, uint256 amount) external onlyOwner { IERC20(rewardCurrency).safeTransfer(msg.sender, amount); emit WithdrawRewards(msg.sender, amount, rewardCurrency); } /**************************** * NON-ADMIN FUNCTIONS ****************************/ /** * @notice Batch claims to reduce gas versus individual submitting all claims. Method will fail * if any individual claims within the batch would fail. * @dev Optimistically tries to batch together consecutive claims for the same account and same * reward token to reduce gas. Therefore, the most gas-cost-optimal way to use this method * is to pass in an array of claims sorted by account and reward currency. * @param claims array of claims to claim. */ function claimMulti(Claim[] memory claims) external { uint256 batchedAmount = 0; uint256 claimCount = claims.length; for (uint256 i = 0; i < claimCount; i++) { Claim memory _claim = claims[i]; _verifyAndMarkClaimed(_claim); batchedAmount = batchedAmount.add(_claim.amount); // If the next claim is NOT the same account or the same token (or this claim is the last one), // then disburse the `batchedAmount` to the current claim's account for the current claim's reward token. uint256 nextI = i + 1; address currentRewardToken = address(merkleWindows[_claim.windowIndex].rewardToken); if ( nextI == claimCount || // This claim is last claim. claims[nextI].account != _claim.account || // Next claim account is different than current one. address(merkleWindows[claims[nextI].windowIndex].rewardToken) != currentRewardToken // Next claim reward token is different than current one. ) { IERC20(currentRewardToken).safeTransfer(_claim.account, batchedAmount); batchedAmount = 0; } } } /** * @notice Claim amount of reward tokens for account, as described by Claim input object. * @dev If the `_claim`'s `amount`, `accountIndex`, and `account` do not exactly match the * values stored in the merkle root for the `_claim`'s `windowIndex` this method * will revert. * @param _claim claim object describing amount, accountIndex, account, window index, and merkle proof. */ function claim(Claim memory _claim) public { _verifyAndMarkClaimed(_claim); merkleWindows[_claim.windowIndex].rewardToken.safeTransfer(_claim.account, _claim.amount); } /** * @notice Returns True if the claim for `accountIndex` has already been completed for the Merkle root at * `windowIndex`. * @dev This method will only work as intended if all `accountIndex`'s are unique for a given `windowIndex`. * The onus is on the Owner of this contract to submit only valid Merkle roots. * @param windowIndex merkle root to check. * @param accountIndex account index to check within window index. * @return True if claim has been executed already, False otherwise. */ function isClaimed(uint256 windowIndex, uint256 accountIndex) public view returns (bool) { uint256 claimedWordIndex = accountIndex / 256; uint256 claimedBitIndex = accountIndex % 256; uint256 claimedWord = claimedBitMap[windowIndex][claimedWordIndex]; uint256 mask = (1 << claimedBitIndex); return claimedWord & mask == mask; } /** * @notice Returns True if leaf described by {account, amount, accountIndex} is stored in Merkle root at given * window index. * @param _claim claim object describing amount, accountIndex, account, window index, and merkle proof. * @return valid True if leaf exists. */ function verifyClaim(Claim memory _claim) public view returns (bool valid) { bytes32 leaf = keccak256(abi.encodePacked(_claim.account, _claim.amount, _claim.accountIndex)); return MerkleProof.verify(_claim.merkleProof, merkleWindows[_claim.windowIndex].merkleRoot, leaf); } /**************************** * PRIVATE FUNCTIONS ****************************/ // Mark claim as completed for `accountIndex` for Merkle root at `windowIndex`. function _setClaimed(uint256 windowIndex, uint256 accountIndex) private { uint256 claimedWordIndex = accountIndex / 256; uint256 claimedBitIndex = accountIndex % 256; claimedBitMap[windowIndex][claimedWordIndex] = claimedBitMap[windowIndex][claimedWordIndex] | (1 << claimedBitIndex); } // Store new Merkle root at `windowindex`. Pull `rewardsDeposited` from caller to seed distribution for this root. function _setWindow( uint256 windowIndex, uint256 rewardsDeposited, address rewardToken, bytes32 merkleRoot, string memory ipfsHash ) private { Window storage window = merkleWindows[windowIndex]; window.merkleRoot = merkleRoot; window.rewardToken = IERC20(rewardToken); window.ipfsHash = ipfsHash; emit CreatedWindow(windowIndex, rewardsDeposited, rewardToken, msg.sender); window.rewardToken.safeTransferFrom(msg.sender, address(this), rewardsDeposited); } // Verify claim is valid and mark it as completed in this contract. function _verifyAndMarkClaimed(Claim memory _claim) private { // Check claimed proof against merkle window at given index. require(verifyClaim(_claim), "Incorrect merkle proof"); // Check the account has not yet claimed for this window. require(!isClaimed(_claim.windowIndex, _claim.accountIndex), "Account has already claimed for this window"); // Proof is correct and claim has not occurred yet, mark claimed complete. _setClaimed(_claim.windowIndex, _claim.accountIndex); emit Claimed( msg.sender, _claim.windowIndex, _claim.account, _claim.accountIndex, _claim.amount, address(merkleWindows[_claim.windowIndex].rewardToken) ); } } pragma solidity ^0.6.0; /** * @dev These functions deal with verification of Merkle trees (hash trees), */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../oracle/interfaces/OracleInterface.sol"; import "../../oracle/interfaces/IdentifierWhitelistInterface.sol"; import "../../oracle/implementation/Constants.sol"; import "../common/FundingRateApplier.sol"; /** * @title Financial contract with priceless position management. * @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying * on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token. */ contract PerpetualPositionManager is FundingRateApplier { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; using SafeERC20 for ExpandedIERC20; /**************************************** * PRICELESS POSITION DATA STRUCTURES * ****************************************/ // Represents a single sponsor's position. All collateral is held by this contract. // This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor. struct PositionData { FixedPoint.Unsigned tokensOutstanding; // Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`. uint256 withdrawalRequestPassTimestamp; FixedPoint.Unsigned withdrawalRequestAmount; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; } // Maps sponsor addresses to their positions. Each sponsor can have only one position. mapping(address => PositionData) public positions; // Keep track of the total collateral and tokens across all positions to enable calculating the // global collateralization ratio without iterating over all positions. FixedPoint.Unsigned public totalTokensOutstanding; // Similar to the rawCollateral in PositionData, this value should not be used directly. // _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust. FixedPoint.Unsigned public rawTotalPositionCollateral; // Synthetic token created by this contract. ExpandedIERC20 public tokenCurrency; // Unique identifier for DVM price feed ticker. bytes32 public priceIdentifier; // Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur. // !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract. // Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests // expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent // contract is extremely risky for any sponsor or synthetic token holder for the contract. uint256 public withdrawalLiveness; // Minimum number of tokens in a sponsor's position. FixedPoint.Unsigned public minSponsorTokens; // Expiry price pulled from the DVM in the case of an emergency shutdown. FixedPoint.Unsigned public emergencyShutdownPrice; /**************************************** * EVENTS * ****************************************/ event Deposit(address indexed sponsor, uint256 indexed collateralAmount); event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount); event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event NewSponsor(address indexed sponsor); event EndedSponsorPosition(address indexed sponsor); event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event Repay(address indexed sponsor, uint256 indexed numTokensRepaid, uint256 indexed newTokenCount); event EmergencyShutdown(address indexed caller, uint256 shutdownTimestamp); event SettleEmergencyShutdown( address indexed caller, uint256 indexed collateralReturned, uint256 indexed tokensBurned ); /**************************************** * MODIFIERS * ****************************************/ modifier onlyCollateralizedPosition(address sponsor) { _onlyCollateralizedPosition(sponsor); _; } modifier noPendingWithdrawal(address sponsor) { _positionHasNoPendingWithdrawal(sponsor); _; } /** * @notice Construct the PerpetualPositionManager. * @dev Deployer of this contract should consider carefully which parties have ability to mint and burn * the synthetic tokens referenced by `_tokenAddress`. This contract's security assumes that no external accounts * can mint new tokens, which could be used to steal all of this contract's locked collateral. * We recommend to only use synthetic token contracts whose sole Owner role (the role capable of adding & removing roles) * is assigned to this contract, whose sole Minter role is assigned to this contract, and whose * total supply is 0 prior to construction of this contract. * @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals. * @param _collateralAddress ERC20 token used as collateral for all positions. * @param _tokenAddress ERC20 token used as synthetic token. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _priceIdentifier registered in the DVM for the synthetic. * @param _fundingRateIdentifier Unique identifier for DVM price feed ticker for child financial contract. * @param _minSponsorTokens minimum number of tokens that must exist at any time in a position. * @param _tokenScaling initial scaling to apply to the token value (i.e. scales the tracking index). * @param _timerAddress Contract that stores the current time in a testing environment. Set to 0x0 for production. */ constructor( uint256 _withdrawalLiveness, address _collateralAddress, address _tokenAddress, address _finderAddress, bytes32 _priceIdentifier, bytes32 _fundingRateIdentifier, FixedPoint.Unsigned memory _minSponsorTokens, address _configStoreAddress, FixedPoint.Unsigned memory _tokenScaling, address _timerAddress ) public FundingRateApplier( _fundingRateIdentifier, _collateralAddress, _finderAddress, _configStoreAddress, _tokenScaling, _timerAddress ) { require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier)); withdrawalLiveness = _withdrawalLiveness; tokenCurrency = ExpandedIERC20(_tokenAddress); minSponsorTokens = _minSponsorTokens; priceIdentifier = _priceIdentifier; } /**************************************** * POSITION FUNCTIONS * ****************************************/ /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param sponsor the sponsor to credit the deposit to. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount) public notEmergencyShutdown() noPendingWithdrawal(sponsor) fees() nonReentrant() { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(sponsor); // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); emit Deposit(sponsor, collateralAmount.rawValue); // Move collateral currency from sender to contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function deposit(FixedPoint.Unsigned memory collateralAmount) public { // This is just a thin wrapper over depositTo that specified the sender as the sponsor. depositTo(msg.sender, collateralAmount); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor. * @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization * ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss. * @param collateralAmount is the amount of collateral to withdraw. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdraw(FixedPoint.Unsigned memory collateralAmount) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(msg.sender); // Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure // position remains above the GCR within the withdrawal. If this is not the case the caller must submit a request. amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount); emit Withdrawal(msg.sender, amountWithdrawn.rawValue); // Move collateral currency from contract to sender. // Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees) // instead of the user requested amount. This eliminates precision loss that could occur // where the user withdraws more collateral than rawCollateral is decremented by. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); } /** * @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw from their position. * @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated. * @param collateralAmount the amount of collateral requested to withdraw */ function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require( collateralAmount.isGreaterThan(0) && collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral)) ); // Update the position object for the user. positionData.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness); positionData.withdrawalRequestAmount = collateralAmount; emit RequestWithdrawal(msg.sender, collateralAmount.rawValue); } /** * @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting * `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency. * @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested * amount exceeds the collateral in the position (due to paying fees). * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdrawPassedRequest() external notEmergencyShutdown() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require( positionData.withdrawalRequestPassTimestamp != 0 && positionData.withdrawalRequestPassTimestamp <= getCurrentTime() ); // If withdrawal request amount is > position collateral, then withdraw the full collateral amount. // This situation is possible due to fees charged since the withdrawal was originally requested. FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount; if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) { amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral); } // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); // Transfer approved withdrawal amount from the contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue); } /** * @notice Cancels a pending withdrawal request. */ function cancelWithdrawal() external notEmergencyShutdown() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); // No pending withdrawal require message removed to save bytecode. require(positionData.withdrawalRequestPassTimestamp != 0); emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); } /** * @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount * ` into the sponsor's position and mints `numTokens` of `tokenCurrency`. * @dev This contract must have the Minter role for the `tokenCurrency`. * @dev Reverts if minting these tokens would put the position's collateralization ratio below the * global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of * `collateralCurrency`. * @param collateralAmount is the number of collateral tokens to collateralize the position with * @param numTokens is the number of tokens to mint from the position. */ function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) public notEmergencyShutdown() fees() nonReentrant() { PositionData storage positionData = positions[msg.sender]; // Either the new create ratio or the resultant position CR must be above the current GCR. require( (_checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount), positionData.tokensOutstanding.add(numTokens) ) || _checkCollateralization(collateralAmount, numTokens)), "Insufficient collateral" ); require(positionData.withdrawalRequestPassTimestamp == 0); if (positionData.tokensOutstanding.isEqual(0)) { require(numTokens.isGreaterThanOrEqual(minSponsorTokens)); emit NewSponsor(msg.sender); } // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); // Add the number of tokens created to the position's outstanding tokens. positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens); totalTokensOutstanding = totalTokensOutstanding.add(numTokens); emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue); // Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); // Note: revert reason removed to save bytecode. require(tokenCurrency.mint(msg.sender, numTokens.rawValue)); } /** * @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`. * @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral * in order to account for precision loss. This contract must be approved to spend at least `numTokens` of * `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function redeem(FixedPoint.Unsigned memory numTokens) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding)); FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding); FixedPoint.Unsigned memory collateralRedeemed = fractionRedeemed.mul(_getFeeAdjustedCollateral(positionData.rawCollateral)); // If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize. if (positionData.tokensOutstanding.isEqual(numTokens)) { amountWithdrawn = _deleteSponsorPosition(msg.sender); } else { // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens)); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); } emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue); // Transfer collateral from contract to caller and burn callers synthetic tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice Burns `numTokens` of `tokenCurrency` to decrease sponsors position size, without sending back `collateralCurrency`. * This is done by a sponsor to increase position CR. Resulting size is bounded by minSponsorTokens. * @dev Can only be called by token sponsor. This contract must be approved to spend `numTokens` of `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt from the sponsor's debt position. */ function repay(FixedPoint.Unsigned memory numTokens) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) fees() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding)); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens)); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); emit Repay(msg.sender, numTokens.rawValue, newTokenCount.rawValue); // Transfer the tokens back from the sponsor and burn them. tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice If the contract is emergency shutdown then all token holders and sponsors can redeem their tokens or * remaining collateral for underlying at the prevailing price defined by a DVM vote. * @dev This burns all tokens from the caller of `tokenCurrency` and sends back the resolved settlement value of * `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for * precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance. * @dev This contract must have the Burner role for the `tokenCurrency`. * @dev Note that this function does not call the updateFundingRate modifier to update the funding rate as this * function is only called after an emergency shutdown & there should be no funding rate updates after the shutdown. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function settleEmergencyShutdown() external isEmergencyShutdown() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { // Set the emergency shutdown price as resolved from the DVM. If DVM has not resolved will revert. if (emergencyShutdownPrice.isEqual(FixedPoint.fromUnscaledUint(0))) { emergencyShutdownPrice = _getOracleEmergencyShutdownPrice(); } // Get caller's tokens balance and calculate amount of underlying entitled to them. FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender)); FixedPoint.Unsigned memory totalRedeemableCollateral = _getFundingRateAppliedTokenDebt(tokensToRedeem).mul(emergencyShutdownPrice); // If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt. PositionData storage positionData = positions[msg.sender]; if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) { // Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying with // the funding rate applied to the outstanding token debt. FixedPoint.Unsigned memory tokenDebtValueInCollateral = _getFundingRateAppliedTokenDebt(positionData.tokensOutstanding).mul(emergencyShutdownPrice); FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral); // If the debt is greater than the remaining collateral, they cannot redeem anything. FixedPoint.Unsigned memory positionRedeemableCollateral = tokenDebtValueInCollateral.isLessThan(positionCollateral) ? positionCollateral.sub(tokenDebtValueInCollateral) : FixedPoint.Unsigned(0); // Add the number of redeemable tokens for the sponsor to their total redeemable collateral. totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral); // Reset the position state as all the value has been removed after settlement. delete positions[msg.sender]; emit EndedSponsorPosition(msg.sender); } // Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized, // the caller will get as much collateral as the contract can pay out. FixedPoint.Unsigned memory payout = FixedPoint.min(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalRedeemableCollateral); // Decrement total contract collateral and outstanding debt. amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout); totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem); emit SettleEmergencyShutdown(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue); // Transfer tokens & collateral and burn the redeemed tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue); tokenCurrency.burn(tokensToRedeem.rawValue); } /**************************************** * GLOBAL STATE FUNCTIONS * ****************************************/ /** * @notice Premature contract settlement under emergency circumstances. * @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`. * Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal * to occur via the `settleEmergencyShutdown` function. */ function emergencyShutdown() external override notEmergencyShutdown() fees() nonReentrant() { // Note: revert reason removed to save bytecode. require(msg.sender == _getFinancialContractsAdminAddress()); emergencyShutdownTimestamp = getCurrentTime(); _requestOraclePrice(emergencyShutdownTimestamp); emit EmergencyShutdown(msg.sender, emergencyShutdownTimestamp); } /** * @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they * reflect the NAV of the contract. However, this functionality doesn't apply to this contract. * @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable * only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing. */ function remargin() external override { return; } /** * @notice Accessor method for a sponsor's collateral. * @dev This is necessary because the struct returned by the positions() method shows * rawCollateral, which isn't a user-readable value. * @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for * example if the `lastPaymentTime != currentTime`. * @param sponsor address whose collateral amount is retrieved. * @return collateralAmount amount of collateral within a sponsors position. */ function getCollateral(address sponsor) external view nonReentrantView() returns (FixedPoint.Unsigned memory collateralAmount) { // Note: do a direct access to avoid the validity check. return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral)); } /** * @notice Accessor method for the total collateral stored within the PerpetualPositionManager. * @return totalCollateral amount of all collateral within the position manager. */ function totalPositionCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory totalCollateral) { return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } function getFundingRateAppliedTokenDebt(FixedPoint.Unsigned memory rawTokenDebt) external view nonReentrantView() returns (FixedPoint.Unsigned memory totalCollateral) { return _getFundingRateAppliedTokenDebt(rawTokenDebt); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire // position if the entire position is being removed. Does not make any external transfers. function _reduceSponsorPosition( address sponsor, FixedPoint.Unsigned memory tokensToRemove, FixedPoint.Unsigned memory collateralToRemove, FixedPoint.Unsigned memory withdrawalAmountToRemove ) internal { PositionData storage positionData = _getPositionData(sponsor); // If the entire position is being removed, delete it instead. if ( tokensToRemove.isEqual(positionData.tokensOutstanding) && _getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove) ) { _deleteSponsorPosition(sponsor); return; } // Decrement the sponsor's collateral and global collateral amounts. _decrementCollateralBalances(positionData, collateralToRemove); // Ensure that the sponsor will meet the min position size after the reduction. positionData.tokensOutstanding = positionData.tokensOutstanding.sub(tokensToRemove); require(positionData.tokensOutstanding.isGreaterThanOrEqual(minSponsorTokens)); // Decrement the position's withdrawal amount. positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove); // Decrement the total outstanding tokens in the overall contract. totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove); } // Deletes a sponsor's position and updates global counters. Does not make any external transfers. function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) { PositionData storage positionToLiquidate = _getPositionData(sponsor); FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral); // Remove the collateral and outstanding from the overall total position. rawTotalPositionCollateral = rawTotalPositionCollateral.sub(positionToLiquidate.rawCollateral); totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding); // Reset the sponsors position to have zero outstanding and collateral. delete positions[sponsor]; emit EndedSponsorPosition(sponsor); // Return fee-adjusted amount of collateral deleted from position. return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalPositionCollateral); } function _getPositionData(address sponsor) internal view onlyCollateralizedPosition(sponsor) returns (PositionData storage) { return positions[sponsor]; } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } function _getOracle() internal view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getFinancialContractsAdminAddress() internal view returns (address) { return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin); } // Requests a price for `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePrice(uint256 requestedTime) internal { _getOracle().requestPrice(priceIdentifier, requestedTime); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory price) { // Create an instance of the oracle and get the price. If the price is not resolved revert. int256 oraclePrice = _getOracle().getPrice(priceIdentifier, requestedTime); // For now we don't want to deal with negative prices in positions. if (oraclePrice < 0) { oraclePrice = 0; } return FixedPoint.Unsigned(uint256(oraclePrice)); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOracleEmergencyShutdownPrice() internal view returns (FixedPoint.Unsigned memory) { return _getOraclePrice(emergencyShutdownTimestamp); } // Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0. function _resetWithdrawalRequest(PositionData storage positionData) internal { positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0); positionData.withdrawalRequestPassTimestamp = 0; } // Ensure individual and global consistency when increasing collateral balances. Returns the change to the position. function _incrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _addCollateral(positionData.rawCollateral, collateralAmount); return _addCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the // position. We elect to return the amount that the global collateral is decreased by, rather than the individual // position's collateral, because we need to maintain the invariant that the global collateral is always // <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn. function _decrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position. // This function is similar to the _decrementCollateralBalances function except this function checks position GCR // between the decrements. This ensures that collateral removal will not leave the position undercollateralized. function _decrementCollateralBalancesCheckGCR( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); require(_checkPositionCollateralization(positionData), "CR below GCR"); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _onlyCollateralizedPosition(address sponsor) internal view { require(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0)); } // Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the // `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral // or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`. function _positionHasNoPendingWithdrawal(address sponsor) internal view { require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0); } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) { return _checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral), positionData.tokensOutstanding ); } // Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global // collateralization ratio. function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private view returns (bool) { FixedPoint.Unsigned memory global = _getCollateralizationRatio(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding); FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens); return !global.isGreaterThan(thisChange); } function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private pure returns (FixedPoint.Unsigned memory ratio) { return numTokens.isLessThanOrEqual(0) ? FixedPoint.fromUnscaledUint(0) : collateral.div(numTokens); } function _getTokenAddress() internal view override returns (address) { return address(tokenCurrency); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/utils/SafeCast.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../../oracle/implementation/Constants.sol"; import "../../oracle/interfaces/OptimisticOracleInterface.sol"; import "../perpetual-multiparty/ConfigStoreInterface.sol"; import "./EmergencyShutdownable.sol"; import "./FeePayer.sol"; /** * @title FundingRateApplier contract. * @notice Provides funding rate payment functionality for the Perpetual contract. */ abstract contract FundingRateApplier is EmergencyShutdownable, FeePayer { using FixedPoint for FixedPoint.Unsigned; using FixedPoint for FixedPoint.Signed; using SafeERC20 for IERC20; using SafeMath for uint256; /**************************************** * FUNDING RATE APPLIER DATA STRUCTURES * ****************************************/ struct FundingRate { // Current funding rate value. FixedPoint.Signed rate; // Identifier to retrieve the funding rate. bytes32 identifier; // Tracks the cumulative funding payments that have been paid to the sponsors. // The multiplier starts at 1, and is updated by computing cumulativeFundingRateMultiplier * (1 + effectivePayment). // Put another way, the cumulativeFeeMultiplier is (1 + effectivePayment1) * (1 + effectivePayment2) ... // For example: // The cumulativeFundingRateMultiplier should start at 1. // If a 1% funding payment is paid to sponsors, the multiplier should update to 1.01. // If another 1% fee is charged, the multiplier should be 1.01^2 (1.0201). FixedPoint.Unsigned cumulativeMultiplier; // Most recent time that the funding rate was updated. uint256 updateTime; // Most recent time that the funding rate was applied and changed the cumulative multiplier. uint256 applicationTime; // The time for the active (if it exists) funding rate proposal. 0 otherwise. uint256 proposalTime; } FundingRate public fundingRate; // Remote config store managed an owner. ConfigStoreInterface public configStore; /**************************************** * EVENTS * ****************************************/ event FundingRateUpdated(int256 newFundingRate, uint256 indexed updateTime, uint256 reward); /**************************************** * MODIFIERS * ****************************************/ // This is overridden to both pay fees (which is done by applyFundingRate()) and apply the funding rate. modifier fees override { // Note: the funding rate is applied on every fee-accruing transaction, where the total change is simply the // rate applied linearly since the last update. This implies that the compounding rate depends on the frequency // of update transactions that have this modifier, and it never reaches the ideal of continuous compounding. // This approximate-compounding pattern is common in the Ethereum ecosystem because of the complexity of // compounding data on-chain. applyFundingRate(); _; } // Note: this modifier is intended to be used if the caller intends to _only_ pay regular fees. modifier paysRegularFees { payRegularFees(); _; } /** * @notice Constructs the FundingRateApplier contract. Called by child contracts. * @param _fundingRateIdentifier identifier that tracks the funding rate of this contract. * @param _collateralAddress address of the collateral token. * @param _finderAddress Finder used to discover financial-product-related contracts. * @param _configStoreAddress address of the remote configuration store managed by an external owner. * @param _tokenScaling initial scaling to apply to the token value (i.e. scales the tracking index). * @param _timerAddress address of the timer contract in test envs, otherwise 0x0. */ constructor( bytes32 _fundingRateIdentifier, address _collateralAddress, address _finderAddress, address _configStoreAddress, FixedPoint.Unsigned memory _tokenScaling, address _timerAddress ) public FeePayer(_collateralAddress, _finderAddress, _timerAddress) EmergencyShutdownable() { uint256 currentTime = getCurrentTime(); fundingRate.updateTime = currentTime; fundingRate.applicationTime = currentTime; // Seed the cumulative multiplier with the token scaling, from which it will be scaled as funding rates are // applied over time. fundingRate.cumulativeMultiplier = _tokenScaling; fundingRate.identifier = _fundingRateIdentifier; configStore = ConfigStoreInterface(_configStoreAddress); } /** * @notice This method takes 3 distinct actions: * 1. Pays out regular fees. * 2. If possible, resolves the outstanding funding rate proposal, pulling the result in and paying out the rewards. * 3. Applies the prevailing funding rate over the most recent period. */ function applyFundingRate() public paysRegularFees() nonReentrant() { _applyEffectiveFundingRate(); } /** * @notice Proposes a new funding rate. Proposer receives a reward if correct. * @param rate funding rate being proposed. * @param timestamp time at which the funding rate was computed. */ function proposeFundingRate(FixedPoint.Signed memory rate, uint256 timestamp) external fees() nonReentrant() returns (FixedPoint.Unsigned memory totalBond) { require(fundingRate.proposalTime == 0, "Proposal in progress"); _validateFundingRate(rate); // Timestamp must be after the last funding rate update time, within the last 30 minutes. uint256 currentTime = getCurrentTime(); uint256 updateTime = fundingRate.updateTime; require( timestamp > updateTime && timestamp >= currentTime.sub(_getConfig().proposalTimePastLimit), "Invalid proposal time" ); // Set the proposal time in order to allow this contract to track this request. fundingRate.proposalTime = timestamp; OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); // Set up optimistic oracle. bytes32 identifier = fundingRate.identifier; bytes memory ancillaryData = _getAncillaryData(); // Note: requestPrice will revert if `timestamp` is less than the current block timestamp. optimisticOracle.requestPrice(identifier, timestamp, ancillaryData, collateralCurrency, 0); totalBond = FixedPoint.Unsigned( optimisticOracle.setBond( identifier, timestamp, ancillaryData, _pfc().mul(_getConfig().proposerBondPercentage).rawValue ) ); // Pull bond from caller and send to optimistic oracle. if (totalBond.isGreaterThan(0)) { collateralCurrency.safeTransferFrom(msg.sender, address(this), totalBond.rawValue); collateralCurrency.safeIncreaseAllowance(address(optimisticOracle), totalBond.rawValue); } optimisticOracle.proposePriceFor( msg.sender, address(this), identifier, timestamp, ancillaryData, rate.rawValue ); } // Returns a token amount scaled by the current funding rate multiplier. // Note: if the contract has paid fees since it was deployed, the raw value should be larger than the returned value. function _getFundingRateAppliedTokenDebt(FixedPoint.Unsigned memory rawTokenDebt) internal view returns (FixedPoint.Unsigned memory tokenDebt) { return rawTokenDebt.mul(fundingRate.cumulativeMultiplier); } function _getOptimisticOracle() internal view returns (OptimisticOracleInterface) { return OptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.OptimisticOracle)); } function _getConfig() internal returns (ConfigStoreInterface.ConfigSettings memory) { return configStore.updateAndGetCurrentConfig(); } function _updateFundingRate() internal { uint256 proposalTime = fundingRate.proposalTime; // If there is no pending proposal then do nothing. Otherwise check to see if we can update the funding rate. if (proposalTime != 0) { // Attempt to update the funding rate. OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); bytes32 identifier = fundingRate.identifier; bytes memory ancillaryData = _getAncillaryData(); // Try to get the price from the optimistic oracle. This call will revert if the request has not resolved // yet. If the request has not resolved yet, then we need to do additional checks to see if we should // "forget" the pending proposal and allow new proposals to update the funding rate. try optimisticOracle.settleAndGetPrice(identifier, proposalTime, ancillaryData) returns (int256 price) { // If successful, determine if the funding rate state needs to be updated. // If the request is more recent than the last update then we should update it. uint256 lastUpdateTime = fundingRate.updateTime; if (proposalTime >= lastUpdateTime) { // Update funding rates fundingRate.rate = FixedPoint.Signed(price); fundingRate.updateTime = proposalTime; // If there was no dispute, send a reward. FixedPoint.Unsigned memory reward = FixedPoint.fromUnscaledUint(0); OptimisticOracleInterface.Request memory request = optimisticOracle.getRequest(address(this), identifier, proposalTime, ancillaryData); if (request.disputer == address(0)) { reward = _pfc().mul(_getConfig().rewardRatePerSecond).mul(proposalTime.sub(lastUpdateTime)); if (reward.isGreaterThan(0)) { _adjustCumulativeFeeMultiplier(reward, _pfc()); collateralCurrency.safeTransfer(request.proposer, reward.rawValue); } } // This event will only be emitted after the fundingRate struct's "updateTime" has been set // to the latest proposal's proposalTime, indicating that the proposal has been published. // So, it suffices to just emit fundingRate.updateTime here. emit FundingRateUpdated(fundingRate.rate.rawValue, fundingRate.updateTime, reward.rawValue); } // Set proposal time to 0 since this proposal has now been resolved. fundingRate.proposalTime = 0; } catch { // Stop tracking and allow other proposals to come in if: // - The requester address is empty, indicating that the Oracle does not know about this funding rate // request. This is possible if the Oracle is replaced while the price request is still pending. // - The request has been disputed. OptimisticOracleInterface.Request memory request = optimisticOracle.getRequest(address(this), identifier, proposalTime, ancillaryData); if (request.disputer != address(0) || request.proposer == address(0)) { fundingRate.proposalTime = 0; } } } } // Constraining the range of funding rates limits the PfC for any dishonest proposer and enhances the // perpetual's security. For example, let's examine the case where the max and min funding rates // are equivalent to +/- 500%/year. This 1000% funding rate range allows a 8.6% profit from corruption for a // proposer who can deter honest proposers for 74 hours: // 1000%/year / 360 days / 24 hours * 74 hours max attack time = ~ 8.6%. // How would attack work? Imagine that the market is very volatile currently and that the "true" funding // rate for the next 74 hours is -500%, but a dishonest proposer successfully proposes a rate of +500% // (after a two hour liveness) and disputes honest proposers for the next 72 hours. This results in a funding // rate error of 1000% for 74 hours, until the DVM can set the funding rate back to its correct value. function _validateFundingRate(FixedPoint.Signed memory rate) internal { require( rate.isLessThanOrEqual(_getConfig().maxFundingRate) && rate.isGreaterThanOrEqual(_getConfig().minFundingRate) ); } // Fetches a funding rate from the Store, determines the period over which to compute an effective fee, // and multiplies the current multiplier by the effective fee. // A funding rate < 1 will reduce the multiplier, and a funding rate of > 1 will increase the multiplier. // Note: 1 is set as the neutral rate because there are no negative numbers in FixedPoint, so we decide to treat // values < 1 as "negative". function _applyEffectiveFundingRate() internal { // If contract is emergency shutdown, then the funding rate multiplier should no longer change. if (emergencyShutdownTimestamp != 0) { return; } uint256 currentTime = getCurrentTime(); uint256 paymentPeriod = currentTime.sub(fundingRate.applicationTime); _updateFundingRate(); // Update the funding rate if there is a resolved proposal. fundingRate.cumulativeMultiplier = _calculateEffectiveFundingRate( paymentPeriod, fundingRate.rate, fundingRate.cumulativeMultiplier ); fundingRate.applicationTime = currentTime; } function _calculateEffectiveFundingRate( uint256 paymentPeriodSeconds, FixedPoint.Signed memory fundingRatePerSecond, FixedPoint.Unsigned memory currentCumulativeFundingRateMultiplier ) internal pure returns (FixedPoint.Unsigned memory newCumulativeFundingRateMultiplier) { // Note: this method uses named return variables to save a little bytecode. // The overall formula that this function is performing: // newCumulativeFundingRateMultiplier = // (1 + (fundingRatePerSecond * paymentPeriodSeconds)) * currentCumulativeFundingRateMultiplier. FixedPoint.Signed memory ONE = FixedPoint.fromUnscaledInt(1); // Multiply the per-second rate over the number of seconds that have elapsed to get the period rate. FixedPoint.Signed memory periodRate = fundingRatePerSecond.mul(SafeCast.toInt256(paymentPeriodSeconds)); // Add one to create the multiplier to scale the existing fee multiplier. FixedPoint.Signed memory signedPeriodMultiplier = ONE.add(periodRate); // Max with 0 to ensure the multiplier isn't negative, then cast to an Unsigned. FixedPoint.Unsigned memory unsignedPeriodMultiplier = FixedPoint.fromSigned(FixedPoint.max(signedPeriodMultiplier, FixedPoint.fromUnscaledInt(0))); // Multiply the existing cumulative funding rate multiplier by the computed period multiplier to get the new // cumulative funding rate multiplier. newCumulativeFundingRateMultiplier = currentCumulativeFundingRateMultiplier.mul(unsignedPeriodMultiplier); } function _getAncillaryData() internal view returns (bytes memory) { // Note: when ancillary data is passed to the optimistic oracle, it should be tagged with the token address // whose funding rate it's trying to get. return abi.encodePacked(_getTokenAddress()); } function _getTokenAddress() internal view virtual returns (address); } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's uintXX casting operators with added overflow * checks. * * Downcasting from uint256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such 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. * * Can be combined with {SafeMath} to extend it to smaller types, by performing * all math on `uint256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; interface ConfigStoreInterface { // All of the configuration settings available for querying by a perpetual. struct ConfigSettings { // Liveness period (in seconds) for an update to currentConfig to become official. uint256 timelockLiveness; // Reward rate paid to successful proposers. Percentage of 1 E.g., .1 is 10%. FixedPoint.Unsigned rewardRatePerSecond; // Bond % (of given contract's PfC) that must be staked by proposers. Percentage of 1, e.g. 0.0005 is 0.05%. FixedPoint.Unsigned proposerBondPercentage; // Maximum funding rate % per second that can be proposed. FixedPoint.Signed maxFundingRate; // Minimum funding rate % per second that can be proposed. FixedPoint.Signed minFundingRate; // Funding rate proposal timestamp cannot be more than this amount of seconds in the past from the latest // update time. uint256 proposalTimePastLimit; } function updateAndGetCurrentConfig() external returns (ConfigSettings memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title EmergencyShutdownable contract. * @notice Any contract that inherits this contract will have an emergency shutdown timestamp state variable. * This contract provides modifiers that can be used by children contracts to determine if the contract is * in the shutdown state. The child contract is expected to implement the logic that happens * once a shutdown occurs. */ abstract contract EmergencyShutdownable { using SafeMath for uint256; /**************************************** * EMERGENCY SHUTDOWN DATA STRUCTURES * ****************************************/ // Timestamp used in case of emergency shutdown. 0 if no shutdown has been triggered. uint256 public emergencyShutdownTimestamp; /**************************************** * MODIFIERS * ****************************************/ modifier notEmergencyShutdown() { _notEmergencyShutdown(); _; } modifier isEmergencyShutdown() { _isEmergencyShutdown(); _; } /**************************************** * EXTERNAL FUNCTIONS * ****************************************/ constructor() public { emergencyShutdownTimestamp = 0; } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ function _notEmergencyShutdown() internal view { // Note: removed require string to save bytecode. require(emergencyShutdownTimestamp == 0); } function _isEmergencyShutdown() internal view { // Note: removed require string to save bytecode. require(emergencyShutdownTimestamp != 0); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../common/FundingRateApplier.sol"; import "../../common/implementation/FixedPoint.sol"; // Implements FundingRateApplier internal methods to enable unit testing. contract FundingRateApplierTest is FundingRateApplier { constructor( bytes32 _fundingRateIdentifier, address _collateralAddress, address _finderAddress, address _configStoreAddress, FixedPoint.Unsigned memory _tokenScaling, address _timerAddress ) public FundingRateApplier( _fundingRateIdentifier, _collateralAddress, _finderAddress, _configStoreAddress, _tokenScaling, _timerAddress ) {} function calculateEffectiveFundingRate( uint256 paymentPeriodSeconds, FixedPoint.Signed memory fundingRatePerSecond, FixedPoint.Unsigned memory currentCumulativeFundingRateMultiplier ) public pure returns (FixedPoint.Unsigned memory) { return _calculateEffectiveFundingRate( paymentPeriodSeconds, fundingRatePerSecond, currentCumulativeFundingRateMultiplier ); } // Required overrides. function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory currentPfc) { return FixedPoint.Unsigned(collateralCurrency.balanceOf(address(this))); } function emergencyShutdown() external override {} function remargin() external override {} function _getTokenAddress() internal view override returns (address) { return address(collateralCurrency); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./ConfigStoreInterface.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @notice ConfigStore stores configuration settings for a perpetual contract and provides an interface for it * to query settings such as reward rates, proposal bond sizes, etc. The configuration settings can be upgraded * by a privileged account and the upgraded changes are timelocked. */ contract ConfigStore is ConfigStoreInterface, Testable, Lockable, Ownable { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; /**************************************** * STORE DATA STRUCTURES * ****************************************/ // Make currentConfig private to force user to call getCurrentConfig, which returns the pendingConfig // if its liveness has expired. ConfigStoreInterface.ConfigSettings private currentConfig; // Beginning on `pendingPassedTimestamp`, the `pendingConfig` can be published as the current config. ConfigStoreInterface.ConfigSettings public pendingConfig; uint256 public pendingPassedTimestamp; /**************************************** * EVENTS * ****************************************/ event ProposedNewConfigSettings( address indexed proposer, uint256 rewardRatePerSecond, uint256 proposerBondPercentage, uint256 timelockLiveness, int256 maxFundingRate, int256 minFundingRate, uint256 proposalTimePastLimit, uint256 proposalPassedTimestamp ); event ChangedConfigSettings( uint256 rewardRatePerSecond, uint256 proposerBondPercentage, uint256 timelockLiveness, int256 maxFundingRate, int256 minFundingRate, uint256 proposalTimePastLimit ); /**************************************** * MODIFIERS * ****************************************/ // Update config settings if possible. modifier updateConfig() { _updateConfig(); _; } /** * @notice Construct the Config Store. An initial configuration is provided and set on construction. * @param _initialConfig Configuration settings to initialize `currentConfig` with. * @param _timerAddress Address of testable Timer contract. */ constructor(ConfigSettings memory _initialConfig, address _timerAddress) public Testable(_timerAddress) { _validateConfig(_initialConfig); currentConfig = _initialConfig; } /** * @notice Returns current config or pending config if pending liveness has expired. * @return ConfigSettings config settings that calling financial contract should view as "live". */ function updateAndGetCurrentConfig() external override updateConfig() nonReentrant() returns (ConfigStoreInterface.ConfigSettings memory) { return currentConfig; } /** * @notice Propose new configuration settings. New settings go into effect after a liveness period passes. * @param newConfig Configuration settings to publish after `currentConfig.timelockLiveness` passes from now. * @dev Callable only by owner. Calling this while there is already a pending proposal will overwrite the pending proposal. */ function proposeNewConfig(ConfigSettings memory newConfig) external onlyOwner() nonReentrant() updateConfig() { _validateConfig(newConfig); // Warning: This overwrites a pending proposal! pendingConfig = newConfig; // Use current config's liveness period to timelock this proposal. pendingPassedTimestamp = getCurrentTime().add(currentConfig.timelockLiveness); emit ProposedNewConfigSettings( msg.sender, newConfig.rewardRatePerSecond.rawValue, newConfig.proposerBondPercentage.rawValue, newConfig.timelockLiveness, newConfig.maxFundingRate.rawValue, newConfig.minFundingRate.rawValue, newConfig.proposalTimePastLimit, pendingPassedTimestamp ); } /** * @notice Publish any pending configuration settings if there is a pending proposal that has passed liveness. */ function publishPendingConfig() external nonReentrant() updateConfig() {} /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Check if pending proposal can overwrite the current config. function _updateConfig() internal { // If liveness has passed, publish proposed configuration settings. if (_pendingProposalPassed()) { currentConfig = pendingConfig; _deletePendingConfig(); emit ChangedConfigSettings( currentConfig.rewardRatePerSecond.rawValue, currentConfig.proposerBondPercentage.rawValue, currentConfig.timelockLiveness, currentConfig.maxFundingRate.rawValue, currentConfig.minFundingRate.rawValue, currentConfig.proposalTimePastLimit ); } } function _deletePendingConfig() internal { delete pendingConfig; pendingPassedTimestamp = 0; } function _pendingProposalPassed() internal view returns (bool) { return (pendingPassedTimestamp != 0 && pendingPassedTimestamp <= getCurrentTime()); } // Use this method to constrain values with which you can set ConfigSettings. function _validateConfig(ConfigStoreInterface.ConfigSettings memory config) internal pure { // We don't set limits on proposal timestamps because there are already natural limits: // - Future: price requests to the OptimisticOracle must be in the past---we can't add further constraints. // - Past: proposal times must always be after the last update time, and a reasonable past limit would be 30 // mins, meaning that no proposal timestamp can be more than 30 minutes behind the current time. // Make sure timelockLiveness is not too long, otherwise contract might not be able to fix itself // before a vulnerability drains its collateral. require(config.timelockLiveness <= 7 days && config.timelockLiveness >= 1 days, "Invalid timelockLiveness"); // The reward rate should be modified as needed to incentivize honest proposers appropriately. // Additionally, the rate should be less than 100% a year => 100% / 360 days / 24 hours / 60 mins / 60 secs // = 0.0000033 FixedPoint.Unsigned memory maxRewardRatePerSecond = FixedPoint.fromUnscaledUint(33).div(1e7); require(config.rewardRatePerSecond.isLessThan(maxRewardRatePerSecond), "Invalid rewardRatePerSecond"); // We don't set a limit on the proposer bond because it is a defense against dishonest proposers. If a proposer // were to successfully propose a very high or low funding rate, then their PfC would be very high. The proposer // could theoretically keep their "evil" funding rate alive indefinitely by continuously disputing honest // proposers, so we would want to be able to set the proposal bond (equal to the dispute bond) higher than their // PfC for each proposal liveness window. The downside of not limiting this is that the config store owner // can set it arbitrarily high and preclude a new funding rate from ever coming in. We suggest setting the // proposal bond based on the configuration's funding rate range like in this discussion: // https://github.com/UMAprotocol/protocol/issues/2039#issuecomment-719734383 // We also don't set a limit on the funding rate max/min because we might need to allow very high magnitude // funding rates in extraordinarily volatile market situations. Note, that even though we do not bound // the max/min, we still recommend that the deployer of this contract set the funding rate max/min values // to bound the PfC of a dishonest proposer. A reasonable range might be the equivalent of [+200%/year, -200%/year]. } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/interfaces/IERC20Standard.sol"; import "../../oracle/implementation/ContractCreator.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/AddressWhitelist.sol"; import "../../common/implementation/Lockable.sol"; import "../common/TokenFactory.sol"; import "../common/SyntheticToken.sol"; import "./PerpetualLib.sol"; import "./ConfigStore.sol"; /** * @title Perpetual Contract creator. * @notice Factory contract to create and register new instances of perpetual contracts. * Responsible for constraining the parameters used to construct a new perpetual. This creator contains a number of constraints * that are applied to newly created contract. These constraints can evolve over time and are * initially constrained to conservative values in this first iteration. Technically there is nothing in the * Perpetual contract requiring these constraints. However, because `createPerpetual()` is intended * to be the only way to create valid financial contracts that are registered with the DVM (via _registerContract), we can enforce deployment configurations here. */ contract PerpetualCreator is ContractCreator, Testable, Lockable { using FixedPoint for FixedPoint.Unsigned; /**************************************** * PERP CREATOR DATA STRUCTURES * ****************************************/ // Immutable params for perpetual contract. struct Params { address collateralAddress; bytes32 priceFeedIdentifier; bytes32 fundingRateIdentifier; string syntheticName; string syntheticSymbol; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPercentage; FixedPoint.Unsigned sponsorDisputeRewardPercentage; FixedPoint.Unsigned disputerDisputeRewardPercentage; FixedPoint.Unsigned minSponsorTokens; FixedPoint.Unsigned tokenScaling; uint256 withdrawalLiveness; uint256 liquidationLiveness; } // Address of TokenFactory used to create a new synthetic token. address public tokenFactoryAddress; event CreatedPerpetual(address indexed perpetualAddress, address indexed deployerAddress); event CreatedConfigStore(address indexed configStoreAddress, address indexed ownerAddress); /** * @notice Constructs the Perpetual contract. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _tokenFactoryAddress ERC20 token factory used to deploy synthetic token instances. * @param _timerAddress Contract that stores the current time in a testing environment. */ constructor( address _finderAddress, address _tokenFactoryAddress, address _timerAddress ) public ContractCreator(_finderAddress) Testable(_timerAddress) nonReentrant() { tokenFactoryAddress = _tokenFactoryAddress; } /** * @notice Creates an instance of perpetual and registers it within the registry. * @param params is a `ConstructorParams` object from Perpetual. * @return address of the deployed contract. */ function createPerpetual(Params memory params, ConfigStore.ConfigSettings memory configSettings) public nonReentrant() returns (address) { require(bytes(params.syntheticName).length != 0, "Missing synthetic name"); require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol"); // Create new config settings store for this contract and reset ownership to the deployer. ConfigStore configStore = new ConfigStore(configSettings, timerAddress); configStore.transferOwnership(msg.sender); emit CreatedConfigStore(address(configStore), configStore.owner()); // Create a new synthetic token using the params. TokenFactory tf = TokenFactory(tokenFactoryAddress); // If the collateral token does not have a `decimals()` method, // then a default precision of 18 will be applied to the newly created synthetic token. uint8 syntheticDecimals = _getSyntheticDecimals(params.collateralAddress); ExpandedIERC20 tokenCurrency = tf.createToken(params.syntheticName, params.syntheticSymbol, syntheticDecimals); address derivative = PerpetualLib.deploy(_convertParams(params, tokenCurrency, address(configStore))); // Give permissions to new derivative contract and then hand over ownership. tokenCurrency.addMinter(derivative); tokenCurrency.addBurner(derivative); tokenCurrency.resetOwner(derivative); _registerContract(new address[](0), derivative); emit CreatedPerpetual(derivative, msg.sender); return derivative; } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ // Converts createPerpetual params to Perpetual constructor params. function _convertParams( Params memory params, ExpandedIERC20 newTokenCurrency, address configStore ) private view returns (Perpetual.ConstructorParams memory constructorParams) { // Known from creator deployment. constructorParams.finderAddress = finderAddress; constructorParams.timerAddress = timerAddress; // Enforce configuration constraints. require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0"); require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0"); _requireWhitelistedCollateral(params.collateralAddress); // We don't want perpetual deployers to be able to intentionally or unintentionally set // liveness periods that could induce arithmetic overflow, but we also don't want // to be opinionated about what livenesses are "correct", so we will somewhat // arbitrarily set the liveness upper bound to 100 years (5200 weeks). In practice, liveness // periods even greater than a few days would make the perpetual unusable for most users. require(params.withdrawalLiveness < 5200 weeks, "Withdrawal liveness too large"); require(params.liquidationLiveness < 5200 weeks, "Liquidation liveness too large"); // To avoid precision loss or overflows, prevent the token scaling from being too large or too small. FixedPoint.Unsigned memory minScaling = FixedPoint.Unsigned(1e8); // 1e-10 FixedPoint.Unsigned memory maxScaling = FixedPoint.Unsigned(1e28); // 1e10 require( params.tokenScaling.isGreaterThan(minScaling) && params.tokenScaling.isLessThan(maxScaling), "Invalid tokenScaling" ); // Input from function call. constructorParams.configStoreAddress = configStore; constructorParams.tokenAddress = address(newTokenCurrency); constructorParams.collateralAddress = params.collateralAddress; constructorParams.priceFeedIdentifier = params.priceFeedIdentifier; constructorParams.fundingRateIdentifier = params.fundingRateIdentifier; constructorParams.collateralRequirement = params.collateralRequirement; constructorParams.disputeBondPercentage = params.disputeBondPercentage; constructorParams.sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage; constructorParams.disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage; constructorParams.minSponsorTokens = params.minSponsorTokens; constructorParams.withdrawalLiveness = params.withdrawalLiveness; constructorParams.liquidationLiveness = params.liquidationLiveness; constructorParams.tokenScaling = params.tokenScaling; } // IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method, // which is possible since the method is only an OPTIONAL method in the ERC20 standard: // https://eips.ethereum.org/EIPS/eip-20#methods. function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) { try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) { return _decimals; } catch { return 18; } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../interfaces/FinderInterface.sol"; import "../../common/implementation/AddressWhitelist.sol"; import "./Registry.sol"; import "./Constants.sol"; /** * @title Base contract for all financial contract creators */ abstract contract ContractCreator { address internal finderAddress; constructor(address _finderAddress) public { finderAddress = _finderAddress; } function _requireWhitelistedCollateral(address collateralAddress) internal view { FinderInterface finder = FinderInterface(finderAddress); AddressWhitelist collateralWhitelist = AddressWhitelist(finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist)); require(collateralWhitelist.isOnWhitelist(collateralAddress), "Collateral not whitelisted"); } function _registerContract(address[] memory parties, address contractToRegister) internal { FinderInterface finder = FinderInterface(finderAddress); Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry)); registry.registerContract(parties, contractToRegister); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "./SyntheticToken.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/implementation/Lockable.sol"; /** * @title Factory for creating new mintable and burnable tokens. */ contract TokenFactory is Lockable { /** * @notice Create a new token and return it to the caller. * @dev The caller will become the only minter and burner and the new owner capable of assigning the roles. * @param tokenName used to describe the new token. * @param tokenSymbol short ticker abbreviation of the name. Ideally < 5 chars. * @param tokenDecimals used to define the precision used in the token's numerical representation. * @return newToken an instance of the newly created token interface. */ function createToken( string calldata tokenName, string calldata tokenSymbol, uint8 tokenDecimals ) external nonReentrant() returns (ExpandedIERC20 newToken) { SyntheticToken mintableToken = new SyntheticToken(tokenName, tokenSymbol, tokenDecimals); mintableToken.addMinter(msg.sender); mintableToken.addBurner(msg.sender); mintableToken.resetOwner(msg.sender); newToken = ExpandedIERC20(address(mintableToken)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../../common/implementation/ExpandedERC20.sol"; import "../../common/implementation/Lockable.sol"; /** * @title Burnable and mintable ERC20. * @dev The contract deployer will initially be the only minter, burner and owner capable of adding new roles. */ contract SyntheticToken is ExpandedERC20, Lockable { /** * @notice Constructs the SyntheticToken. * @param tokenName The name which describes the new token. * @param tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars. * @param tokenDecimals The number of decimals to define token precision. */ constructor( string memory tokenName, string memory tokenSymbol, uint8 tokenDecimals ) public ExpandedERC20(tokenName, tokenSymbol, tokenDecimals) nonReentrant() {} /** * @notice Add Minter role to account. * @dev The caller must have the Owner role. * @param account The address to which the Minter role is added. */ function addMinter(address account) external override nonReentrant() { addMember(uint256(Roles.Minter), account); } /** * @notice Remove Minter role from account. * @dev The caller must have the Owner role. * @param account The address from which the Minter role is removed. */ function removeMinter(address account) external nonReentrant() { removeMember(uint256(Roles.Minter), account); } /** * @notice Add Burner role to account. * @dev The caller must have the Owner role. * @param account The address to which the Burner role is added. */ function addBurner(address account) external override nonReentrant() { addMember(uint256(Roles.Burner), account); } /** * @notice Removes Burner role from account. * @dev The caller must have the Owner role. * @param account The address from which the Burner role is removed. */ function removeBurner(address account) external nonReentrant() { removeMember(uint256(Roles.Burner), account); } /** * @notice Reset Owner role to account. * @dev The caller must have the Owner role. * @param account The new holder of the Owner role. */ function resetOwner(address account) external override nonReentrant() { resetMember(uint256(Roles.Owner), account); } /** * @notice Checks if a given account holds the Minter role. * @param account The address which is checked for the Minter role. * @return bool True if the provided account is a Minter. */ function isMinter(address account) public view nonReentrantView() returns (bool) { return holdsRole(uint256(Roles.Minter), account); } /** * @notice Checks if a given account holds the Burner role. * @param account The address which is checked for the Burner role. * @return bool True if the provided account is a Burner. */ function isBurner(address account) public view nonReentrantView() returns (bool) { return holdsRole(uint256(Roles.Burner), account); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./Perpetual.sol"; /** * @title Provides convenient Perpetual Multi Party contract utilities. * @dev Using this library to deploy Perpetuals allows calling contracts to avoid importing the full bytecode. */ library PerpetualLib { /** * @notice Returns address of new Perpetual deployed with given `params` configuration. * @dev Caller will need to register new Perpetual with the Registry to begin requesting prices. Caller is also * responsible for enforcing constraints on `params`. * @param params is a `ConstructorParams` object from Perpetual. * @return address of the deployed Perpetual contract */ function deploy(Perpetual.ConstructorParams memory params) public returns (address) { Perpetual derivative = new Perpetual(params); return address(derivative); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./PerpetualLiquidatable.sol"; /** * @title Perpetual Multiparty Contract. * @notice Convenient wrapper for Liquidatable. */ contract Perpetual is PerpetualLiquidatable { /** * @notice Constructs the Perpetual contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public PerpetualLiquidatable(params) // Note: since there is no logic here, there is no need to add a re-entrancy guard. { } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./PerpetualPositionManager.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @title PerpetualLiquidatable * @notice Adds logic to a position-managing contract that enables callers to liquidate an undercollateralized position. * @dev The liquidation has a liveness period before expiring successfully, during which someone can "dispute" the * liquidation, which sends a price request to the relevant Oracle to settle the final collateralization ratio based on * a DVM price. The contract enforces dispute rewards in order to incentivize disputers to correctly dispute false * liquidations and compensate position sponsors who had their position incorrectly liquidated. Importantly, a * prospective disputer must deposit a dispute bond that they can lose in the case of an unsuccessful dispute. * NOTE: this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on * transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing * money themselves). */ contract PerpetualLiquidatable is PerpetualPositionManager { using FixedPoint for FixedPoint.Unsigned; using SafeMath for uint256; using SafeERC20 for IERC20; /**************************************** * LIQUIDATION DATA STRUCTURES * ****************************************/ // Because of the check in withdrawable(), the order of these enum values should not change. enum Status { Uninitialized, NotDisputed, Disputed, DisputeSucceeded, DisputeFailed } struct LiquidationData { // Following variables set upon creation of liquidation: address sponsor; // Address of the liquidated position's sponsor address liquidator; // Address who created this liquidation Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle // Following variables determined by the position that is being liquidated: FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute // Amount of collateral being liquidated, which could be different from // lockedCollateral if there were pending withdrawals at the time of liquidation FixedPoint.Unsigned liquidatedCollateral; // Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation. FixedPoint.Unsigned rawUnitCollateral; // Following variable set upon initiation of a dispute: address disputer; // Person who is disputing a liquidation // Following variable set upon a resolution of a dispute: FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute FixedPoint.Unsigned finalFee; } // Define the contract's constructor parameters as a struct to enable more variables to be specified. // This is required to enable more params, over and above Solidity's limits. struct ConstructorParams { // Params for PerpetualPositionManager only. uint256 withdrawalLiveness; address configStoreAddress; address collateralAddress; address tokenAddress; address finderAddress; address timerAddress; bytes32 priceFeedIdentifier; bytes32 fundingRateIdentifier; FixedPoint.Unsigned minSponsorTokens; FixedPoint.Unsigned tokenScaling; // Params specifically for PerpetualLiquidatable. uint256 liquidationLiveness; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPercentage; FixedPoint.Unsigned sponsorDisputeRewardPercentage; FixedPoint.Unsigned disputerDisputeRewardPercentage; } // This struct is used in the `withdrawLiquidation` method that disperses liquidation and dispute rewards. // `payToX` stores the total collateral to withdraw from the contract to pay X. This value might differ // from `paidToX` due to precision loss between accounting for the `rawCollateral` versus the // fee-adjusted collateral. These variables are stored within a struct to avoid the stack too deep error. struct RewardsData { FixedPoint.Unsigned payToSponsor; FixedPoint.Unsigned payToLiquidator; FixedPoint.Unsigned payToDisputer; FixedPoint.Unsigned paidToSponsor; FixedPoint.Unsigned paidToLiquidator; FixedPoint.Unsigned paidToDisputer; } // Liquidations are unique by ID per sponsor mapping(address => LiquidationData[]) public liquidations; // Total collateral in liquidation. FixedPoint.Unsigned public rawLiquidationCollateral; // Immutable contract parameters: // Amount of time for pending liquidation before expiry. // !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors. // Extremely low liveness values increase the chance that opportunistic invalid liquidations // expire without dispute, thereby decreasing the usability for sponsors and increasing the risk // for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic // token holder for the contract. uint256 public liquidationLiveness; // Required collateral:TRV ratio for a position to be considered sufficiently collateralized. FixedPoint.Unsigned public collateralRequirement; // Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer // Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%" FixedPoint.Unsigned public disputeBondPercentage; // Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public sponsorDisputeRewardPercentage; // Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public disputerDisputeRewardPercentage; /**************************************** * EVENTS * ****************************************/ event LiquidationCreated( address indexed sponsor, address indexed liquidator, uint256 indexed liquidationId, uint256 tokensOutstanding, uint256 lockedCollateral, uint256 liquidatedCollateral, uint256 liquidationTime ); event LiquidationDisputed( address indexed sponsor, address indexed liquidator, address indexed disputer, uint256 liquidationId, uint256 disputeBondAmount ); event DisputeSettled( address indexed caller, address indexed sponsor, address indexed liquidator, address disputer, uint256 liquidationId, bool disputeSucceeded ); event LiquidationWithdrawn( address indexed caller, uint256 paidToLiquidator, uint256 paidToDisputer, uint256 paidToSponsor, Status indexed liquidationStatus, uint256 settlementPrice ); /**************************************** * MODIFIERS * ****************************************/ modifier disputable(uint256 liquidationId, address sponsor) { _disputable(liquidationId, sponsor); _; } modifier withdrawable(uint256 liquidationId, address sponsor) { _withdrawable(liquidationId, sponsor); _; } /** * @notice Constructs the liquidatable contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public PerpetualPositionManager( params.withdrawalLiveness, params.collateralAddress, params.tokenAddress, params.finderAddress, params.priceFeedIdentifier, params.fundingRateIdentifier, params.minSponsorTokens, params.configStoreAddress, params.tokenScaling, params.timerAddress ) { require(params.collateralRequirement.isGreaterThan(1)); require(params.sponsorDisputeRewardPercentage.add(params.disputerDisputeRewardPercentage).isLessThan(1)); // Set liquidatable specific variables. liquidationLiveness = params.liquidationLiveness; collateralRequirement = params.collateralRequirement; disputeBondPercentage = params.disputeBondPercentage; sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage; disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage; } /**************************************** * LIQUIDATION FUNCTIONS * ****************************************/ /** * @notice Liquidates the sponsor's position if the caller has enough * synthetic tokens to retire the position's outstanding tokens. Liquidations above * a minimum size also reset an ongoing "slow withdrawal"'s liveness. * @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be * approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param sponsor address of the sponsor to liquidate. * @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value. * @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value. * @param maxTokensToLiquidate max number of tokens to liquidate. * @param deadline abort the liquidation if the transaction is mined after this timestamp. * @return liquidationId ID of the newly created liquidation. * @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position. * @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully. */ function createLiquidation( address sponsor, FixedPoint.Unsigned calldata minCollateralPerToken, FixedPoint.Unsigned calldata maxCollateralPerToken, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) external notEmergencyShutdown() fees() nonReentrant() returns ( uint256 liquidationId, FixedPoint.Unsigned memory tokensLiquidated, FixedPoint.Unsigned memory finalFeeBond ) { // Check that this transaction was mined pre-deadline. require(getCurrentTime() <= deadline, "Mined after deadline"); // Retrieve Position data for sponsor PositionData storage positionToLiquidate = _getPositionData(sponsor); tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding); require(tokensLiquidated.isGreaterThan(0)); // Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral, // then set this to 0, otherwise set it to (startCollateral - withdrawal request amount). FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral); FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0); if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) { startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount); } // Scoping to get rid of a stack too deep error. { FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding; // The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken]. require( maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal), "CR is more than max liq. price" ); // minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens. require( minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal), "CR is less than min liq. price" ); } // Compute final fee at time of liquidation. finalFeeBond = _computeFinalFees(); // These will be populated within the scope below. FixedPoint.Unsigned memory lockedCollateral; FixedPoint.Unsigned memory liquidatedCollateral; // Scoping to get rid of a stack too deep error. The amount of tokens to remove from the position // are not funding-rate adjusted because the multiplier only affects their redemption value, not their // notional. { FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding); // The actual amount of collateral that gets moved to the liquidation. lockedCollateral = startCollateral.mul(ratio); // For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of // withdrawal requests. liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio); // Part of the withdrawal request is also removed. Ideally: // liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral. FixedPoint.Unsigned memory withdrawalAmountToRemove = positionToLiquidate.withdrawalRequestAmount.mul(ratio); _reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove); } // Add to the global liquidation collateral count. _addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond)); // Construct liquidation object. // Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new // LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push. liquidationId = liquidations[sponsor].length; liquidations[sponsor].push( LiquidationData({ sponsor: sponsor, liquidator: msg.sender, state: Status.NotDisputed, liquidationTime: getCurrentTime(), tokensOutstanding: _getFundingRateAppliedTokenDebt(tokensLiquidated), lockedCollateral: lockedCollateral, liquidatedCollateral: liquidatedCollateral, rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)), disputer: address(0), settlementPrice: FixedPoint.fromUnscaledUint(0), finalFee: finalFeeBond }) ); // If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than // some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be // "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold // is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal. // We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter // denominated in token currency units and we can avoid adding another parameter. FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens; if ( positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal. positionToLiquidate.withdrawalRequestPassTimestamp > getCurrentTime() && // The slow withdrawal has not yet expired. tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold". ) { positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness); } emit LiquidationCreated( sponsor, msg.sender, liquidationId, _getFundingRateAppliedTokenDebt(tokensLiquidated).rawValue, lockedCollateral.rawValue, liquidatedCollateral.rawValue, getCurrentTime() ); // Destroy tokens tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue); tokenCurrency.burn(tokensLiquidated.rawValue); // Pull final fee from liquidator. collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue); } /** * @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond and pay a fixed final * fee charged on each price request. * @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes. * This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute * bond amount is calculated from `disputeBondPercentage` times the collateral in the liquidation. * @param liquidationId of the disputed liquidation. * @param sponsor the address of the sponsor whose liquidation is being disputed. * @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond). */ function dispute(uint256 liquidationId, address sponsor) external disputable(liquidationId, sponsor) fees() nonReentrant() returns (FixedPoint.Unsigned memory totalPaid) { LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId); // Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees. FixedPoint.Unsigned memory disputeBondAmount = disputedLiquidation.lockedCollateral.mul(disputeBondPercentage).mul( _getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral) ); _addCollateral(rawLiquidationCollateral, disputeBondAmount); // Request a price from DVM. Liquidation is pending dispute until DVM returns a price. disputedLiquidation.state = Status.Disputed; disputedLiquidation.disputer = msg.sender; // Enqueue a request with the DVM. _requestOraclePrice(disputedLiquidation.liquidationTime); emit LiquidationDisputed( sponsor, disputedLiquidation.liquidator, msg.sender, liquidationId, disputeBondAmount.rawValue ); totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee); // Pay the final fee for requesting price from the DVM. _payFinalFees(msg.sender, disputedLiquidation.finalFee); // Transfer the dispute bond amount from the caller to this contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue); } /** * @notice After a dispute has settled or after a non-disputed liquidation has expired, * anyone can call this method to disperse payments to the sponsor, liquidator, and disputer. * @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment. * If the dispute FAILED: only the liquidator receives payment. This method deletes the liquidation data. * This method will revert if rewards have already been dispersed. * @param liquidationId uniquely identifies the sponsor's liquidation. * @param sponsor address of the sponsor associated with the liquidation. * @return data about rewards paid out. */ function withdrawLiquidation(uint256 liquidationId, address sponsor) public withdrawable(liquidationId, sponsor) fees() nonReentrant() returns (RewardsData memory) { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settles the liquidation if necessary. This call will revert if the price has not resolved yet. _settle(liquidationId, sponsor); // Calculate rewards as a function of the TRV. // Note1: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata. // Note2: the tokenRedemptionValue uses the tokensOutstanding which was calculated using the funding rate at // liquidation time from _getFundingRateAppliedTokenDebt. Therefore the TRV considers the full debt value at that time. FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral); FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice; FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(settlementPrice).mul(feeAttenuation); FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation); FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPercentage); FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation); // There are three main outcome states: either the dispute succeeded, failed or was not updated. // Based on the state, different parties of a liquidation receive different amounts. // After assigning rewards based on the liquidation status, decrease the total collateral held in this contract // by the amount to pay each party. The actual amounts withdrawn might differ if _removeCollateral causes // precision loss. RewardsData memory rewards; if (liquidation.state == Status.DisputeSucceeded) { // If the dispute is successful then all three users should receive rewards: // Pay DISPUTER: disputer reward + dispute bond + returned final fee rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee); // Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward rewards.payToSponsor = sponsorDisputeReward.add(collateral.sub(tokenRedemptionValue)); // Pay LIQUIDATOR: TRV - dispute reward - sponsor reward // If TRV > Collateral, then subtract rewards from collateral // NOTE: This should never be below zero since we prevent (sponsorDisputePercentage+disputerDisputePercentage) >= 0 in // the constructor when these params are set. rewards.payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(disputerDisputeReward); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); rewards.paidToSponsor = _removeCollateral(rawLiquidationCollateral, rewards.payToSponsor); rewards.paidToDisputer = _removeCollateral(rawLiquidationCollateral, rewards.payToDisputer); collateralCurrency.safeTransfer(liquidation.disputer, rewards.paidToDisputer.rawValue); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); collateralCurrency.safeTransfer(liquidation.sponsor, rewards.paidToSponsor.rawValue); // In the case of a failed dispute only the liquidator can withdraw. } else if (liquidation.state == Status.DisputeFailed) { // Pay LIQUIDATOR: collateral + dispute bond + returned final fee rewards.payToLiquidator = collateral.add(disputeBondAmount).add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); // If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this // state as a dispute failed and the liquidator can withdraw. } else if (liquidation.state == Status.NotDisputed) { // Pay LIQUIDATOR: collateral + returned final fee rewards.payToLiquidator = collateral.add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); } emit LiquidationWithdrawn( msg.sender, rewards.paidToLiquidator.rawValue, rewards.paidToDisputer.rawValue, rewards.paidToSponsor.rawValue, liquidation.state, settlementPrice.rawValue ); // Free up space after collateral is withdrawn by removing the liquidation object from the array. delete liquidations[sponsor][liquidationId]; return rewards; } /** * @notice Gets all liquidation information for a given sponsor address. * @param sponsor address of the position sponsor. * @return liquidationData array of all liquidation information for the given sponsor address. */ function getLiquidations(address sponsor) external view nonReentrantView() returns (LiquidationData[] memory liquidationData) { return liquidations[sponsor]; } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // This settles a liquidation if it is in the Disputed state. If not, it will immediately return. // If the liquidation is in the Disputed state, but a price is not available, this will revert. function _settle(uint256 liquidationId, address sponsor) internal { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settlement only happens when state == Disputed and will only happen once per liquidation. // If this liquidation is not ready to be settled, this method should return immediately. if (liquidation.state != Status.Disputed) { return; } // Get the returned price from the oracle. If this has not yet resolved will revert. liquidation.settlementPrice = _getOraclePrice(liquidation.liquidationTime); // Find the value of the tokens in the underlying collateral. FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(liquidation.settlementPrice); // The required collateral is the value of the tokens in underlying * required collateral ratio. FixedPoint.Unsigned memory requiredCollateral = tokenRedemptionValue.mul(collateralRequirement); // If the position has more than the required collateral it is solvent and the dispute is valid (liquidation is invalid) // Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals. bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral); liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed; emit DisputeSettled( msg.sender, sponsor, liquidation.liquidator, liquidation.disputer, liquidationId, disputeSucceeded ); } function _pfc() internal view override returns (FixedPoint.Unsigned memory) { return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral)); } function _getLiquidationData(address sponsor, uint256 liquidationId) internal view returns (LiquidationData storage liquidation) { LiquidationData[] storage liquidationArray = liquidations[sponsor]; // Revert if the caller is attempting to access an invalid liquidation // (one that has never been created or one has never been initialized). require( liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized ); return liquidationArray[liquidationId]; } function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) { return liquidation.liquidationTime.add(liquidationLiveness); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _disputable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); require( (getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.NotDisputed), "Liquidation not disputable" ); } function _withdrawable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); Status state = liquidation.state; // Must be disputed or the liquidation has passed expiry. require( (state > Status.NotDisputed) || ((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.NotDisputed)) ); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/interfaces/IERC20Standard.sol"; import "../../oracle/implementation/ContractCreator.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/AddressWhitelist.sol"; import "../../common/implementation/Lockable.sol"; import "../common/TokenFactory.sol"; import "../common/SyntheticToken.sol"; import "./ExpiringMultiPartyLib.sol"; /** * @title Expiring Multi Party Contract creator. * @notice Factory contract to create and register new instances of expiring multiparty contracts. * Responsible for constraining the parameters used to construct a new EMP. This creator contains a number of constraints * that are applied to newly created expiring multi party contract. These constraints can evolve over time and are * initially constrained to conservative values in this first iteration. Technically there is nothing in the * ExpiringMultiParty contract requiring these constraints. However, because `createExpiringMultiParty()` is intended * to be the only way to create valid financial contracts that are registered with the DVM (via _registerContract), we can enforce deployment configurations here. */ contract ExpiringMultiPartyCreator is ContractCreator, Testable, Lockable { using FixedPoint for FixedPoint.Unsigned; /**************************************** * EMP CREATOR DATA STRUCTURES * ****************************************/ struct Params { uint256 expirationTimestamp; address collateralAddress; bytes32 priceFeedIdentifier; string syntheticName; string syntheticSymbol; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPercentage; FixedPoint.Unsigned sponsorDisputeRewardPercentage; FixedPoint.Unsigned disputerDisputeRewardPercentage; FixedPoint.Unsigned minSponsorTokens; uint256 withdrawalLiveness; uint256 liquidationLiveness; address financialProductLibraryAddress; } // Address of TokenFactory used to create a new synthetic token. address public tokenFactoryAddress; event CreatedExpiringMultiParty(address indexed expiringMultiPartyAddress, address indexed deployerAddress); /** * @notice Constructs the ExpiringMultiPartyCreator contract. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _tokenFactoryAddress ERC20 token factory used to deploy synthetic token instances. * @param _timerAddress Contract that stores the current time in a testing environment. */ constructor( address _finderAddress, address _tokenFactoryAddress, address _timerAddress ) public ContractCreator(_finderAddress) Testable(_timerAddress) nonReentrant() { tokenFactoryAddress = _tokenFactoryAddress; } /** * @notice Creates an instance of expiring multi party and registers it within the registry. * @param params is a `ConstructorParams` object from ExpiringMultiParty. * @return address of the deployed ExpiringMultiParty contract. */ function createExpiringMultiParty(Params memory params) public nonReentrant() returns (address) { // Create a new synthetic token using the params. require(bytes(params.syntheticName).length != 0, "Missing synthetic name"); require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol"); TokenFactory tf = TokenFactory(tokenFactoryAddress); // If the collateral token does not have a `decimals()` method, then a default precision of 18 will be // applied to the newly created synthetic token. uint8 syntheticDecimals = _getSyntheticDecimals(params.collateralAddress); ExpandedIERC20 tokenCurrency = tf.createToken(params.syntheticName, params.syntheticSymbol, syntheticDecimals); address derivative = ExpiringMultiPartyLib.deploy(_convertParams(params, tokenCurrency)); // Give permissions to new derivative contract and then hand over ownership. tokenCurrency.addMinter(derivative); tokenCurrency.addBurner(derivative); tokenCurrency.resetOwner(derivative); _registerContract(new address[](0), derivative); emit CreatedExpiringMultiParty(derivative, msg.sender); return derivative; } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ // Converts createExpiringMultiParty params to ExpiringMultiParty constructor params. function _convertParams(Params memory params, ExpandedIERC20 newTokenCurrency) private view returns (ExpiringMultiParty.ConstructorParams memory constructorParams) { // Known from creator deployment. constructorParams.finderAddress = finderAddress; constructorParams.timerAddress = timerAddress; // Enforce configuration constraints. require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0"); require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0"); require(params.expirationTimestamp > now, "Invalid expiration time"); _requireWhitelistedCollateral(params.collateralAddress); // We don't want EMP deployers to be able to intentionally or unintentionally set // liveness periods that could induce arithmetic overflow, but we also don't want // to be opinionated about what livenesses are "correct", so we will somewhat // arbitrarily set the liveness upper bound to 100 years (5200 weeks). In practice, liveness // periods even greater than a few days would make the EMP unusable for most users. require(params.withdrawalLiveness < 5200 weeks, "Withdrawal liveness too large"); require(params.liquidationLiveness < 5200 weeks, "Liquidation liveness too large"); // Input from function call. constructorParams.tokenAddress = address(newTokenCurrency); constructorParams.expirationTimestamp = params.expirationTimestamp; constructorParams.collateralAddress = params.collateralAddress; constructorParams.priceFeedIdentifier = params.priceFeedIdentifier; constructorParams.collateralRequirement = params.collateralRequirement; constructorParams.disputeBondPercentage = params.disputeBondPercentage; constructorParams.sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage; constructorParams.disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage; constructorParams.minSponsorTokens = params.minSponsorTokens; constructorParams.withdrawalLiveness = params.withdrawalLiveness; constructorParams.liquidationLiveness = params.liquidationLiveness; constructorParams.financialProductLibraryAddress = params.financialProductLibraryAddress; } // IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method, // which is possible since the method is only an OPTIONAL method in the ERC20 standard: // https://eips.ethereum.org/EIPS/eip-20#methods. function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) { try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) { return _decimals; } catch { return 18; } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./ExpiringMultiParty.sol"; /** * @title Provides convenient Expiring Multi Party contract utilities. * @dev Using this library to deploy EMP's allows calling contracts to avoid importing the full EMP bytecode. */ library ExpiringMultiPartyLib { /** * @notice Returns address of new EMP deployed with given `params` configuration. * @dev Caller will need to register new EMP with the Registry to begin requesting prices. Caller is also * responsible for enforcing constraints on `params`. * @param params is a `ConstructorParams` object from ExpiringMultiParty. * @return address of the deployed ExpiringMultiParty contract */ function deploy(ExpiringMultiParty.ConstructorParams memory params) public returns (address) { ExpiringMultiParty derivative = new ExpiringMultiParty(params); return address(derivative); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./Liquidatable.sol"; /** * @title Expiring Multi Party. * @notice Convenient wrapper for Liquidatable. */ contract ExpiringMultiParty is Liquidatable { /** * @notice Constructs the ExpiringMultiParty contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PricelessPositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public Liquidatable(params) // Note: since there is no logic here, there is no need to add a re-entrancy guard. { } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "./PricelessPositionManager.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @title Liquidatable * @notice Adds logic to a position-managing contract that enables callers to liquidate an undercollateralized position. * @dev The liquidation has a liveness period before expiring successfully, during which someone can "dispute" the * liquidation, which sends a price request to the relevant Oracle to settle the final collateralization ratio based on * a DVM price. The contract enforces dispute rewards in order to incentivize disputers to correctly dispute false * liquidations and compensate position sponsors who had their position incorrectly liquidated. Importantly, a * prospective disputer must deposit a dispute bond that they can lose in the case of an unsuccessful dispute. * NOTE: this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on * transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing * money themselves). */ contract Liquidatable is PricelessPositionManager { using FixedPoint for FixedPoint.Unsigned; using SafeMath for uint256; using SafeERC20 for IERC20; using Address for address; /**************************************** * LIQUIDATION DATA STRUCTURES * ****************************************/ // Because of the check in withdrawable(), the order of these enum values should not change. enum Status { Uninitialized, NotDisputed, Disputed, DisputeSucceeded, DisputeFailed } struct LiquidationData { // Following variables set upon creation of liquidation: address sponsor; // Address of the liquidated position's sponsor address liquidator; // Address who created this liquidation Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle // Following variables determined by the position that is being liquidated: FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute // Amount of collateral being liquidated, which could be different from // lockedCollateral if there were pending withdrawals at the time of liquidation FixedPoint.Unsigned liquidatedCollateral; // Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation. FixedPoint.Unsigned rawUnitCollateral; // Following variable set upon initiation of a dispute: address disputer; // Person who is disputing a liquidation // Following variable set upon a resolution of a dispute: FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute FixedPoint.Unsigned finalFee; } // Define the contract's constructor parameters as a struct to enable more variables to be specified. // This is required to enable more params, over and above Solidity's limits. struct ConstructorParams { // Params for PricelessPositionManager only. uint256 expirationTimestamp; uint256 withdrawalLiveness; address collateralAddress; address tokenAddress; address finderAddress; address timerAddress; address financialProductLibraryAddress; bytes32 priceFeedIdentifier; FixedPoint.Unsigned minSponsorTokens; // Params specifically for Liquidatable. uint256 liquidationLiveness; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPercentage; FixedPoint.Unsigned sponsorDisputeRewardPercentage; FixedPoint.Unsigned disputerDisputeRewardPercentage; } // This struct is used in the `withdrawLiquidation` method that disperses liquidation and dispute rewards. // `payToX` stores the total collateral to withdraw from the contract to pay X. This value might differ // from `paidToX` due to precision loss between accounting for the `rawCollateral` versus the // fee-adjusted collateral. These variables are stored within a struct to avoid the stack too deep error. struct RewardsData { FixedPoint.Unsigned payToSponsor; FixedPoint.Unsigned payToLiquidator; FixedPoint.Unsigned payToDisputer; FixedPoint.Unsigned paidToSponsor; FixedPoint.Unsigned paidToLiquidator; FixedPoint.Unsigned paidToDisputer; } // Liquidations are unique by ID per sponsor mapping(address => LiquidationData[]) public liquidations; // Total collateral in liquidation. FixedPoint.Unsigned public rawLiquidationCollateral; // Immutable contract parameters: // Amount of time for pending liquidation before expiry. // !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors. // Extremely low liveness values increase the chance that opportunistic invalid liquidations // expire without dispute, thereby decreasing the usability for sponsors and increasing the risk // for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic // token holder for the contract. uint256 public liquidationLiveness; // Required collateral:TRV ratio for a position to be considered sufficiently collateralized. FixedPoint.Unsigned public collateralRequirement; // Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer // Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%" FixedPoint.Unsigned public disputeBondPercentage; // Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public sponsorDisputeRewardPercentage; // Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public disputerDisputeRewardPercentage; /**************************************** * EVENTS * ****************************************/ event LiquidationCreated( address indexed sponsor, address indexed liquidator, uint256 indexed liquidationId, uint256 tokensOutstanding, uint256 lockedCollateral, uint256 liquidatedCollateral, uint256 liquidationTime ); event LiquidationDisputed( address indexed sponsor, address indexed liquidator, address indexed disputer, uint256 liquidationId, uint256 disputeBondAmount ); event DisputeSettled( address indexed caller, address indexed sponsor, address indexed liquidator, address disputer, uint256 liquidationId, bool disputeSucceeded ); event LiquidationWithdrawn( address indexed caller, uint256 paidToLiquidator, uint256 paidToDisputer, uint256 paidToSponsor, Status indexed liquidationStatus, uint256 settlementPrice ); /**************************************** * MODIFIERS * ****************************************/ modifier disputable(uint256 liquidationId, address sponsor) { _disputable(liquidationId, sponsor); _; } modifier withdrawable(uint256 liquidationId, address sponsor) { _withdrawable(liquidationId, sponsor); _; } /** * @notice Constructs the liquidatable contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PricelessPositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public PricelessPositionManager( params.expirationTimestamp, params.withdrawalLiveness, params.collateralAddress, params.tokenAddress, params.finderAddress, params.priceFeedIdentifier, params.minSponsorTokens, params.timerAddress, params.financialProductLibraryAddress ) nonReentrant() { require(params.collateralRequirement.isGreaterThan(1)); require(params.sponsorDisputeRewardPercentage.add(params.disputerDisputeRewardPercentage).isLessThan(1)); // Set liquidatable specific variables. liquidationLiveness = params.liquidationLiveness; collateralRequirement = params.collateralRequirement; disputeBondPercentage = params.disputeBondPercentage; sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage; disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage; } /**************************************** * LIQUIDATION FUNCTIONS * ****************************************/ /** * @notice Liquidates the sponsor's position if the caller has enough * synthetic tokens to retire the position's outstanding tokens. Liquidations above * a minimum size also reset an ongoing "slow withdrawal"'s liveness. * @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be * approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param sponsor address of the sponsor to liquidate. * @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value. * @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value. * @param maxTokensToLiquidate max number of tokens to liquidate. * @param deadline abort the liquidation if the transaction is mined after this timestamp. * @return liquidationId ID of the newly created liquidation. * @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position. * @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully. */ function createLiquidation( address sponsor, FixedPoint.Unsigned calldata minCollateralPerToken, FixedPoint.Unsigned calldata maxCollateralPerToken, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) external fees() onlyPreExpiration() nonReentrant() returns ( uint256 liquidationId, FixedPoint.Unsigned memory tokensLiquidated, FixedPoint.Unsigned memory finalFeeBond ) { // Check that this transaction was mined pre-deadline. require(getCurrentTime() <= deadline, "Mined after deadline"); // Retrieve Position data for sponsor PositionData storage positionToLiquidate = _getPositionData(sponsor); tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding); require(tokensLiquidated.isGreaterThan(0)); // Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral, // then set this to 0, otherwise set it to (startCollateral - withdrawal request amount). FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral); FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0); if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) { startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount); } // Scoping to get rid of a stack too deep error. { FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding; // The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken]. // maxCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens. require( maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal), "CR is more than max liq. price" ); // minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens. require( minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal), "CR is less than min liq. price" ); } // Compute final fee at time of liquidation. finalFeeBond = _computeFinalFees(); // These will be populated within the scope below. FixedPoint.Unsigned memory lockedCollateral; FixedPoint.Unsigned memory liquidatedCollateral; // Scoping to get rid of a stack too deep error. { FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding); // The actual amount of collateral that gets moved to the liquidation. lockedCollateral = startCollateral.mul(ratio); // For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of // withdrawal requests. liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio); // Part of the withdrawal request is also removed. Ideally: // liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral. FixedPoint.Unsigned memory withdrawalAmountToRemove = positionToLiquidate.withdrawalRequestAmount.mul(ratio); _reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove); } // Add to the global liquidation collateral count. _addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond)); // Construct liquidation object. // Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new // LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push. liquidationId = liquidations[sponsor].length; liquidations[sponsor].push( LiquidationData({ sponsor: sponsor, liquidator: msg.sender, state: Status.NotDisputed, liquidationTime: getCurrentTime(), tokensOutstanding: tokensLiquidated, lockedCollateral: lockedCollateral, liquidatedCollateral: liquidatedCollateral, rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)), disputer: address(0), settlementPrice: FixedPoint.fromUnscaledUint(0), finalFee: finalFeeBond }) ); // If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than // some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be // "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold // is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal. // We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter // denominated in token currency units and we can avoid adding another parameter. FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens; if ( positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal. positionToLiquidate.withdrawalRequestPassTimestamp > getCurrentTime() && // The slow withdrawal has not yet expired. tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold". ) { positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness); } emit LiquidationCreated( sponsor, msg.sender, liquidationId, tokensLiquidated.rawValue, lockedCollateral.rawValue, liquidatedCollateral.rawValue, getCurrentTime() ); // Destroy tokens tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue); tokenCurrency.burn(tokensLiquidated.rawValue); // Pull final fee from liquidator. collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue); } /** * @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond * and pay a fixed final fee charged on each price request. * @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes. * This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute * bond amount is calculated from `disputeBondPercentage` times the collateral in the liquidation. * @param liquidationId of the disputed liquidation. * @param sponsor the address of the sponsor whose liquidation is being disputed. * @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond). */ function dispute(uint256 liquidationId, address sponsor) external disputable(liquidationId, sponsor) fees() nonReentrant() returns (FixedPoint.Unsigned memory totalPaid) { LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId); // Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees. FixedPoint.Unsigned memory disputeBondAmount = disputedLiquidation.lockedCollateral.mul(disputeBondPercentage).mul( _getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral) ); _addCollateral(rawLiquidationCollateral, disputeBondAmount); // Request a price from DVM. Liquidation is pending dispute until DVM returns a price. disputedLiquidation.state = Status.Disputed; disputedLiquidation.disputer = msg.sender; // Enqueue a request with the DVM. _requestOraclePriceLiquidation(disputedLiquidation.liquidationTime); emit LiquidationDisputed( sponsor, disputedLiquidation.liquidator, msg.sender, liquidationId, disputeBondAmount.rawValue ); totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee); // Pay the final fee for requesting price from the DVM. _payFinalFees(msg.sender, disputedLiquidation.finalFee); // Transfer the dispute bond amount from the caller to this contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue); } /** * @notice After a dispute has settled or after a non-disputed liquidation has expired, * anyone can call this method to disperse payments to the sponsor, liquidator, and disdputer. * @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment. * If the dispute FAILED: only the liquidator can receive payment. * This method will revert if rewards have already been dispersed. * @param liquidationId uniquely identifies the sponsor's liquidation. * @param sponsor address of the sponsor associated with the liquidation. * @return data about rewards paid out. */ function withdrawLiquidation(uint256 liquidationId, address sponsor) public withdrawable(liquidationId, sponsor) fees() nonReentrant() returns (RewardsData memory) { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settles the liquidation if necessary. This call will revert if the price has not resolved yet. _settle(liquidationId, sponsor); // Calculate rewards as a function of the TRV. // Note: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata. FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral); FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice; FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(settlementPrice).mul(feeAttenuation); FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation); FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPercentage); FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation); // There are three main outcome states: either the dispute succeeded, failed or was not updated. // Based on the state, different parties of a liquidation receive different amounts. // After assigning rewards based on the liquidation status, decrease the total collateral held in this contract // by the amount to pay each party. The actual amounts withdrawn might differ if _removeCollateral causes // precision loss. RewardsData memory rewards; if (liquidation.state == Status.DisputeSucceeded) { // If the dispute is successful then all three users should receive rewards: // Pay DISPUTER: disputer reward + dispute bond + returned final fee rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee); // Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward rewards.payToSponsor = sponsorDisputeReward.add(collateral.sub(tokenRedemptionValue)); // Pay LIQUIDATOR: TRV - dispute reward - sponsor reward // If TRV > Collateral, then subtract rewards from collateral // NOTE: `payToLiquidator` should never be below zero since we enforce that // (sponsorDisputePct+disputerDisputePct) <= 1 in the constructor when these params are set. rewards.payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(disputerDisputeReward); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); rewards.paidToSponsor = _removeCollateral(rawLiquidationCollateral, rewards.payToSponsor); rewards.paidToDisputer = _removeCollateral(rawLiquidationCollateral, rewards.payToDisputer); collateralCurrency.safeTransfer(liquidation.disputer, rewards.paidToDisputer.rawValue); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); collateralCurrency.safeTransfer(liquidation.sponsor, rewards.paidToSponsor.rawValue); // In the case of a failed dispute only the liquidator can withdraw. } else if (liquidation.state == Status.DisputeFailed) { // Pay LIQUIDATOR: collateral + dispute bond + returned final fee rewards.payToLiquidator = collateral.add(disputeBondAmount).add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); // If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this // state as a dispute failed and the liquidator can withdraw. } else if (liquidation.state == Status.NotDisputed) { // Pay LIQUIDATOR: collateral + returned final fee rewards.payToLiquidator = collateral.add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); } emit LiquidationWithdrawn( msg.sender, rewards.paidToLiquidator.rawValue, rewards.paidToDisputer.rawValue, rewards.paidToSponsor.rawValue, liquidation.state, settlementPrice.rawValue ); // Free up space after collateral is withdrawn by removing the liquidation object from the array. delete liquidations[sponsor][liquidationId]; return rewards; } /** * @notice Gets all liquidation information for a given sponsor address. * @param sponsor address of the position sponsor. * @return liquidationData array of all liquidation information for the given sponsor address. */ function getLiquidations(address sponsor) external view nonReentrantView() returns (LiquidationData[] memory liquidationData) { return liquidations[sponsor]; } /** * @notice Accessor method to calculate a transformed collateral requirement using the finanical product library specified during contract deployment. If no library was provided then no modification to the collateral requirement is done. * @param price input price used as an input to transform the collateral requirement. * @return transformedCollateralRequirement collateral requirement with transformation applied to it. * @dev This method should never revert. */ function transformCollateralRequirement(FixedPoint.Unsigned memory price) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _transformCollateralRequirement(price); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // This settles a liquidation if it is in the Disputed state. If not, it will immediately return. // If the liquidation is in the Disputed state, but a price is not available, this will revert. function _settle(uint256 liquidationId, address sponsor) internal { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settlement only happens when state == Disputed and will only happen once per liquidation. // If this liquidation is not ready to be settled, this method should return immediately. if (liquidation.state != Status.Disputed) { return; } // Get the returned price from the oracle. If this has not yet resolved will revert. liquidation.settlementPrice = _getOraclePriceLiquidation(liquidation.liquidationTime); // Find the value of the tokens in the underlying collateral. FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(liquidation.settlementPrice); // The required collateral is the value of the tokens in underlying * required collateral ratio. The Transform // Collateral requirement method applies a from the financial Product library to change the scaled the collateral // requirement based on the settlement price. If no library was specified when deploying the emp then this makes no change. FixedPoint.Unsigned memory requiredCollateral = tokenRedemptionValue.mul(_transformCollateralRequirement(liquidation.settlementPrice)); // If the position has more than the required collateral it is solvent and the dispute is valid(liquidation is invalid) // Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals. bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral); liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed; emit DisputeSettled( msg.sender, sponsor, liquidation.liquidator, liquidation.disputer, liquidationId, disputeSucceeded ); } function _pfc() internal view override returns (FixedPoint.Unsigned memory) { return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral)); } function _getLiquidationData(address sponsor, uint256 liquidationId) internal view returns (LiquidationData storage liquidation) { LiquidationData[] storage liquidationArray = liquidations[sponsor]; // Revert if the caller is attempting to access an invalid liquidation // (one that has never been created or one has never been initialized). require( liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized, "Invalid liquidation ID" ); return liquidationArray[liquidationId]; } function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) { return liquidation.liquidationTime.add(liquidationLiveness); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _disputable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); require( (getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.NotDisputed), "Liquidation not disputable" ); } function _withdrawable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); Status state = liquidation.state; // Must be disputed or the liquidation has passed expiry. require( (state > Status.NotDisputed) || ((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.NotDisputed)), "Liquidation not withdrawable" ); } function _transformCollateralRequirement(FixedPoint.Unsigned memory price) internal view returns (FixedPoint.Unsigned memory) { if (!address(financialProductLibrary).isContract()) return collateralRequirement; try financialProductLibrary.transformCollateralRequirement(price, collateralRequirement) returns ( FixedPoint.Unsigned memory transformedCollateralRequirement ) { return transformedCollateralRequirement; } catch { return collateralRequirement; } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./FinancialProductLibrary.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title Structured Note Financial Product Library * @notice Adds custom price transformation logic to modify the behavior of the expiring multi party contract. The * contract holds say 1 WETH in collateral and pays out that 1 WETH if, at expiry, ETHUSD is below a set strike. If * ETHUSD is above that strike, the contract pays out a given dollar amount of ETH. * Example: expiry is DEC 31. Strike is $400. Each token is backed by 1 WETH * If ETHUSD < $400 at expiry, token is redeemed for 1 ETH. * If ETHUSD >= $400 at expiry, token is redeemed for $400 worth of ETH, as determined by the DVM. */ contract StructuredNoteFinancialProductLibrary is FinancialProductLibrary, Ownable, Lockable { mapping(address => FixedPoint.Unsigned) financialProductStrikes; /** * @notice Enables the deployer of the library to set the strike price for an associated financial product. * @param financialProduct address of the financial product. * @param strikePrice the strike price for the structured note to be applied to the financial product. * @dev Note: a) Only the owner (deployer) of this library can set new strike prices b) A strike price cannot be 0. * c) A strike price can only be set once to prevent the deployer from changing the strike after the fact. * d) financialProduct must exposes an expirationTimestamp method. */ function setFinancialProductStrike(address financialProduct, FixedPoint.Unsigned memory strikePrice) public onlyOwner nonReentrant() { require(strikePrice.isGreaterThan(0), "Cant set 0 strike"); require(financialProductStrikes[financialProduct].isEqual(0), "Strike already set"); require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract"); financialProductStrikes[financialProduct] = strikePrice; } /** * @notice Returns the strike price associated with a given financial product address. * @param financialProduct address of the financial product. * @return strikePrice for the associated financial product. */ function getStrikeForFinancialProduct(address financialProduct) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return financialProductStrikes[financialProduct]; } /** * @notice Returns a transformed price by applying the structured note payout structure. * @param oraclePrice price from the oracle to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedPrice the input oracle price with the price transformation logic applied to it. */ function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender]; require(strike.isGreaterThan(0), "Caller has no strike"); // If price request is made before expiry, return 1. Thus we can keep the contract 100% collateralized with // each token backed 1:1 by collateral currency. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return FixedPoint.fromUnscaledUint(1); } if (oraclePrice.isLessThan(strike)) { return FixedPoint.fromUnscaledUint(1); } else { // Token expires to be worth strike $ worth of collateral. // eg if ETHUSD is $500 and strike is $400, token is redeemable for 400/500 = 0.8 WETH. return strike.div(oraclePrice); } } /** * @notice Returns a transformed collateral requirement by applying the structured note payout structure. If the price * of the structured note is greater than the strike then the collateral requirement scales down accordingly. * @param oraclePrice price from the oracle to transform the collateral requirement. * @param collateralRequirement financial products collateral requirement to be scaled according to price and strike. * @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it. */ function transformCollateralRequirement( FixedPoint.Unsigned memory oraclePrice, FixedPoint.Unsigned memory collateralRequirement ) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender]; require(strike.isGreaterThan(0), "Caller has no strike"); // If the price is less than the strike than the original collateral requirement is used. if (oraclePrice.isLessThan(strike)) { return collateralRequirement; } else { // If the price is more than the strike then the collateral requirement is scaled by the strike. For example // a strike of $400 and a CR of 1.2 would yield: // ETHUSD = $350, payout is 1 WETH. CR is multiplied by 1. resulting CR = 1.2 // ETHUSD = $400, payout is 1 WETH. CR is multiplied by 1. resulting CR = 1.2 // ETHUSD = $425, payout is 0.941 WETH (worth $400). CR is multiplied by 0.941. resulting CR = 1.1292 // ETHUSD = $500, payout is 0.8 WETH (worth $400). CR multiplied by 0.8. resulting CR = 0.96 return collateralRequirement.mul(strike.div(oraclePrice)); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./FinancialProductLibrary.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title Pre-Expiration Identifier Transformation Financial Product Library * @notice Adds custom identifier transformation to enable a financial contract to use two different identifiers, depending * on when a price request is made. If the request is made before expiration then a transformation is made to the identifier * & if it is at or after expiration then the original identifier is returned. This library enables self referential * TWAP identifier to be used on synthetics pre-expiration, in conjunction with a separate identifier at expiration. */ contract PreExpirationIdentifierTransformationFinancialProductLibrary is FinancialProductLibrary, Lockable { mapping(address => bytes32) financialProductTransformedIdentifiers; /** * @notice Enables the deployer of the library to set the transformed identifier for an associated financial product. * @param financialProduct address of the financial product. * @param transformedIdentifier the identifier for the financial product to be used if the contract is pre expiration. * @dev Note: a) Any address can set identifier transformations b) The identifier can't be set to blank. c) A * transformed price can only be set once to prevent the deployer from changing it after the fact. d) financialProduct * must expose an expirationTimestamp method. */ function setFinancialProductTransformedIdentifier(address financialProduct, bytes32 transformedIdentifier) public nonReentrant() { require(transformedIdentifier != "", "Cant set to empty transformation"); require(financialProductTransformedIdentifiers[financialProduct] == "", "Transformation already set"); require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract"); financialProductTransformedIdentifiers[financialProduct] = transformedIdentifier; } /** * @notice Returns the transformed identifier associated with a given financial product address. * @param financialProduct address of the financial product. * @return transformed identifier for the associated financial product. */ function getTransformedIdentifierForFinancialProduct(address financialProduct) public view nonReentrantView() returns (bytes32) { return financialProductTransformedIdentifiers[financialProduct]; } /** * @notice Returns a transformed price identifier if the contract is pre-expiration and no transformation if post. * @param identifier input price identifier to be transformed. * @param requestTime timestamp the identifier is to be used at. * @return transformedPriceIdentifier the input price identifier with the transformation logic applied to it. */ function transformPriceIdentifier(bytes32 identifier, uint256 requestTime) public view override nonReentrantView() returns (bytes32) { require(financialProductTransformedIdentifiers[msg.sender] != "", "Caller has no transformation"); // If the request time is before contract expiration then return the transformed identifier. Else, return the // original price identifier. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return financialProductTransformedIdentifiers[msg.sender]; } else { return identifier; } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./FinancialProductLibrary.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title Post-Expiration Identifier Transformation Financial Product Library * @notice Adds custom identifier transformation to enable a financial contract to use two different identifiers, depending * on when a price request is made. If the request is made at or after expiration then a transformation is made to the identifier * & if it is before expiration then the original identifier is returned. This library enables self referential * TWAP identifier to be used on synthetics pre-expiration, in conjunction with a separate identifier at expiration. */ contract PostExpirationIdentifierTransformationFinancialProductLibrary is FinancialProductLibrary, Lockable { mapping(address => bytes32) financialProductTransformedIdentifiers; /** * @notice Enables the deployer of the library to set the transformed identifier for an associated financial product. * @param financialProduct address of the financial product. * @param transformedIdentifier the identifier for the financial product to be used if the contract is post expiration. * @dev Note: a) Any address can set identifier transformations b) The identifier can't be set to blank. c) A * transformed price can only be set once to prevent the deployer from changing it after the fact. d) financialProduct * must expose an expirationTimestamp method. */ function setFinancialProductTransformedIdentifier(address financialProduct, bytes32 transformedIdentifier) public nonReentrant() { require(transformedIdentifier != "", "Cant set to empty transformation"); require(financialProductTransformedIdentifiers[financialProduct] == "", "Transformation already set"); require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract"); financialProductTransformedIdentifiers[financialProduct] = transformedIdentifier; } /** * @notice Returns the transformed identifier associated with a given financial product address. * @param financialProduct address of the financial product. * @return transformed identifier for the associated financial product. */ function getTransformedIdentifierForFinancialProduct(address financialProduct) public view nonReentrantView() returns (bytes32) { return financialProductTransformedIdentifiers[financialProduct]; } /** * @notice Returns a transformed price identifier if the contract is post-expiration and no transformation if pre. * @param identifier input price identifier to be transformed. * @param requestTime timestamp the identifier is to be used at. * @return transformedPriceIdentifier the input price identifier with the transformation logic applied to it. */ function transformPriceIdentifier(bytes32 identifier, uint256 requestTime) public view override nonReentrantView() returns (bytes32) { require(financialProductTransformedIdentifiers[msg.sender] != "", "Caller has no transformation"); // If the request time is after contract expiration then return the transformed identifier. Else, return the // original price identifier. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return identifier; } else { return financialProductTransformedIdentifiers[msg.sender]; } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./FinancialProductLibrary.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title KPI Options Financial Product Library * @notice Adds custom tranformation logic to modify the price and collateral requirement behavior of the expiring multi party contract. * If a price request is made pre-expiry, the price should always be set to 2 and the collateral requirement should be set to 1. * Post-expiry, the collateral requirement is left as 1 and the price is left unchanged. */ contract KpiOptionsFinancialProductLibrary is FinancialProductLibrary, Lockable { /** * @notice Returns a transformed price for pre-expiry price requests. * @param oraclePrice price from the oracle to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedPrice the input oracle price with the price transformation logic applied to it. */ function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { // If price request is made before expiry, return 2. Thus we can keep the contract 100% collateralized with // each token backed 1:2 by collateral currency. Post-expiry, leave unchanged. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return FixedPoint.fromUnscaledUint(2); } else { return oraclePrice; } } /** * @notice Returns a transformed collateral requirement that is set to be equivalent to 2 tokens pre-expiry. * @param oraclePrice price from the oracle to transform the collateral requirement. * @param collateralRequirement financial products collateral requirement to be scaled to a flat rate. * @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it. */ function transformCollateralRequirement( FixedPoint.Unsigned memory oraclePrice, FixedPoint.Unsigned memory collateralRequirement ) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { // Always return 1. return FixedPoint.fromUnscaledUint(1); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./FinancialProductLibrary.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title CoveredCall Financial Product Library * @notice Adds custom price transformation logic to modify the behavior of the expiring multi party contract. The * contract holds say 1 WETH in collateral and pays out a portion of that, at expiry, if ETHUSD is above a set strike. If * ETHUSD is below that strike, the contract pays out 0. The fraction paid out if above the strike is defined by * (oraclePrice - strikePrice) / oraclePrice; * Example: expiry is DEC 31. Strike is $400. Each token is backed by 1 WETH. * If ETHUSD = $600 at expiry, the call is $200 in the money, and the contract pays out 0.333 WETH (worth $200). * If ETHUSD = $800 at expiry, the call is $400 in the money, and the contract pays out 0.5 WETH (worth $400). * If ETHUSD =< $400 at expiry, the call is out of the money, and the contract pays out 0 WETH. */ contract CoveredCallFinancialProductLibrary is FinancialProductLibrary, Lockable { mapping(address => FixedPoint.Unsigned) private financialProductStrikes; /** * @notice Enables any address to set the strike price for an associated financial product. * @param financialProduct address of the financial product. * @param strikePrice the strike price for the covered call to be applied to the financial product. * @dev Note: a) Any address can set the initial strike price b) A strike price cannot be 0. * c) A strike price can only be set once to prevent the deployer from changing the strike after the fact. * d) For safety, a strike price should be set before depositing any synthetic tokens in a liquidity pool. * e) financialProduct must expose an expirationTimestamp method. */ function setFinancialProductStrike(address financialProduct, FixedPoint.Unsigned memory strikePrice) public nonReentrant() { require(strikePrice.isGreaterThan(0), "Cant set 0 strike"); require(financialProductStrikes[financialProduct].isEqual(0), "Strike already set"); require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract"); financialProductStrikes[financialProduct] = strikePrice; } /** * @notice Returns the strike price associated with a given financial product address. * @param financialProduct address of the financial product. * @return strikePrice for the associated financial product. */ function getStrikeForFinancialProduct(address financialProduct) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return financialProductStrikes[financialProduct]; } /** * @notice Returns a transformed price by applying the call option payout structure. * @param oraclePrice price from the oracle to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedPrice the input oracle price with the price transformation logic applied to it. */ function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender]; require(strike.isGreaterThan(0), "Caller has no strike"); // If price request is made before expiry, return 1. Thus we can keep the contract 100% collateralized with // each token backed 1:1 by collateral currency. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return FixedPoint.fromUnscaledUint(1); } if (oraclePrice.isLessThanOrEqual(strike)) { return FixedPoint.fromUnscaledUint(0); } else { // Token expires to be worth the fraction of a collateral token that's in the money. // eg if ETHUSD is $500 and strike is $400, token is redeemable for 100/500 = 0.2 WETH (worth $100). // Note: oraclePrice cannot be 0 here because it would always satisfy the if above because 0 <= x is always // true. return (oraclePrice.sub(strike)).div(oraclePrice); } } /** * @notice Returns a transformed collateral requirement by applying the covered call payout structure. * @param oraclePrice price from the oracle to transform the collateral requirement. * @param collateralRequirement financial products collateral requirement to be scaled according to price and strike. * @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it. */ function transformCollateralRequirement( FixedPoint.Unsigned memory oraclePrice, FixedPoint.Unsigned memory collateralRequirement ) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender]; require(strike.isGreaterThan(0), "Caller has no strike"); // Always return 1 because option must be collateralized by 1 token. return FixedPoint.fromUnscaledUint(1); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/Lockable.sol"; import "./ReentrancyAttack.sol"; // Tests reentrancy guards defined in Lockable.sol. // Extends https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.1/contracts/mocks/ReentrancyMock.sol. contract ReentrancyMock is Lockable { uint256 public counter; constructor() public { counter = 0; } function callback() external nonReentrant { _count(); } function countAndSend(ReentrancyAttack attacker) external nonReentrant { _count(); bytes4 func = bytes4(keccak256("callback()")); attacker.callSender(func); } function countAndCall(ReentrancyAttack attacker) external nonReentrant { _count(); bytes4 func = bytes4(keccak256("getCount()")); attacker.callSender(func); } function countLocalRecursive(uint256 n) public nonReentrant { if (n > 0) { _count(); countLocalRecursive(n - 1); } } function countThisRecursive(uint256 n) public nonReentrant { if (n > 0) { _count(); // solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(this).call(abi.encodeWithSignature("countThisRecursive(uint256)", n - 1)); require(success, "ReentrancyMock: failed call"); } } function countLocalCall() public nonReentrant { getCount(); } function countThisCall() public nonReentrant { // solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(this).call(abi.encodeWithSignature("getCount()")); require(success, "ReentrancyMock: failed call"); } function getCount() public view nonReentrantView returns (uint256) { return counter; } function _count() private { counter += 1; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; // Tests reentrancy guards defined in Lockable.sol. // Copied from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.1/contracts/mocks/ReentrancyAttack.sol. contract ReentrancyAttack { function callSender(bytes4 data) public { // solhint-disable-next-line avoid-low-level-calls (bool success, ) = msg.sender.call(abi.encodeWithSelector(data)); require(success, "ReentrancyAttack: failed call"); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../common/FeePayer.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../oracle/interfaces/IdentifierWhitelistInterface.sol"; import "../../oracle/interfaces/OracleInterface.sol"; import "../../oracle/implementation/ContractCreator.sol"; /** * @title Token Deposit Box * @notice This is a minimal example of a financial template that depends on price requests from the DVM. * This contract should be thought of as a "Deposit Box" into which the user deposits some ERC20 collateral. * The main feature of this box is that the user can withdraw their ERC20 corresponding to a desired USD amount. * When the user wants to make a withdrawal, a price request is enqueued with the UMA DVM. * For simplicty, the user is constrained to have one outstanding withdrawal request at any given time. * Regular fees are charged on the collateral in the deposit box throughout the lifetime of the deposit box, * and final fees are charged on each price request. * * This example is intended to accompany a technical tutorial for how to integrate the DVM into a project. * The main feature this demo serves to showcase is how to build a financial product on-chain that "pulls" price * requests from the DVM on-demand, which is an implementation of the "priceless" oracle framework. * * The typical user flow would be: * - User sets up a deposit box for the (wETH - USD) price-identifier. The "collateral currency" in this deposit * box is therefore wETH. * The user can subsequently make withdrawal requests for USD-denominated amounts of wETH. * - User deposits 10 wETH into their deposit box. * - User later requests to withdraw $100 USD of wETH. * - DepositBox asks DVM for latest wETH/USD exchange rate. * - DVM resolves the exchange rate at: 1 wETH is worth 200 USD. * - DepositBox transfers 0.5 wETH to user. */ contract DepositBox is FeePayer, ContractCreator { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; // Represents a single caller's deposit box. All collateral is held by this contract. struct DepositBoxData { // Requested amount of collateral, denominated in quote asset of the price identifier. // Example: If the price identifier is wETH-USD, and the `withdrawalRequestAmount = 100`, then // this represents a withdrawal request for 100 USD worth of wETH. FixedPoint.Unsigned withdrawalRequestAmount; // Timestamp of the latest withdrawal request. A withdrawal request is pending if `requestPassTimestamp != 0`. uint256 requestPassTimestamp; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; } // Maps addresses to their deposit boxes. Each address can have only one position. mapping(address => DepositBoxData) private depositBoxes; // Unique identifier for DVM price feed ticker. bytes32 private priceIdentifier; // Similar to the rawCollateral in DepositBoxData, this value should not be used directly. // _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust. FixedPoint.Unsigned private rawTotalDepositBoxCollateral; // This blocks every public state-modifying method until it flips to true, via the `initialize()` method. bool private initialized; /**************************************** * EVENTS * ****************************************/ event NewDepositBox(address indexed user); event EndedDepositBox(address indexed user); event Deposit(address indexed user, uint256 indexed collateralAmount); event RequestWithdrawal(address indexed user, uint256 indexed collateralAmount, uint256 requestPassTimestamp); event RequestWithdrawalExecuted( address indexed user, uint256 indexed collateralAmount, uint256 exchangeRate, uint256 requestPassTimestamp ); event RequestWithdrawalCanceled( address indexed user, uint256 indexed collateralAmount, uint256 requestPassTimestamp ); /**************************************** * MODIFIERS * ****************************************/ modifier noPendingWithdrawal(address user) { _depositBoxHasNoPendingWithdrawal(user); _; } modifier isInitialized() { _isInitialized(); _; } /**************************************** * PUBLIC FUNCTIONS * ****************************************/ /** * @notice Construct the DepositBox. * @param _collateralAddress ERC20 token to be deposited. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _priceIdentifier registered in the DVM, used to price the ERC20 deposited. * The price identifier consists of a "base" asset and a "quote" asset. The "base" asset corresponds to the collateral ERC20 * currency deposited into this account, and it is denominated in the "quote" asset on withdrawals. * An example price identifier would be "ETH-USD" which will resolve and return the USD price of ETH. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( address _collateralAddress, address _finderAddress, bytes32 _priceIdentifier, address _timerAddress ) public ContractCreator(_finderAddress) FeePayer(_collateralAddress, _finderAddress, _timerAddress) nonReentrant() { require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier), "Unsupported price identifier"); priceIdentifier = _priceIdentifier; } /** * @notice This should be called after construction of the DepositBox and handles registration with the Registry, which is required * to make price requests in production environments. * @dev This contract must hold the `ContractCreator` role with the Registry in order to register itself as a financial-template with the DVM. * Note that `_registerContract` cannot be called from the constructor because this contract first needs to be given the `ContractCreator` role * in order to register with the `Registry`. But, its address is not known until after deployment. */ function initialize() public nonReentrant() { initialized = true; _registerContract(new address[](0), address(this)); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into caller's deposit box. * @dev This contract must be approved to spend at least `collateralAmount` of `collateralCurrency`. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function deposit(FixedPoint.Unsigned memory collateralAmount) public isInitialized() fees() nonReentrant() { require(collateralAmount.isGreaterThan(0), "Invalid collateral amount"); DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; if (_getFeeAdjustedCollateral(depositBoxData.rawCollateral).isEqual(0)) { emit NewDepositBox(msg.sender); } // Increase the individual deposit box and global collateral balance by collateral amount. _incrementCollateralBalances(depositBoxData, collateralAmount); emit Deposit(msg.sender, collateralAmount.rawValue); // Move collateral currency from sender to contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); } /** * @notice Starts a withdrawal request that allows the sponsor to withdraw `denominatedCollateralAmount` * from their position denominated in the quote asset of the price identifier, following a DVM price resolution. * @dev The request will be pending for the duration of the DVM vote and can be cancelled at any time. * Only one withdrawal request can exist for the user. * @param denominatedCollateralAmount the quote-asset denominated amount of collateral requested to withdraw. */ function requestWithdrawal(FixedPoint.Unsigned memory denominatedCollateralAmount) public isInitialized() noPendingWithdrawal(msg.sender) nonReentrant() { DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; require(denominatedCollateralAmount.isGreaterThan(0), "Invalid collateral amount"); // Update the position object for the user. depositBoxData.withdrawalRequestAmount = denominatedCollateralAmount; depositBoxData.requestPassTimestamp = getCurrentTime(); emit RequestWithdrawal(msg.sender, denominatedCollateralAmount.rawValue, depositBoxData.requestPassTimestamp); // Every price request costs a fixed fee. Check that this user has enough deposited to cover the final fee. FixedPoint.Unsigned memory finalFee = _computeFinalFees(); require( _getFeeAdjustedCollateral(depositBoxData.rawCollateral).isGreaterThanOrEqual(finalFee), "Cannot pay final fee" ); _payFinalFees(address(this), finalFee); // A price request is sent for the current timestamp. _requestOraclePrice(depositBoxData.requestPassTimestamp); } /** * @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and subsequent DVM price resolution), * withdraws `depositBoxData.withdrawalRequestAmount` of collateral currency denominated in the quote asset. * @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested * amount exceeds the collateral in the position (due to paying fees). * @return amountWithdrawn The actual amount of collateral withdrawn. */ function executeWithdrawal() external isInitialized() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; require( depositBoxData.requestPassTimestamp != 0 && depositBoxData.requestPassTimestamp <= getCurrentTime(), "Invalid withdraw request" ); // Get the resolved price or revert. FixedPoint.Unsigned memory exchangeRate = _getOraclePrice(depositBoxData.requestPassTimestamp); // Calculate denomated amount of collateral based on resolved exchange rate. // Example 1: User wants to withdraw $100 of ETH, exchange rate is $200/ETH, therefore user to receive 0.5 ETH. // Example 2: User wants to withdraw $250 of ETH, exchange rate is $200/ETH, therefore user to receive 1.25 ETH. FixedPoint.Unsigned memory denominatedAmountToWithdraw = depositBoxData.withdrawalRequestAmount.div(exchangeRate); // If withdrawal request amount is > collateral, then withdraw the full collateral amount and delete the deposit box data. if (denominatedAmountToWithdraw.isGreaterThan(_getFeeAdjustedCollateral(depositBoxData.rawCollateral))) { denominatedAmountToWithdraw = _getFeeAdjustedCollateral(depositBoxData.rawCollateral); // Reset the position state as all the value has been removed after settlement. emit EndedDepositBox(msg.sender); } // Decrease the individual deposit box and global collateral balance. amountWithdrawn = _decrementCollateralBalances(depositBoxData, denominatedAmountToWithdraw); emit RequestWithdrawalExecuted( msg.sender, amountWithdrawn.rawValue, exchangeRate.rawValue, depositBoxData.requestPassTimestamp ); // Reset withdrawal request by setting withdrawal request timestamp to 0. _resetWithdrawalRequest(depositBoxData); // Transfer approved withdrawal amount from the contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); } /** * @notice Cancels a pending withdrawal request. */ function cancelWithdrawal() external isInitialized() nonReentrant() { DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; require(depositBoxData.requestPassTimestamp != 0, "No pending withdrawal"); emit RequestWithdrawalCanceled( msg.sender, depositBoxData.withdrawalRequestAmount.rawValue, depositBoxData.requestPassTimestamp ); // Reset withdrawal request by setting withdrawal request timestamp to 0. _resetWithdrawalRequest(depositBoxData); } /** * @notice `emergencyShutdown` and `remargin` are required to be implemented by all financial contracts and exposed to the DVM, but * because this is a minimal demo they will simply exit silently. */ function emergencyShutdown() external override isInitialized() nonReentrant() { return; } /** * @notice Same comment as `emergencyShutdown`. For the sake of simplicity, this will simply exit silently. */ function remargin() external override isInitialized() nonReentrant() { return; } /** * @notice Accessor method for a user's collateral. * @dev This is necessary because the struct returned by the depositBoxes() method shows * rawCollateral, which isn't a user-readable value. * @param user address whose collateral amount is retrieved. * @return the fee-adjusted collateral amount in the deposit box (i.e. available for withdrawal). */ function getCollateral(address user) external view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(depositBoxes[user].rawCollateral); } /** * @notice Accessor method for the total collateral stored within the entire contract. * @return the total fee-adjusted collateral amount in the contract (i.e. across all users). */ function totalDepositBoxCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Requests a price for `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePrice(uint256 requestedTime) internal { OracleInterface oracle = _getOracle(); oracle.requestPrice(priceIdentifier, requestedTime); } // Ensure individual and global consistency when increasing collateral balances. Returns the change to the position. function _incrementCollateralBalances( DepositBoxData storage depositBoxData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _addCollateral(depositBoxData.rawCollateral, collateralAmount); return _addCollateral(rawTotalDepositBoxCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the // position. We elect to return the amount that the global collateral is decreased by, rather than the individual // position's collateral, because we need to maintain the invariant that the global collateral is always // <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn. function _decrementCollateralBalances( DepositBoxData storage depositBoxData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(depositBoxData.rawCollateral, collateralAmount); return _removeCollateral(rawTotalDepositBoxCollateral, collateralAmount); } function _resetWithdrawalRequest(DepositBoxData storage depositBoxData) internal { depositBoxData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0); depositBoxData.requestPassTimestamp = 0; } function _depositBoxHasNoPendingWithdrawal(address user) internal view { require(depositBoxes[user].requestPassTimestamp == 0, "Pending withdrawal"); } function _isInitialized() internal view { require(initialized, "Uninitialized contract"); } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } function _getOracle() internal view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) { OracleInterface oracle = _getOracle(); require(oracle.hasPrice(priceIdentifier, requestedTime), "Unresolved oracle price"); int256 oraclePrice = oracle.getPrice(priceIdentifier, requestedTime); // For simplicity we don't want to deal with negative prices. if (oraclePrice < 0) { oraclePrice = 0; } return FixedPoint.Unsigned(uint256(oraclePrice)); } // `_pfc()` is inherited from FeePayer and must be implemented to return the available pool of collateral from // which fees can be charged. For this contract, the available fee pool is simply all of the collateral locked up in the // contract. function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "./VotingToken.sol"; /** * @title Migration contract for VotingTokens. * @dev Handles migrating token holders from one token to the next. */ contract TokenMigrator { using FixedPoint for FixedPoint.Unsigned; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ VotingToken public oldToken; ExpandedIERC20 public newToken; uint256 public snapshotId; FixedPoint.Unsigned public rate; mapping(address => bool) public hasMigrated; /** * @notice Construct the TokenMigrator contract. * @dev This function triggers the snapshot upon which all migrations will be based. * @param _rate the number of old tokens it takes to generate one new token. * @param _oldToken address of the token being migrated from. * @param _newToken address of the token being migrated to. */ constructor( FixedPoint.Unsigned memory _rate, address _oldToken, address _newToken ) public { // Prevents division by 0 in migrateTokens(). // Also it doesn’t make sense to have “0 old tokens equate to 1 new token”. require(_rate.isGreaterThan(0), "Rate can't be 0"); rate = _rate; newToken = ExpandedIERC20(_newToken); oldToken = VotingToken(_oldToken); snapshotId = oldToken.snapshot(); } /** * @notice Migrates the tokenHolder's old tokens to new tokens. * @dev This function can only be called once per `tokenHolder`. Anyone can call this method * on behalf of any other token holder since there is no disadvantage to receiving the tokens earlier. * @param tokenHolder address of the token holder to migrate. */ function migrateTokens(address tokenHolder) external { require(!hasMigrated[tokenHolder], "Already migrated tokens"); hasMigrated[tokenHolder] = true; FixedPoint.Unsigned memory oldBalance = FixedPoint.Unsigned(oldToken.balanceOfAt(tokenHolder, snapshotId)); if (!oldBalance.isGreaterThan(0)) { return; } FixedPoint.Unsigned memory newBalance = oldBalance.div(rate); require(newToken.mint(tokenHolder, newBalance.rawValue), "Mint failed"); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/ExpandedERC20.sol"; contract TokenSender { function transferERC20( address tokenAddress, address recipientAddress, uint256 amount ) public returns (bool) { IERC20 token = IERC20(tokenAddress); token.transfer(recipientAddress, amount); return true; } } pragma solidity ^0.6.0; import "../GSN/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./IDepositExecute.sol"; import "./IBridge.sol"; import "./IERCHandler.sol"; import "./IGenericHandler.sol"; /** @title Facilitates deposits, creation and votiing of deposit proposals, and deposit executions. @author ChainSafe Systems. */ contract Bridge is Pausable, AccessControl { using SafeMath for uint256; uint8 public _chainID; uint256 public _relayerThreshold; uint256 public _totalRelayers; uint256 public _totalProposals; uint256 public _fee; uint256 public _expiry; enum Vote { No, Yes } enum ProposalStatus { Inactive, Active, Passed, Executed, Cancelled } struct Proposal { bytes32 _resourceID; bytes32 _dataHash; address[] _yesVotes; address[] _noVotes; ProposalStatus _status; uint256 _proposedBlock; } // destinationChainID => number of deposits mapping(uint8 => uint64) public _depositCounts; // resourceID => handler address mapping(bytes32 => address) public _resourceIDToHandlerAddress; // depositNonce => destinationChainID => bytes mapping(uint64 => mapping(uint8 => bytes)) public _depositRecords; // destinationChainID + depositNonce => dataHash => Proposal mapping(uint72 => mapping(bytes32 => Proposal)) public _proposals; // destinationChainID + depositNonce => dataHash => relayerAddress => bool mapping(uint72 => mapping(bytes32 => mapping(address => bool))) public _hasVotedOnProposal; event RelayerThresholdChanged(uint256 indexed newThreshold); event RelayerAdded(address indexed relayer); event RelayerRemoved(address indexed relayer); event Deposit(uint8 indexed destinationChainID, bytes32 indexed resourceID, uint64 indexed depositNonce); event ProposalEvent( uint8 indexed originChainID, uint64 indexed depositNonce, ProposalStatus indexed status, bytes32 resourceID, bytes32 dataHash ); event ProposalVote( uint8 indexed originChainID, uint64 indexed depositNonce, ProposalStatus indexed status, bytes32 resourceID ); bytes32 public constant RELAYER_ROLE = keccak256("RELAYER_ROLE"); modifier onlyAdmin() { _onlyAdmin(); _; } modifier onlyAdminOrRelayer() { _onlyAdminOrRelayer(); _; } modifier onlyRelayers() { _onlyRelayers(); _; } function _onlyAdminOrRelayer() private { require( hasRole(DEFAULT_ADMIN_ROLE, msg.sender) || hasRole(RELAYER_ROLE, msg.sender), "sender is not relayer or admin" ); } function _onlyAdmin() private { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "sender doesn't have admin role"); } function _onlyRelayers() private { require(hasRole(RELAYER_ROLE, msg.sender), "sender doesn't have relayer role"); } /** @notice Initializes Bridge, creates and grants {msg.sender} the admin role, creates and grants {initialRelayers} the relayer role. @param chainID ID of chain the Bridge contract exists on. @param initialRelayers Addresses that should be initially granted the relayer role. @param initialRelayerThreshold Number of votes needed for a deposit proposal to be considered passed. */ constructor( uint8 chainID, address[] memory initialRelayers, uint256 initialRelayerThreshold, uint256 fee, uint256 expiry ) public { _chainID = chainID; _relayerThreshold = initialRelayerThreshold; _fee = fee; _expiry = expiry; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setRoleAdmin(RELAYER_ROLE, DEFAULT_ADMIN_ROLE); for (uint256 i; i < initialRelayers.length; i++) { grantRole(RELAYER_ROLE, initialRelayers[i]); _totalRelayers++; } } /** @notice Returns true if {relayer} has the relayer role. @param relayer Address to check. */ function isRelayer(address relayer) external view returns (bool) { return hasRole(RELAYER_ROLE, relayer); } /** @notice Removes admin role from {msg.sender} and grants it to {newAdmin}. @notice Only callable by an address that currently has the admin role. @param newAdmin Address that admin role will be granted to. */ function renounceAdmin(address newAdmin) external onlyAdmin { grantRole(DEFAULT_ADMIN_ROLE, newAdmin); renounceRole(DEFAULT_ADMIN_ROLE, msg.sender); } /** @notice Pauses deposits, proposal creation and voting, and deposit executions. @notice Only callable by an address that currently has the admin role. */ function adminPauseTransfers() external onlyAdmin { _pause(); } /** @notice Unpauses deposits, proposal creation and voting, and deposit executions. @notice Only callable by an address that currently has the admin role. */ function adminUnpauseTransfers() external onlyAdmin { _unpause(); } /** @notice Modifies the number of votes required for a proposal to be considered passed. @notice Only callable by an address that currently has the admin role. @param newThreshold Value {_relayerThreshold} will be changed to. @notice Emits {RelayerThresholdChanged} event. */ function adminChangeRelayerThreshold(uint256 newThreshold) external onlyAdmin { _relayerThreshold = newThreshold; emit RelayerThresholdChanged(newThreshold); } /** @notice Grants {relayerAddress} the relayer role and increases {_totalRelayer} count. @notice Only callable by an address that currently has the admin role. @param relayerAddress Address of relayer to be added. @notice Emits {RelayerAdded} event. */ function adminAddRelayer(address relayerAddress) external onlyAdmin { require(!hasRole(RELAYER_ROLE, relayerAddress), "addr already has relayer role!"); grantRole(RELAYER_ROLE, relayerAddress); emit RelayerAdded(relayerAddress); _totalRelayers++; } /** @notice Removes relayer role for {relayerAddress} and decreases {_totalRelayer} count. @notice Only callable by an address that currently has the admin role. @param relayerAddress Address of relayer to be removed. @notice Emits {RelayerRemoved} event. */ function adminRemoveRelayer(address relayerAddress) external onlyAdmin { require(hasRole(RELAYER_ROLE, relayerAddress), "addr doesn't have relayer role!"); revokeRole(RELAYER_ROLE, relayerAddress); emit RelayerRemoved(relayerAddress); _totalRelayers--; } /** @notice Sets a new resource for handler contracts that use the IERCHandler interface, and maps the {handlerAddress} to {resourceID} in {_resourceIDToHandlerAddress}. @notice Only callable by an address that currently has the admin role. @param handlerAddress Address of handler resource will be set for. @param resourceID ResourceID to be used when making deposits. @param tokenAddress Address of contract to be called when a deposit is made and a deposited is executed. */ function adminSetResource( address handlerAddress, bytes32 resourceID, address tokenAddress ) external onlyAdmin { _resourceIDToHandlerAddress[resourceID] = handlerAddress; IERCHandler handler = IERCHandler(handlerAddress); handler.setResource(resourceID, tokenAddress); } /** @notice Sets a new resource for handler contracts that use the IGenericHandler interface, and maps the {handlerAddress} to {resourceID} in {_resourceIDToHandlerAddress}. @notice Only callable by an address that currently has the admin role. @param handlerAddress Address of handler resource will be set for. @param resourceID ResourceID to be used when making deposits. @param contractAddress Address of contract to be called when a deposit is made and a deposited is executed. */ function adminSetGenericResource( address handlerAddress, bytes32 resourceID, address contractAddress, bytes4 depositFunctionSig, bytes4 executeFunctionSig ) external onlyAdmin { _resourceIDToHandlerAddress[resourceID] = handlerAddress; IGenericHandler handler = IGenericHandler(handlerAddress); handler.setResource(resourceID, contractAddress, depositFunctionSig, executeFunctionSig); } /** @notice Sets a resource as burnable for handler contracts that use the IERCHandler interface. @notice Only callable by an address that currently has the admin role. @param handlerAddress Address of handler resource will be set for. @param tokenAddress Address of contract to be called when a deposit is made and a deposited is executed. */ function adminSetBurnable(address handlerAddress, address tokenAddress) external onlyAdmin { IERCHandler handler = IERCHandler(handlerAddress); handler.setBurnable(tokenAddress); } /** @notice Returns a proposal. @param originChainID Chain ID deposit originated from. @param depositNonce ID of proposal generated by proposal's origin Bridge contract. @param dataHash Hash of data to be provided when deposit proposal is executed. @return Proposal which consists of: - _dataHash Hash of data to be provided when deposit proposal is executed. - _yesVotes Number of votes in favor of proposal. - _noVotes Number of votes against proposal. - _status Current status of proposal. */ function getProposal( uint8 originChainID, uint64 depositNonce, bytes32 dataHash ) external view returns (Proposal memory) { uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(originChainID); return _proposals[nonceAndID][dataHash]; } /** @notice Changes deposit fee. @notice Only callable by admin. @param newFee Value {_fee} will be updated to. */ function adminChangeFee(uint256 newFee) external onlyAdmin { require(_fee != newFee, "Current fee is equal to new fee"); _fee = newFee; } /** @notice Used to manually withdraw funds from ERC safes. @param handlerAddress Address of handler to withdraw from. @param tokenAddress Address of token to withdraw. @param recipient Address to withdraw tokens to. @param amountOrTokenID Either the amount of ERC20 tokens or the ERC721 token ID to withdraw. */ function adminWithdraw( address handlerAddress, address tokenAddress, address recipient, uint256 amountOrTokenID ) external onlyAdmin { IERCHandler handler = IERCHandler(handlerAddress); handler.withdraw(tokenAddress, recipient, amountOrTokenID); } /** @notice Initiates a transfer using a specified handler contract. @notice Only callable when Bridge is not paused. @param destinationChainID ID of chain deposit will be bridged to. @param resourceID ResourceID used to find address of handler to be used for deposit. @param data Additional data to be passed to specified handler. @notice Emits {Deposit} event. */ function deposit( uint8 destinationChainID, bytes32 resourceID, bytes calldata data ) external payable whenNotPaused { require(msg.value == _fee, "Incorrect fee supplied"); address handler = _resourceIDToHandlerAddress[resourceID]; require(handler != address(0), "resourceID not mapped to handler"); uint64 depositNonce = ++_depositCounts[destinationChainID]; _depositRecords[depositNonce][destinationChainID] = data; IDepositExecute depositHandler = IDepositExecute(handler); depositHandler.deposit(resourceID, destinationChainID, depositNonce, msg.sender, data); emit Deposit(destinationChainID, resourceID, depositNonce); } /** @notice When called, {msg.sender} will be marked as voting in favor of proposal. @notice Only callable by relayers when Bridge is not paused. @param chainID ID of chain deposit originated from. @param depositNonce ID of deposited generated by origin Bridge contract. @param dataHash Hash of data provided when deposit was made. @notice Proposal must not have already been passed or executed. @notice {msg.sender} must not have already voted on proposal. @notice Emits {ProposalEvent} event with status indicating the proposal status. @notice Emits {ProposalVote} event. */ function voteProposal( uint8 chainID, uint64 depositNonce, bytes32 resourceID, bytes32 dataHash ) external onlyRelayers whenNotPaused { uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID); Proposal storage proposal = _proposals[nonceAndID][dataHash]; require(_resourceIDToHandlerAddress[resourceID] != address(0), "no handler for resourceID"); require(uint256(proposal._status) <= 1, "proposal already passed/executed/cancelled"); require(!_hasVotedOnProposal[nonceAndID][dataHash][msg.sender], "relayer already voted"); if (uint256(proposal._status) == 0) { ++_totalProposals; _proposals[nonceAndID][dataHash] = Proposal({ _resourceID: resourceID, _dataHash: dataHash, _yesVotes: new address[](1), _noVotes: new address[](0), _status: ProposalStatus.Active, _proposedBlock: block.number }); proposal._yesVotes[0] = msg.sender; emit ProposalEvent(chainID, depositNonce, ProposalStatus.Active, resourceID, dataHash); } else { if (block.number.sub(proposal._proposedBlock) > _expiry) { // if the number of blocks that has passed since this proposal was // submitted exceeds the expiry threshold set, cancel the proposal proposal._status = ProposalStatus.Cancelled; emit ProposalEvent(chainID, depositNonce, ProposalStatus.Cancelled, resourceID, dataHash); } else { require(dataHash == proposal._dataHash, "datahash mismatch"); proposal._yesVotes.push(msg.sender); } } if (proposal._status != ProposalStatus.Cancelled) { _hasVotedOnProposal[nonceAndID][dataHash][msg.sender] = true; emit ProposalVote(chainID, depositNonce, proposal._status, resourceID); // If _depositThreshold is set to 1, then auto finalize // or if _relayerThreshold has been exceeded if (_relayerThreshold <= 1 || proposal._yesVotes.length >= _relayerThreshold) { proposal._status = ProposalStatus.Passed; emit ProposalEvent(chainID, depositNonce, ProposalStatus.Passed, resourceID, dataHash); } } } /** @notice Executes a deposit proposal that is considered passed using a specified handler contract. @notice Only callable by relayers when Bridge is not paused. @param chainID ID of chain deposit originated from. @param depositNonce ID of deposited generated by origin Bridge contract. @param dataHash Hash of data originally provided when deposit was made. @notice Proposal must be past expiry threshold. @notice Emits {ProposalEvent} event with status {Cancelled}. */ function cancelProposal( uint8 chainID, uint64 depositNonce, bytes32 dataHash ) public onlyAdminOrRelayer { uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID); Proposal storage proposal = _proposals[nonceAndID][dataHash]; require(proposal._status != ProposalStatus.Cancelled, "Proposal already cancelled"); require(block.number.sub(proposal._proposedBlock) > _expiry, "Proposal not at expiry threshold"); proposal._status = ProposalStatus.Cancelled; emit ProposalEvent(chainID, depositNonce, ProposalStatus.Cancelled, proposal._resourceID, proposal._dataHash); } /** @notice Executes a deposit proposal that is considered passed using a specified handler contract. @notice Only callable by relayers when Bridge is not paused. @param chainID ID of chain deposit originated from. @param resourceID ResourceID to be used when making deposits. @param depositNonce ID of deposited generated by origin Bridge contract. @param data Data originally provided when deposit was made. @notice Proposal must have Passed status. @notice Hash of {data} must equal proposal's {dataHash}. @notice Emits {ProposalEvent} event with status {Executed}. */ function executeProposal( uint8 chainID, uint64 depositNonce, bytes calldata data, bytes32 resourceID ) external onlyRelayers whenNotPaused { address handler = _resourceIDToHandlerAddress[resourceID]; uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID); bytes32 dataHash = keccak256(abi.encodePacked(handler, data)); Proposal storage proposal = _proposals[nonceAndID][dataHash]; require(proposal._status != ProposalStatus.Inactive, "proposal is not active"); require(proposal._status == ProposalStatus.Passed, "proposal already transferred"); require(dataHash == proposal._dataHash, "data doesn't match datahash"); proposal._status = ProposalStatus.Executed; IDepositExecute depositHandler = IDepositExecute(_resourceIDToHandlerAddress[proposal._resourceID]); depositHandler.executeProposal(proposal._resourceID, data); emit ProposalEvent(chainID, depositNonce, proposal._status, proposal._resourceID, proposal._dataHash); } /** @notice Transfers eth in the contract to the specified addresses. The parameters addrs and amounts are mapped 1-1. This means that the address at index 0 for addrs will receive the amount (in WEI) from amounts at index 0. @param addrs Array of addresses to transfer {amounts} to. @param amounts Array of amonuts to transfer to {addrs}. */ function transferFunds(address payable[] calldata addrs, uint256[] calldata amounts) external onlyAdmin { for (uint256 i = 0; i < addrs.length; i++) { addrs[i].transfer(amounts[i]); } } } pragma solidity ^0.6.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../GSN/Context.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, _msgSender())); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } pragma solidity ^0.6.0; /** @title Interface for handler contracts that support deposits and deposit executions. @author ChainSafe Systems. */ interface IDepositExecute { /** @notice It is intended that deposit are made using the Bridge contract. @param destinationChainID Chain ID deposit is expected to be bridged to. @param depositNonce This value is generated as an ID by the Bridge contract. @param depositer Address of account making the deposit in the Bridge contract. @param data Consists of additional data needed for a specific deposit. */ function deposit( bytes32 resourceID, uint8 destinationChainID, uint64 depositNonce, address depositer, bytes calldata data ) external; /** @notice It is intended that proposals are executed by the Bridge contract. @param data Consists of additional data needed for a specific deposit execution. */ function executeProposal(bytes32 resourceID, bytes calldata data) external; } pragma solidity ^0.6.0; /** @title Interface for Bridge contract. @author ChainSafe Systems. */ interface IBridge { /** @notice Exposing getter for {_chainID} instead of forcing the use of call. @return uint8 The {_chainID} that is currently set for the Bridge contract. */ function _chainID() external returns (uint8); } pragma solidity ^0.6.0; /** @title Interface to be used with handlers that support ERC20s and ERC721s. @author ChainSafe Systems. */ interface IERCHandler { /** @notice Correlates {resourceID} with {contractAddress}. @param resourceID ResourceID to be used when making deposits. @param contractAddress Address of contract to be called when a deposit is made and a deposited is executed. */ function setResource(bytes32 resourceID, address contractAddress) external; /** @notice Marks {contractAddress} as mintable/burnable. @param contractAddress Address of contract to be used when making or executing deposits. */ function setBurnable(address contractAddress) external; /** @notice Used to manually release funds from ERC safes. @param tokenAddress Address of token contract to release. @param recipient Address to release tokens to. @param amountOrTokenID Either the amount of ERC20 tokens or the ERC721 token ID to release. */ function withdraw( address tokenAddress, address recipient, uint256 amountOrTokenID ) external; } pragma solidity ^0.6.0; /** @title Interface for handler that handles generic deposits and deposit executions. @author ChainSafe Systems. */ interface IGenericHandler { /** @notice Correlates {resourceID} with {contractAddress}, {depositFunctionSig}, and {executeFunctionSig}. @param resourceID ResourceID to be used when making deposits. @param contractAddress Address of contract to be called when a deposit is made and a deposited is executed. @param depositFunctionSig Function signature of method to be called in {contractAddress} when a deposit is made. @param executeFunctionSig Function signature of method to be called in {contractAddress} when a deposit is executed. */ function setResource( bytes32 resourceID, address contractAddress, bytes4 depositFunctionSig, bytes4 executeFunctionSig ) external; } pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./IGenericHandler.sol"; /** @title Handles generic deposits and deposit executions. @author ChainSafe Systems. @notice This contract is intended to be used with the Bridge contract. */ contract GenericHandler is IGenericHandler { address public _bridgeAddress; struct DepositRecord { uint8 _destinationChainID; address _depositer; bytes32 _resourceID; bytes _metaData; } // depositNonce => Deposit Record mapping(uint8 => mapping(uint64 => DepositRecord)) public _depositRecords; // resourceID => contract address mapping(bytes32 => address) public _resourceIDToContractAddress; // contract address => resourceID mapping(address => bytes32) public _contractAddressToResourceID; // contract address => deposit function signature mapping(address => bytes4) public _contractAddressToDepositFunctionSignature; // contract address => execute proposal function signature mapping(address => bytes4) public _contractAddressToExecuteFunctionSignature; // token contract address => is whitelisted mapping(address => bool) public _contractWhitelist; modifier onlyBridge() { _onlyBridge(); _; } function _onlyBridge() private { require(msg.sender == _bridgeAddress, "sender must be bridge contract"); } /** @param bridgeAddress Contract address of previously deployed Bridge. @param initialResourceIDs Resource IDs used to identify a specific contract address. These are the Resource IDs this contract will initially support. @param initialContractAddresses These are the addresses the {initialResourceIDs} will point to, and are the contracts that will be called to perform deposit and execution calls. @param initialDepositFunctionSignatures These are the function signatures {initialContractAddresses} will point to, and are the function that will be called when executing {deposit} @param initialExecuteFunctionSignatures These are the function signatures {initialContractAddresses} will point to, and are the function that will be called when executing {executeProposal} @dev {initialResourceIDs}, {initialContractAddresses}, {initialDepositFunctionSignatures}, and {initialExecuteFunctionSignatures} must all have the same length. Also, values must be ordered in the way that that index x of any mentioned array must be intended for value x of any other array, e.g. {initialContractAddresses}[0] is the intended address for {initialDepositFunctionSignatures}[0]. */ constructor( address bridgeAddress, bytes32[] memory initialResourceIDs, address[] memory initialContractAddresses, bytes4[] memory initialDepositFunctionSignatures, bytes4[] memory initialExecuteFunctionSignatures ) public { require( initialResourceIDs.length == initialContractAddresses.length, "initialResourceIDs and initialContractAddresses len mismatch" ); require( initialContractAddresses.length == initialDepositFunctionSignatures.length, "provided contract addresses and function signatures len mismatch" ); require( initialDepositFunctionSignatures.length == initialExecuteFunctionSignatures.length, "provided deposit and execute function signatures len mismatch" ); _bridgeAddress = bridgeAddress; for (uint256 i = 0; i < initialResourceIDs.length; i++) { _setResource( initialResourceIDs[i], initialContractAddresses[i], initialDepositFunctionSignatures[i], initialExecuteFunctionSignatures[i] ); } } /** @param depositNonce This ID will have been generated by the Bridge contract. @param destId ID of chain deposit will be bridged to. @return DepositRecord which consists of: - _destinationChainID ChainID deposited tokens are intended to end up on. - _resourceID ResourceID used when {deposit} was executed. - _depositer Address that initially called {deposit} in the Bridge contract. - _metaData Data to be passed to method executed in corresponding {resourceID} contract. */ function getDepositRecord(uint64 depositNonce, uint8 destId) external view returns (DepositRecord memory) { return _depositRecords[destId][depositNonce]; } /** @notice First verifies {_resourceIDToContractAddress}[{resourceID}] and {_contractAddressToResourceID}[{contractAddress}] are not already set, then sets {_resourceIDToContractAddress} with {contractAddress}, {_contractAddressToResourceID} with {resourceID}, {_contractAddressToDepositFunctionSignature} with {depositFunctionSig}, {_contractAddressToExecuteFunctionSignature} with {executeFunctionSig}, and {_contractWhitelist} to true for {contractAddress}. @param resourceID ResourceID to be used when making deposits. @param contractAddress Address of contract to be called when a deposit is made and a deposited is executed. @param depositFunctionSig Function signature of method to be called in {contractAddress} when a deposit is made. @param executeFunctionSig Function signature of method to be called in {contractAddress} when a deposit is executed. */ function setResource( bytes32 resourceID, address contractAddress, bytes4 depositFunctionSig, bytes4 executeFunctionSig ) external override onlyBridge { _setResource(resourceID, contractAddress, depositFunctionSig, executeFunctionSig); } /** @notice A deposit is initiatied by making a deposit in the Bridge contract. @param destinationChainID Chain ID deposit is expected to be bridged to. @param depositNonce This value is generated as an ID by the Bridge contract. @param depositer Address of account making the deposit in the Bridge contract. @param data Consists of: {resourceID}, {lenMetaData}, and {metaData} all padded to 32 bytes. @notice Data passed into the function should be constructed as follows: len(data) uint256 bytes 0 - 32 data bytes bytes 64 - END @notice {contractAddress} is required to be whitelisted @notice If {_contractAddressToDepositFunctionSignature}[{contractAddress}] is set, {metaData} is expected to consist of needed function arguments. */ function deposit( bytes32 resourceID, uint8 destinationChainID, uint64 depositNonce, address depositer, bytes calldata data ) external onlyBridge { bytes32 lenMetadata; bytes memory metadata; assembly { // Load length of metadata from data + 64 lenMetadata := calldataload(0xC4) // Load free memory pointer metadata := mload(0x40) mstore(0x40, add(0x20, add(metadata, lenMetadata))) // func sig (4) + destinationChainId (padded to 32) + depositNonce (32) + depositor (32) + // bytes length (32) + resourceId (32) + length (32) = 0xC4 calldatacopy( metadata, // copy to metadata 0xC4, // copy from calldata after metadata length declaration @0xC4 sub(calldatasize(), 0xC4) // copy size (calldatasize - (0xC4 + the space metaData takes up)) ) } address contractAddress = _resourceIDToContractAddress[resourceID]; require(_contractWhitelist[contractAddress], "provided contractAddress is not whitelisted"); bytes4 sig = _contractAddressToDepositFunctionSignature[contractAddress]; if (sig != bytes4(0)) { bytes memory callData = abi.encodePacked(sig, metadata); (bool success, ) = contractAddress.call(callData); require(success, "delegatecall to contractAddress failed"); } _depositRecords[destinationChainID][depositNonce] = DepositRecord( destinationChainID, depositer, resourceID, metadata ); } /** @notice Proposal execution should be initiated when a proposal is finalized in the Bridge contract. @param data Consists of {resourceID}, {lenMetaData}, and {metaData}. @notice Data passed into the function should be constructed as follows: len(data) uint256 bytes 0 - 32 data bytes bytes 32 - END @notice {contractAddress} is required to be whitelisted @notice If {_contractAddressToExecuteFunctionSignature}[{contractAddress}] is set, {metaData} is expected to consist of needed function arguments. */ function executeProposal(bytes32 resourceID, bytes calldata data) external onlyBridge { bytes memory metaData; assembly { // metadata has variable length // load free memory pointer to store metadata metaData := mload(0x40) // first 32 bytes of variable length in storage refer to length let lenMeta := calldataload(0x64) mstore(0x40, add(0x60, add(metaData, lenMeta))) // in the calldata, metadata is stored @0x64 after accounting for function signature, and 2 previous params calldatacopy( metaData, // copy to metaData 0x64, // copy from calldata after data length declaration at 0x64 sub(calldatasize(), 0x64) // copy size (calldatasize - 0x64) ) } address contractAddress = _resourceIDToContractAddress[resourceID]; require(_contractWhitelist[contractAddress], "provided contractAddress is not whitelisted"); bytes4 sig = _contractAddressToExecuteFunctionSignature[contractAddress]; if (sig != bytes4(0)) { bytes memory callData = abi.encodePacked(sig, metaData); (bool success, ) = contractAddress.call(callData); require(success, "delegatecall to contractAddress failed"); } } function _setResource( bytes32 resourceID, address contractAddress, bytes4 depositFunctionSig, bytes4 executeFunctionSig ) internal { _resourceIDToContractAddress[resourceID] = contractAddress; _contractAddressToResourceID[contractAddress] = resourceID; _contractAddressToDepositFunctionSignature[contractAddress] = depositFunctionSig; _contractAddressToExecuteFunctionSignature[contractAddress] = executeFunctionSig; _contractWhitelist[contractAddress] = true; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../../interfaces/VotingInterface.sol"; import "../VoteTiming.sol"; // Wraps the library VoteTiming for testing purposes. contract VoteTimingTest { using VoteTiming for VoteTiming.Data; VoteTiming.Data public voteTiming; constructor(uint256 phaseLength) public { wrapInit(phaseLength); } function wrapComputeCurrentRoundId(uint256 currentTime) external view returns (uint256) { return voteTiming.computeCurrentRoundId(currentTime); } function wrapComputeCurrentPhase(uint256 currentTime) external view returns (VotingAncillaryInterface.Phase) { return voteTiming.computeCurrentPhase(currentTime); } function wrapInit(uint256 phaseLength) public { voteTiming.init(phaseLength); } } pragma solidity ^0.6.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "@uniswap/lib/contracts/libraries/Babylonian.sol"; import "@uniswap/lib/contracts/libraries/TransferHelper.sol"; import "@uniswap/lib/contracts/libraries/FullMath.sol"; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol"; /** * @title UniswapBroker * @notice Trading contract used to arb uniswap pairs to a desired "true" price. Intended use is to arb UMA perpetual * synthetics that trade off peg. This implementation can ber used in conjunction with a DSProxy contract to atomically * swap and move a uniswap market. */ contract UniswapBroker { using SafeMath for uint256; /** * @notice Swaps an amount of either token such that the trade results in the uniswap pair's price being as close as * possible to the truePrice. * @dev True price is expressed in the ratio of token A to token B. * @dev The caller must approve this contract to spend whichever token is intended to be swapped. * @param tradingAsEOA bool to indicate if the UniswapBroker is being called by a DSProxy or an EOA. * @param uniswapRouter address of the uniswap router used to facilitate trades. * @param uniswapFactory address of the uniswap factory used to fetch current pair reserves. * @param swappedTokens array of addresses which are to be swapped. The order does not matter as the function will figure * out which tokens need to be exchanged to move the market to the desired "true" price. * @param truePriceTokens array of unit used to represent the true price. 0th value is the numerator of the true price * and the 1st value is the the denominator of the true price. * @param maxSpendTokens array of unit to represent the max to spend in the two tokens. * @param to recipient of the trade proceeds. * @param deadline to limit when the trade can execute. If the tx is mined after this timestamp then revert. */ function swapToPrice( bool tradingAsEOA, address uniswapRouter, address uniswapFactory, address[2] memory swappedTokens, uint256[2] memory truePriceTokens, uint256[2] memory maxSpendTokens, address to, uint256 deadline ) public { IUniswapV2Router01 router = IUniswapV2Router01(uniswapRouter); // true price is expressed as a ratio, so both values must be non-zero require(truePriceTokens[0] != 0 && truePriceTokens[1] != 0, "SwapToPrice: ZERO_PRICE"); // caller can specify 0 for either if they wish to swap in only one direction, but not both require(maxSpendTokens[0] != 0 || maxSpendTokens[1] != 0, "SwapToPrice: ZERO_SPEND"); bool aToB; uint256 amountIn; { (uint256 reserveA, uint256 reserveB) = getReserves(uniswapFactory, swappedTokens[0], swappedTokens[1]); (aToB, amountIn) = computeTradeToMoveMarket(truePriceTokens[0], truePriceTokens[1], reserveA, reserveB); } require(amountIn > 0, "SwapToPrice: ZERO_AMOUNT_IN"); // spend up to the allowance of the token in uint256 maxSpend = aToB ? maxSpendTokens[0] : maxSpendTokens[1]; if (amountIn > maxSpend) { amountIn = maxSpend; } address tokenIn = aToB ? swappedTokens[0] : swappedTokens[1]; address tokenOut = aToB ? swappedTokens[1] : swappedTokens[0]; TransferHelper.safeApprove(tokenIn, address(router), amountIn); if (tradingAsEOA) TransferHelper.safeTransferFrom(tokenIn, msg.sender, address(this), amountIn); address[] memory path = new address[](2); path[0] = tokenIn; path[1] = tokenOut; router.swapExactTokensForTokens( amountIn, 0, // amountOutMin: we can skip computing this number because the math is tested within the uniswap tests. path, to, deadline ); } /** * @notice Given the "true" price a token (represented by truePriceTokenA/truePriceTokenB) and the reservers in the * uniswap pair, calculate: a) the direction of trade (aToB) and b) the amount needed to trade (amountIn) to move * the pool price to be equal to the true price. * @dev Note that this method uses the Babylonian square root method which has a small margin of error which will * result in a small over or under estimation on the size of the trade needed. * @param truePriceTokenA the nominator of the true price. * @param truePriceTokenB the denominator of the true price. * @param reserveA number of token A in the pair reserves * @param reserveB number of token B in the pair reserves */ // function computeTradeToMoveMarket( uint256 truePriceTokenA, uint256 truePriceTokenB, uint256 reserveA, uint256 reserveB ) public pure returns (bool aToB, uint256 amountIn) { aToB = FullMath.mulDiv(reserveA, truePriceTokenB, reserveB) < truePriceTokenA; uint256 invariant = reserveA.mul(reserveB); // The trade ∆a of token a required to move the market to some desired price P' from the current price P can be // found with ∆a=(kP')^1/2-Ra. uint256 leftSide = Babylonian.sqrt( FullMath.mulDiv( invariant, aToB ? truePriceTokenA : truePriceTokenB, aToB ? truePriceTokenB : truePriceTokenA ) ); uint256 rightSide = (aToB ? reserveA : reserveB); if (leftSide < rightSide) return (false, 0); // compute the amount that must be sent to move the price back to the true price. amountIn = leftSide.sub(rightSide); } // The methods below are taken from https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/libraries/UniswapV2Library.sol // We could import this library into this contract but this library is dependent Uniswap's SafeMath, which is bound // to solidity 6.6.6. Hardhat can easily deal with two different sets of solidity versions within one project so // unit tests would continue to work fine. However, this would break truffle support in the repo as truffle cant // handel having two different solidity versions. As a work around, the specific methods needed in the UniswapBroker // are simply moved here to maintain truffle support. function getReserves( address factory, address tokenA, address tokenB ) public view returns (uint256 reserveA, uint256 reserveB) { (address token0, ) = sortTokens(tokenA, tokenB); (uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, "UniswapV2Library: IDENTICAL_ADDRESSES"); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), "UniswapV2Library: ZERO_ADDRESS"); } // calculates the CREATE2 address for a pair without making any external calls function pairFor( address factory, address tokenA, address tokenB ) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address( uint256( keccak256( abi.encodePacked( hex"ff", factory, keccak256(abi.encodePacked(token0, token1)), hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" // init code hash ) ) ) ); } } pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.4.0; // computes square roots using the babylonian method // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method library Babylonian { // credit for this implementation goes to // https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687 function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; // this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2); // however that code costs significantly more gas uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return (r < r1 ? r : r1); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.6.0; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::safeApprove: approve failed' ); } function safeTransfer( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::safeTransfer: transfer failed' ); } function safeTransferFrom( address token, address from, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::transferFrom: transferFrom failed' ); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'TransferHelper::safeTransferETH: ETH transfer failed'); } } // SPDX-License-Identifier: CC-BY-4.0 pragma solidity >=0.4.0; // taken from https://medium.com/coinmonks/math-in-solidity-part-3-percents-and-proportions-4db014e080b1 // license is CC-BY-4.0 library FullMath { function fullMul(uint256 x, uint256 y) internal pure returns (uint256 l, uint256 h) { uint256 mm = mulmod(x, y, uint256(-1)); l = x * y; h = mm - l; if (mm < l) h -= 1; } function fullDiv( uint256 l, uint256 h, uint256 d ) private pure returns (uint256) { uint256 pow2 = d & -d; d /= pow2; l /= pow2; l += h * ((-pow2) / pow2 + 1); uint256 r = 1; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; return l * r; } function mulDiv( uint256 x, uint256 y, uint256 d ) internal pure returns (uint256) { (uint256 l, uint256 h) = fullMul(x, y); uint256 mm = mulmod(x, y, d); if (mm > l) h -= 1; l -= mm; if (h == 0) return l / d; require(h < d, 'FullMath: FULLDIV_OVERFLOW'); return fullDiv(l, h, d); } } pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@uniswap/lib/contracts/libraries/TransferHelper.sol"; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @title ReserveCurrencyLiquidator * @notice Helper contract to enable a liquidator to hold one reserver currency and liquidate against any number of * financial contracts. Is assumed to be called by a DSProxy which holds reserve currency. */ contract ReserveCurrencyLiquidator { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; /** * @notice Swaps required amount of reserve currency to collateral currency which is then used to mint tokens to * liquidate a position within one transaction. * @dev After the liquidation is done the DSProxy that called this method will have an open position AND pending * liquidation within the financial contract. The bot using the DSProxy should withdraw the liquidation once it has * passed liveness. At this point the position can be manually unwound. * @dev Any synthetics & collateral that the DSProxy already has are considered in the amount swapped and minted. * These existing tokens will be used first before any swaps or mints are done. * @dev If there is a token shortfall (either from not enough reserve to buy sufficient collateral or not enough * collateral to begins with or due to slippage) the script will liquidate as much as possible given the reserves. * @param uniswapRouter address of the uniswap router used to facilitate trades. * @param financialContract address of the financial contract on which the liquidation is occurring. * @param reserveCurrency address of the token to swap for collateral. THis is the common currency held by the DSProxy. * @param liquidatedSponsor address of the sponsor to be liquidated. * @param maxReserveTokenSpent maximum number of reserve tokens to spend in the trade. Bounds slippage. * @param minCollateralPerTokenLiquidated abort the liquidation if the position's collateral per token is below this value. * @param maxCollateralPerTokenLiquidated abort the liquidation if the position's collateral per token exceeds this value. * @param maxTokensToLiquidate max number of tokens to liquidate. For a full liquidation this is the full position debt. * @param deadline abort the trade and liquidation if the transaction is mined after this timestamp. **/ function swapMintLiquidate( address uniswapRouter, address financialContract, address reserveCurrency, address liquidatedSponsor, FixedPoint.Unsigned calldata maxReserveTokenSpent, FixedPoint.Unsigned calldata minCollateralPerTokenLiquidated, FixedPoint.Unsigned calldata maxCollateralPerTokenLiquidated, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) public { IFinancialContract fc = IFinancialContract(financialContract); // 1. Calculate the token shortfall. This is the synthetics to liquidate minus any synthetics the DSProxy already // has. If this number is negative(balance large than synthetics to liquidate) the return 0 (no shortfall). FixedPoint.Unsigned memory tokenShortfall = subOrZero(maxTokensToLiquidate, getSyntheticBalance(fc)); // 2. Calculate how much collateral is needed to make up the token shortfall from minting new synthetics. FixedPoint.Unsigned memory gcr = fc.pfc().divCeil(fc.totalTokensOutstanding()); FixedPoint.Unsigned memory collateralToMintShortfall = tokenShortfall.mulCeil(gcr); // 3. Calculate the total collateral required. This considers the final fee for the given collateral type + any // collateral needed to mint the token short fall. FixedPoint.Unsigned memory totalCollateralRequired = getFinalFee(fc).add(collateralToMintShortfall); // 4.a. Calculate how much collateral needs to be purchased. If the DSProxy already has some collateral then this // will factor this in. If the DSProxy has more collateral than the total amount required the purchased = 0. FixedPoint.Unsigned memory collateralToBePurchased = subOrZero(totalCollateralRequired, getCollateralBalance(fc)); // 4.b. If there is some collateral to be purchased, execute a trade on uniswap to meet the shortfall. // Note the path assumes a direct route from the reserve currency to the collateral currency. if (collateralToBePurchased.isGreaterThan(0) && reserveCurrency != fc.collateralCurrency()) { IUniswapV2Router01 router = IUniswapV2Router01(uniswapRouter); address[] memory path = new address[](2); path[0] = reserveCurrency; path[1] = fc.collateralCurrency(); TransferHelper.safeApprove(reserveCurrency, address(router), maxReserveTokenSpent.rawValue); router.swapTokensForExactTokens( collateralToBePurchased.rawValue, maxReserveTokenSpent.rawValue, path, address(this), deadline ); } // 4.c. If at this point we were not able to get the required amount of collateral (due to insufficient reserve // or not enough collateral in the contract) the script should try to liquidate as much as it can regardless. // Update the values of total collateral to the current collateral balance and re-compute the tokenShortfall // as the maximum tokens that could be liquidated at the current GCR. if (totalCollateralRequired.isGreaterThan(getCollateralBalance(fc))) { totalCollateralRequired = getCollateralBalance(fc); collateralToMintShortfall = totalCollateralRequired.sub(getFinalFee(fc)); tokenShortfall = collateralToMintShortfall.divCeil(gcr); } // 5. Mint the shortfall synthetics with collateral. Note we are minting at the GCR. // If the DSProxy already has enough tokens (tokenShortfall = 0) we still preform the approval on the collateral // currency as this is needed to pay the final fee in the liquidation tx. TransferHelper.safeApprove(fc.collateralCurrency(), address(fc), totalCollateralRequired.rawValue); if (tokenShortfall.isGreaterThan(0)) fc.create(collateralToMintShortfall, tokenShortfall); // The liquidatableTokens is either the maxTokensToLiquidate (if we were able to buy/mint enough) or the full // token token balance at this point if there was a shortfall. FixedPoint.Unsigned memory liquidatableTokens = maxTokensToLiquidate; if (maxTokensToLiquidate.isGreaterThan(getSyntheticBalance(fc))) liquidatableTokens = getSyntheticBalance(fc); // 6. Liquidate position with newly minted synthetics. TransferHelper.safeApprove(fc.tokenCurrency(), address(fc), liquidatableTokens.rawValue); fc.createLiquidation( liquidatedSponsor, minCollateralPerTokenLiquidated, maxCollateralPerTokenLiquidated, liquidatableTokens, deadline ); } // Helper method to work around subtraction overflow in the case of: a - b with b > a. function subOrZero(FixedPoint.Unsigned memory a, FixedPoint.Unsigned memory b) internal pure returns (FixedPoint.Unsigned memory) { return b.isGreaterThanOrEqual(a) ? FixedPoint.fromUnscaledUint(0) : a.sub(b); } // Helper method to return the current final fee for a given financial contract instance. function getFinalFee(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) { return IStore(IFinder(fc.finder()).getImplementationAddress("Store")).computeFinalFee(fc.collateralCurrency()); } // Helper method to return the collateral balance of this contract. function getCollateralBalance(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) { return FixedPoint.Unsigned(IERC20(fc.collateralCurrency()).balanceOf(address(this))); } // Helper method to return the synthetic balance of this contract. function getSyntheticBalance(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) { return FixedPoint.Unsigned(IERC20(fc.tokenCurrency()).balanceOf(address(this))); } } // Define some simple interfaces for dealing with UMA contracts. interface IFinancialContract { struct PositionData { FixedPoint.Unsigned tokensOutstanding; uint256 withdrawalRequestPassTimestamp; FixedPoint.Unsigned withdrawalRequestAmount; FixedPoint.Unsigned rawCollateral; uint256 transferPositionRequestPassTimestamp; } function positions(address sponsor) external returns (PositionData memory); function collateralCurrency() external returns (address); function tokenCurrency() external returns (address); function finder() external returns (address); function pfc() external returns (FixedPoint.Unsigned memory); function totalTokensOutstanding() external returns (FixedPoint.Unsigned memory); function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) external; function createLiquidation( address sponsor, FixedPoint.Unsigned calldata minCollateralPerToken, FixedPoint.Unsigned calldata maxCollateralPerToken, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) external returns ( uint256 liquidationId, FixedPoint.Unsigned memory tokensLiquidated, FixedPoint.Unsigned memory finalFeeBond ); } interface IStore { function computeFinalFee(address currency) external returns (FixedPoint.Unsigned memory); } interface IFinder { function getImplementationAddress(bytes32 interfaceName) external view returns (address); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "@uniswap/lib/contracts/libraries/TransferHelper.sol"; // Simple contract used to redeem tokens using a DSProxy from an emp. contract TokenRedeemer { function redeem(address financialContractAddress, FixedPoint.Unsigned memory numTokens) public returns (FixedPoint.Unsigned memory) { IFinancialContract fc = IFinancialContract(financialContractAddress); TransferHelper.safeApprove(fc.tokenCurrency(), financialContractAddress, numTokens.rawValue); return fc.redeem(numTokens); } } interface IFinancialContract { function redeem(FixedPoint.Unsigned memory numTokens) external returns (FixedPoint.Unsigned memory amountWithdrawn); function tokenCurrency() external returns (address); } /* MultiRoleTest contract. */ // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/MultiRole.sol"; // The purpose of this contract is to make the MultiRole creation methods externally callable for testing purposes. contract MultiRoleTest is MultiRole { function createSharedRole( uint256 roleId, uint256 managingRoleId, address[] calldata initialMembers ) external { _createSharedRole(roleId, managingRoleId, initialMembers); } function createExclusiveRole( uint256 roleId, uint256 managingRoleId, address initialMember ) external { _createExclusiveRole(roleId, managingRoleId, initialMember); } // solhint-disable-next-line no-empty-blocks function revertIfNotHoldingRole(uint256 roleId) external view onlyRoleHolder(roleId) {} } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/Testable.sol"; // TestableTest is derived from the abstract contract Testable for testing purposes. contract TestableTest is Testable { // solhint-disable-next-line no-empty-blocks constructor(address _timerAddress) public Testable(_timerAddress) {} function getTestableTimeAndBlockTime() external view returns (uint256 testableTime, uint256 blockTime) { // solhint-disable-next-line not-rely-on-time return (getCurrentTime(), now); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../interfaces/VaultInterface.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Mock for yearn-style vaults for use in tests. */ contract VaultMock is VaultInterface { IERC20 public override token; uint256 private pricePerFullShare = 0; constructor(IERC20 _token) public { token = _token; } function getPricePerFullShare() external view override returns (uint256) { return pricePerFullShare; } function setPricePerFullShare(uint256 _pricePerFullShare) external { pricePerFullShare = _pricePerFullShare; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Interface for Yearn-style vaults. * @dev This only contains the methods/events that we use in our contracts or offchain infrastructure. */ abstract contract VaultInterface { // Return the underlying token. function token() external view virtual returns (IERC20); // Gets the number of return tokens that a "share" of this vault is worth. function getPricePerFullShare() external view virtual returns (uint256); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Implements only the required ERC20 methods. This contract is used * test how contracts handle ERC20 contracts that have not implemented `decimals()` * @dev Mostly copied from Consensys EIP-20 implementation: * https://github.com/ConsenSys/Tokens/blob/fdf687c69d998266a95f15216b1955a4965a0a6d/contracts/eip20/EIP20.sol */ contract BasicERC20 is IERC20 { uint256 private constant MAX_UINT256 = 2**256 - 1; mapping(address => uint256) public balances; mapping(address => mapping(address => uint256)) public allowed; uint256 private _totalSupply; constructor(uint256 _initialAmount) public { balances[msg.sender] = _initialAmount; _totalSupply = _initialAmount; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function transfer(address _to, uint256 _value) public override returns (bool success) { require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; } function transferFrom( address _from, address _to, uint256 _value ) public override returns (bool success) { uint256 allowance = allowed[_from][msg.sender]; require(balances[_from] >= _value && allowance >= _value); balances[_to] += _value; balances[_from] -= _value; if (allowance < MAX_UINT256) { allowed[_from][msg.sender] -= _value; } emit Transfer(_from, _to, _value); //solhint-disable-line indent, no-unused-vars return true; } function balanceOf(address _owner) public view override returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public override returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); //solhint-disable-line indent, no-unused-vars return true; } function allowance(address _owner, address _spender) public view override returns (uint256 remaining) { return allowed[_owner][_spender]; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../ResultComputation.sol"; import "../../../common/implementation/FixedPoint.sol"; // Wraps the library ResultComputation for testing purposes. contract ResultComputationTest { using ResultComputation for ResultComputation.Data; ResultComputation.Data public data; function wrapAddVote(int256 votePrice, uint256 numberTokens) external { data.addVote(votePrice, FixedPoint.Unsigned(numberTokens)); } function wrapGetResolvedPrice(uint256 minVoteThreshold) external view returns (bool isResolved, int256 price) { return data.getResolvedPrice(FixedPoint.Unsigned(minVoteThreshold)); } function wrapWasVoteCorrect(bytes32 revealHash) external view returns (bool) { return data.wasVoteCorrect(revealHash); } function wrapGetTotalCorrectlyVotedTokens() external view returns (uint256) { return data.getTotalCorrectlyVotedTokens().rawValue; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../Voting.sol"; import "../../../common/implementation/FixedPoint.sol"; // Test contract used to access internal variables in the Voting contract. contract VotingTest is Voting { constructor( uint256 _phaseLength, FixedPoint.Unsigned memory _gatPercentage, FixedPoint.Unsigned memory _inflationRate, uint256 _rewardsExpirationTimeout, address _votingToken, address _finder, address _timerAddress ) public Voting( _phaseLength, _gatPercentage, _inflationRate, _rewardsExpirationTimeout, _votingToken, _finder, _timerAddress ) {} function getPendingPriceRequestsArray() external view returns (bytes32[] memory) { return pendingPriceRequests; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/FixedPoint.sol"; // Wraps the FixedPoint library for testing purposes. contract UnsignedFixedPointTest { using FixedPoint for FixedPoint.Unsigned; using FixedPoint for uint256; using SafeMath for uint256; function wrapFromUnscaledUint(uint256 a) external pure returns (uint256) { return FixedPoint.fromUnscaledUint(a).rawValue; } function wrapIsEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isEqual(FixedPoint.Unsigned(b)); } function wrapMixedIsEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isEqual(b); } function wrapIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThan(FixedPoint.Unsigned(b)); } function wrapIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThanOrEqual(FixedPoint.Unsigned(b)); } function wrapMixedIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThan(b); } function wrapMixedIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThanOrEqual(b); } function wrapMixedIsGreaterThanOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isGreaterThan(FixedPoint.Unsigned(b)); } function wrapMixedIsGreaterThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isGreaterThanOrEqual(FixedPoint.Unsigned(b)); } function wrapIsLessThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThan(FixedPoint.Unsigned(b)); } function wrapIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThanOrEqual(FixedPoint.Unsigned(b)); } function wrapMixedIsLessThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThan(b); } function wrapMixedIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThanOrEqual(b); } function wrapMixedIsLessThanOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isLessThan(FixedPoint.Unsigned(b)); } function wrapMixedIsLessThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isLessThanOrEqual(FixedPoint.Unsigned(b)); } function wrapMin(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).min(FixedPoint.Unsigned(b)).rawValue; } function wrapMax(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).max(FixedPoint.Unsigned(b)).rawValue; } function wrapAdd(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).add(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedAdd(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).add(b).rawValue; } function wrapSub(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).sub(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSub(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).sub(b).rawValue; } // The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSubOpposite(uint256 a, uint256 b) external pure returns (uint256) { return a.sub(FixedPoint.Unsigned(b)).rawValue; } function wrapMul(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mul(FixedPoint.Unsigned(b)).rawValue; } function wrapMulCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mulCeil(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedMul(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mul(b).rawValue; } function wrapMixedMulCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mulCeil(b).rawValue; } function wrapDiv(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).div(FixedPoint.Unsigned(b)).rawValue; } function wrapDivCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).divCeil(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDiv(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).div(b).rawValue; } function wrapMixedDivCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).divCeil(b).rawValue; } // The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDivOpposite(uint256 a, uint256 b) external pure returns (uint256) { return a.div(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapPow(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).pow(b).rawValue; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/FixedPoint.sol"; // Wraps the FixedPoint library for testing purposes. contract SignedFixedPointTest { using FixedPoint for FixedPoint.Signed; using FixedPoint for int256; using SafeMath for int256; function wrapFromSigned(int256 a) external pure returns (uint256) { return FixedPoint.fromSigned(FixedPoint.Signed(a)).rawValue; } function wrapFromUnsigned(uint256 a) external pure returns (int256) { return FixedPoint.fromUnsigned(FixedPoint.Unsigned(a)).rawValue; } function wrapFromUnscaledInt(int256 a) external pure returns (int256) { return FixedPoint.fromUnscaledInt(a).rawValue; } function wrapIsEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isEqual(FixedPoint.Signed(b)); } function wrapMixedIsEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isEqual(b); } function wrapIsGreaterThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThan(FixedPoint.Signed(b)); } function wrapIsGreaterThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThanOrEqual(FixedPoint.Signed(b)); } function wrapMixedIsGreaterThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThan(b); } function wrapMixedIsGreaterThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThanOrEqual(b); } function wrapMixedIsGreaterThanOpposite(int256 a, int256 b) external pure returns (bool) { return a.isGreaterThan(FixedPoint.Signed(b)); } function wrapMixedIsGreaterThanOrEqualOpposite(int256 a, int256 b) external pure returns (bool) { return a.isGreaterThanOrEqual(FixedPoint.Signed(b)); } function wrapIsLessThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThan(FixedPoint.Signed(b)); } function wrapIsLessThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThanOrEqual(FixedPoint.Signed(b)); } function wrapMixedIsLessThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThan(b); } function wrapMixedIsLessThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThanOrEqual(b); } function wrapMixedIsLessThanOpposite(int256 a, int256 b) external pure returns (bool) { return a.isLessThan(FixedPoint.Signed(b)); } function wrapMixedIsLessThanOrEqualOpposite(int256 a, int256 b) external pure returns (bool) { return a.isLessThanOrEqual(FixedPoint.Signed(b)); } function wrapMin(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).min(FixedPoint.Signed(b)).rawValue; } function wrapMax(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).max(FixedPoint.Signed(b)).rawValue; } function wrapAdd(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).add(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedAdd(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).add(b).rawValue; } function wrapSub(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).sub(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSub(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).sub(b).rawValue; } // The second int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSubOpposite(int256 a, int256 b) external pure returns (int256) { return a.sub(FixedPoint.Signed(b)).rawValue; } function wrapMul(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mul(FixedPoint.Signed(b)).rawValue; } function wrapMulAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mulAwayFromZero(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedMul(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mul(b).rawValue; } function wrapMixedMulAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mulAwayFromZero(b).rawValue; } function wrapDiv(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).div(FixedPoint.Signed(b)).rawValue; } function wrapDivAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).divAwayFromZero(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDiv(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).div(b).rawValue; } function wrapMixedDivAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).divAwayFromZero(b).rawValue; } // The second int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDivOpposite(int256 a, int256 b) external pure returns (int256) { return a.div(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapPow(int256 a, uint256 b) external pure returns (int256) { return FixedPoint.Signed(a).pow(b).rawValue; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; /** * @title Simple Perpetual Mock to serve trivial functions */ contract PerpetualMock { struct FundingRate { FixedPoint.Signed rate; bytes32 identifier; FixedPoint.Unsigned cumulativeMultiplier; uint256 updateTime; uint256 applicationTime; uint256 proposalTime; } using FixedPoint for FixedPoint.Unsigned; using FixedPoint for FixedPoint.Signed; FundingRate public fundingRate; // Interface functions required to be implemented in order for an instance of this contract to be passed into the // off-chain FinancialContractClient helper module: FixedPoint.Unsigned public collateralRequirement; uint256 public liquidationLiveness; FixedPoint.Unsigned public cumulativeFeeMultiplier; mapping(address => uint256) public positions; mapping(address => uint256) public liquidations; event NewSponsor(address indexed sponsor); event EndedSponsorPosition(); event LiquidationCreated(); function getCurrentTime() public view returns (uint256) { return now; } // Public methods that are useful for tests: function setFundingRate(FundingRate memory _fundingRate) external { fundingRate = _fundingRate; } function applyFundingRate() external { fundingRate.applicationTime = block.timestamp; // Simplified rate calcualtion. // multiplier = multiplier * (1 + rate) fundingRate.cumulativeMultiplier = fundingRate.cumulativeMultiplier.mul( FixedPoint.fromSigned(FixedPoint.fromUnscaledInt(1).add(fundingRate.rate)) ); } }
Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global collateralization ratio.
function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private view returns (bool) { FixedPoint.Unsigned memory global = _getCollateralizationRatio(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding); FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens); return !global.isGreaterThan(thisChange); }
99,536
./full_match/1/0xdF3b985E15281EfecF203998200b26F024699F47/sources/browser/Brrr.sol
Adds stimulus package to be claimed by users Calling conditions: - Only can be added by founding fathers /
function addStimulus(uint128 _id, uint256 _total_amount, uint256 _ending_in_days, uint256 _amount_to_get) isOnline public returns (bool) { require( hasRole(FOUNDING_FATHER, msg.sender), "Caller is not a Founding Father" ); require(_all_Claim_ids[_id] == false, "ID already used"); require(_total_amount <= TreasuryReserve); _all_Claim_ids[_id] = true; _all_Claims[_id]._amount = _total_amount*10**18; _all_Claims[_id]._amount_to_give = _amount_to_get; _all_Claims[_id]._ending = block.timestamp + (_ending_in_days * 1 days); return true; }
8,441,547
./full_match/420/0x9c57DDCbD3359Db43f155C674aC36eC5EFe143C4/sources/contracts/SportMarkets/LiquidityPool/SportAMMLiquidityPool.sol
Prepare round closing excercise options of trading markets and ensure there are no markets left unresolved
function processRoundClosingBatch(uint batchSize) external nonReentrant whenNotPaused { require(roundClosingPrepared, "Round closing not prepared"); require(usersProcessedInRound < usersPerRound[round].length, "All users already processed"); require(batchSize > 0, "batchSize has to be greater than 0"); address roundPool = roundPools[round]; uint endCursor = usersProcessedInRound + batchSize; if (endCursor > usersPerRound[round].length) { endCursor = usersPerRound[round].length; } for (uint i = usersProcessedInRound; i < endCursor; i++) { address user = usersPerRound[round][i]; uint balanceAfterCurRound = (balancesPerRound[round][user] * profitAndLossPerRound[round]) / ONE; if (!withdrawalRequested[user] && (profitAndLossPerRound[round] > 0)) { balancesPerRound[round + 1][user] = balancesPerRound[round + 1][user] + balanceAfterCurRound; usersPerRound[round + 1].push(user); if (address(stakingThales) != address(0)) { stakingThales.updateVolume(user, balanceAfterCurRound); } balancesPerRound[round + 1][user] = 0; sUSD.safeTransferFrom(roundPool, user, balanceAfterCurRound); withdrawalRequested[user] = false; emit Claimed(user, balanceAfterCurRound); } usersProcessedInRound = usersProcessedInRound + 1; } }
13,228,271
/* //SPDX-License-Identifier: MIT */ pragma solidity ^0.8.2; import "./ENS.sol"; import "./IERC721.sol"; import "./IERC721Enumerable.sol"; import "./Ownable.sol"; import "./Strings.sol"; interface IERC20 { function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); } contract KoteEnsMapper is Ownable { using Strings for uint256; ENS private ens; IERC721Enumerable public nft; bytes32 public domainHash; mapping(bytes32 => mapping(string => string)) public texts; mapping(address => uint256) public nextRegisterTimestamp; string public domainLabel = "kote"; string public nftImageBaseUri = "https://ipfs.io/ipfs/QmbQTvwHbZjciMHLpPFYb8NFBzAjEftdAm3i9PBjwZ7NzN/"; bool public useEIP155 = true; mapping(bytes32 => uint256) public hashToIdMap; mapping(uint256 => bytes32) public tokenHashmap; mapping(bytes32 => string) public hashToDomainMap; uint256 public reset_period = 7257600; //12 weeks bool public publicClaimOpen = false; mapping(address => bool) public address_whitelist; event TextChanged(bytes32 indexed node, string indexed indexedKey, string key); event RegisterSubdomain(address indexed registrar, uint256 indexed token_id, string indexed label); constructor(){ ens = ENS(0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e); nft = IERC721Enumerable(0x32A322C7C77840c383961B8aB503c9f45440c81f); domainHash = getDomainHash(); } //<interface-functions> function supportsInterface(bytes4 interfaceID) public pure returns (bool) { return interfaceID == 0x3b3b57de //addr || interfaceID == 0x59d1d43c //text || interfaceID == 0x691f3431 //name || interfaceID == 0x01ffc9a7; //supportsInterface << [inception] } function text(bytes32 node, string calldata key) external view returns (string memory) { uint256 token_id = hashToIdMap[node]; require(token_id > 0 && tokenHashmap[token_id] != 0x0, "Invalid address"); if(keccak256(abi.encodePacked(key)) == keccak256("avatar")){ //eip155 string did not seem to work in any supported dapps during testing despite the returned string being properly //formatted. So the toggle was added so that we can direct link the image using http:// if this still does not work on //mainnet return useEIP155 ? string(abi.encodePacked("eip155:1/erc721:", addressToString(address(nft)), "/", token_id.toString())) : string(abi.encodePacked(nftImageBaseUri, token_id.toString(),".png")); } else{ return texts[node][key]; } } function addr(bytes32 nodeID) public view returns (address) { uint256 token_id = hashToIdMap[nodeID]; require(token_id > 0 && tokenHashmap[token_id] != 0x0, "Invalid address"); return nft.ownerOf(token_id); } function name(bytes32 node) view public returns (string memory){ return (hashToIdMap[node] == 0) ? "" : string(abi.encodePacked(hashToDomainMap[node], ".", domainLabel, ".eth")); } //</interface-functions> //--------------------------------------------------------------------------------------------// //<read-functions> function domainMap(string calldata label) public view returns(bytes32){ bytes32 encoded_label = keccak256(abi.encodePacked(label)); bytes32 big_hash = keccak256(abi.encodePacked(domainHash, encoded_label)); return hashToIdMap[big_hash] > 0 ? big_hash : bytes32(0x0); } function getClaimableIdsForAddress(address addy) public view returns(uint256[] memory){ if(((address_whitelist[addy] || publicClaimOpen) && block.timestamp > nextRegisterTimestamp[addy]) || owner() == addy){ return getAllIds(addy); } else{ return new uint256[](0); } } function getAllIds(address addy) private view returns(uint256[] memory){ uint256 balance = nft.balanceOf(addy); uint256[] memory ids = new uint256[](balance); uint256 count; for(uint256 i; i < balance; i++){ uint256 id = nft.tokenOfOwnerByIndex(addy, i); if(tokenHashmap[id] == 0x0){ ids[count++] = id; } } uint256[] memory trim_ids = new uint256[](count); for(uint256 i; i < count; i++){ trim_ids[i] = ids[i]; } return trim_ids; } function getTokenDomain(uint256 token_id) private view returns(string memory uri){ require(tokenHashmap[token_id] != 0x0, "Token does not have an ENS register"); uri = string(abi.encodePacked(hashToDomainMap[tokenHashmap[token_id]] ,"." ,domainLabel, ".eth")); } function getTokensDomains(uint256[] memory token_ids) public view returns(string[] memory){ string[] memory uris = new string[](token_ids.length); for(uint256 i; i < token_ids.length; i++){ uris[i] = getTokenDomain(token_ids[i]); } return uris; } function getAllCatsWithDomains(address addy) public view returns(uint256[] memory){ uint256 balance = nft.balanceOf(addy); uint256[] memory ids = new uint256[](balance); uint256 count; for(uint256 i; i < balance; i++){ uint256 id = nft.tokenOfOwnerByIndex(addy, i); if(tokenHashmap[id] != 0x0){ ids[count++] = id; } } uint256[] memory trim_ids = new uint256[](count); for(uint256 i; i < count; i++){ trim_ids[i] = ids[i]; } return trim_ids; } //</read-functions> //--------------------------------------------------------------------------------------------// //<helper-functions> function addressToString(address _addr) private pure returns(string memory) { bytes32 value = bytes32(uint256(uint160(_addr))); bytes memory alphabet = "0123456789abcdef"; bytes memory str = new bytes(51); str[0] = "0"; str[1] = "x"; for (uint i = 0; i < 20; i++) { str[2+i*2] = alphabet[uint(uint8(value[i + 12] >> 4))]; str[3+i*2] = alphabet[uint(uint8(value[i + 12] & 0x0f))]; } return string(str); } //this is the correct method for creating a 2 level ENS namehash function getDomainHash() private view returns (bytes32 namehash) { namehash = 0x0; namehash = keccak256(abi.encodePacked(namehash, keccak256(abi.encodePacked('eth')))); namehash = keccak256(abi.encodePacked(namehash, keccak256(abi.encodePacked(domainLabel)))); } //</helper-functions> //--------------------------------------------------------------------------------------------// //<authorised-functions> function setDomain(string calldata label, uint256 token_id) public isAuthorised(token_id) { require(tokenHashmap[token_id] == 0x0, "Token has already been set"); require(address_whitelist[msg.sender] || publicClaimOpen || owner() == msg.sender, "Not authorised"); require(block.timestamp > nextRegisterTimestamp[msg.sender], "Wallet must wait more time to register"); bytes32 encoded_label = keccak256(abi.encodePacked(label)); bytes32 big_hash = keccak256(abi.encodePacked(domainHash, encoded_label)); //contract owner can update / overwrite records. << this may be changed in the future with an updated method but as this is still //an experiment we'd like to retain some level of control over the sub-domains // //ens.recordExists seems to not be reliable (tested removing records through ENS control panel and this still returns true) require(!ens.recordExists(big_hash) || msg.sender == owner(), "sub-domain already exists"); ens.setSubnodeRecord(domainHash, encoded_label, owner(), address(this), 0); hashToIdMap[big_hash] = token_id; tokenHashmap[token_id] = big_hash; hashToDomainMap[big_hash] = label; if (owner() != msg.sender){ nextRegisterTimestamp[msg.sender] = block.timestamp + reset_period; //if user is on whitelist then remove if (address_whitelist[msg.sender]){ address_whitelist[msg.sender] = false; } } emit RegisterSubdomain(nft.ownerOf(token_id), token_id, label); } function setText(bytes32 node, string calldata key, string calldata value) external isAuthorised(hashToIdMap[node]) { uint256 token_id = hashToIdMap[node]; require(token_id > 0 && tokenHashmap[token_id] != 0x0, "Invalid address"); require(keccak256(abi.encodePacked(key)) != keccak256("avatar"), "cannot set avatar"); texts[node][key] = value; emit TextChanged(node, key, key); } function resetHash(uint256 token_id) public isAuthorised(token_id) { bytes32 domain = tokenHashmap[token_id]; require(ens.recordExists(domain), "Sub-domain does not exist"); //reset domain mappings hashToDomainMap[domain] = ""; hashToIdMap[domain] = 0; tokenHashmap[token_id] = 0x0; //allow sender to reclaim (if public == true) if(nextRegisterTimestamp[msg.sender] > block.timestamp && msg.sender != owner()){ nextRegisterTimestamp[msg.sender] = block.timestamp + (60 * 30); //30 minute cooldown } } //</authorised-functions> //--------------------------------------------------------------------------------------------// // <owner-functions> function addAddressWhitelist(address[] calldata addresses) public onlyOwner { for(uint256 i; i < addresses.length; i++){ address_whitelist[addresses[i]] = true; } } function setDomainLabel(string calldata label) public onlyOwner { domainLabel = label; domainHash = getDomainHash(); } function setNftAddress(address addy) public onlyOwner{ nft = IERC721Enumerable(addy); } function toggleNftImageLink() public onlyOwner{ useEIP155 = !useEIP155; } function setNftImageBaseUri(string memory _uri) public onlyOwner{ nftImageBaseUri = _uri; } function setEnsAddress(address addy) public onlyOwner { ens = ENS(addy); } function resetAddressForClaim(address addy) public onlyOwner { nextRegisterTimestamp[addy] = 0; } function togglePublicClaim() public onlyOwner { publicClaimOpen = !publicClaimOpen; } function updateResetPeriod(uint256 time) public onlyOwner { reset_period = time; } function renounceOwnership() public override onlyOwner { require(false, "ENS is responsibility. You cannot renounce ownership."); super.renounceOwnership(); } //just never know.. do you. function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } function withdrawTokens(IERC20 token) public onlyOwner { require(address(token) != address(0)); uint256 balance = token.balanceOf(address(this)); token.transfer(msg.sender, balance); } //</owner-functions> modifier isAuthorised(uint256 tokenId) { require(owner() == msg.sender || nft.ownerOf(tokenId) == msg.sender, "Not authorised"); _; } }
just never know.. do you.
function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); }
1,448,661
./full_match/3/0x5Cdb4992f4c81a54eBd19b1a1aC8Cec679E9620f/sources/contracts/Auction.sol
userRelativeBidAmounts is not cleared on withdrawal and stay in contract for history
function _withdraw(uint auctionId) private nonReentrant { Auction storage auction = auctions[auctionId]; address user = msg.sender; uint amount = userActualStakeAmounts[user][auctionId]; require(amount > 0, "HardStakingNFTAuction: This auction stake was withdrawn"); require(userStakeLocks[user][auctionId] < block.timestamp, "HardStakingNFTAuction: Locked"); require(auction.topBidder != user, "HardStakingNFTAuction: Cannot withdraw on won auction, use processSuccesfullAuction"); stakeToken.transfer(user, amount); if (address(auctionReferralManager) != address(0)) auctionReferralManager.processStake(msg.sender, amount, false); _totalSupply = _totalSupply.sub(amount); _balances[user] = _balances[user].sub(amount); userActualStakeAmounts[user][auctionId] = 0; emit Withdraw(user, amount); }
14,226,916
./partial_match/1/0x1D72D4746647B7Fe84e2bCDEfD96C119FB9CB0f0/sources/DeltaTimeInventory.sol
public function to invoke `onERC1155Received` on a target address The call is not executed if the target address is not a contract operator transfer msg sender from address representing the previous owner of the given ID to target address that will receive the token id uint256 ID of the `non-fungible token / non-fungible collection / fungible collection` to be transferred data bytes optional data to send along with the call erc721 bool whether transfer to ERC721 contract erc721Safe bool whether transfer to ERC721 contract safely return whether the call correctly returned the expected magic value/
function _checkERC1155AndCallSafeTransfer( address operator, address from, address to, uint256 id, uint256 value, bytes memory data, bool erc721, bool erc721Safe ) internal returns (bool) { if (!Address.isContract(to)) { return true; } if (erc721) { if (!_checkIsERC1155Receiver(to)) { if (erc721Safe) { return _checkERC721AndCallSafeTransfer(operator, from, to, id, data); return true; } } } }
4,462,369
// SPDX-License-Identifier: MIT pragma solidity ^0.8.11; // @title NFTCloner ERC721 contract // @version 1.0 // @author luax.eth // @url https://nftcloner.xyz/ import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; contract NFTCloner is IERC721Metadata { using Strings for uint256; // Contract owner, set as immutalble after initialisation address private immutable owner; // Token name string public name; // Token symbole string public symbol; // Token URI string private uri; // Mapping from token ID to owner address mapping(uint256 => address) private owners; // Mapping owner address to token ID mapping(address => uint256) private ownedToken; // Total supply uint256 public totalSupply; constructor( string memory _name, string memory _symbol, string memory _uri ) { owner = msg.sender; name = _name; symbol = _symbol; uri = _uri; } /** * @notice Get the metadata URI for the token. */ function tokenURI(uint256 _tokenId) external view returns (string memory) { require(owners[_tokenId] != address(0)); return string(abi.encodePacked(uri, "nft/", _tokenId.toString(), ".json")); } /** * @notice Get the metata URI for the contract. */ function contractURI() external view returns (string memory) { return string(abi.encodePacked(uri, "metadata.json")); } /** * @notice Mint a new token * @dev Store token ID to owner map and owner to token ID map, * and emit Transfer event. * Only one token per owner is allowed. */ function mint() external { require(ownedToken[msg.sender] == 0); totalSupply++; uint256 tokenId = totalSupply; owners[tokenId] = msg.sender; ownedToken[msg.sender] = tokenId; emit Transfer(address(0), msg.sender, tokenId); } /** * @notice Burn an existing token * @dev Remove token ID to owner map and owner to token ID map, * and emit Transfer event. */ function burn() external { uint256 tokenId = ownedToken[msg.sender]; address tokenOwner = owners[tokenId]; require(msg.sender == tokenOwner); ownedToken[msg.sender] = 0; owners[tokenId] = address(0); emit Transfer(tokenOwner, address(0), tokenId); } /** * @notice Update name, symbole and URI. * @dev Only the contract owner can update the contract metadata. */ function updateInfo( string memory _name, string memory _symbol, string memory _uri ) external { require(msg.sender == owner); name = _name; symbol = _symbol; uri = _uri; } /** * @dev Returns true if this contract implements the interface defined by `_interfaceId`. */ function supportsInterface(bytes4 _interfaceId) external pure returns (bool) { return _interfaceId == type(IERC721).interfaceId || _interfaceId == type(IERC721Metadata).interfaceId; } /** * @dev Returns the balance of `_owner` account. */ function balanceOf(address _owner) external view returns (uint256) { require(ownedToken[_owner] > 0); return 1; } /** * @dev Returns the owner of the `tokenId` token. */ function ownerOf(uint256 _tokenId) external view returns (address) { require(owners[_tokenId] != address(0)); return owners[_tokenId]; } /** * @dev Returns the token ID of `_owner` account. */ function tokenByOwner(address _owner) external view returns (uint256) { require(ownedToken[_owner] != 0); return ownedToken[_owner]; } // The following methods are just here to be ERC721 compliant, // but they are not used in this implementation, // this mean that it's not possible to transfer tokens. function approve(address, uint256) external pure {} function getApproved(uint256) external pure returns (address) { return address(0); } function isApprovedForAll(address, address) external pure returns (bool) { return false; } function setApprovalForAll(address, bool) external pure {} function safeTransferFrom( address, address, uint256 ) external pure {} function transferFrom( address, address, uint256 ) external pure {} function safeTransferFrom( address, address, uint256, bytes calldata ) external pure {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
Returns true if this contract implements the interface defined by `_interfaceId`./
function supportsInterface(bytes4 _interfaceId) external pure returns (bool) { return _interfaceId == type(IERC721).interfaceId || _interfaceId == type(IERC721Metadata).interfaceId; }
5,984,533
./partial_match/1/0x7296333e1615721f4Bd9Df1a3070537484A50CF8/sources/Pool.sol
Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement on the return value: the return value is optional (but if data is returned, it must not be false). token The token targeted by the call. data The call data (encoded using abi.encode or one of its variants)./ We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that the target address contains contract code and also asserts for success in the low-level call. Return data is optional solhint-disable-next-line max-line-length
function _callOptionalReturn(IERC20 token, bytes memory data) private { bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { require( abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed" ); } }
4,384,325
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "../periphery/WithdrawableV2.sol"; import "../interfaces/IPendleYieldTokenHolder.sol"; import "../interfaces/IPendleRewardManager.sol"; import "../interfaces/IPendleForge.sol"; import "../interfaces/IPendleYieldToken.sol"; /** @notice for each Forge deployed, there will be a corresponding PendleRewardManager contract, which manages the COMP/StkAAVE rewards accrued in the PendleYieldTokenHolder contracts created by the Forge for each yield contract. @dev the logic of distributing rewards is very similar to that of PendleCompoundMarket & PendleCompoundLiquidityMining Any major differences are likely to be bugs */ contract PendleRewardManager is IPendleRewardManager, WithdrawableV2, ReentrancyGuard { using SafeERC20 for IERC20; using SafeMath for uint256; bytes32 public immutable override forgeId; IPendleForge private forge; IERC20 private rewardToken; // we only update the rewards for a yieldTokenHolder if it has been >= updateFrequency[underlyingAsset] blocks // since the last time rewards was updated for the yieldTokenHolder (lastUpdatedForYieldTokenHolder[underlyingAsset][expiry]) mapping(address => uint256) updateFrequency; mapping(address => mapping(uint256 => uint256)) lastUpdatedForYieldTokenHolder; bool public skippingRewards; // This MULTIPLIER is to scale the real paramL value up, to preserve precision uint256 private constant MULTIPLIER = 1e20; IPendleData private data; IPendleRouter private router; struct RewardData { uint256 paramL; uint256 lastRewardBalance; mapping(address => uint256) lastParamL; mapping(address => uint256) dueRewards; } // rewardData[underlyingAsset][expiry] stores the information related // to the rewards stored in the corresponding PendleYieldTokenHolder // as well as information needed to calculate rewards for each user (lastParamL) mapping(address => mapping(uint256 => RewardData)) private rewardData; modifier isValidOT(address _underlyingAsset, uint256 _expiry) { require(data.isValidOT(forgeId, _underlyingAsset, _expiry), "INVALID_OT"); _; } modifier onlyForge() { require(msg.sender == address(forge), "ONLY_FORGE"); _; } constructor(address _governanceManager, bytes32 _forgeId) PermissionsV2(_governanceManager) { forgeId = _forgeId; } function initialize(address _forgeAddress) external { require(msg.sender == initializer, "FORBIDDEN"); require(address(_forgeAddress) != address(0), "ZERO_ADDRESS"); forge = IPendleForge(_forgeAddress); require(forge.forgeId() == forgeId, "FORGE_ID_MISMATCH"); initializer = address(0); rewardToken = forge.rewardToken(); data = forge.data(); router = forge.router(); } function readRewardData( address _underlyingAsset, uint256 _expiry, address user ) external view returns ( uint256 paramL, uint256 lastRewardBalance, uint256 lastParamL, uint256 dueRewards ) { RewardData storage rwd = rewardData[_underlyingAsset][_expiry]; paramL = rwd.paramL; lastRewardBalance = rwd.lastRewardBalance; lastParamL = rwd.lastParamL[user]; dueRewards = rwd.dueRewards[user]; } /** Use: To set how often rewards should be updated for yieldTokenHolders of an underlyingAsset Conditions: * The underlyingAsset must already exist in the forge * Must be called by governance */ function setUpdateFrequency( address[] calldata underlyingAssets, uint256[] calldata frequencies ) external override onlyGovernance { require(underlyingAssets.length == frequencies.length, "ARRAY_LENGTH_MISMATCH"); for (uint256 i = 0; i < underlyingAssets.length; i++) { // make sure the underlyingAsset exists in the forge // since this call will revert otherwise forge.getYieldBearingToken(underlyingAssets[i]); updateFrequency[underlyingAssets[i]] = frequencies[i]; } emit UpdateFrequencySet(underlyingAssets, frequencies); } /** Use: To set how often rewards should be updated for yieldTokenHolders of an underlyingAsset Conditions: * The underlyingAsset must already exist in the forge * Must be called by governance */ function setSkippingRewards(bool _skippingRewards) external override onlyGovernance { skippingRewards = _skippingRewards; emit SkippingRewardsSet(_skippingRewards); } /** Use: To claim the COMP/StkAAVE for any OT holder. Newly accrued rewards are equally accrued to all OT holders in the process. Conditions: * Can be called by anyone, to claim for anyone INVARIANTs: * this function must be called before any action that changes the OT balance of user * To ensure this, we call this function in the _beforeTokenTransfer hook of the OT token contract (indirectly through the forge) */ function redeemRewards( address _underlyingAsset, uint256 _expiry, address _user ) external override isValidOT(_underlyingAsset, _expiry) nonReentrant returns (uint256 dueRewards) { dueRewards = _beforeTransferPendingRewards(_underlyingAsset, _expiry, _user); address _yieldTokenHolder = forge.yieldTokenHolders(_underlyingAsset, _expiry); if (dueRewards != 0) { // The yieldTokenHolder already approved this reward manager contract to spend max uint256 rewardToken.safeTransferFrom(_yieldTokenHolder, _user, dueRewards); } } /** @notice Update the pending rewards for an user @dev This must be called before any transfer / mint/ burn action of OT (and this has been implemented in the beforeTokenTransfer of the PendleOwnershipToken) Conditions: * Can only be called by forge */ function updatePendingRewards( address _underlyingAsset, uint256 _expiry, address _user ) external override onlyForge nonReentrant { _updatePendingRewards(_underlyingAsset, _expiry, _user); } /** @notice Manually updateParamL, which is to update the rewards accounting for a particular (underlyingAsset, expiry) This transaction can be called by anyone who wants to spend the gas to make sure the rewards from Aave/Compound is claimed and distributed to the current timestamp, by-passing the caching mechanism */ function updateParamLManual(address _underlyingAsset, uint256 _expiry) external override nonReentrant { _updateParamL(_underlyingAsset, _expiry, true); } /** @notice To be called before the pending rewards of any users is redeemed */ function _beforeTransferPendingRewards( address _underlyingAsset, uint256 _expiry, address _user ) internal returns (uint256 amountOut) { _updatePendingRewards(_underlyingAsset, _expiry, _user); RewardData storage rwd = rewardData[_underlyingAsset][_expiry]; amountOut = rwd.dueRewards[_user]; rwd.dueRewards[_user] = 0; rwd.lastRewardBalance = rwd.lastRewardBalance.sub(amountOut); emit DueRewardsSettled(forgeId, _underlyingAsset, _expiry, amountOut, _user); } /** * Very similar to updateLpInterests in PendleCompoundLiquidityMining. Any major differences are likely to be bugs Please refer to it for more details */ function _updatePendingRewards( address _underlyingAsset, uint256 _expiry, address _user ) internal { // - When skippingRewards is set, _updateParamL() will not update anything (implemented in _checkNeedUpdateParamL) // - We will still need to update the rewards for the user no matter what, because their last transaction might be // before skippingRewards is turned on _updateParamL(_underlyingAsset, _expiry, false); RewardData storage rwd = rewardData[_underlyingAsset][_expiry]; uint256 userLastParamL = rwd.lastParamL[_user]; if (userLastParamL == 0) { // ParamL is always >=1, so this user must have gotten OT for the first time, // and shouldn't get any rewards rwd.lastParamL[_user] = rwd.paramL; return; } if (userLastParamL == rwd.paramL) { // - User's lastParamL is the latest param L, dont need to update anything // - When skippingRewards is turned on and paramL always stays the same, // this function will terminate here for most users // (except for the ones who have not updated rewards until the current paramL) return; } IPendleYieldToken ot = data.otTokens(forgeId, _underlyingAsset, _expiry); uint256 principal = ot.balanceOf(_user); uint256 rewardsAmountPerOT = rwd.paramL.sub(userLastParamL); uint256 rewardsFromOT = principal.mul(rewardsAmountPerOT).div(MULTIPLIER); rwd.dueRewards[_user] = rwd.dueRewards[_user].add(rewardsFromOT); rwd.lastParamL[_user] = rwd.paramL; } // we only need to update param L, if it has been more than updateFrequency[_underlyingAsset] blocks function _checkNeedUpdateParamL( address _underlyingAsset, uint256 _expiry, bool _manualUpdate ) internal view returns (bool needUpdate) { if (skippingRewards) return false; if (_manualUpdate) return true; // always update if its a manual update needUpdate = block.number - lastUpdatedForYieldTokenHolder[_underlyingAsset][_expiry] >= updateFrequency[_underlyingAsset]; } /** * Very similar to updateLpInterests in PendleCompoundLiquidityMining. Any major differences are likely to be bugs Please refer to it for more details * This function must be called only by updatePendingRewards */ function _updateParamL( address _underlyingAsset, uint256 _expiry, bool _manualUpdate // if its a manual update called by updateParamLManual(), always update ) internal { if (!_checkNeedUpdateParamL(_underlyingAsset, _expiry, _manualUpdate)) return; address yieldTokenHolder = forge.yieldTokenHolders(_underlyingAsset, _expiry); require(yieldTokenHolder != address(0), "INVALID_YIELD_TOKEN_HOLDER"); RewardData storage rwd = rewardData[_underlyingAsset][_expiry]; if (rwd.paramL == 0) { // paramL always starts from 1, to make sure that if a user's lastParamL is 0, // they must be getting OT for the very first time, and we will know it in _updatePendingRewards() rwd.paramL = 1; } // First, claim any pending COMP/StkAAVE rewards to the YieldTokenHolder IPendleYieldTokenHolder(yieldTokenHolder).redeemRewards(); IPendleYieldToken ot = data.otTokens(forgeId, _underlyingAsset, _expiry); uint256 currentRewardBalance = rewardToken.balanceOf(yieldTokenHolder); // * firstTerm is always paramL. But we are still doing this way to make it consistent // in the way that we calculate interests/rewards, across Market, LiquidityMining and RewardManager // * paramR is basically the new amount of rewards that came in since the last time we called _updateParamL (uint256 firstTerm, uint256 paramR) = _getFirstTermAndParamR(_underlyingAsset, _expiry, currentRewardBalance); uint256 totalOT = ot.totalSupply(); // secondTerm is basically the amount of new rewards per LP uint256 secondTerm; if (totalOT != 0) { secondTerm = paramR.mul(MULTIPLIER).div(totalOT); } // Update new states rwd.paramL = firstTerm.add(secondTerm); rwd.lastRewardBalance = currentRewardBalance; lastUpdatedForYieldTokenHolder[_underlyingAsset][_expiry] = block.number; } function _getFirstTermAndParamR( address _underlyingAsset, uint256 _expiry, uint256 currentRewardBalance ) internal view returns (uint256 firstTerm, uint256 paramR) { RewardData storage rwd = rewardData[_underlyingAsset][_expiry]; firstTerm = rwd.paramL; paramR = currentRewardBalance.sub(rwd.lastRewardBalance); } // There shouldn't be any fund in here // hence governance is allowed to withdraw anything from here. function _allowedToWithdraw(address) internal pure override returns (bool allowed) { allowed = true; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ 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); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) 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. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.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, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, 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 (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @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) { 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, reverting 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) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * 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, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * 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, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./PermissionsV2.sol"; abstract contract WithdrawableV2 is PermissionsV2 { using SafeERC20 for IERC20; event EtherWithdraw(uint256 amount, address sendTo); event TokenWithdraw(IERC20 token, uint256 amount, address sendTo); /** * @dev Allows governance to withdraw Ether in a Pendle contract * in case of accidental ETH transfer into the contract. * @param amount The amount of Ether to withdraw. * @param sendTo The recipient address. */ function withdrawEther(uint256 amount, address payable sendTo) external onlyGovernance { (bool success, ) = sendTo.call{value: amount}(""); require(success, "WITHDRAW_FAILED"); emit EtherWithdraw(amount, sendTo); } /** * @dev Allows governance to withdraw all IERC20 compatible tokens in a Pendle * contract in case of accidental token transfer into the contract. * @param token IERC20 The address of the token contract. * @param amount The amount of IERC20 tokens to withdraw. * @param sendTo The recipient address. */ function withdrawToken( IERC20 token, uint256 amount, address sendTo ) external onlyGovernance { require(_allowedToWithdraw(address(token)), "TOKEN_NOT_ALLOWED"); token.safeTransfer(sendTo, amount); emit TokenWithdraw(token, amount, sendTo); } // must be overridden by the sub contracts, so we must consider explicitly // in each and every contract which tokens are allowed to be withdrawn function _allowedToWithdraw(address) internal view virtual returns (bool allowed); } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; interface IPendleYieldTokenHolder { function redeemRewards() external; function setUpEmergencyMode(address spender) external; function yieldToken() external returns (address); function forge() external returns (address); function rewardToken() external returns (address); function expiry() external returns (uint256); } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; interface IPendleRewardManager { event UpdateFrequencySet(address[], uint256[]); event SkippingRewardsSet(bool); event DueRewardsSettled( bytes32 forgeId, address underlyingAsset, uint256 expiry, uint256 amountOut, address user ); function redeemRewards( address _underlyingAsset, uint256 _expiry, address _user ) external returns (uint256 dueRewards); function updatePendingRewards( address _underlyingAsset, uint256 _expiry, address _user ) external; function updateParamLManual(address _underlyingAsset, uint256 _expiry) external; function setUpdateFrequency( address[] calldata underlyingAssets, uint256[] calldata frequencies ) external; function setSkippingRewards(bool skippingRewards) external; function forgeId() external returns (bytes32); } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; import "./IPendleRouter.sol"; import "./IPendleRewardManager.sol"; import "./IPendleYieldContractDeployer.sol"; import "./IPendleData.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IPendleForge { /** * @dev Emitted when the Forge has minted the OT and XYT tokens. * @param forgeId The forgeId * @param underlyingAsset The address of the underlying yield token. * @param expiry The expiry of the XYT token * @param amountToTokenize The amount of yield bearing assets to tokenize * @param amountTokenMinted The amount of OT/XYT minted **/ event MintYieldTokens( bytes32 forgeId, address indexed underlyingAsset, uint256 indexed expiry, uint256 amountToTokenize, uint256 amountTokenMinted, address indexed user ); /** * @dev Emitted when the Forge has created new yield token contracts. * @param forgeId The forgeId * @param underlyingAsset The address of the underlying asset. * @param expiry The date in epoch time when the contract will expire. * @param ot The address of the ownership token. * @param xyt The address of the new future yield token. **/ event NewYieldContracts( bytes32 forgeId, address indexed underlyingAsset, uint256 indexed expiry, address ot, address xyt, address yieldBearingAsset ); /** * @dev Emitted when the Forge has redeemed the OT and XYT tokens. * @param forgeId The forgeId * @param underlyingAsset the address of the underlying asset * @param expiry The expiry of the XYT token * @param amountToRedeem The amount of OT to be redeemed. * @param redeemedAmount The amount of yield token received **/ event RedeemYieldToken( bytes32 forgeId, address indexed underlyingAsset, uint256 indexed expiry, uint256 amountToRedeem, uint256 redeemedAmount, address indexed user ); /** * @dev Emitted when interest claim is settled * @param forgeId The forgeId * @param underlyingAsset the address of the underlying asset * @param expiry The expiry of the XYT token * @param user Interest receiver Address * @param amount The amount of interest claimed **/ event DueInterestsSettled( bytes32 forgeId, address indexed underlyingAsset, uint256 indexed expiry, uint256 amount, uint256 forgeFeeAmount, address indexed user ); /** * @dev Emitted when forge fee is withdrawn * @param forgeId The forgeId * @param underlyingAsset the address of the underlying asset * @param expiry The expiry of the XYT token * @param amount The amount of interest claimed **/ event ForgeFeeWithdrawn( bytes32 forgeId, address indexed underlyingAsset, uint256 indexed expiry, uint256 amount ); function setUpEmergencyMode( address _underlyingAsset, uint256 _expiry, address spender ) external; function newYieldContracts(address underlyingAsset, uint256 expiry) external returns (address ot, address xyt); function redeemAfterExpiry( address user, address underlyingAsset, uint256 expiry ) external returns (uint256 redeemedAmount); function redeemDueInterests( address user, address underlyingAsset, uint256 expiry ) external returns (uint256 interests); function updateDueInterests( address underlyingAsset, uint256 expiry, address user ) external; function updatePendingRewards( address _underlyingAsset, uint256 _expiry, address _user ) external; function redeemUnderlying( address user, address underlyingAsset, uint256 expiry, uint256 amountToRedeem ) external returns (uint256 redeemedAmount); function mintOtAndXyt( address underlyingAsset, uint256 expiry, uint256 amountToTokenize, address to ) external returns ( address ot, address xyt, uint256 amountTokenMinted ); function withdrawForgeFee(address underlyingAsset, uint256 expiry) external; function getYieldBearingToken(address underlyingAsset) external returns (address); /** * @notice Gets a reference to the PendleRouter contract. * @return Returns the router contract reference. **/ function router() external view returns (IPendleRouter); function data() external view returns (IPendleData); function rewardManager() external view returns (IPendleRewardManager); function yieldContractDeployer() external view returns (IPendleYieldContractDeployer); function rewardToken() external view returns (IERC20); /** * @notice Gets the bytes32 ID of the forge. * @return Returns the forge and protocol identifier. **/ function forgeId() external view returns (bytes32); function dueInterests( address _underlyingAsset, uint256 expiry, address _user ) external view returns (uint256); function yieldTokenHolders(address _underlyingAsset, uint256 _expiry) external view returns (address yieldTokenHolder); } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./IPendleBaseToken.sol"; import "./IPendleForge.sol"; interface IPendleYieldToken is IERC20, IPendleBaseToken { /** * @notice Emitted when burning OT or XYT tokens. * @param user The address performing the burn. * @param amount The amount to be burned. **/ event Burn(address indexed user, uint256 amount); /** * @notice Emitted when minting OT or XYT tokens. * @param user The address performing the mint. * @param amount The amount to be minted. **/ event Mint(address indexed user, uint256 amount); /** * @notice Burns OT or XYT tokens from user, reducing the total supply. * @param user The address performing the burn. * @param amount The amount to be burned. **/ function burn(address user, uint256 amount) external; /** * @notice Mints new OT or XYT tokens for user, increasing the total supply. * @param user The address to send the minted tokens. * @param amount The amount to be minted. **/ function mint(address user, uint256 amount) external; /** * @notice Gets the forge address of the PendleForge contract for this yield token. * @return Retuns the forge address. **/ function forge() external view returns (IPendleForge); /** * @notice Returns the address of the underlying asset. * @return Returns the underlying asset address. **/ function underlyingAsset() external view returns (address); /** * @notice Returns the address of the underlying yield token. * @return Returns the underlying yield token address. **/ function underlyingYieldToken() external view returns (address); /** * @notice let the router approve itself to spend OT/XYT/LP from any wallet * @param user user to approve **/ function approveRouter(address user) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../core/PendleGovernanceManager.sol"; import "../interfaces/IPermissionsV2.sol"; abstract contract PermissionsV2 is IPermissionsV2 { PendleGovernanceManager public immutable override governanceManager; address internal initializer; constructor(address _governanceManager) { require(_governanceManager != address(0), "ZERO_ADDRESS"); initializer = msg.sender; governanceManager = PendleGovernanceManager(_governanceManager); } modifier initialized() { require(initializer == address(0), "NOT_INITIALIZED"); _; } modifier onlyGovernance() { require(msg.sender == _governance(), "ONLY_GOVERNANCE"); _; } function _governance() internal view returns (address) { return governanceManager.governance(); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; contract PendleGovernanceManager { address public governance; address public pendingGovernance; event GovernanceClaimed(address newGovernance, address previousGovernance); event TransferGovernancePending(address pendingGovernance); constructor(address _governance) { require(_governance != address(0), "ZERO_ADDRESS"); governance = _governance; } modifier onlyGovernance() { require(msg.sender == governance, "ONLY_GOVERNANCE"); _; } /** * @dev Allows the pendingGovernance address to finalize the change governance process. */ function claimGovernance() external { require(pendingGovernance == msg.sender, "WRONG_GOVERNANCE"); emit GovernanceClaimed(pendingGovernance, governance); governance = pendingGovernance; pendingGovernance = address(0); } /** * @dev Allows the current governance to set the pendingGovernance address. * @param _governance The address to transfer ownership to. */ function transferGovernance(address _governance) external onlyGovernance { require(_governance != address(0), "ZERO_ADDRESS"); pendingGovernance = _governance; emit TransferGovernancePending(pendingGovernance); } } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; pragma abicoder v2; import "../core/PendleGovernanceManager.sol"; interface IPermissionsV2 { function governanceManager() external returns (PendleGovernanceManager); } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; pragma abicoder v2; import "../interfaces/IWETH.sol"; import "./IPendleData.sol"; import "../libraries/PendleStructs.sol"; import "./IPendleMarketFactory.sol"; interface IPendleRouter { /** * @notice Emitted when a market for a future yield token and an ERC20 token is created. * @param marketFactoryId Forge identifier. * @param xyt The address of the tokenized future yield token as the base asset. * @param token The address of an ERC20 token as the quote asset. * @param market The address of the newly created market. **/ event MarketCreated( bytes32 marketFactoryId, address indexed xyt, address indexed token, address indexed market ); /** * @notice Emitted when a swap happens on the market. * @param trader The address of msg.sender. * @param inToken The input token. * @param outToken The output token. * @param exactIn The exact amount being traded. * @param exactOut The exact amount received. * @param market The market address. **/ event SwapEvent( address indexed trader, address inToken, address outToken, uint256 exactIn, uint256 exactOut, address market ); /** * @dev Emitted when user adds liquidity * @param sender The user who added liquidity. * @param token0Amount the amount of token0 (xyt) provided by user * @param token1Amount the amount of token1 provided by user * @param market The market address. * @param exactOutLp The exact LP minted */ event Join( address indexed sender, uint256 token0Amount, uint256 token1Amount, address market, uint256 exactOutLp ); /** * @dev Emitted when user removes liquidity * @param sender The user who removed liquidity. * @param token0Amount the amount of token0 (xyt) given to user * @param token1Amount the amount of token1 given to user * @param market The market address. * @param exactInLp The exact Lp to remove */ event Exit( address indexed sender, uint256 token0Amount, uint256 token1Amount, address market, uint256 exactInLp ); /** * @notice Gets a reference to the PendleData contract. * @return Returns the data contract reference. **/ function data() external view returns (IPendleData); /** * @notice Gets a reference of the WETH9 token contract address. * @return WETH token reference. **/ function weth() external view returns (IWETH); /*********** * FORGE * ***********/ function newYieldContracts( bytes32 forgeId, address underlyingAsset, uint256 expiry ) external returns (address ot, address xyt); function redeemAfterExpiry( bytes32 forgeId, address underlyingAsset, uint256 expiry ) external returns (uint256 redeemedAmount); function redeemDueInterests( bytes32 forgeId, address underlyingAsset, uint256 expiry, address user ) external returns (uint256 interests); function redeemUnderlying( bytes32 forgeId, address underlyingAsset, uint256 expiry, uint256 amountToRedeem ) external returns (uint256 redeemedAmount); function renewYield( bytes32 forgeId, uint256 oldExpiry, address underlyingAsset, uint256 newExpiry, uint256 renewalRate ) external returns ( uint256 redeemedAmount, uint256 amountRenewed, address ot, address xyt, uint256 amountTokenMinted ); function tokenizeYield( bytes32 forgeId, address underlyingAsset, uint256 expiry, uint256 amountToTokenize, address to ) external returns ( address ot, address xyt, uint256 amountTokenMinted ); /*********** * MARKET * ***********/ function addMarketLiquidityDual( bytes32 _marketFactoryId, address _xyt, address _token, uint256 _desiredXytAmount, uint256 _desiredTokenAmount, uint256 _xytMinAmount, uint256 _tokenMinAmount ) external payable returns ( uint256 amountXytUsed, uint256 amountTokenUsed, uint256 lpOut ); function addMarketLiquiditySingle( bytes32 marketFactoryId, address xyt, address token, bool forXyt, uint256 exactInAsset, uint256 minOutLp ) external payable returns (uint256 exactOutLp); function removeMarketLiquidityDual( bytes32 marketFactoryId, address xyt, address token, uint256 exactInLp, uint256 minOutXyt, uint256 minOutToken ) external returns (uint256 exactOutXyt, uint256 exactOutToken); function removeMarketLiquiditySingle( bytes32 marketFactoryId, address xyt, address token, bool forXyt, uint256 exactInLp, uint256 minOutAsset ) external returns (uint256 exactOutXyt, uint256 exactOutToken); /** * @notice Creates a market given a protocol ID, future yield token, and an ERC20 token. * @param marketFactoryId Market Factory identifier. * @param xyt Token address of the future yield token as base asset. * @param token Token address of an ERC20 token as quote asset. * @return market Returns the address of the newly created market. **/ function createMarket( bytes32 marketFactoryId, address xyt, address token ) external returns (address market); function bootstrapMarket( bytes32 marketFactoryId, address xyt, address token, uint256 initialXytLiquidity, uint256 initialTokenLiquidity ) external payable; function swapExactIn( address tokenIn, address tokenOut, uint256 inTotalAmount, uint256 minOutTotalAmount, bytes32 marketFactoryId ) external payable returns (uint256 outTotalAmount); function swapExactOut( address tokenIn, address tokenOut, uint256 outTotalAmount, uint256 maxInTotalAmount, bytes32 marketFactoryId ) external payable returns (uint256 inTotalAmount); function redeemLpInterests(address market, address user) external returns (uint256 interests); } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; interface IPendleYieldContractDeployer { function forgeId() external returns (bytes32); function forgeOwnershipToken( address _underlyingAsset, string memory _name, string memory _symbol, uint8 _decimals, uint256 _expiry ) external returns (address ot); function forgeFutureYieldToken( address _underlyingAsset, string memory _name, string memory _symbol, uint8 _decimals, uint256 _expiry ) external returns (address xyt); function deployYieldTokenHolder(address yieldToken, uint256 expiry) external returns (address yieldTokenHolder); } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; import "./IPendleRouter.sol"; import "./IPendleYieldToken.sol"; import "./IPendlePausingManager.sol"; import "./IPendleMarket.sol"; interface IPendleData { /** * @notice Emitted when validity of a forge-factory pair is updated * @param _forgeId the forge id * @param _marketFactoryId the market factory id * @param _valid valid or not **/ event ForgeFactoryValiditySet(bytes32 _forgeId, bytes32 _marketFactoryId, bool _valid); /** * @notice Emitted when Pendle and PendleFactory addresses have been updated. * @param treasury The address of the new treasury contract. **/ event TreasurySet(address treasury); /** * @notice Emitted when LockParams is changed **/ event LockParamsSet(uint256 lockNumerator, uint256 lockDenominator); /** * @notice Emitted when ExpiryDivisor is changed **/ event ExpiryDivisorSet(uint256 expiryDivisor); /** * @notice Emitted when forge fee is changed **/ event ForgeFeeSet(uint256 forgeFee); /** * @notice Emitted when interestUpdateRateDeltaForMarket is changed * @param interestUpdateRateDeltaForMarket new interestUpdateRateDeltaForMarket setting **/ event InterestUpdateRateDeltaForMarketSet(uint256 interestUpdateRateDeltaForMarket); /** * @notice Emitted when market fees are changed * @param _swapFee new swapFee setting * @param _protocolSwapFee new protocolSwapFee setting **/ event MarketFeesSet(uint256 _swapFee, uint256 _protocolSwapFee); /** * @notice Emitted when the curve shift block delta is changed * @param _blockDelta new block delta setting **/ event CurveShiftBlockDeltaSet(uint256 _blockDelta); /** * @dev Emitted when new forge is added * @param marketFactoryId Human Readable Market Factory ID in Bytes * @param marketFactoryAddress The Market Factory Address */ event NewMarketFactory(bytes32 indexed marketFactoryId, address indexed marketFactoryAddress); /** * @notice Set/update validity of a forge-factory pair * @param _forgeId the forge id * @param _marketFactoryId the market factory id * @param _valid valid or not **/ function setForgeFactoryValidity( bytes32 _forgeId, bytes32 _marketFactoryId, bool _valid ) external; /** * @notice Sets the PendleTreasury contract addresses. * @param newTreasury Address of new treasury contract. **/ function setTreasury(address newTreasury) external; /** * @notice Gets a reference to the PendleRouter contract. * @return Returns the router contract reference. **/ function router() external view returns (IPendleRouter); /** * @notice Gets a reference to the PendleRouter contract. * @return Returns the router contract reference. **/ function pausingManager() external view returns (IPendlePausingManager); /** * @notice Gets the treasury contract address where fees are being sent to. * @return Address of the treasury contract. **/ function treasury() external view returns (address); /*********** * FORGE * ***********/ /** * @notice Emitted when a forge for a protocol is added. * @param forgeId Forge and protocol identifier. * @param forgeAddress The address of the added forge. **/ event ForgeAdded(bytes32 indexed forgeId, address indexed forgeAddress); /** * @notice Adds a new forge for a protocol. * @param forgeId Forge and protocol identifier. * @param forgeAddress The address of the added forge. **/ function addForge(bytes32 forgeId, address forgeAddress) external; /** * @notice Store new OT and XYT details. * @param forgeId Forge and protocol identifier. * @param ot The address of the new XYT. * @param xyt The address of the new XYT. * @param underlyingAsset Token address of the underlying asset. * @param expiry Yield contract expiry in epoch time. **/ function storeTokens( bytes32 forgeId, address ot, address xyt, address underlyingAsset, uint256 expiry ) external; /** * @notice Set a new forge fee * @param _forgeFee new forge fee **/ function setForgeFee(uint256 _forgeFee) external; /** * @notice Gets the OT and XYT tokens. * @param forgeId Forge and protocol identifier. * @param underlyingYieldToken Token address of the underlying yield token. * @param expiry Yield contract expiry in epoch time. * @return ot The OT token references. * @return xyt The XYT token references. **/ function getPendleYieldTokens( bytes32 forgeId, address underlyingYieldToken, uint256 expiry ) external view returns (IPendleYieldToken ot, IPendleYieldToken xyt); /** * @notice Gets a forge given the identifier. * @param forgeId Forge and protocol identifier. * @return forgeAddress Returns the forge address. **/ function getForgeAddress(bytes32 forgeId) external view returns (address forgeAddress); /** * @notice Checks if an XYT token is valid. * @param forgeId The forgeId of the forge. * @param underlyingAsset Token address of the underlying asset. * @param expiry Yield contract expiry in epoch time. * @return True if valid, false otherwise. **/ function isValidXYT( bytes32 forgeId, address underlyingAsset, uint256 expiry ) external view returns (bool); /** * @notice Checks if an OT token is valid. * @param forgeId The forgeId of the forge. * @param underlyingAsset Token address of the underlying asset. * @param expiry Yield contract expiry in epoch time. * @return True if valid, false otherwise. **/ function isValidOT( bytes32 forgeId, address underlyingAsset, uint256 expiry ) external view returns (bool); function validForgeFactoryPair(bytes32 _forgeId, bytes32 _marketFactoryId) external view returns (bool); /** * @notice Gets a reference to a specific OT. * @param forgeId Forge and protocol identifier. * @param underlyingYieldToken Token address of the underlying yield token. * @param expiry Yield contract expiry in epoch time. * @return ot Returns the reference to an OT. **/ function otTokens( bytes32 forgeId, address underlyingYieldToken, uint256 expiry ) external view returns (IPendleYieldToken ot); /** * @notice Gets a reference to a specific XYT. * @param forgeId Forge and protocol identifier. * @param underlyingAsset Token address of the underlying asset * @param expiry Yield contract expiry in epoch time. * @return xyt Returns the reference to an XYT. **/ function xytTokens( bytes32 forgeId, address underlyingAsset, uint256 expiry ) external view returns (IPendleYieldToken xyt); /*********** * MARKET * ***********/ event MarketPairAdded(address indexed market, address indexed xyt, address indexed token); function addMarketFactory(bytes32 marketFactoryId, address marketFactoryAddress) external; function isMarket(address _addr) external view returns (bool result); function isXyt(address _addr) external view returns (bool result); function addMarket( bytes32 marketFactoryId, address xyt, address token, address market ) external; function setMarketFees(uint256 _swapFee, uint256 _protocolSwapFee) external; function setInterestUpdateRateDeltaForMarket(uint256 _interestUpdateRateDeltaForMarket) external; function setLockParams(uint256 _lockNumerator, uint256 _lockDenominator) external; function setExpiryDivisor(uint256 _expiryDivisor) external; function setCurveShiftBlockDelta(uint256 _blockDelta) external; /** * @notice Displays the number of markets currently existing. * @return Returns markets length, **/ function allMarketsLength() external view returns (uint256); function forgeFee() external view returns (uint256); function interestUpdateRateDeltaForMarket() external view returns (uint256); function expiryDivisor() external view returns (uint256); function lockNumerator() external view returns (uint256); function lockDenominator() external view returns (uint256); function swapFee() external view returns (uint256); function protocolSwapFee() external view returns (uint256); function curveShiftBlockDelta() external view returns (uint256); function getMarketByIndex(uint256 index) external view returns (address market); /** * @notice Gets a market given a future yield token and an ERC20 token. * @param xyt Token address of the future yield token as base asset. * @param token Token address of an ERC20 token as quote asset. * @return market Returns the market address. **/ function getMarket( bytes32 marketFactoryId, address xyt, address token ) external view returns (address market); /** * @notice Gets a market factory given the identifier. * @param marketFactoryId MarketFactory identifier. * @return marketFactoryAddress Returns the factory address. **/ function getMarketFactoryAddress(bytes32 marketFactoryId) external view returns (address marketFactoryAddress); function getMarketFromKey( address xyt, address token, bytes32 marketFactoryId ) external view returns (address market); } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IWETH is IERC20 { function deposit() external payable; function withdraw(uint256 wad) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity 0.7.6; struct TokenReserve { uint256 weight; uint256 balance; } struct PendingTransfer { uint256 amount; bool isOut; } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; import "./IPendleRouter.sol"; interface IPendleMarketFactory { /** * @notice Creates a market given a protocol ID, future yield token, and an ERC20 token. * @param xyt Token address of the futuonlyCorere yield token as base asset. * @param token Token address of an ERC20 token as quote asset. * @return market Returns the address of the newly created market. **/ function createMarket(address xyt, address token) external returns (address market); /** * @notice Gets a reference to the PendleRouter contract. * @return Returns the router contract reference. **/ function router() external view returns (IPendleRouter); function marketFactoryId() external view returns (bytes32); } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; interface IPendlePausingManager { event AddPausingAdmin(address admin); event RemovePausingAdmin(address admin); event PendingForgeEmergencyHandler(address _pendingForgeHandler); event PendingMarketEmergencyHandler(address _pendingMarketHandler); event PendingLiqMiningEmergencyHandler(address _pendingLiqMiningHandler); event ForgeEmergencyHandlerSet(address forgeEmergencyHandler); event MarketEmergencyHandlerSet(address marketEmergencyHandler); event LiqMiningEmergencyHandlerSet(address liqMiningEmergencyHandler); event PausingManagerLocked(); event ForgeHandlerLocked(); event MarketHandlerLocked(); event LiqMiningHandlerLocked(); event SetForgePaused(bytes32 forgeId, bool settingToPaused); event SetForgeAssetPaused(bytes32 forgeId, address underlyingAsset, bool settingToPaused); event SetForgeAssetExpiryPaused( bytes32 forgeId, address underlyingAsset, uint256 expiry, bool settingToPaused ); event SetForgeLocked(bytes32 forgeId); event SetForgeAssetLocked(bytes32 forgeId, address underlyingAsset); event SetForgeAssetExpiryLocked(bytes32 forgeId, address underlyingAsset, uint256 expiry); event SetMarketFactoryPaused(bytes32 marketFactoryId, bool settingToPaused); event SetMarketPaused(bytes32 marketFactoryId, address market, bool settingToPaused); event SetMarketFactoryLocked(bytes32 marketFactoryId); event SetMarketLocked(bytes32 marketFactoryId, address market); event SetLiqMiningPaused(address liqMiningContract, bool settingToPaused); event SetLiqMiningLocked(address liqMiningContract); function forgeEmergencyHandler() external view returns ( address handler, address pendingHandler, uint256 timelockDeadline ); function marketEmergencyHandler() external view returns ( address handler, address pendingHandler, uint256 timelockDeadline ); function liqMiningEmergencyHandler() external view returns ( address handler, address pendingHandler, uint256 timelockDeadline ); function permLocked() external view returns (bool); function permForgeHandlerLocked() external view returns (bool); function permMarketHandlerLocked() external view returns (bool); function permLiqMiningHandlerLocked() external view returns (bool); function isPausingAdmin(address) external view returns (bool); function setPausingAdmin(address admin, bool isAdmin) external; function requestForgeHandlerChange(address _pendingForgeHandler) external; function requestMarketHandlerChange(address _pendingMarketHandler) external; function requestLiqMiningHandlerChange(address _pendingLiqMiningHandler) external; function applyForgeHandlerChange() external; function applyMarketHandlerChange() external; function applyLiqMiningHandlerChange() external; function lockPausingManagerPermanently() external; function lockForgeHandlerPermanently() external; function lockMarketHandlerPermanently() external; function lockLiqMiningHandlerPermanently() external; function setForgePaused(bytes32 forgeId, bool paused) external; function setForgeAssetPaused( bytes32 forgeId, address underlyingAsset, bool paused ) external; function setForgeAssetExpiryPaused( bytes32 forgeId, address underlyingAsset, uint256 expiry, bool paused ) external; function setForgeLocked(bytes32 forgeId) external; function setForgeAssetLocked(bytes32 forgeId, address underlyingAsset) external; function setForgeAssetExpiryLocked( bytes32 forgeId, address underlyingAsset, uint256 expiry ) external; function checkYieldContractStatus( bytes32 forgeId, address underlyingAsset, uint256 expiry ) external returns (bool _paused, bool _locked); function setMarketFactoryPaused(bytes32 marketFactoryId, bool paused) external; function setMarketPaused( bytes32 marketFactoryId, address market, bool paused ) external; function setMarketFactoryLocked(bytes32 marketFactoryId) external; function setMarketLocked(bytes32 marketFactoryId, address market) external; function checkMarketStatus(bytes32 marketFactoryId, address market) external returns (bool _paused, bool _locked); function setLiqMiningPaused(address liqMiningContract, bool settingToPaused) external; function setLiqMiningLocked(address liqMiningContract) external; function checkLiqMiningStatus(address liqMiningContract) external returns (bool _paused, bool _locked); } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; pragma abicoder v2; import "./IPendleRouter.sol"; import "./IPendleBaseToken.sol"; import "../libraries/PendleStructs.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IPendleMarket is IERC20 { /** * @notice Emitted when reserves pool has been updated * @param reserve0 The XYT reserves. * @param weight0 The XYT weight * @param reserve1 The generic token reserves. * For the generic Token weight it can be inferred by (2^40) - weight0 **/ event Sync(uint256 reserve0, uint256 weight0, uint256 reserve1); function setUpEmergencyMode(address spender) external; function bootstrap( address user, uint256 initialXytLiquidity, uint256 initialTokenLiquidity ) external returns (PendingTransfer[2] memory transfers, uint256 exactOutLp); function addMarketLiquiditySingle( address user, address inToken, uint256 inAmount, uint256 minOutLp ) external returns (PendingTransfer[2] memory transfers, uint256 exactOutLp); function addMarketLiquidityDual( address user, uint256 _desiredXytAmount, uint256 _desiredTokenAmount, uint256 _xytMinAmount, uint256 _tokenMinAmount ) external returns (PendingTransfer[2] memory transfers, uint256 lpOut); function removeMarketLiquidityDual( address user, uint256 inLp, uint256 minOutXyt, uint256 minOutToken ) external returns (PendingTransfer[2] memory transfers); function removeMarketLiquiditySingle( address user, address outToken, uint256 exactInLp, uint256 minOutToken ) external returns (PendingTransfer[2] memory transfers); function swapExactIn( address inToken, uint256 inAmount, address outToken, uint256 minOutAmount ) external returns (uint256 outAmount, PendingTransfer[2] memory transfers); function swapExactOut( address inToken, uint256 maxInAmount, address outToken, uint256 outAmount ) external returns (uint256 inAmount, PendingTransfer[2] memory transfers); function redeemLpInterests(address user) external returns (uint256 interests); function getReserves() external view returns ( uint256 xytBalance, uint256 xytWeight, uint256 tokenBalance, uint256 tokenWeight, uint256 currentBlock ); function factoryId() external view returns (bytes32); function token() external view returns (address); function xyt() external view returns (address); } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IPendleBaseToken is IERC20 { /** * @notice Decreases the allowance granted to spender by the caller. * @param spender The address to reduce the allowance from. * @param subtractedValue The amount allowance to subtract. * @return Returns true if allowance has decreased, otherwise false. **/ function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool); /** * @notice The yield contract start in epoch time. * @return Returns the yield start date. **/ function start() external view returns (uint256); /** * @notice The yield contract expiry in epoch time. * @return Returns the yield expiry date. **/ function expiry() external view returns (uint256); /** * @notice Increases the allowance granted to spender by the caller. * @param spender The address to increase the allowance from. * @param addedValue The amount allowance to add. * @return Returns true if allowance has increased, otherwise false **/ function increaseAllowance(address spender, uint256 addedValue) external returns (bool); /** * @notice Returns the number of decimals the token uses. * @return Returns the token's decimals. **/ function decimals() external view returns (uint8); /** * @notice Returns the name of the token. * @return Returns the token's name. **/ function name() external view returns (string memory); /** * @notice Returns the symbol of the token. * @return Returns the token's symbol. **/ function symbol() external view returns (string memory); /** * @notice approve using the owner's signature **/ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; }
must be overridden by the sub contracts, so we must consider explicitly in each and every contract which tokens are allowed to be withdrawn SPDX-License-Identifier: MIT MIT License =========== Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE/
interface IPendleYieldTokenHolder { function redeemRewards() external; function setUpEmergencyMode(address spender) external; function yieldToken() external returns (address); function forge() external returns (address); function rewardToken() external returns (address); function expiry() external returns (uint256); }
5,771,450
/* * Havven Contract * * The collateral token of the Havven stablecoin system. * * version: nUSDa.1 * date: 29 Jun 2018 * url: https://github.com/Havven/havven/releases/tag/nUSDa.1 * * MIT License * =========== * * Copyright (c) 2018 Havven * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.4.24; /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: SafeDecimalMath.sol version: 1.0 author: Anton Jurisevic date: 2018-2-5 checked: Mike Spain approved: Samuel Brooks ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- A fixed point decimal library that provides basic mathematical operations, and checks for unsafe arguments, for example that would lead to overflows. Exceptions are thrown whenever those unsafe operations occur. ----------------------------------------------------------------- */ /** * @title Safely manipulate unsigned fixed-point decimals at a given precision level. * @dev Functions accepting uints in this contract and derived contracts * are taken to be such fixed point decimals (including fiat, ether, and nomin quantities). */ contract SafeDecimalMath { /* Number of decimal places in the representation. */ uint8 public constant decimals = 18; /* The number representing 1.0. */ uint public constant UNIT = 10 ** uint(decimals); /** * @return True iff adding x and y will not overflow. */ function addIsSafe(uint x, uint y) pure internal returns (bool) { return x + y >= y; } /** * @return The result of adding x and y, throwing an exception in case of overflow. */ function safeAdd(uint x, uint y) pure internal returns (uint) { require(x + y >= y); return x + y; } /** * @return True iff subtracting y from x will not overflow in the negative direction. */ function subIsSafe(uint x, uint y) pure internal returns (bool) { return y <= x; } /** * @return The result of subtracting y from x, throwing an exception in case of overflow. */ function safeSub(uint x, uint y) pure internal returns (uint) { require(y <= x); return x - y; } /** * @return True iff multiplying x and y would not overflow. */ function mulIsSafe(uint x, uint y) pure internal returns (bool) { if (x == 0) { return true; } return (x * y) / x == y; } /** * @return The result of multiplying x and y, throwing an exception in case of overflow. */ function safeMul(uint x, uint y) pure internal returns (uint) { if (x == 0) { return 0; } uint p = x * y; require(p / x == y); return p; } /** * @return The result of multiplying x and y, interpreting the operands as fixed-point * decimals. Throws an exception in case of overflow. * * @dev A unit factor is divided out after the product of x and y is evaluated, * so that product must be less than 2**256. * Incidentally, the internal division always rounds down: one could have rounded to the nearest integer, * but then one would be spending a significant fraction of a cent (of order a microether * at present gas prices) in order to save less than one part in 0.5 * 10^18 per operation, if the operands * contain small enough fractional components. It would also marginally diminish the * domain this function is defined upon. */ function safeMul_dec(uint x, uint y) pure internal returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ return safeMul(x, y) / UNIT; } /** * @return True iff the denominator of x/y is nonzero. */ function divIsSafe(uint x, uint y) pure internal returns (bool) { return y != 0; } /** * @return The result of dividing x by y, throwing an exception if the divisor is zero. */ function safeDiv(uint x, uint y) pure internal returns (uint) { /* Although a 0 denominator already throws an exception, * it is equivalent to a THROW operation, which consumes all gas. * A require statement emits REVERT instead, which remits remaining gas. */ require(y != 0); return x / y; } /** * @return The result of dividing x by y, interpreting the operands as fixed point decimal numbers. * @dev Throws an exception in case of overflow or zero divisor; x must be less than 2^256 / UNIT. * Internal rounding is downward: a similar caveat holds as with safeDecMul(). */ function safeDiv_dec(uint x, uint y) pure internal returns (uint) { /* Reintroduce the UNIT factor that will be divided out by y. */ return safeDiv(safeMul(x, UNIT), y); } /** * @dev Convert an unsigned integer to a unsigned fixed-point decimal. * Throw an exception if the result would be out of range. */ function intToDec(uint i) pure internal returns (uint) { return safeMul(i, UNIT); } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: Owned.sol version: 1.1 author: Anton Jurisevic Dominic Romanowski date: 2018-2-26 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- An Owned contract, to be inherited by other contracts. Requires its owner to be explicitly set in the constructor. Provides an onlyOwner access modifier. To change owner, the current owner must nominate the next owner, who then has to accept the nomination. The nomination can be cancelled before it is accepted by the new owner by having the previous owner change the nomination (setting it to 0). ----------------------------------------------------------------- */ /** * @title A contract with an owner. * @notice Contract ownership can be transferred by first nominating the new owner, * who must then accept the ownership, which prevents accidental incorrect ownership transfers. */ contract Owned { address public owner; address public nominatedOwner; /** * @dev Owned Constructor */ constructor(address _owner) public { require(_owner != address(0)); owner = _owner; emit OwnerChanged(address(0), _owner); } /** * @notice Nominate a new owner of this contract. * @dev Only the current owner may nominate a new owner. */ function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } /** * @notice Accept the nomination to be owner. */ function acceptOwnership() external { require(msg.sender == nominatedOwner); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { require(msg.sender == owner); _; } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: SelfDestructible.sol version: 1.2 author: Anton Jurisevic date: 2018-05-29 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- This contract allows an inheriting contract to be destroyed after its owner indicates an intention and then waits for a period without changing their mind. All ether contained in the contract is forwarded to a nominated beneficiary upon destruction. ----------------------------------------------------------------- */ /** * @title A contract that can be destroyed by its owner after a delay elapses. */ contract SelfDestructible is Owned { uint public initiationTime; bool public selfDestructInitiated; address public selfDestructBeneficiary; uint public constant SELFDESTRUCT_DELAY = 4 weeks; /** * @dev Constructor * @param _owner The account which controls this contract. */ constructor(address _owner) Owned(_owner) public { require(_owner != address(0)); selfDestructBeneficiary = _owner; emit SelfDestructBeneficiaryUpdated(_owner); } /** * @notice Set the beneficiary address of this contract. * @dev Only the contract owner may call this. The provided beneficiary must be non-null. * @param _beneficiary The address to pay any eth contained in this contract to upon self-destruction. */ function setSelfDestructBeneficiary(address _beneficiary) external onlyOwner { require(_beneficiary != address(0)); selfDestructBeneficiary = _beneficiary; emit SelfDestructBeneficiaryUpdated(_beneficiary); } /** * @notice Begin the self-destruction counter of this contract. * Once the delay has elapsed, the contract may be self-destructed. * @dev Only the contract owner may call this. */ function initiateSelfDestruct() external onlyOwner { initiationTime = now; selfDestructInitiated = true; emit SelfDestructInitiated(SELFDESTRUCT_DELAY); } /** * @notice Terminate and reset the self-destruction timer. * @dev Only the contract owner may call this. */ function terminateSelfDestruct() external onlyOwner { initiationTime = 0; selfDestructInitiated = false; emit SelfDestructTerminated(); } /** * @notice If the self-destruction delay has elapsed, destroy this contract and * remit any ether it owns to the beneficiary address. * @dev Only the contract owner may call this. */ function selfDestruct() external onlyOwner { require(selfDestructInitiated && initiationTime + SELFDESTRUCT_DELAY < now); address beneficiary = selfDestructBeneficiary; emit SelfDestructed(beneficiary); selfdestruct(beneficiary); } event SelfDestructTerminated(); event SelfDestructed(address beneficiary); event SelfDestructInitiated(uint selfDestructDelay); event SelfDestructBeneficiaryUpdated(address newBeneficiary); } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: State.sol version: 1.1 author: Dominic Romanowski Anton Jurisevic date: 2018-05-15 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- This contract is used side by side with external state token contracts, such as Havven and Nomin. It provides an easy way to upgrade contract logic while maintaining all user balances and allowances. This is designed to make the changeover as easy as possible, since mappings are not so cheap or straightforward to migrate. The first deployed contract would create this state contract, using it as its store of balances. When a new contract is deployed, it links to the existing state contract, whose owner would then change its associated contract to the new one. ----------------------------------------------------------------- */ contract State is Owned { // the address of the contract that can modify variables // this can only be changed by the owner of this contract address public associatedContract; constructor(address _owner, address _associatedContract) Owned(_owner) public { associatedContract = _associatedContract; emit AssociatedContractUpdated(_associatedContract); } /* ========== SETTERS ========== */ // Change the associated contract to a new address function setAssociatedContract(address _associatedContract) external onlyOwner { associatedContract = _associatedContract; emit AssociatedContractUpdated(_associatedContract); } /* ========== MODIFIERS ========== */ modifier onlyAssociatedContract { require(msg.sender == associatedContract); _; } /* ========== EVENTS ========== */ event AssociatedContractUpdated(address associatedContract); } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: TokenState.sol version: 1.1 author: Dominic Romanowski Anton Jurisevic date: 2018-05-15 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- A contract that holds the state of an ERC20 compliant token. This contract is used side by side with external state token contracts, such as Havven and Nomin. It provides an easy way to upgrade contract logic while maintaining all user balances and allowances. This is designed to make the changeover as easy as possible, since mappings are not so cheap or straightforward to migrate. The first deployed contract would create this state contract, using it as its store of balances. When a new contract is deployed, it links to the existing state contract, whose owner would then change its associated contract to the new one. ----------------------------------------------------------------- */ /** * @title ERC20 Token State * @notice Stores balance information of an ERC20 token contract. */ contract TokenState is State { /* ERC20 fields. */ mapping(address => uint) public balanceOf; mapping(address => mapping(address => uint)) public allowance; /** * @dev Constructor * @param _owner The address which controls this contract. * @param _associatedContract The ERC20 contract whose state this composes. */ constructor(address _owner, address _associatedContract) State(_owner, _associatedContract) public {} /* ========== SETTERS ========== */ /** * @notice Set ERC20 allowance. * @dev Only the associated contract may call this. * @param tokenOwner The authorising party. * @param spender The authorised party. * @param value The total value the authorised party may spend on the * authorising party's behalf. */ function setAllowance(address tokenOwner, address spender, uint value) external onlyAssociatedContract { allowance[tokenOwner][spender] = value; } /** * @notice Set the balance in a given account * @dev Only the associated contract may call this. * @param account The account whose value to set. * @param value The new balance of the given account. */ function setBalanceOf(address account, uint value) external onlyAssociatedContract { balanceOf[account] = value; } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: Proxy.sol version: 1.3 author: Anton Jurisevic date: 2018-05-29 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- A proxy contract that, if it does not recognise the function being called on it, passes all value and call data to an underlying target contract. This proxy has the capacity to toggle between DELEGATECALL and CALL style proxy functionality. The former executes in the proxy's context, and so will preserve msg.sender and store data at the proxy address. The latter will not. Therefore, any contract the proxy wraps in the CALL style must implement the Proxyable interface, in order that it can pass msg.sender into the underlying contract as the state parameter, messageSender. ----------------------------------------------------------------- */ contract Proxy is Owned { Proxyable public target; bool public useDELEGATECALL; constructor(address _owner) Owned(_owner) public {} function setTarget(Proxyable _target) external onlyOwner { target = _target; emit TargetUpdated(_target); } function setUseDELEGATECALL(bool value) external onlyOwner { useDELEGATECALL = value; } function _emit(bytes callData, uint numTopics, bytes32 topic1, bytes32 topic2, bytes32 topic3, bytes32 topic4) external onlyTarget { uint size = callData.length; bytes memory _callData = callData; assembly { /* The first 32 bytes of callData contain its length (as specified by the abi). * Length is assumed to be a uint256 and therefore maximum of 32 bytes * in length. It is also leftpadded to be a multiple of 32 bytes. * This means moving call_data across 32 bytes guarantees we correctly access * the data itself. */ switch numTopics case 0 { log0(add(_callData, 32), size) } case 1 { log1(add(_callData, 32), size, topic1) } case 2 { log2(add(_callData, 32), size, topic1, topic2) } case 3 { log3(add(_callData, 32), size, topic1, topic2, topic3) } case 4 { log4(add(_callData, 32), size, topic1, topic2, topic3, topic4) } } } function() external payable { if (useDELEGATECALL) { assembly { /* Copy call data into free memory region. */ let free_ptr := mload(0x40) calldatacopy(free_ptr, 0, calldatasize) /* Forward all gas and call data to the target contract. */ let result := delegatecall(gas, sload(target_slot), free_ptr, calldatasize, 0, 0) returndatacopy(free_ptr, 0, returndatasize) /* Revert if the call failed, otherwise return the result. */ if iszero(result) { revert(free_ptr, returndatasize) } return(free_ptr, returndatasize) } } else { /* Here we are as above, but must send the messageSender explicitly * since we are using CALL rather than DELEGATECALL. */ target.setMessageSender(msg.sender); assembly { let free_ptr := mload(0x40) calldatacopy(free_ptr, 0, calldatasize) /* We must explicitly forward ether to the underlying contract as well. */ let result := call(gas, sload(target_slot), callvalue, free_ptr, calldatasize, 0, 0) returndatacopy(free_ptr, 0, returndatasize) if iszero(result) { revert(free_ptr, returndatasize) } return(free_ptr, returndatasize) } } } modifier onlyTarget { require(Proxyable(msg.sender) == target); _; } event TargetUpdated(Proxyable newTarget); } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: Proxyable.sol version: 1.1 author: Anton Jurisevic date: 2018-05-15 checked: Mike Spain approved: Samuel Brooks ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- A proxyable contract that works hand in hand with the Proxy contract to allow for anyone to interact with the underlying contract both directly and through the proxy. ----------------------------------------------------------------- */ // This contract should be treated like an abstract contract contract Proxyable is Owned { /* The proxy this contract exists behind. */ Proxy public proxy; /* The caller of the proxy, passed through to this contract. * Note that every function using this member must apply the onlyProxy or * optionalProxy modifiers, otherwise their invocations can use stale values. */ address messageSender; constructor(address _proxy, address _owner) Owned(_owner) public { proxy = Proxy(_proxy); emit ProxyUpdated(_proxy); } function setProxy(address _proxy) external onlyOwner { proxy = Proxy(_proxy); emit ProxyUpdated(_proxy); } function setMessageSender(address sender) external onlyProxy { messageSender = sender; } modifier onlyProxy { require(Proxy(msg.sender) == proxy); _; } modifier optionalProxy { if (Proxy(msg.sender) != proxy) { messageSender = msg.sender; } _; } modifier optionalProxy_onlyOwner { if (Proxy(msg.sender) != proxy) { messageSender = msg.sender; } require(messageSender == owner); _; } event ProxyUpdated(address proxyAddress); } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: ExternStateToken.sol version: 1.3 author: Anton Jurisevic Dominic Romanowski date: 2018-05-29 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- A partial ERC20 token contract, designed to operate with a proxy. To produce a complete ERC20 token, transfer and transferFrom tokens must be implemented, using the provided _byProxy internal functions. This contract utilises an external state for upgradeability. ----------------------------------------------------------------- */ /** * @title ERC20 Token contract, with detached state and designed to operate behind a proxy. */ contract ExternStateToken is SafeDecimalMath, SelfDestructible, Proxyable { /* ========== STATE VARIABLES ========== */ /* Stores balances and allowances. */ TokenState public tokenState; /* Other ERC20 fields. * Note that the decimals field is defined in SafeDecimalMath.*/ string public name; string public symbol; uint public totalSupply; /** * @dev Constructor. * @param _proxy The proxy associated with this contract. * @param _name Token's ERC20 name. * @param _symbol Token's ERC20 symbol. * @param _totalSupply The total supply of the token. * @param _tokenState The TokenState contract address. * @param _owner The owner of this contract. */ constructor(address _proxy, TokenState _tokenState, string _name, string _symbol, uint _totalSupply, address _owner) SelfDestructible(_owner) Proxyable(_proxy, _owner) public { name = _name; symbol = _symbol; totalSupply = _totalSupply; tokenState = _tokenState; } /* ========== VIEWS ========== */ /** * @notice Returns the ERC20 allowance of one party to spend on behalf of another. * @param owner The party authorising spending of their funds. * @param spender The party spending tokenOwner's funds. */ function allowance(address owner, address spender) public view returns (uint) { return tokenState.allowance(owner, spender); } /** * @notice Returns the ERC20 token balance of a given account. */ function balanceOf(address account) public view returns (uint) { return tokenState.balanceOf(account); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Set the address of the TokenState contract. * @dev This can be used to "pause" transfer functionality, by pointing the tokenState at 0x000.. * as balances would be unreachable. */ function setTokenState(TokenState _tokenState) external optionalProxy_onlyOwner { tokenState = _tokenState; emitTokenStateUpdated(_tokenState); } function _internalTransfer(address from, address to, uint value) internal returns (bool) { /* Disallow transfers to irretrievable-addresses. */ require(to != address(0)); require(to != address(this)); require(to != address(proxy)); /* Insufficient balance will be handled by the safe subtraction. */ tokenState.setBalanceOf(from, safeSub(tokenState.balanceOf(from), value)); tokenState.setBalanceOf(to, safeAdd(tokenState.balanceOf(to), value)); emitTransfer(from, to, value); return true; } /** * @dev Perform an ERC20 token transfer. Designed to be called by transfer functions possessing * the onlyProxy or optionalProxy modifiers. */ function _transfer_byProxy(address from, address to, uint value) internal returns (bool) { return _internalTransfer(from, to, value); } /** * @dev Perform an ERC20 token transferFrom. Designed to be called by transferFrom functions * possessing the optionalProxy or optionalProxy modifiers. */ function _transferFrom_byProxy(address sender, address from, address to, uint value) internal returns (bool) { /* Insufficient allowance will be handled by the safe subtraction. */ tokenState.setAllowance(from, sender, safeSub(tokenState.allowance(from, sender), value)); return _internalTransfer(from, to, value); } /** * @notice Approves spender to transfer on the message sender's behalf. */ function approve(address spender, uint value) public optionalProxy returns (bool) { address sender = messageSender; tokenState.setAllowance(sender, spender, value); emitApproval(sender, spender, value); return true; } /* ========== EVENTS ========== */ event Transfer(address indexed from, address indexed to, uint value); bytes32 constant TRANSFER_SIG = keccak256("Transfer(address,address,uint256)"); function emitTransfer(address from, address to, uint value) internal { proxy._emit(abi.encode(value), 3, TRANSFER_SIG, bytes32(from), bytes32(to), 0); } event Approval(address indexed owner, address indexed spender, uint value); bytes32 constant APPROVAL_SIG = keccak256("Approval(address,address,uint256)"); function emitApproval(address owner, address spender, uint value) internal { proxy._emit(abi.encode(value), 3, APPROVAL_SIG, bytes32(owner), bytes32(spender), 0); } event TokenStateUpdated(address newTokenState); bytes32 constant TOKENSTATEUPDATED_SIG = keccak256("TokenStateUpdated(address)"); function emitTokenStateUpdated(address newTokenState) internal { proxy._emit(abi.encode(newTokenState), 1, TOKENSTATEUPDATED_SIG, 0, 0, 0); } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: FeeToken.sol version: 1.3 author: Anton Jurisevic Dominic Romanowski Kevin Brown date: 2018-05-29 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- A token which also has a configurable fee rate charged on its transfers. This is designed to be overridden in order to produce an ERC20-compliant token. These fees accrue into a pool, from which a nominated authority may withdraw. This contract utilises an external state for upgradeability. ----------------------------------------------------------------- */ /** * @title ERC20 Token contract, with detached state. * Additionally charges fees on each transfer. */ contract FeeToken is ExternStateToken { /* ========== STATE VARIABLES ========== */ /* ERC20 members are declared in ExternStateToken. */ /* A percentage fee charged on each transfer. */ uint public transferFeeRate; /* Fee may not exceed 10%. */ uint constant MAX_TRANSFER_FEE_RATE = UNIT / 10; /* The address with the authority to distribute fees. */ address public feeAuthority; /* The address that fees will be pooled in. */ address public constant FEE_ADDRESS = 0xfeefeefeefeefeefeefeefeefeefeefeefeefeef; /* ========== CONSTRUCTOR ========== */ /** * @dev Constructor. * @param _proxy The proxy associated with this contract. * @param _name Token's ERC20 name. * @param _symbol Token's ERC20 symbol. * @param _totalSupply The total supply of the token. * @param _transferFeeRate The fee rate to charge on transfers. * @param _feeAuthority The address which has the authority to withdraw fees from the accumulated pool. * @param _owner The owner of this contract. */ constructor(address _proxy, TokenState _tokenState, string _name, string _symbol, uint _totalSupply, uint _transferFeeRate, address _feeAuthority, address _owner) ExternStateToken(_proxy, _tokenState, _name, _symbol, _totalSupply, _owner) public { feeAuthority = _feeAuthority; /* Constructed transfer fee rate should respect the maximum fee rate. */ require(_transferFeeRate <= MAX_TRANSFER_FEE_RATE); transferFeeRate = _transferFeeRate; } /* ========== SETTERS ========== */ /** * @notice Set the transfer fee, anywhere within the range 0-10%. * @dev The fee rate is in decimal format, with UNIT being the value of 100%. */ function setTransferFeeRate(uint _transferFeeRate) external optionalProxy_onlyOwner { require(_transferFeeRate <= MAX_TRANSFER_FEE_RATE); transferFeeRate = _transferFeeRate; emitTransferFeeRateUpdated(_transferFeeRate); } /** * @notice Set the address of the user/contract responsible for collecting or * distributing fees. */ function setFeeAuthority(address _feeAuthority) public optionalProxy_onlyOwner { feeAuthority = _feeAuthority; emitFeeAuthorityUpdated(_feeAuthority); } /* ========== VIEWS ========== */ /** * @notice Calculate the Fee charged on top of a value being sent * @return Return the fee charged */ function transferFeeIncurred(uint value) public view returns (uint) { return safeMul_dec(value, transferFeeRate); /* Transfers less than the reciprocal of transferFeeRate should be completely eaten up by fees. * This is on the basis that transfers less than this value will result in a nil fee. * Probably too insignificant to worry about, but the following code will achieve it. * if (fee == 0 && transferFeeRate != 0) { * return _value; * } * return fee; */ } /** * @notice The value that you would need to send so that the recipient receives * a specified value. */ function transferPlusFee(uint value) external view returns (uint) { return safeAdd(value, transferFeeIncurred(value)); } /** * @notice The amount the recipient will receive if you send a certain number of tokens. */ function amountReceived(uint value) public view returns (uint) { return safeDiv_dec(value, safeAdd(UNIT, transferFeeRate)); } /** * @notice Collected fees sit here until they are distributed. * @dev The balance of the nomin contract itself is the fee pool. */ function feePool() external view returns (uint) { return tokenState.balanceOf(FEE_ADDRESS); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Base of transfer functions */ function _internalTransfer(address from, address to, uint amount, uint fee) internal returns (bool) { /* Disallow transfers to irretrievable-addresses. */ require(to != address(0)); require(to != address(this)); require(to != address(proxy)); /* Insufficient balance will be handled by the safe subtraction. */ tokenState.setBalanceOf(from, safeSub(tokenState.balanceOf(from), safeAdd(amount, fee))); tokenState.setBalanceOf(to, safeAdd(tokenState.balanceOf(to), amount)); tokenState.setBalanceOf(FEE_ADDRESS, safeAdd(tokenState.balanceOf(FEE_ADDRESS), fee)); /* Emit events for both the transfer itself and the fee. */ emitTransfer(from, to, amount); emitTransfer(from, FEE_ADDRESS, fee); return true; } /** * @notice ERC20 friendly transfer function. */ function _transfer_byProxy(address sender, address to, uint value) internal returns (bool) { uint received = amountReceived(value); uint fee = safeSub(value, received); return _internalTransfer(sender, to, received, fee); } /** * @notice ERC20 friendly transferFrom function. */ function _transferFrom_byProxy(address sender, address from, address to, uint value) internal returns (bool) { /* The fee is deducted from the amount sent. */ uint received = amountReceived(value); uint fee = safeSub(value, received); /* Reduce the allowance by the amount we're transferring. * The safeSub call will handle an insufficient allowance. */ tokenState.setAllowance(from, sender, safeSub(tokenState.allowance(from, sender), value)); return _internalTransfer(from, to, received, fee); } /** * @notice Ability to transfer where the sender pays the fees (not ERC20) */ function _transferSenderPaysFee_byProxy(address sender, address to, uint value) internal returns (bool) { /* The fee is added to the amount sent. */ uint fee = transferFeeIncurred(value); return _internalTransfer(sender, to, value, fee); } /** * @notice Ability to transferFrom where they sender pays the fees (not ERC20). */ function _transferFromSenderPaysFee_byProxy(address sender, address from, address to, uint value) internal returns (bool) { /* The fee is added to the amount sent. */ uint fee = transferFeeIncurred(value); uint total = safeAdd(value, fee); /* Reduce the allowance by the amount we're transferring. */ tokenState.setAllowance(from, sender, safeSub(tokenState.allowance(from, sender), total)); return _internalTransfer(from, to, value, fee); } /** * @notice Withdraw tokens from the fee pool into a given account. * @dev Only the fee authority may call this. */ function withdrawFees(address account, uint value) external onlyFeeAuthority returns (bool) { require(account != address(0)); /* 0-value withdrawals do nothing. */ if (value == 0) { return false; } /* Safe subtraction ensures an exception is thrown if the balance is insufficient. */ tokenState.setBalanceOf(FEE_ADDRESS, safeSub(tokenState.balanceOf(FEE_ADDRESS), value)); tokenState.setBalanceOf(account, safeAdd(tokenState.balanceOf(account), value)); emitFeesWithdrawn(account, value); emitTransfer(FEE_ADDRESS, account, value); return true; } /** * @notice Donate tokens from the sender's balance into the fee pool. */ function donateToFeePool(uint n) external optionalProxy returns (bool) { address sender = messageSender; /* Empty donations are disallowed. */ uint balance = tokenState.balanceOf(sender); require(balance != 0); /* safeSub ensures the donor has sufficient balance. */ tokenState.setBalanceOf(sender, safeSub(balance, n)); tokenState.setBalanceOf(FEE_ADDRESS, safeAdd(tokenState.balanceOf(FEE_ADDRESS), n)); emitFeesDonated(sender, n); emitTransfer(sender, FEE_ADDRESS, n); return true; } /* ========== MODIFIERS ========== */ modifier onlyFeeAuthority { require(msg.sender == feeAuthority); _; } /* ========== EVENTS ========== */ event TransferFeeRateUpdated(uint newFeeRate); bytes32 constant TRANSFERFEERATEUPDATED_SIG = keccak256("TransferFeeRateUpdated(uint256)"); function emitTransferFeeRateUpdated(uint newFeeRate) internal { proxy._emit(abi.encode(newFeeRate), 1, TRANSFERFEERATEUPDATED_SIG, 0, 0, 0); } event FeeAuthorityUpdated(address newFeeAuthority); bytes32 constant FEEAUTHORITYUPDATED_SIG = keccak256("FeeAuthorityUpdated(address)"); function emitFeeAuthorityUpdated(address newFeeAuthority) internal { proxy._emit(abi.encode(newFeeAuthority), 1, FEEAUTHORITYUPDATED_SIG, 0, 0, 0); } event FeesWithdrawn(address indexed account, uint value); bytes32 constant FEESWITHDRAWN_SIG = keccak256("FeesWithdrawn(address,uint256)"); function emitFeesWithdrawn(address account, uint value) internal { proxy._emit(abi.encode(value), 2, FEESWITHDRAWN_SIG, bytes32(account), 0, 0); } event FeesDonated(address indexed donor, uint value); bytes32 constant FEESDONATED_SIG = keccak256("FeesDonated(address,uint256)"); function emitFeesDonated(address donor, uint value) internal { proxy._emit(abi.encode(value), 2, FEESDONATED_SIG, bytes32(donor), 0, 0); } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: Court.sol version: 1.2 author: Anton Jurisevic Mike Spain Dominic Romanowski date: 2018-05-29 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- This provides the nomin contract with a confiscation facility, if enough havven owners vote to confiscate a target account's nomins. This is designed to provide a mechanism to respond to abusive contracts such as nomin wrappers, which would allow users to trade wrapped nomins without accruing fees on those transactions. In order to prevent tyranny, an account may only be frozen if users controlling at least 30% of the value of havvens participate, and a two thirds majority is attained in that vote. In order to prevent tyranny of the majority or mob justice, confiscation motions are only approved if the havven foundation approves the result. This latter requirement may be lifted in future versions. The foundation, or any user with a sufficient havven balance may bring a confiscation motion. A motion lasts for a default period of one week, with a further confirmation period in which the foundation approves the result. The latter period may conclude early upon the foundation's decision to either veto or approve the mooted confiscation motion. If the confirmation period elapses without the foundation making a decision, the motion fails. The weight of a havven holder's vote is determined by examining their average balance over the last completed fee period prior to the beginning of a given motion. Thus, since a fee period can roll over in the middle of a motion, we must also track a user's average balance of the last two periods. This system is designed such that it cannot be attacked by users transferring funds between themselves, while also not requiring them to lock their havvens for the duration of the vote. This is possible since any transfer that increases the average balance in one account will be reflected by an equivalent reduction in the voting weight in the other. At present a user may cast a vote only for one motion at a time, but may cancel their vote at any time except during the confirmation period, when the vote tallies must remain static until the matter has been settled. A motion to confiscate the balance of a given address composes a state machine built of the following states: Waiting: - A user with standing brings a motion: If the target address is not frozen; initialise vote tallies to 0; transition to the Voting state. - An account cancels a previous residual vote: remain in the Waiting state. Voting: - The foundation vetoes the in-progress motion: transition to the Waiting state. - The voting period elapses: transition to the Confirmation state. - An account votes (for or against the motion): its weight is added to the appropriate tally; remain in the Voting state. - An account cancels its previous vote: its weight is deducted from the appropriate tally (if any); remain in the Voting state. Confirmation: - The foundation vetoes the completed motion: transition to the Waiting state. - The foundation approves confiscation of the target account: freeze the target account, transfer its nomin balance to the fee pool; transition to the Waiting state. - The confirmation period elapses: transition to the Waiting state. User votes are not automatically cancelled upon the conclusion of a motion. Therefore, after a motion comes to a conclusion, if a user wishes to vote in another motion, they must manually cancel their vote in order to do so. This procedure is designed to be relatively simple. There are some things that can be added to enhance the functionality at the expense of simplicity and efficiency: - Democratic unfreezing of nomin accounts (induces multiple categories of vote) - Configurable per-vote durations; - Vote standing denominated in a fiat quantity rather than a quantity of havvens; - Confiscate from multiple addresses in a single vote; We might consider updating the contract with any of these features at a later date if necessary. ----------------------------------------------------------------- */ /** * @title A court contract allowing a democratic mechanism to dissuade token wrappers. */ contract Court is SafeDecimalMath, Owned { /* ========== STATE VARIABLES ========== */ /* The addresses of the token contracts this confiscation court interacts with. */ Havven public havven; Nomin public nomin; /* The minimum issued nomin balance required to be considered to have * standing to begin confiscation proceedings. */ uint public minStandingBalance = 100 * UNIT; /* The voting period lasts for this duration, * and if set, must fall within the given bounds. */ uint public votingPeriod = 1 weeks; uint constant MIN_VOTING_PERIOD = 3 days; uint constant MAX_VOTING_PERIOD = 4 weeks; /* Duration of the period during which the foundation may confirm * or veto a motion that has concluded. * If set, the confirmation duration must fall within the given bounds. */ uint public confirmationPeriod = 1 weeks; uint constant MIN_CONFIRMATION_PERIOD = 1 days; uint constant MAX_CONFIRMATION_PERIOD = 2 weeks; /* No fewer than this fraction of total available voting power must * participate in a motion in order for a quorum to be reached. * The participation fraction required may be set no lower than 10%. * As a fraction, it is expressed in terms of UNIT, not as an absolute quantity. */ uint public requiredParticipation = 3 * UNIT / 10; uint constant MIN_REQUIRED_PARTICIPATION = UNIT / 10; /* At least this fraction of participating votes must be in favour of * confiscation for the motion to pass. * The required majority may be no lower than 50%. * As a fraction, it is expressed in terms of UNIT, not as an absolute quantity. */ uint public requiredMajority = (2 * UNIT) / 3; uint constant MIN_REQUIRED_MAJORITY = UNIT / 2; /* The next ID to use for opening a motion. * The 0 motion ID corresponds to no motion, * and is used as a null value for later comparison. */ uint nextMotionID = 1; /* Mapping from motion IDs to target addresses. */ mapping(uint => address) public motionTarget; /* The ID a motion on an address is currently operating at. * Zero if no such motion is running. */ mapping(address => uint) public targetMotionID; /* The timestamp at which a motion began. This is used to determine * whether a motion is: running, in the confirmation period, * or has concluded. * A motion runs from its start time t until (t + votingPeriod), * and then the confirmation period terminates no later than * (t + votingPeriod + confirmationPeriod). */ mapping(uint => uint) public motionStartTime; /* The tallies for and against confiscation of a given balance. * These are set to zero at the start of a motion, and also on conclusion, * just to keep the state clean. */ mapping(uint => uint) public votesFor; mapping(uint => uint) public votesAgainst; /* The last average balance of a user at the time they voted * in a particular motion. * If we did not save this information then we would have to * disallow transfers into an account lest it cancel a vote * with greater weight than that with which it originally voted, * and the fee period rolled over in between. */ // TODO: This may be unnecessary now that votes are forced to be // within a fee period. Likely possible to delete this. mapping(address => mapping(uint => uint)) voteWeight; /* The possible vote types. * Abstention: not participating in a motion; This is the default value. * Yea: voting in favour of a motion. * Nay: voting against a motion. */ enum Vote {Abstention, Yea, Nay} /* A given account's vote in some confiscation motion. * This requires the default value of the Vote enum to correspond to an abstention. */ mapping(address => mapping(uint => Vote)) public vote; /* ========== CONSTRUCTOR ========== */ /** * @dev Court Constructor. */ constructor(Havven _havven, Nomin _nomin, address _owner) Owned(_owner) public { havven = _havven; nomin = _nomin; } /* ========== SETTERS ========== */ /** * @notice Set the minimum required havven balance to have standing to bring a motion. * @dev Only the contract owner may call this. */ function setMinStandingBalance(uint balance) external onlyOwner { /* No requirement on the standing threshold here; * the foundation can set this value such that * anyone or no one can actually start a motion. */ minStandingBalance = balance; } /** * @notice Set the length of time a vote runs for. * @dev Only the contract owner may call this. The proposed duration must fall * within sensible bounds (3 days to 4 weeks), and must be no longer than a single fee period. */ function setVotingPeriod(uint duration) external onlyOwner { require(MIN_VOTING_PERIOD <= duration && duration <= MAX_VOTING_PERIOD); /* Require that the voting period is no longer than a single fee period, * So that a single vote can span at most two fee periods. */ require(duration <= havven.feePeriodDuration()); votingPeriod = duration; } /** * @notice Set the confirmation period after a vote has concluded. * @dev Only the contract owner may call this. The proposed duration must fall * within sensible bounds (1 day to 2 weeks). */ function setConfirmationPeriod(uint duration) external onlyOwner { require(MIN_CONFIRMATION_PERIOD <= duration && duration <= MAX_CONFIRMATION_PERIOD); confirmationPeriod = duration; } /** * @notice Set the required fraction of all Havvens that need to be part of * a vote for it to pass. */ function setRequiredParticipation(uint fraction) external onlyOwner { require(MIN_REQUIRED_PARTICIPATION <= fraction); requiredParticipation = fraction; } /** * @notice Set what portion of voting havvens need to be in the affirmative * to allow it to pass. */ function setRequiredMajority(uint fraction) external onlyOwner { require(MIN_REQUIRED_MAJORITY <= fraction); requiredMajority = fraction; } /* ========== VIEW FUNCTIONS ========== */ /** * @notice There is a motion in progress on the specified * account, and votes are being accepted in that motion. */ function motionVoting(uint motionID) public view returns (bool) { return motionStartTime[motionID] < now && now < motionStartTime[motionID] + votingPeriod; } /** * @notice A vote on the target account has concluded, but the motion * has not yet been approved, vetoed, or closed. */ function motionConfirming(uint motionID) public view returns (bool) { /* These values are timestamps, they will not overflow * as they can only ever be initialised to relatively small values. */ uint startTime = motionStartTime[motionID]; return startTime + votingPeriod <= now && now < startTime + votingPeriod + confirmationPeriod; } /** * @notice A vote motion either not begun, or it has completely terminated. */ function motionWaiting(uint motionID) public view returns (bool) { /* These values are timestamps, they will not overflow * as they can only ever be initialised to relatively small values. */ return motionStartTime[motionID] + votingPeriod + confirmationPeriod <= now; } /** * @notice If the motion was to terminate at this instant, it would pass. * That is: there was sufficient participation and a sizeable enough majority. */ function motionPasses(uint motionID) public view returns (bool) { uint yeas = votesFor[motionID]; uint nays = votesAgainst[motionID]; uint totalVotes = safeAdd(yeas, nays); if (totalVotes == 0) { return false; } uint participation = safeDiv_dec(totalVotes, havven.totalIssuanceLastAverageBalance()); uint fractionInFavour = safeDiv_dec(yeas, totalVotes); /* We require the result to be strictly greater than the requirement * to enforce a majority being "50% + 1", and so on. */ return participation > requiredParticipation && fractionInFavour > requiredMajority; } /** * @notice Return if the specified account has voted on the specified motion */ function hasVoted(address account, uint motionID) public view returns (bool) { return vote[account][motionID] != Vote.Abstention; } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Begin a motion to confiscate the funds in a given nomin account. * @dev Only the foundation, or accounts with sufficient havven balances * may elect to start such a motion. * @return Returns the ID of the motion that was begun. */ function beginMotion(address target) external returns (uint) { /* A confiscation motion must be mooted by someone with standing. */ require((havven.issuanceLastAverageBalance(msg.sender) >= minStandingBalance) || msg.sender == owner); /* Require that the voting period is longer than a single fee period, * So that a single vote can span at most two fee periods. */ require(votingPeriod <= havven.feePeriodDuration()); /* There must be no confiscation motion already running for this account. */ require(targetMotionID[target] == 0); /* Disallow votes on accounts that are currently frozen. */ require(!nomin.frozen(target)); /* It is necessary to roll over the fee period if it has elapsed, or else * the vote might be initialised having begun in the past. */ havven.rolloverFeePeriodIfElapsed(); uint motionID = nextMotionID++; motionTarget[motionID] = target; targetMotionID[target] = motionID; /* Start the vote at the start of the next fee period */ uint startTime = havven.feePeriodStartTime() + havven.feePeriodDuration(); motionStartTime[motionID] = startTime; emit MotionBegun(msg.sender, target, motionID, startTime); return motionID; } /** * @notice Shared vote setup function between voteFor and voteAgainst. * @return Returns the voter's vote weight. */ function setupVote(uint motionID) internal returns (uint) { /* There must be an active vote for this target running. * Vote totals must only change during the voting phase. */ require(motionVoting(motionID)); /* The voter must not have an active vote this motion. */ require(!hasVoted(msg.sender, motionID)); /* The voter may not cast votes on themselves. */ require(msg.sender != motionTarget[motionID]); uint weight = havven.recomputeLastAverageBalance(msg.sender); /* Users must have a nonzero voting weight to vote. */ require(weight > 0); voteWeight[msg.sender][motionID] = weight; return weight; } /** * @notice The sender casts a vote in favour of confiscation of the * target account's nomin balance. */ function voteFor(uint motionID) external { uint weight = setupVote(motionID); vote[msg.sender][motionID] = Vote.Yea; votesFor[motionID] = safeAdd(votesFor[motionID], weight); emit VotedFor(msg.sender, motionID, weight); } /** * @notice The sender casts a vote against confiscation of the * target account's nomin balance. */ function voteAgainst(uint motionID) external { uint weight = setupVote(motionID); vote[msg.sender][motionID] = Vote.Nay; votesAgainst[motionID] = safeAdd(votesAgainst[motionID], weight); emit VotedAgainst(msg.sender, motionID, weight); } /** * @notice Cancel an existing vote by the sender on a motion * to confiscate the target balance. */ function cancelVote(uint motionID) external { /* An account may cancel its vote either before the confirmation phase * when the motion is still open, or after the confirmation phase, * when the motion has concluded. * But the totals must not change during the confirmation phase itself. */ require(!motionConfirming(motionID)); Vote senderVote = vote[msg.sender][motionID]; /* If the sender has not voted then there is no need to update anything. */ require(senderVote != Vote.Abstention); /* If we are not voting, there is no reason to update the vote totals. */ if (motionVoting(motionID)) { if (senderVote == Vote.Yea) { votesFor[motionID] = safeSub(votesFor[motionID], voteWeight[msg.sender][motionID]); } else { /* Since we already ensured that the vote is not an abstention, * the only option remaining is Vote.Nay. */ votesAgainst[motionID] = safeSub(votesAgainst[motionID], voteWeight[msg.sender][motionID]); } /* A cancelled vote is only meaningful if a vote is running. */ emit VoteCancelled(msg.sender, motionID); } delete voteWeight[msg.sender][motionID]; delete vote[msg.sender][motionID]; } /** * @notice clear all data associated with a motionID for hygiene purposes. */ function _closeMotion(uint motionID) internal { delete targetMotionID[motionTarget[motionID]]; delete motionTarget[motionID]; delete motionStartTime[motionID]; delete votesFor[motionID]; delete votesAgainst[motionID]; emit MotionClosed(motionID); } /** * @notice If a motion has concluded, or if it lasted its full duration but not passed, * then anyone may close it. */ function closeMotion(uint motionID) external { require((motionConfirming(motionID) && !motionPasses(motionID)) || motionWaiting(motionID)); _closeMotion(motionID); } /** * @notice The foundation may only confiscate a balance during the confirmation * period after a motion has passed. */ function approveMotion(uint motionID) external onlyOwner { require(motionConfirming(motionID) && motionPasses(motionID)); address target = motionTarget[motionID]; nomin.freezeAndConfiscate(target); _closeMotion(motionID); emit MotionApproved(motionID); } /* @notice The foundation may veto a motion at any time. */ function vetoMotion(uint motionID) external onlyOwner { require(!motionWaiting(motionID)); _closeMotion(motionID); emit MotionVetoed(motionID); } /* ========== EVENTS ========== */ event MotionBegun(address indexed initiator, address indexed target, uint indexed motionID, uint startTime); event VotedFor(address indexed voter, uint indexed motionID, uint weight); event VotedAgainst(address indexed voter, uint indexed motionID, uint weight); event VoteCancelled(address indexed voter, uint indexed motionID); event MotionClosed(uint indexed motionID); event MotionVetoed(uint indexed motionID); event MotionApproved(uint indexed motionID); } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: Nomin.sol version: 1.2 author: Anton Jurisevic Mike Spain Dominic Romanowski Kevin Brown date: 2018-05-29 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- Havven-backed nomin stablecoin contract. This contract issues nomins, which are tokens worth 1 USD each. Nomins are issuable by Havven holders who have to lock up some value of their havvens to issue H * Cmax nomins. Where Cmax is some value less than 1. A configurable fee is charged on nomin transfers and deposited into a common pot, which havven holders may withdraw from once per fee period. ----------------------------------------------------------------- */ contract Nomin is FeeToken { /* ========== STATE VARIABLES ========== */ // The address of the contract which manages confiscation votes. Court public court; Havven public havven; // Accounts which have lost the privilege to transact in nomins. mapping(address => bool) public frozen; // Nomin transfers incur a 15 bp fee by default. uint constant TRANSFER_FEE_RATE = 15 * UNIT / 10000; string constant TOKEN_NAME = "Nomin USD"; string constant TOKEN_SYMBOL = "nUSD"; /* ========== CONSTRUCTOR ========== */ constructor(address _proxy, TokenState _tokenState, Havven _havven, uint _totalSupply, address _owner) FeeToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, _totalSupply, TRANSFER_FEE_RATE, _havven, // The havven contract is the fee authority. _owner) public { require(_proxy != 0 && address(_havven) != 0 && _owner != 0); // It should not be possible to transfer to the fee pool directly (or confiscate its balance). frozen[FEE_ADDRESS] = true; havven = _havven; } /* ========== SETTERS ========== */ function setCourt(Court _court) external optionalProxy_onlyOwner { court = _court; emitCourtUpdated(_court); } function setHavven(Havven _havven) external optionalProxy_onlyOwner { // havven should be set as the feeAuthority after calling this depending on // havven's internal logic havven = _havven; setFeeAuthority(_havven); emitHavvenUpdated(_havven); } /* ========== MUTATIVE FUNCTIONS ========== */ /* Override ERC20 transfer function in order to check * whether the recipient account is frozen. Note that there is * no need to check whether the sender has a frozen account, * since their funds have already been confiscated, * and no new funds can be transferred to it.*/ function transfer(address to, uint value) public optionalProxy returns (bool) { require(!frozen[to]); return _transfer_byProxy(messageSender, to, value); } /* Override ERC20 transferFrom function in order to check * whether the recipient account is frozen. */ function transferFrom(address from, address to, uint value) public optionalProxy returns (bool) { require(!frozen[to]); return _transferFrom_byProxy(messageSender, from, to, value); } function transferSenderPaysFee(address to, uint value) public optionalProxy returns (bool) { require(!frozen[to]); return _transferSenderPaysFee_byProxy(messageSender, to, value); } function transferFromSenderPaysFee(address from, address to, uint value) public optionalProxy returns (bool) { require(!frozen[to]); return _transferFromSenderPaysFee_byProxy(messageSender, from, to, value); } /* If a confiscation court motion has passed and reached the confirmation * state, the court may transfer the target account's balance to the fee pool * and freeze its participation in further transactions. */ function freezeAndConfiscate(address target) external onlyCourt { // A motion must actually be underway. uint motionID = court.targetMotionID(target); require(motionID != 0); // These checks are strictly unnecessary, // since they are already checked in the court contract itself. require(court.motionConfirming(motionID)); require(court.motionPasses(motionID)); require(!frozen[target]); // Confiscate the balance in the account and freeze it. uint balance = tokenState.balanceOf(target); tokenState.setBalanceOf(FEE_ADDRESS, safeAdd(tokenState.balanceOf(FEE_ADDRESS), balance)); tokenState.setBalanceOf(target, 0); frozen[target] = true; emitAccountFrozen(target, balance); emitTransfer(target, FEE_ADDRESS, balance); } /* The owner may allow a previously-frozen contract to once * again accept and transfer nomins. */ function unfreezeAccount(address target) external optionalProxy_onlyOwner { require(frozen[target] && target != FEE_ADDRESS); frozen[target] = false; emitAccountUnfrozen(target); } /* Allow havven to issue a certain number of * nomins from an account. */ function issue(address account, uint amount) external onlyHavven { tokenState.setBalanceOf(account, safeAdd(tokenState.balanceOf(account), amount)); totalSupply = safeAdd(totalSupply, amount); emitTransfer(address(0), account, amount); emitIssued(account, amount); } /* Allow havven to burn a certain number of * nomins from an account. */ function burn(address account, uint amount) external onlyHavven { tokenState.setBalanceOf(account, safeSub(tokenState.balanceOf(account), amount)); totalSupply = safeSub(totalSupply, amount); emitTransfer(account, address(0), amount); emitBurned(account, amount); } /* ========== MODIFIERS ========== */ modifier onlyHavven() { require(Havven(msg.sender) == havven); _; } modifier onlyCourt() { require(Court(msg.sender) == court); _; } /* ========== EVENTS ========== */ event CourtUpdated(address newCourt); bytes32 constant COURTUPDATED_SIG = keccak256("CourtUpdated(address)"); function emitCourtUpdated(address newCourt) internal { proxy._emit(abi.encode(newCourt), 1, COURTUPDATED_SIG, 0, 0, 0); } event HavvenUpdated(address newHavven); bytes32 constant HAVVENUPDATED_SIG = keccak256("HavvenUpdated(address)"); function emitHavvenUpdated(address newHavven) internal { proxy._emit(abi.encode(newHavven), 1, HAVVENUPDATED_SIG, 0, 0, 0); } event AccountFrozen(address indexed target, uint balance); bytes32 constant ACCOUNTFROZEN_SIG = keccak256("AccountFrozen(address,uint256)"); function emitAccountFrozen(address target, uint balance) internal { proxy._emit(abi.encode(balance), 2, ACCOUNTFROZEN_SIG, bytes32(target), 0, 0); } event AccountUnfrozen(address indexed target); bytes32 constant ACCOUNTUNFROZEN_SIG = keccak256("AccountUnfrozen(address)"); function emitAccountUnfrozen(address target) internal { proxy._emit(abi.encode(), 2, ACCOUNTUNFROZEN_SIG, bytes32(target), 0, 0); } event Issued(address indexed account, uint amount); bytes32 constant ISSUED_SIG = keccak256("Issued(address,uint256)"); function emitIssued(address account, uint amount) internal { proxy._emit(abi.encode(amount), 2, ISSUED_SIG, bytes32(account), 0, 0); } event Burned(address indexed account, uint amount); bytes32 constant BURNED_SIG = keccak256("Burned(address,uint256)"); function emitBurned(address account, uint amount) internal { proxy._emit(abi.encode(amount), 2, BURNED_SIG, bytes32(account), 0, 0); } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: LimitedSetup.sol version: 1.1 author: Anton Jurisevic date: 2018-05-15 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- A contract with a limited setup period. Any function modified with the setup modifier will cease to work after the conclusion of the configurable-length post-construction setup period. ----------------------------------------------------------------- */ /** * @title Any function decorated with the modifier this contract provides * deactivates after a specified setup period. */ contract LimitedSetup { uint setupExpiryTime; /** * @dev LimitedSetup Constructor. * @param setupDuration The time the setup period will last for. */ constructor(uint setupDuration) public { setupExpiryTime = now + setupDuration; } modifier onlyDuringSetup { require(now < setupExpiryTime); _; } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: HavvenEscrow.sol version: 1.1 author: Anton Jurisevic Dominic Romanowski Mike Spain date: 2018-05-29 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- This contract allows the foundation to apply unique vesting schedules to havven funds sold at various discounts in the token sale. HavvenEscrow gives users the ability to inspect their vested funds, their quantities and vesting dates, and to withdraw the fees that accrue on those funds. The fees are handled by withdrawing the entire fee allocation for all havvens inside the escrow contract, and then allowing the contract itself to subdivide that pool up proportionally within itself. Every time the fee period rolls over in the main Havven contract, the HavvenEscrow fee pool is remitted back into the main fee pool to be redistributed in the next fee period. ----------------------------------------------------------------- */ /** * @title A contract to hold escrowed havvens and free them at given schedules. */ contract HavvenEscrow is SafeDecimalMath, Owned, LimitedSetup(8 weeks) { /* The corresponding Havven contract. */ Havven public havven; /* Lists of (timestamp, quantity) pairs per account, sorted in ascending time order. * These are the times at which each given quantity of havvens vests. */ mapping(address => uint[2][]) public vestingSchedules; /* An account's total vested havven balance to save recomputing this for fee extraction purposes. */ mapping(address => uint) public totalVestedAccountBalance; /* The total remaining vested balance, for verifying the actual havven balance of this contract against. */ uint public totalVestedBalance; uint constant TIME_INDEX = 0; uint constant QUANTITY_INDEX = 1; /* Limit vesting entries to disallow unbounded iteration over vesting schedules. */ uint constant MAX_VESTING_ENTRIES = 20; /* ========== CONSTRUCTOR ========== */ constructor(address _owner, Havven _havven) Owned(_owner) public { havven = _havven; } /* ========== SETTERS ========== */ function setHavven(Havven _havven) external onlyOwner { havven = _havven; emit HavvenUpdated(_havven); } /* ========== VIEW FUNCTIONS ========== */ /** * @notice A simple alias to totalVestedAccountBalance: provides ERC20 balance integration. */ function balanceOf(address account) public view returns (uint) { return totalVestedAccountBalance[account]; } /** * @notice The number of vesting dates in an account's schedule. */ function numVestingEntries(address account) public view returns (uint) { return vestingSchedules[account].length; } /** * @notice Get a particular schedule entry for an account. * @return A pair of uints: (timestamp, havven quantity). */ function getVestingScheduleEntry(address account, uint index) public view returns (uint[2]) { return vestingSchedules[account][index]; } /** * @notice Get the time at which a given schedule entry will vest. */ function getVestingTime(address account, uint index) public view returns (uint) { return getVestingScheduleEntry(account,index)[TIME_INDEX]; } /** * @notice Get the quantity of havvens associated with a given schedule entry. */ function getVestingQuantity(address account, uint index) public view returns (uint) { return getVestingScheduleEntry(account,index)[QUANTITY_INDEX]; } /** * @notice Obtain the index of the next schedule entry that will vest for a given user. */ function getNextVestingIndex(address account) public view returns (uint) { uint len = numVestingEntries(account); for (uint i = 0; i < len; i++) { if (getVestingTime(account, i) != 0) { return i; } } return len; } /** * @notice Obtain the next schedule entry that will vest for a given user. * @return A pair of uints: (timestamp, havven quantity). */ function getNextVestingEntry(address account) public view returns (uint[2]) { uint index = getNextVestingIndex(account); if (index == numVestingEntries(account)) { return [uint(0), 0]; } return getVestingScheduleEntry(account, index); } /** * @notice Obtain the time at which the next schedule entry will vest for a given user. */ function getNextVestingTime(address account) external view returns (uint) { return getNextVestingEntry(account)[TIME_INDEX]; } /** * @notice Obtain the quantity which the next schedule entry will vest for a given user. */ function getNextVestingQuantity(address account) external view returns (uint) { return getNextVestingEntry(account)[QUANTITY_INDEX]; } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Withdraws a quantity of havvens back to the havven contract. * @dev This may only be called by the owner during the contract's setup period. */ function withdrawHavvens(uint quantity) external onlyOwner onlyDuringSetup { havven.transfer(havven, quantity); } /** * @notice Destroy the vesting information associated with an account. */ function purgeAccount(address account) external onlyOwner onlyDuringSetup { delete vestingSchedules[account]; totalVestedBalance = safeSub(totalVestedBalance, totalVestedAccountBalance[account]); delete totalVestedAccountBalance[account]; } /** * @notice Add a new vesting entry at a given time and quantity to an account's schedule. * @dev A call to this should be accompanied by either enough balance already available * in this contract, or a corresponding call to havven.endow(), to ensure that when * the funds are withdrawn, there is enough balance, as well as correctly calculating * the fees. * This may only be called by the owner during the contract's setup period. * Note; although this function could technically be used to produce unbounded * arrays, it's only in the foundation's command to add to these lists. * @param account The account to append a new vesting entry to. * @param time The absolute unix timestamp after which the vested quantity may be withdrawn. * @param quantity The quantity of havvens that will vest. */ function appendVestingEntry(address account, uint time, uint quantity) public onlyOwner onlyDuringSetup { /* No empty or already-passed vesting entries allowed. */ require(now < time); require(quantity != 0); /* There must be enough balance in the contract to provide for the vesting entry. */ totalVestedBalance = safeAdd(totalVestedBalance, quantity); require(totalVestedBalance <= havven.balanceOf(this)); /* Disallow arbitrarily long vesting schedules in light of the gas limit. */ uint scheduleLength = vestingSchedules[account].length; require(scheduleLength <= MAX_VESTING_ENTRIES); if (scheduleLength == 0) { totalVestedAccountBalance[account] = quantity; } else { /* Disallow adding new vested havvens earlier than the last one. * Since entries are only appended, this means that no vesting date can be repeated. */ require(getVestingTime(account, numVestingEntries(account) - 1) < time); totalVestedAccountBalance[account] = safeAdd(totalVestedAccountBalance[account], quantity); } vestingSchedules[account].push([time, quantity]); } /** * @notice Construct a vesting schedule to release a quantities of havvens * over a series of intervals. * @dev Assumes that the quantities are nonzero * and that the sequence of timestamps is strictly increasing. * This may only be called by the owner during the contract's setup period. */ function addVestingSchedule(address account, uint[] times, uint[] quantities) external onlyOwner onlyDuringSetup { for (uint i = 0; i < times.length; i++) { appendVestingEntry(account, times[i], quantities[i]); } } /** * @notice Allow a user to withdraw any havvens in their schedule that have vested. */ function vest() external { uint numEntries = numVestingEntries(msg.sender); uint total; for (uint i = 0; i < numEntries; i++) { uint time = getVestingTime(msg.sender, i); /* The list is sorted; when we reach the first future time, bail out. */ if (time > now) { break; } uint qty = getVestingQuantity(msg.sender, i); if (qty == 0) { continue; } vestingSchedules[msg.sender][i] = [0, 0]; total = safeAdd(total, qty); } if (total != 0) { totalVestedBalance = safeSub(totalVestedBalance, total); totalVestedAccountBalance[msg.sender] = safeSub(totalVestedAccountBalance[msg.sender], total); havven.transfer(msg.sender, total); emit Vested(msg.sender, now, total); } } /* ========== EVENTS ========== */ event HavvenUpdated(address newHavven); event Vested(address indexed beneficiary, uint time, uint value); } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: Havven.sol version: 1.2 author: Anton Jurisevic Dominic Romanowski date: 2018-05-15 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- Havven token contract. Havvens are transferable ERC20 tokens, and also give their holders the following privileges. An owner of havvens may participate in nomin confiscation votes, they may also have the right to issue nomins at the discretion of the foundation for this version of the contract. After a fee period terminates, the duration and fees collected for that period are computed, and the next period begins. Thus an account may only withdraw the fees owed to them for the previous period, and may only do so once per period. Any unclaimed fees roll over into the common pot for the next period. == Average Balance Calculations == The fee entitlement of a havven holder is proportional to their average issued nomin balance over the last fee period. This is computed by measuring the area under the graph of a user's issued nomin balance over time, and then when a new fee period begins, dividing through by the duration of the fee period. We need only update values when the balances of an account is modified. This occurs when issuing or burning for issued nomin balances, and when transferring for havven balances. This is for efficiency, and adds an implicit friction to interacting with havvens. A havven holder pays for his own recomputation whenever he wants to change his position, which saves the foundation having to maintain a pot dedicated to resourcing this. A hypothetical user's balance history over one fee period, pictorially: s ____ | | | |___ p |____|___|___ __ _ _ f t n Here, the balance was s between times f and t, at which time a transfer occurred, updating the balance to p, until n, when the present transfer occurs. When a new transfer occurs at time n, the balance being p, we must: - Add the area p * (n - t) to the total area recorded so far - Update the last transfer time to n So if this graph represents the entire current fee period, the average havvens held so far is ((t-f)*s + (n-t)*p) / (n-f). The complementary computations must be performed for both sender and recipient. Note that a transfer keeps global supply of havvens invariant. The sum of all balances is constant, and unmodified by any transfer. So the sum of all balances multiplied by the duration of a fee period is also constant, and this is equivalent to the sum of the area of every user's time/balance graph. Dividing through by that duration yields back the total havven supply. So, at the end of a fee period, we really do yield a user's average share in the havven supply over that period. A slight wrinkle is introduced if we consider the time r when the fee period rolls over. Then the previous fee period k-1 is before r, and the current fee period k is afterwards. If the last transfer took place before r, but the latest transfer occurred afterwards: k-1 | k s __|_ | | | | | |____ p |__|_|____|___ __ _ _ | f | t n r In this situation the area (r-f)*s contributes to fee period k-1, while the area (t-r)*s contributes to fee period k. We will implicitly consider a zero-value transfer to have occurred at time r. Their fee entitlement for the previous period will be finalised at the time of their first transfer during the current fee period, or when they query or withdraw their fee entitlement. In the implementation, the duration of different fee periods may be slightly irregular, as the check that they have rolled over occurs only when state-changing havven operations are performed. == Issuance and Burning == In this version of the havven contract, nomins can only be issued by those that have been nominated by the havven foundation. Nomins are assumed to be valued at $1, as they are a stable unit of account. All nomins issued require a proportional value of havvens to be locked, where the proportion is governed by the current issuance ratio. This means for every $1 of Havvens locked up, $(issuanceRatio) nomins can be issued. i.e. to issue 100 nomins, 100/issuanceRatio dollars of havvens need to be locked up. To determine the value of some amount of havvens(H), an oracle is used to push the price of havvens (P_H) in dollars to the contract. The value of H would then be: H * P_H. Any havvens that are locked up by this issuance process cannot be transferred. The amount that is locked floats based on the price of havvens. If the price of havvens moves up, less havvens are locked, so they can be issued against, or transferred freely. If the price of havvens moves down, more havvens are locked, even going above the initial wallet balance. ----------------------------------------------------------------- */ /** * @title Havven ERC20 contract. * @notice The Havven contracts does not only facilitate transfers and track balances, * but it also computes the quantity of fees each havven holder is entitled to. */ contract Havven is ExternStateToken { /* ========== STATE VARIABLES ========== */ /* A struct for handing values associated with average balance calculations */ struct IssuanceData { /* Sums of balances*duration in the current fee period. /* range: decimals; units: havven-seconds */ uint currentBalanceSum; /* The last period's average balance */ uint lastAverageBalance; /* The last time the data was calculated */ uint lastModified; } /* Issued nomin balances for individual fee entitlements */ mapping(address => IssuanceData) public issuanceData; /* The total number of issued nomins for determining fee entitlements */ IssuanceData public totalIssuanceData; /* The time the current fee period began */ uint public feePeriodStartTime; /* The time the last fee period began */ uint public lastFeePeriodStartTime; /* Fee periods will roll over in no shorter a time than this. * The fee period cannot actually roll over until a fee-relevant * operation such as withdrawal or a fee period duration update occurs, * so this is just a target, and the actual duration may be slightly longer. */ uint public feePeriodDuration = 4 weeks; /* ...and must target between 1 day and six months. */ uint constant MIN_FEE_PERIOD_DURATION = 1 days; uint constant MAX_FEE_PERIOD_DURATION = 26 weeks; /* The quantity of nomins that were in the fee pot at the time */ /* of the last fee rollover, at feePeriodStartTime. */ uint public lastFeesCollected; /* Whether a user has withdrawn their last fees */ mapping(address => bool) public hasWithdrawnFees; Nomin public nomin; HavvenEscrow public escrow; /* The address of the oracle which pushes the havven price to this contract */ address public oracle; /* The price of havvens written in UNIT */ uint public price; /* The time the havven price was last updated */ uint public lastPriceUpdateTime; /* How long will the contract assume the price of havvens is correct */ uint public priceStalePeriod = 3 hours; /* A quantity of nomins greater than this ratio * may not be issued against a given value of havvens. */ uint public issuanceRatio = UNIT / 5; /* No more nomins may be issued than the value of havvens backing them. */ uint constant MAX_ISSUANCE_RATIO = UNIT; /* Whether the address can issue nomins or not. */ mapping(address => bool) public isIssuer; /* The number of currently-outstanding nomins the user has issued. */ mapping(address => uint) public nominsIssued; uint constant HAVVEN_SUPPLY = 1e8 * UNIT; uint constant ORACLE_FUTURE_LIMIT = 10 minutes; string constant TOKEN_NAME = "Havven"; string constant TOKEN_SYMBOL = "HAV"; /* ========== CONSTRUCTOR ========== */ /** * @dev Constructor * @param _tokenState A pre-populated contract containing token balances. * If the provided address is 0x0, then a fresh one will be constructed with the contract owning all tokens. * @param _owner The owner of this contract. */ constructor(address _proxy, TokenState _tokenState, address _owner, address _oracle, uint _price, address[] _issuers, Havven _oldHavven) ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, HAVVEN_SUPPLY, _owner) public { oracle = _oracle; price = _price; lastPriceUpdateTime = now; uint i; if (_oldHavven == address(0)) { feePeriodStartTime = now; lastFeePeriodStartTime = now - feePeriodDuration; for (i = 0; i < _issuers.length; i++) { isIssuer[_issuers[i]] = true; } } else { feePeriodStartTime = _oldHavven.feePeriodStartTime(); lastFeePeriodStartTime = _oldHavven.lastFeePeriodStartTime(); uint cbs; uint lab; uint lm; (cbs, lab, lm) = _oldHavven.totalIssuanceData(); totalIssuanceData.currentBalanceSum = cbs; totalIssuanceData.lastAverageBalance = lab; totalIssuanceData.lastModified = lm; for (i = 0; i < _issuers.length; i++) { address issuer = _issuers[i]; isIssuer[issuer] = true; uint nomins = _oldHavven.nominsIssued(issuer); if (nomins == 0) { // It is not valid in general to skip those with no currently-issued nomins. // But for this release, issuers with nonzero issuanceData have current issuance. continue; } (cbs, lab, lm) = _oldHavven.issuanceData(issuer); nominsIssued[issuer] = nomins; issuanceData[issuer].currentBalanceSum = cbs; issuanceData[issuer].lastAverageBalance = lab; issuanceData[issuer].lastModified = lm; } } } /* ========== SETTERS ========== */ /** * @notice Set the associated Nomin contract to collect fees from. * @dev Only the contract owner may call this. */ function setNomin(Nomin _nomin) external optionalProxy_onlyOwner { nomin = _nomin; emitNominUpdated(_nomin); } /** * @notice Set the associated havven escrow contract. * @dev Only the contract owner may call this. */ function setEscrow(HavvenEscrow _escrow) external optionalProxy_onlyOwner { escrow = _escrow; emitEscrowUpdated(_escrow); } /** * @notice Set the targeted fee period duration. * @dev Only callable by the contract owner. The duration must fall within * acceptable bounds (1 day to 26 weeks). Upon resetting this the fee period * may roll over if the target duration was shortened sufficiently. */ function setFeePeriodDuration(uint duration) external optionalProxy_onlyOwner { require(MIN_FEE_PERIOD_DURATION <= duration && duration <= MAX_FEE_PERIOD_DURATION); feePeriodDuration = duration; emitFeePeriodDurationUpdated(duration); rolloverFeePeriodIfElapsed(); } /** * @notice Set the Oracle that pushes the havven price to this contract */ function setOracle(address _oracle) external optionalProxy_onlyOwner { oracle = _oracle; emitOracleUpdated(_oracle); } /** * @notice Set the stale period on the updated havven price * @dev No max/minimum, as changing it wont influence anything but issuance by the foundation */ function setPriceStalePeriod(uint time) external optionalProxy_onlyOwner { priceStalePeriod = time; } /** * @notice Set the issuanceRatio for issuance calculations. * @dev Only callable by the contract owner. */ function setIssuanceRatio(uint _issuanceRatio) external optionalProxy_onlyOwner { require(_issuanceRatio <= MAX_ISSUANCE_RATIO); issuanceRatio = _issuanceRatio; emitIssuanceRatioUpdated(_issuanceRatio); } /** * @notice Set whether the specified can issue nomins or not. */ function setIssuer(address account, bool value) external optionalProxy_onlyOwner { isIssuer[account] = value; emitIssuersUpdated(account, value); } /* ========== VIEWS ========== */ function issuanceCurrentBalanceSum(address account) external view returns (uint) { return issuanceData[account].currentBalanceSum; } function issuanceLastAverageBalance(address account) external view returns (uint) { return issuanceData[account].lastAverageBalance; } function issuanceLastModified(address account) external view returns (uint) { return issuanceData[account].lastModified; } function totalIssuanceCurrentBalanceSum() external view returns (uint) { return totalIssuanceData.currentBalanceSum; } function totalIssuanceLastAverageBalance() external view returns (uint) { return totalIssuanceData.lastAverageBalance; } function totalIssuanceLastModified() external view returns (uint) { return totalIssuanceData.lastModified; } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice ERC20 transfer function. */ function transfer(address to, uint value) public optionalProxy returns (bool) { address sender = messageSender; require(nominsIssued[sender] == 0 || value <= transferableHavvens(sender)); /* Perform the transfer: if there is a problem, * an exception will be thrown in this call. */ _transfer_byProxy(sender, to, value); return true; } /** * @notice ERC20 transferFrom function. */ function transferFrom(address from, address to, uint value) public optionalProxy returns (bool) { address sender = messageSender; require(nominsIssued[from] == 0 || value <= transferableHavvens(from)); /* Perform the transfer: if there is a problem, * an exception will be thrown in this call. */ _transferFrom_byProxy(sender, from, to, value); return true; } /** * @notice Compute the last period's fee entitlement for the message sender * and then deposit it into their nomin account. */ function withdrawFees() external optionalProxy { address sender = messageSender; rolloverFeePeriodIfElapsed(); /* Do not deposit fees into frozen accounts. */ require(!nomin.frozen(sender)); /* Check the period has rolled over first. */ updateIssuanceData(sender, nominsIssued[sender], nomin.totalSupply()); /* Only allow accounts to withdraw fees once per period. */ require(!hasWithdrawnFees[sender]); uint feesOwed; uint lastTotalIssued = totalIssuanceData.lastAverageBalance; if (lastTotalIssued > 0) { /* Sender receives a share of last period's collected fees proportional * with their average fraction of the last period's issued nomins. */ feesOwed = safeDiv_dec( safeMul_dec(issuanceData[sender].lastAverageBalance, lastFeesCollected), lastTotalIssued ); } hasWithdrawnFees[sender] = true; if (feesOwed != 0) { nomin.withdrawFees(sender, feesOwed); } emitFeesWithdrawn(messageSender, feesOwed); } /** * @notice Update the havven balance averages since the last transfer * or entitlement adjustment. * @dev Since this updates the last transfer timestamp, if invoked * consecutively, this function will do nothing after the first call. * Also, this will adjust the total issuance at the same time. */ function updateIssuanceData(address account, uint preBalance, uint lastTotalSupply) internal { /* update the total balances first */ totalIssuanceData = computeIssuanceData(lastTotalSupply, totalIssuanceData); if (issuanceData[account].lastModified < feePeriodStartTime) { hasWithdrawnFees[account] = false; } issuanceData[account] = computeIssuanceData(preBalance, issuanceData[account]); } /** * @notice Compute the new IssuanceData on the old balance */ function computeIssuanceData(uint preBalance, IssuanceData preIssuance) internal view returns (IssuanceData) { uint currentBalanceSum = preIssuance.currentBalanceSum; uint lastAverageBalance = preIssuance.lastAverageBalance; uint lastModified = preIssuance.lastModified; if (lastModified < feePeriodStartTime) { if (lastModified < lastFeePeriodStartTime) { /* The balance was last updated before the previous fee period, so the average * balance in this period is their pre-transfer balance. */ lastAverageBalance = preBalance; } else { /* The balance was last updated during the previous fee period. */ /* No overflow or zero denominator problems, since lastFeePeriodStartTime < feePeriodStartTime < lastModified. * implies these quantities are strictly positive. */ uint timeUpToRollover = feePeriodStartTime - lastModified; uint lastFeePeriodDuration = feePeriodStartTime - lastFeePeriodStartTime; uint lastBalanceSum = safeAdd(currentBalanceSum, safeMul(preBalance, timeUpToRollover)); lastAverageBalance = lastBalanceSum / lastFeePeriodDuration; } /* Roll over to the next fee period. */ currentBalanceSum = safeMul(preBalance, now - feePeriodStartTime); } else { /* The balance was last updated during the current fee period. */ currentBalanceSum = safeAdd( currentBalanceSum, safeMul(preBalance, now - lastModified) ); } return IssuanceData(currentBalanceSum, lastAverageBalance, now); } /** * @notice Recompute and return the given account's last average balance. */ function recomputeLastAverageBalance(address account) external returns (uint) { updateIssuanceData(account, nominsIssued[account], nomin.totalSupply()); return issuanceData[account].lastAverageBalance; } /** * @notice Issue nomins against the sender's havvens. * @dev Issuance is only allowed if the havven price isn't stale and the sender is an issuer. */ function issueNomins(uint amount) public optionalProxy requireIssuer(messageSender) /* No need to check if price is stale, as it is checked in issuableNomins. */ { address sender = messageSender; require(amount <= remainingIssuableNomins(sender)); uint lastTot = nomin.totalSupply(); uint preIssued = nominsIssued[sender]; nomin.issue(sender, amount); nominsIssued[sender] = safeAdd(preIssued, amount); updateIssuanceData(sender, preIssued, lastTot); } function issueMaxNomins() external optionalProxy { issueNomins(remainingIssuableNomins(messageSender)); } /** * @notice Burn nomins to clear issued nomins/free havvens. */ function burnNomins(uint amount) /* it doesn't matter if the price is stale or if the user is an issuer, as non-issuers have issued no nomins.*/ external optionalProxy { address sender = messageSender; uint lastTot = nomin.totalSupply(); uint preIssued = nominsIssued[sender]; /* nomin.burn does a safeSub on balance (so it will revert if there are not enough nomins). */ nomin.burn(sender, amount); /* This safe sub ensures amount <= number issued */ nominsIssued[sender] = safeSub(preIssued, amount); updateIssuanceData(sender, preIssued, lastTot); } /** * @notice Check if the fee period has rolled over. If it has, set the new fee period start * time, and record the fees collected in the nomin contract. */ function rolloverFeePeriodIfElapsed() public { /* If the fee period has rolled over... */ if (now >= feePeriodStartTime + feePeriodDuration) { lastFeesCollected = nomin.feePool(); lastFeePeriodStartTime = feePeriodStartTime; feePeriodStartTime = now; emitFeePeriodRollover(now); } } /* ========== Issuance/Burning ========== */ /** * @notice The maximum nomins an issuer can issue against their total havven quantity. This ignores any * already issued nomins. */ function maxIssuableNomins(address issuer) view public priceNotStale returns (uint) { if (!isIssuer[issuer]) { return 0; } if (escrow != HavvenEscrow(0)) { uint totalOwnedHavvens = safeAdd(tokenState.balanceOf(issuer), escrow.balanceOf(issuer)); return safeMul_dec(HAVtoUSD(totalOwnedHavvens), issuanceRatio); } else { return safeMul_dec(HAVtoUSD(tokenState.balanceOf(issuer)), issuanceRatio); } } /** * @notice The remaining nomins an issuer can issue against their total havven quantity. */ function remainingIssuableNomins(address issuer) view public returns (uint) { uint issued = nominsIssued[issuer]; uint max = maxIssuableNomins(issuer); if (issued > max) { return 0; } else { return safeSub(max, issued); } } /** * @notice The total havvens owned by this account, both escrowed and unescrowed, * against which nomins can be issued. * This includes those already being used as collateral (locked), and those * available for further issuance (unlocked). */ function collateral(address account) public view returns (uint) { uint bal = tokenState.balanceOf(account); if (escrow != address(0)) { bal = safeAdd(bal, escrow.balanceOf(account)); } return bal; } /** * @notice The collateral that would be locked by issuance, which can exceed the account's actual collateral. */ function issuanceDraft(address account) public view returns (uint) { uint issued = nominsIssued[account]; if (issued == 0) { return 0; } return USDtoHAV(safeDiv_dec(issued, issuanceRatio)); } /** * @notice Collateral that has been locked due to issuance, and cannot be * transferred to other addresses. This is capped at the account's total collateral. */ function lockedCollateral(address account) public view returns (uint) { uint debt = issuanceDraft(account); uint collat = collateral(account); if (debt > collat) { return collat; } return debt; } /** * @notice Collateral that is not locked and available for issuance. */ function unlockedCollateral(address account) public view returns (uint) { uint locked = lockedCollateral(account); uint collat = collateral(account); return safeSub(collat, locked); } /** * @notice The number of havvens that are free to be transferred by an account. * @dev If they have enough available Havvens, it could be that * their havvens are escrowed, however the transfer would then * fail. This means that escrowed havvens are locked first, * and then the actual transferable ones. */ function transferableHavvens(address account) public view returns (uint) { uint draft = issuanceDraft(account); uint collat = collateral(account); // In the case where the issuanceDraft exceeds the collateral, nothing is free if (draft > collat) { return 0; } uint bal = balanceOf(account); // In the case where the draft exceeds the escrow, but not the whole collateral // return the fraction of the balance that remains free if (draft > safeSub(collat, bal)) { return safeSub(collat, draft); } // In the case where the draft doesn't exceed the escrow, return the entire balance return bal; } /** * @notice The value in USD for a given amount of HAV */ function HAVtoUSD(uint hav_dec) public view priceNotStale returns (uint) { return safeMul_dec(hav_dec, price); } /** * @notice The value in HAV for a given amount of USD */ function USDtoHAV(uint usd_dec) public view priceNotStale returns (uint) { return safeDiv_dec(usd_dec, price); } /** * @notice Access point for the oracle to update the price of havvens. */ function updatePrice(uint newPrice, uint timeSent) external onlyOracle /* Should be callable only by the oracle. */ { /* Must be the most recently sent price, but not too far in the future. * (so we can't lock ourselves out of updating the oracle for longer than this) */ require(lastPriceUpdateTime < timeSent && timeSent < now + ORACLE_FUTURE_LIMIT); price = newPrice; lastPriceUpdateTime = timeSent; emitPriceUpdated(newPrice, timeSent); /* Check the fee period rollover within this as the price should be pushed every 15min. */ rolloverFeePeriodIfElapsed(); } /** * @notice Check if the price of havvens hasn't been updated for longer than the stale period. */ function priceIsStale() public view returns (bool) { return safeAdd(lastPriceUpdateTime, priceStalePeriod) < now; } /* ========== MODIFIERS ========== */ modifier requireIssuer(address account) { require(isIssuer[account]); _; } modifier onlyOracle { require(msg.sender == oracle); _; } modifier priceNotStale { require(!priceIsStale()); _; } /* ========== EVENTS ========== */ event PriceUpdated(uint newPrice, uint timestamp); bytes32 constant PRICEUPDATED_SIG = keccak256("PriceUpdated(uint256,uint256)"); function emitPriceUpdated(uint newPrice, uint timestamp) internal { proxy._emit(abi.encode(newPrice, timestamp), 1, PRICEUPDATED_SIG, 0, 0, 0); } event IssuanceRatioUpdated(uint newRatio); bytes32 constant ISSUANCERATIOUPDATED_SIG = keccak256("IssuanceRatioUpdated(uint256)"); function emitIssuanceRatioUpdated(uint newRatio) internal { proxy._emit(abi.encode(newRatio), 1, ISSUANCERATIOUPDATED_SIG, 0, 0, 0); } event FeePeriodRollover(uint timestamp); bytes32 constant FEEPERIODROLLOVER_SIG = keccak256("FeePeriodRollover(uint256)"); function emitFeePeriodRollover(uint timestamp) internal { proxy._emit(abi.encode(timestamp), 1, FEEPERIODROLLOVER_SIG, 0, 0, 0); } event FeePeriodDurationUpdated(uint duration); bytes32 constant FEEPERIODDURATIONUPDATED_SIG = keccak256("FeePeriodDurationUpdated(uint256)"); function emitFeePeriodDurationUpdated(uint duration) internal { proxy._emit(abi.encode(duration), 1, FEEPERIODDURATIONUPDATED_SIG, 0, 0, 0); } event FeesWithdrawn(address indexed account, uint value); bytes32 constant FEESWITHDRAWN_SIG = keccak256("FeesWithdrawn(address,uint256)"); function emitFeesWithdrawn(address account, uint value) internal { proxy._emit(abi.encode(value), 2, FEESWITHDRAWN_SIG, bytes32(account), 0, 0); } event OracleUpdated(address newOracle); bytes32 constant ORACLEUPDATED_SIG = keccak256("OracleUpdated(address)"); function emitOracleUpdated(address newOracle) internal { proxy._emit(abi.encode(newOracle), 1, ORACLEUPDATED_SIG, 0, 0, 0); } event NominUpdated(address newNomin); bytes32 constant NOMINUPDATED_SIG = keccak256("NominUpdated(address)"); function emitNominUpdated(address newNomin) internal { proxy._emit(abi.encode(newNomin), 1, NOMINUPDATED_SIG, 0, 0, 0); } event EscrowUpdated(address newEscrow); bytes32 constant ESCROWUPDATED_SIG = keccak256("EscrowUpdated(address)"); function emitEscrowUpdated(address newEscrow) internal { proxy._emit(abi.encode(newEscrow), 1, ESCROWUPDATED_SIG, 0, 0, 0); } event IssuersUpdated(address indexed account, bool indexed value); bytes32 constant ISSUERSUPDATED_SIG = keccak256("IssuersUpdated(address,bool)"); function emitIssuersUpdated(address account, bool value) internal { proxy._emit(abi.encode(), 3, ISSUERSUPDATED_SIG, bytes32(account), bytes32(value ? 1 : 0), 0); } }
Set the length of time a vote runs for. Only the contract owner may call this. The proposed duration must fall within sensible bounds (3 days to 4 weeks), and must be no longer than a single fee period./
function setVotingPeriod(uint duration) external onlyOwner { require(MIN_VOTING_PERIOD <= duration && duration <= MAX_VOTING_PERIOD); require(duration <= havven.feePeriodDuration()); votingPeriod = duration;
6,482,217
// SPDX-License-Identifier: MIT pragma solidity 0.7.5; import './Context.sol'; import './Strings.sol'; import './ERC165.sol'; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Context, IAccessControlUpgradeable, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged( bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole ); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( 'AccessControl: account ', Strings.toHexString(uint160(account), 20), ' is missing role ', Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), 'AccessControl: can only renounce roles for self'); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /* * @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 GSN 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 payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = '0123456789abcdef'; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return '0'; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return '0x00'; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = '0'; buffer[1] = 'x'; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, 'Strings: hex length insufficient'); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; import './IERC165.sol'; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import { AccessControlUpgradeable } from '../../../dependencies/open-zeppelin/AccessControlUpgradeable.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { IRewardsOracle } from '../../../interfaces/IRewardsOracle.sol'; import { ReentrancyGuard } from '../../../utils/ReentrancyGuard.sol'; import { VersionedInitializable } from '../../../utils/VersionedInitializable.sol'; import { MD1Types } from '../lib/MD1Types.sol'; /** * @title MD1Storage * @author dYdX * * @dev Storage contract. Contains or inherits from all contract with storage. */ abstract contract MD1Storage is AccessControlUpgradeable, ReentrancyGuard, VersionedInitializable { // ============ Configuration ============ /// @dev The oracle which provides Merkle root updates. IRewardsOracle internal _REWARDS_ORACLE_; /// @dev The IPNS name to which trader and market maker exchange statistics are published. string internal _IPNS_NAME_; /// @dev Period of time after the epoch end after which the new epoch exchange statistics should /// be available on IPFS via the IPNS name. This can be used as a trigger for “keepers” who are /// incentivized to call the proposeRoot() and updateRoot() functions as needed. uint256 internal _IPFS_UPDATE_PERIOD_; /// @dev Max rewards distributed per epoch as market maker incentives. uint256 internal _MARKET_MAKER_REWARDS_AMOUNT_; /// @dev Max rewards distributed per epoch as trader incentives. uint256 internal _TRADER_REWARDS_AMOUNT_; /// @dev Parameter affecting the calculation of trader rewards. This is a value /// between 0 and 1, represented here in units out of 10^18. uint256 internal _TRADER_SCORE_ALPHA_; // ============ Epoch Schedule ============ /// @dev The parameters specifying the function from timestamp to epoch number. MD1Types.EpochParameters internal _EPOCH_PARAMETERS_; // ============ Root Updates ============ /// @dev The active Merkle root and associated parameters. MD1Types.MerkleRoot internal _ACTIVE_ROOT_; /// @dev The proposed Merkle root and associated parameters. MD1Types.MerkleRoot internal _PROPOSED_ROOT_; /// @dev The time at which the proposed root may become active. uint256 internal _WAITING_PERIOD_END_; /// @dev Whether root updates are currently paused. bool internal _ARE_ROOT_UPDATES_PAUSED_; // ============ Claims ============ /// @dev Mapping of (user address) => (number of tokens claimed). mapping(address => uint256) internal _CLAIMED_; /// @dev Whether the user has opted into allowing anyone to trigger a claim on their behalf. mapping(address => bool) internal _ALWAYS_ALLOW_CLAIMS_FOR_; } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ 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); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; interface IRewardsOracle { /** * @notice Returns the oracle value, agreed upon by all oracle signers. If the signers have not * agreed upon a value, should return zero for all return values. * * @return merkleRoot The Merkle root for the next Merkle distributor update. * @return epoch The epoch number corresponding to the new Merkle root. * @return ipfsCid An IPFS CID pointing to the Merkle tree data. */ function read() external virtual view returns (bytes32 merkleRoot, uint256 epoch, bytes memory ipfsCid); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; /** * @title ReentrancyGuard * @author dYdX * * @dev Updated ReentrancyGuard library designed to be used with Proxy Contracts. */ abstract contract ReentrancyGuard { uint256 private constant NOT_ENTERED = 1; uint256 private constant ENTERED = uint256(int256(-1)); uint256 private _STATUS_; constructor() internal { _STATUS_ = NOT_ENTERED; } modifier nonReentrant() { require(_STATUS_ != ENTERED, 'ReentrancyGuard: reentrant call'); _STATUS_ = ENTERED; _; _STATUS_ = NOT_ENTERED; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; /** * @title VersionedInitializable * @author Aave, inspired by the OpenZeppelin Initializable contract * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. * */ abstract contract VersionedInitializable { /** * @dev Indicates that the contract has been initialized. */ uint256 internal lastInitializedRevision = 0; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { uint256 revision = getRevision(); require(revision > lastInitializedRevision, "Contract instance has already been initialized"); lastInitializedRevision = revision; _; } /// @dev returns the revision number of the contract. /// Needs to be defined in the inherited class as a constant. function getRevision() internal pure virtual returns(uint256); // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; library MD1Types { /** * @dev The parameters used to convert a timestamp to an epoch number. */ struct EpochParameters { uint128 interval; uint128 offset; } /** * @dev The parameters related to a certain version of the Merkle root. */ struct MerkleRoot { bytes32 merkleRoot; uint256 epoch; bytes ipfsCid; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import { IRewardsOracle } from '../../../interfaces/IRewardsOracle.sol'; import { MD1Types } from '../lib/MD1Types.sol'; import { MD1Storage } from './MD1Storage.sol'; /** * @title MD1Getters * @author dYdX * * @notice Simple getter functions. */ abstract contract MD1Getters is MD1Storage { /** * @notice Get the address of the oracle which provides Merkle root updates. * * @return The address of the oracle. */ function getRewardsOracle() external view returns (IRewardsOracle) { return _REWARDS_ORACLE_; } /** * @notice Get the IPNS name to which trader and market maker exchange statistics are published. * * @return The IPNS name. */ function getIpnsName() external view returns (string memory) { return _IPNS_NAME_; } /** * @notice Get the period of time after the epoch end after which the new epoch exchange * statistics should be available on IPFS via the IPNS name. * * @return The IPFS update period, in seconds. */ function getIpfsUpdatePeriod() external view returns (uint256) { return _IPFS_UPDATE_PERIOD_; } /** * @notice Get the rewards formula parameters. * * @return Max rewards distributed per epoch as market maker incentives. * @return Max rewards distributed per epoch as trader incentives. * @return The alpha parameter between 0 and 1, in units out of 10^18. */ function getRewardsParameters() external view returns (uint256, uint256, uint256) { return ( _MARKET_MAKER_REWARDS_AMOUNT_, _TRADER_REWARDS_AMOUNT_, _TRADER_SCORE_ALPHA_ ); } /** * @notice Get the parameters specifying the function from timestamp to epoch number. * * @return The parameters struct with `interval` and `offset` fields. */ function getEpochParameters() external view returns (MD1Types.EpochParameters memory) { return _EPOCH_PARAMETERS_; } /** * @notice Get the active Merkle root and associated parameters. * * @return merkleRoot The active Merkle root. * @return epoch The epoch number corresponding to this Merkle tree. * @return ipfsCid An IPFS CID pointing to the Merkle tree data. */ function getActiveRoot() external view returns (bytes32 merkleRoot, uint256 epoch, bytes memory ipfsCid) { merkleRoot = _ACTIVE_ROOT_.merkleRoot; epoch = _ACTIVE_ROOT_.epoch; ipfsCid = _ACTIVE_ROOT_.ipfsCid; } /** * @notice Get the proposed Merkle root and associated parameters. * * @return merkleRoot The active Merkle root. * @return epoch The epoch number corresponding to this Merkle tree. * @return ipfsCid An IPFS CID pointing to the Merkle tree data. */ function getProposedRoot() external view returns (bytes32 merkleRoot, uint256 epoch, bytes memory ipfsCid) { merkleRoot = _PROPOSED_ROOT_.merkleRoot; epoch = _PROPOSED_ROOT_.epoch; ipfsCid = _PROPOSED_ROOT_.ipfsCid; } /** * @notice Get the time at which the proposed root may become active. * * @return The time at which the proposed root may become active, in epoch seconds. */ function getWaitingPeriodEnd() external view returns (uint256) { return _WAITING_PERIOD_END_; } /** * @notice Check whether root updates are currently paused. * * @return Boolean `true` if root updates are currently paused, otherwise, `false`. */ function getAreRootUpdatesPaused() external view returns (bool) { return _ARE_ROOT_UPDATES_PAUSED_; } /** * @notice Get the tokens claimed so far by a given user. * * @param user The address of the user. * * @return The tokens claimed so far by that user. */ function getClaimed(address user) external view returns (uint256) { return _CLAIMED_[user]; } /** * @notice Check whether the user opted into allowing anyone to trigger a claim on their behalf. * * @param user The address of the user. * * @return Boolean `true` if any address may trigger claims for the user, otherwise `false`. */ function getAlwaysAllowClaimsFor(address user) external view returns (bool) { return _ALWAYS_ALLOW_CLAIMS_FOR_[user]; } } // Contracts by dYdX Foundation. Individual files are released under different licenses. // // https://dydx.community // https://github.com/dydxfoundation/governance-contracts // // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import { SafeMath } from '../../dependencies/open-zeppelin/SafeMath.sol'; import { Ownable } from '../../dependencies/open-zeppelin/Ownable.sol'; import { MerkleProof } from '../../dependencies/open-zeppelin/MerkleProof.sol'; import { IERC20 } from '../../interfaces/IERC20.sol'; import { IRewardsOracle } from '../../interfaces/IRewardsOracle.sol'; import { MD1Claims } from './impl/MD1Claims.sol'; import { MD1RootUpdates } from './impl/MD1RootUpdates.sol'; import { MD1Configuration } from './impl/MD1Configuration.sol'; import { MD1Getters } from './impl/MD1Getters.sol'; /** * @title MerkleDistributorV1 * @author dYdX * * @notice Distributes DYDX token rewards according to a Merkle tree of balances. The tree can be * updated periodially with each user's cumulative rewards balance, allowing new rewards to be * distributed to users over time. * * An update is performed by setting the proposed Merkle root to the latest value returned by * the oracle contract. The proposed Merkle root can be made active after a waiting period has * elapsed. During the waiting period, dYdX governance has the opportunity to freeze the Merkle * root, in case the proposed root is incorrect or malicious. */ contract MerkleDistributorV1 is MD1RootUpdates, MD1Claims, MD1Configuration, MD1Getters { // ============ Constructor ============ constructor( address rewardsToken, address rewardsTreasury ) MD1Claims(rewardsToken, rewardsTreasury) {} // ============ External Functions ============ function initialize( address rewardsOracle, string calldata ipnsName, uint256 ipfsUpdatePeriod, uint256 marketMakerRewardsAmount, uint256 traderRewardsAmount, uint256 traderScoreAlpha, uint256 epochInterval, uint256 epochOffset ) external initializer { __MD1Roles_init(); __MD1Configuration_init( rewardsOracle, ipnsName, ipfsUpdatePeriod, marketMakerRewardsAmount, traderRewardsAmount, traderScoreAlpha ); __MD1EpochSchedule_init(epochInterval, epochOffset); } // ============ Internal Functions ============ /** * @dev Returns the revision of the implementation contract. Used by VersionedInitializable. * * @return The revision number. */ function getRevision() internal pure override returns (uint256) { return 1; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @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. */ 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. */ 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. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; import './Context.sol'; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), 'Ownable: caller is not the owner'); _; } /** * @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() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), 'Ownable: new owner is the zero address'); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol'; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { MerkleProof } from '../../../dependencies/open-zeppelin/MerkleProof.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { MD1Types } from '../lib/MD1Types.sol'; import { MD1Roles } from './MD1Roles.sol'; /** * @title MD1Claims * @author dYdX * * @notice Allows rewards to be claimed by providing a Merkle proof of the rewards amount. */ abstract contract MD1Claims is MD1Roles { using SafeERC20 for IERC20; using SafeMath for uint256; // ============ Constants ============ /// @notice The token distributed as rewards. IERC20 public immutable REWARDS_TOKEN; /// @notice Address to pull rewards from. Must have provided an allowance to this contract. address public immutable REWARDS_TREASURY; // ============ Events ============ /// @notice Emitted when a user claims rewards. event RewardsClaimed( address account, uint256 amount ); /// @notice Emitted when a user opts into or out of the claim-for allowlist. event AlwaysAllowClaimForUpdated( address user, bool allow ); // ============ Constructor ============ constructor( address rewardsToken, address rewardsTreasury ) { REWARDS_TOKEN = IERC20(rewardsToken); REWARDS_TREASURY = rewardsTreasury; } // ============ External Functions ============ /** * @notice Claim the remaining unclaimed rewards for the sender. * * Reverts if the provided Merkle proof is invalid. * * @param cumulativeAmount The total all-time rewards this user has earned. * @param merkleProof The Merkle proof for the user and cumulative amount. * * @return The number of rewards tokens claimed. */ function claimRewards( uint256 cumulativeAmount, bytes32[] calldata merkleProof ) external nonReentrant returns (uint256) { return _claimRewards(msg.sender, cumulativeAmount, merkleProof); } /** * @notice Claim the remaining unclaimed rewards for a user, and send them to that user. * * The caller must be authorized with CLAIM_OPERATOR_ROLE unless the specified user has opted * into the claim-for allowlist. In any case, rewards are transfered to the original user * specified in the Merkle tree. * * Reverts if the provided Merkle proof is invalid. * * @param user Address of the user on whose behalf to trigger a claim. * @param cumulativeAmount The total all-time rewards this user has earned. * @param merkleProof The Merkle proof for the user and cumulative amount. * * @return The number of rewards tokens claimed. */ function claimRewardsFor( address user, uint256 cumulativeAmount, bytes32[] calldata merkleProof ) external nonReentrant returns (uint256) { require( ( hasRole(CLAIM_OPERATOR_ROLE, msg.sender) || _ALWAYS_ALLOW_CLAIMS_FOR_[user] ), 'MD1Claims: Do not have permission to claim for this user' ); return _claimRewards(user, cumulativeAmount, merkleProof); } /** * @notice Opt into allowing anyone to claim on the sender's behalf. * * Note that this does not affect who receives the funds. The user specified in the Merkle tree * receives those rewards regardless of who issues the claim. * * Note that addresses with the CLAIM_OPERATOR_ROLE ignore this allowlist when triggering claims. * * @param allow Whether or not to allow claims on the sender's behalf. */ function setAlwaysAllowClaimsFor( bool allow ) external nonReentrant { _ALWAYS_ALLOW_CLAIMS_FOR_[msg.sender] = allow; emit AlwaysAllowClaimForUpdated(msg.sender, allow); } // ============ Internal Functions ============ /** * @notice Claim the remaining unclaimed rewards for a user, and send them to that user. * * Reverts if the provided Merkle proof is invalid. * * @param user Address of the user. * @param cumulativeAmount The total all-time rewards this user has earned. * @param merkleProof The Merkle proof for the user and cumulative amount. * * @return The number of rewards tokens claimed. */ function _claimRewards( address user, uint256 cumulativeAmount, bytes32[] calldata merkleProof ) internal returns (uint256) { // Get the active Merkle root. bytes32 merkleRoot = _ACTIVE_ROOT_.merkleRoot; // Verify the Merkle proof. bytes32 node = keccak256(abi.encodePacked(user, cumulativeAmount)); require(MerkleProof.verify(merkleProof, merkleRoot, node), 'MD1Claims: Invalid Merkle proof'); // Get the claimable amount. // // Note: If this reverts, then there was an error in the Merkle tree, since the cumulative // amount for a given user should never decrease over time. uint256 claimable = cumulativeAmount.sub(_CLAIMED_[user]); if (claimable == 0) { return 0; } // Mark the user as having claimed the full amount. _CLAIMED_[user] = cumulativeAmount; // Send the user the claimable amount. REWARDS_TOKEN.safeTransferFrom(REWARDS_TREASURY, user, claimable); emit RewardsClaimed(user, claimable); return claimable; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { MerkleProof } from '../../../dependencies/open-zeppelin/MerkleProof.sol'; import { MD1Types } from '../lib/MD1Types.sol'; import { MD1Pausable } from './MD1Pausable.sol'; /** * @title MD1RootUpdates * @author dYdX * * @notice Handles updates to the Merkle root. */ abstract contract MD1RootUpdates is MD1Pausable { using SafeMath for uint256; // ============ Constants ============ /// @notice The waiting period before a proposed Merkle root can become active, in seconds. uint256 public constant WAITING_PERIOD = 7 days; // ============ Events ============ /// @notice Emitted when a new Merkle root is proposed and the waiting period begins. event RootProposed( bytes32 merkleRoot, uint256 epoch, bytes ipfsCid, uint256 waitingPeriodEnd ); /// @notice Emitted when a new Merkle root becomes active. event RootUpdated( bytes32 merkleRoot, uint256 epoch, bytes ipfsCid ); // ============ External Functions ============ /** * @notice Set the proposed root parameters to the values returned by the oracle, and start the * waiting period. Anyone may call this function. * * Reverts if the oracle root is bytes32(0). * Reverts if the oracle root parameters are equal to the proposed root parameters. * Reverts if the oracle root epoch is not equal to the next root epoch. */ function proposeRoot() external nonReentrant { // Read the latest values from the oracle. ( bytes32 merkleRoot, uint256 epoch, bytes memory ipfsCid ) = _REWARDS_ORACLE_.read(); require(merkleRoot != bytes32(0), 'MD1RootUpdates: Oracle root is zero (unset)'); require( ( merkleRoot != _PROPOSED_ROOT_.merkleRoot || epoch != _PROPOSED_ROOT_.epoch || keccak256(ipfsCid) != keccak256(_PROPOSED_ROOT_.ipfsCid) ), 'MD1RootUpdates: Oracle root was already proposed' ); require(epoch == getNextRootEpoch(), 'MD1RootUpdates: Oracle epoch is not next root epoch'); // Set the proposed root and the waiting period for the proposed root to become active. _PROPOSED_ROOT_ = MD1Types.MerkleRoot({ merkleRoot: merkleRoot, epoch: epoch, ipfsCid: ipfsCid }); uint256 waitingPeriodEnd = block.timestamp.add(WAITING_PERIOD); _WAITING_PERIOD_END_ = waitingPeriodEnd; emit RootProposed(merkleRoot, epoch, ipfsCid, waitingPeriodEnd); } /** * @notice Set the active root parameters to the proposed root parameters. * * Reverts if root updates are paused. * Reverts if the proposed root is bytes32(0). * Reverts if the proposed root epoch is not equal to the next root epoch. * Reverts if the waiting period for the proposed root has not elapsed. */ function updateRoot() external nonReentrant whenNotPaused { // Get the proposed root parameters. bytes32 merkleRoot = _PROPOSED_ROOT_.merkleRoot; uint256 epoch = _PROPOSED_ROOT_.epoch; bytes memory ipfsCid = _PROPOSED_ROOT_.ipfsCid; require(merkleRoot != bytes32(0), 'MD1RootUpdates: Proposed root is zero (unset)'); require(epoch == getNextRootEpoch(), 'MD1RootUpdates: Proposed epoch is not next root epoch'); require( block.timestamp >= _WAITING_PERIOD_END_, 'MD1RootUpdates: Waiting period has not elapsed' ); // Set the active root. _ACTIVE_ROOT_.merkleRoot = merkleRoot; _ACTIVE_ROOT_.epoch = epoch; _ACTIVE_ROOT_.ipfsCid = ipfsCid; emit RootUpdated(merkleRoot, epoch, ipfsCid); } /** * @notice Returns true if there is a proposed root waiting to become active, the waiting period * for that root has elapsed, and root updates are not paused. * * @return Boolean `true` if the active root can be updated to the proposed root, else `false`. */ function canUpdateRoot() external view returns (bool) { return ( hasPendingRoot() && block.timestamp >= _WAITING_PERIOD_END_ && !_ARE_ROOT_UPDATES_PAUSED_ ); } // ============ Public Functions ============ /** * @notice Returns true if there is a proposed root waiting to become active. This is the case if * and only if the proposed root is not zero and the proposed root epoch is equal to the next * root epoch. */ function hasPendingRoot() public view returns (bool) { // Get the proposed parameters. bytes32 merkleRoot = _PROPOSED_ROOT_.merkleRoot; uint256 epoch = _PROPOSED_ROOT_.epoch; if (merkleRoot == bytes32(0)) { return false; } return epoch == getNextRootEpoch(); } /** * @notice Get the next root epoch. If the active root is zero, then the next root epoch is zero, * otherwise, it is equal to the active root epoch plus one. */ function getNextRootEpoch() public view returns (uint256) { bytes32 merkleRoot = _ACTIVE_ROOT_.merkleRoot; if (merkleRoot == bytes32(0)) { return 0; } return _ACTIVE_ROOT_.epoch.add(1); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import { IRewardsOracle } from '../../../interfaces/IRewardsOracle.sol'; import { MD1EpochSchedule } from './MD1EpochSchedule.sol'; import { MD1Roles } from './MD1Roles.sol'; import { MD1Types } from '../lib/MD1Types.sol'; /** * @title MD1Configuration * @author dYdX * * @notice Functions for modifying the Merkle distributor rewards configuration. * * The more sensitive configuration values, which potentially give full control over the contents * of the Merkle tree, may only be updated by the OWNER_ROLE. Other values may be configured by * the CONFIG_UPDATER_ROLE. * * Note that these configuration values are made available externally but are not used internally * within this contract, with the exception of the IPFS update period which is used by * the getIpfsEpoch() function. */ abstract contract MD1Configuration is MD1EpochSchedule, MD1Roles { // ============ Constants ============ uint256 public constant TRADER_SCORE_ALPHA_BASE = 10 ** 18; // ============ Events ============ event RewardsOracleChanged( address rewardsOracle ); event IpnsNameUpdated( string ipnsName ); event IpfsUpdatePeriodUpdated( uint256 ipfsUpdatePeriod ); event RewardsParametersUpdated( uint256 marketMakerRewardsAmount, uint256 traderRewardsAmount, uint256 traderScoreAlpha ); // ============ Initializer ============ function __MD1Configuration_init( address rewardsOracle, string calldata ipnsName, uint256 ipfsUpdatePeriod, uint256 marketMakerRewardsAmount, uint256 traderRewardsAmount, uint256 traderScoreAlpha ) internal { _setRewardsOracle(rewardsOracle); _setIpnsName(ipnsName); _setIpfsUpdatePeriod(ipfsUpdatePeriod); _setRewardsParameters( marketMakerRewardsAmount, traderRewardsAmount, traderScoreAlpha ); } // ============ External Functions ============ /** * @notice Set the address of the oracle which provides Merkle root updates. * * @param rewardsOracle The new oracle address. */ function setRewardsOracle( address rewardsOracle ) external onlyRole(OWNER_ROLE) nonReentrant { _setRewardsOracle(rewardsOracle); } /** * @notice Set the IPNS name to which trader and market maker exchange statistics are published. * * @param ipnsName The new IPNS name. */ function setIpnsName( string calldata ipnsName ) external onlyRole(OWNER_ROLE) nonReentrant { _setIpnsName(ipnsName); } /** * @notice Set the period of time after the epoch end after which the new epoch exchange * statistics should be available on IPFS via the IPNS name. * * This can be used as a trigger for “keepers” who are incentivized to call the proposeRoot() * and updateRoot() functions as needed. * * @param ipfsUpdatePeriod The new IPFS update period, in seconds. */ function setIpfsUpdatePeriod( uint256 ipfsUpdatePeriod ) external onlyRole(CONFIG_UPDATER_ROLE) nonReentrant { _setIpfsUpdatePeriod(ipfsUpdatePeriod); } /** * @notice Set the rewards formula parameters. * * @param marketMakerRewardsAmount Max rewards distributed per epoch as market maker incentives. * @param traderRewardsAmount Max rewards distributed per epoch as trader incentives. * @param traderScoreAlpha The alpha parameter between 0 and 1, in units out of 10^18. */ function setRewardsParameters( uint256 marketMakerRewardsAmount, uint256 traderRewardsAmount, uint256 traderScoreAlpha ) external onlyRole(CONFIG_UPDATER_ROLE) nonReentrant { _setRewardsParameters(marketMakerRewardsAmount, traderRewardsAmount, traderScoreAlpha); } /** * @notice Set the parameters defining the function from timestamp to epoch number. * * @param interval The length of an epoch, in seconds. * @param offset The start of epoch zero, in seconds. */ function setEpochParameters( uint256 interval, uint256 offset ) external onlyRole(CONFIG_UPDATER_ROLE) nonReentrant { _setEpochParameters(interval, offset); } // ============ Internal Functions ============ function _setRewardsOracle( address rewardsOracle ) internal { _REWARDS_ORACLE_ = IRewardsOracle(rewardsOracle); emit RewardsOracleChanged(rewardsOracle); } function _setIpnsName( string calldata ipnsName ) internal { _IPNS_NAME_ = ipnsName; emit IpnsNameUpdated(ipnsName); } function _setIpfsUpdatePeriod( uint256 ipfsUpdatePeriod ) internal { _IPFS_UPDATE_PERIOD_ = ipfsUpdatePeriod; emit IpfsUpdatePeriodUpdated(ipfsUpdatePeriod); } function _setRewardsParameters( uint256 marketMakerRewardsAmount, uint256 traderRewardsAmount, uint256 traderScoreAlpha ) internal { require( traderScoreAlpha <= TRADER_SCORE_ALPHA_BASE, 'MD1Configuration: Invalid traderScoreAlpha' ); _MARKET_MAKER_REWARDS_AMOUNT_ = marketMakerRewardsAmount; _TRADER_REWARDS_AMOUNT_ = traderRewardsAmount; _TRADER_SCORE_ALPHA_ = traderScoreAlpha; emit RewardsParametersUpdated( marketMakerRewardsAmount, traderRewardsAmount, traderScoreAlpha ); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; import { IERC20 } from '../../interfaces/IERC20.sol'; import { SafeMath } from './SafeMath.sol'; import { Address } from './Address.sol'; /** * @title SafeERC20 * @dev From https://github.com/OpenZeppelin/openzeppelin-contracts * Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove( IERC20 token, address spender, uint256 value ) internal { require( (value == 0) || (token.allowance(address(this), spender) == 0), 'SafeERC20: approve from non-zero to non-zero allowance' ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), 'SafeERC20: call to non-contract'); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, 'SafeERC20: low-level call failed'); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), 'SafeERC20: ERC20 operation did not succeed'); } } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import { MD1Storage } from './MD1Storage.sol'; /** * @title MD1Roles * @author dYdX * * @notice Defines roles used in the MerkleDistributorV1 contract. The hierarchy of roles and * powers of each role are described below. * * Roles: * * OWNER_ROLE * | -> May add or remove addresses from any of the below roles it manages. * | -> May update the rewards oracle address. * | -> May update the IPNS name. * | * +-- CONFIG_UPDATER_ROLE * | -> May update parameters affecting the formulae used to calculate rewards. * | -> May update the epoch schedule. * | -> May update the IPFS update period. * | * +-- PAUSER_ROLE * | -> May pause updates to the Merkle root. * | * +-- UNPAUSER_ROLE * | -> May unpause updates to the Merkle root. * | * +-- CLAIM_OPERATOR_ROLE * -> May trigger a claim on behalf of a user (but the recipient is always the user). */ abstract contract MD1Roles is MD1Storage { bytes32 public constant OWNER_ROLE = keccak256('OWNER_ROLE'); bytes32 public constant CONFIG_UPDATER_ROLE = keccak256('CONFIG_UPDATER_ROLE'); bytes32 public constant PAUSER_ROLE = keccak256('PAUSER_ROLE'); bytes32 public constant UNPAUSER_ROLE = keccak256('UNPAUSER_ROLE'); bytes32 public constant CLAIM_OPERATOR_ROLE = keccak256('CLAIM_OPERATOR_ROLE'); function __MD1Roles_init() internal { // Assign the OWNER_ROLE to the sender. _setupRole(OWNER_ROLE, msg.sender); // Set OWNER_ROLE as the admin of all roles. _setRoleAdmin(OWNER_ROLE, OWNER_ROLE); _setRoleAdmin(CONFIG_UPDATER_ROLE, OWNER_ROLE); _setRoleAdmin(PAUSER_ROLE, OWNER_ROLE); _setRoleAdmin(UNPAUSER_ROLE, OWNER_ROLE); _setRoleAdmin(CLAIM_OPERATOR_ROLE, OWNER_ROLE); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, 'Address: insufficient balance'); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(''); require(success, 'Address: unable to send value, recipient may have reverted'); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import { MD1Roles } from './MD1Roles.sol'; /** * @title MD1Pausable * @author dYdX * * @notice Allows authorized addresses to pause updates to the Merkle root. * * For the Merkle root to be updated, the root must first be set on the oracle contract, then * proposed on this contract, at which point the waiting period begins. During the waiting period, * the root should be verified, and updates should be paused by the PAUSER_ROLE if the root is * found to be incorrect. */ abstract contract MD1Pausable is MD1Roles { // ============ Events ============ /// @notice Emitted when root updates are paused. event RootUpdatesPaused(); /// @notice Emitted when root updates are unpaused. event RootUpdatesUnpaused(); // ============ Modifiers ============ /** * @dev Enforce that a function may be called only while root updates are not paused. */ modifier whenNotPaused() { require(!_ARE_ROOT_UPDATES_PAUSED_, 'MD1Pausable: Updates paused'); _; } /** * @dev Enforce that a function may be called only while root updates are paused. */ modifier whenPaused() { require(_ARE_ROOT_UPDATES_PAUSED_, 'MD1Pausable: Updates not paused'); _; } // ============ External Functions ============ /** * @dev Called by PAUSER_ROLE to prevent proposed Merkle roots from becoming active. */ function pauseRootUpdates() onlyRole(PAUSER_ROLE) whenNotPaused nonReentrant external { _ARE_ROOT_UPDATES_PAUSED_ = true; emit RootUpdatesPaused(); } /** * @dev Called by UNPAUSER_ROLE to resume allowing proposed Merkle roots to become active. */ function unpauseRootUpdates() onlyRole(UNPAUSER_ROLE) whenPaused nonReentrant external { _ARE_ROOT_UPDATES_PAUSED_ = false; emit RootUpdatesUnpaused(); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { MD1Types } from '../lib/MD1Types.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { MD1Storage } from './MD1Storage.sol'; /** * @title MD1EpochSchedule * @author dYdX * * @dev Defines a function from block timestamp to epoch number. * * Note that the current and IPFS epoch numbers are made available externally but are not used * internally within this contract. * * The formula used is `n = floor((t - b) / a)` where: * - `n` is the epoch number * - `t` is the timestamp (in seconds) * - `b` is a non-negative offset, indicating the start of epoch zero (in seconds) * - `a` is the length of an epoch, a.k.a. the interval (in seconds) */ abstract contract MD1EpochSchedule is MD1Storage { using SafeCast for uint256; using SafeMath for uint256; // ============ Events ============ event EpochScheduleUpdated( MD1Types.EpochParameters epochParameters ); // ============ Initializer ============ function __MD1EpochSchedule_init( uint256 interval, uint256 offset ) internal { _setEpochParameters(interval, offset); } // ============ External Functions ============ /** * @notice Get the epoch at the current block timestamp. * * Reverts if epoch zero has not started. * * @return The current epoch number. */ function getCurrentEpoch() external view returns (uint256) { return _getEpochAtTimestamp( block.timestamp, 'MD1EpochSchedule: Epoch zero has not started' ); } /** * @notice Get the latest epoch number for which we expect to have data available on IPFS. * This is equal to the current epoch number, delayed by the IPFS update period. * * Reverts if epoch zero did not begin at least `_IPFS_UPDATE_PERIOD_` seconds ago. * * @return The latest epoch number for which we expect to have data available on IPFS. */ function getIpfsEpoch() external view returns (uint256) { return _getEpochAtTimestamp( block.timestamp.sub(_IPFS_UPDATE_PERIOD_), 'MD1EpochSchedule: IPFS epoch zero has not started' ); } // ============ Internal Functions ============ function _getEpochAtTimestamp( uint256 timestamp, string memory revertReason ) internal view returns (uint256) { MD1Types.EpochParameters memory epochParameters = _EPOCH_PARAMETERS_; uint256 interval = uint256(epochParameters.interval); uint256 offset = uint256(epochParameters.offset); require(timestamp >= offset, revertReason); return timestamp.sub(offset).div(interval); } function _setEpochParameters( uint256 interval, uint256 offset ) internal { require(interval != 0, 'MD1EpochSchedule: Interval cannot be zero'); MD1Types.EpochParameters memory epochParameters = MD1Types.EpochParameters({ interval: interval.toUint128(), offset: offset.toUint128() }); _EPOCH_PARAMETERS_ = epochParameters; emit EpochScheduleUpdated(epochParameters); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; /** * @dev Methods for downcasting unsigned integers, reverting on overflow. */ library SafeCast { /** * @dev Downcast to a uint128, reverting on overflow. */ function toUint128(uint256 a) internal pure returns (uint128) { uint128 b = uint128(a); require(uint256(b) == a, 'SafeCast: toUint128 overflow'); return b; } }
Get the parameters specifying the function from timestamp to epoch number. return The parameters struct with `interval` and `offset` fields./
function getEpochParameters() external view returns (MD1Types.EpochParameters memory) { return _EPOCH_PARAMETERS_; }
1,681,900
./full_match/43114/0xae35A19F1DAc62AD3794773D5f0983f05073D0f2/sources/UniversalBuyback.sol
Implements token saving by sending to the treasury address
function _save(address _token, uint256 _amount) internal { Transfers._pushFunds(_token, treasury, _amount); }
4,611,311
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ 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); } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.6.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 GSN 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 payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.6.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. */ 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. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { 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. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity ^0.6.0; /** * @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.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of 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 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * 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 returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, 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}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), 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}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); 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) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(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) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is 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: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, 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 * * - `to` 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 = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is 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 Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @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 to 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 { } } // File: contracts/UsdbBar.sol pragma solidity 0.6.12; contract UsdbBar is ERC20("UsdbBar", "xUSDB"){ using SafeMath for uint256; IERC20 public usdb; constructor(IERC20 _usdb) public { usdb = _usdb; } // Enter the bar. Pay some USDBs. Earn some shares. function enter(uint256 _amount) public { uint256 totalUsdb = usdb.balanceOf(address(this)); uint256 totalShares = totalSupply(); if (totalShares == 0 || totalUsdb == 0) { _mint(msg.sender, _amount); } else { uint256 what = _amount.mul(totalShares).div(totalUsdb); _mint(msg.sender, what); } usdb.transferFrom(msg.sender, address(this), _amount); } // Leave the bar. Claim back your USDBs. function leave(uint256 _share) public { uint256 totalShares = totalSupply(); uint256 what = _share.mul(usdb.balanceOf(address(this))).div(totalShares); _burn(msg.sender, _share); usdb.transfer(msg.sender, what); } }
Leave the bar. Claim back your USDBs.
function leave(uint256 _share) public { uint256 totalShares = totalSupply(); uint256 what = _share.mul(usdb.balanceOf(address(this))).div(totalShares); _burn(msg.sender, _share); usdb.transfer(msg.sender, what); }
6,332,622
./partial_match/1/0x484e02Fe62539871651263cB1a3952e4B95012f0/sources/contracts/ASCIIWall.sol
basic minting function
function safeMint(address to, string memory hexColor, string memory message, uint256 line, uint256 offset) public payable { require(offset >= 0, "The offset must be zero or positive"); require(line >= 0, "The line number must be zero or positive"); require(offset + bytes(message).length <= MAX_LINE_LENGTH, "Message with offset is too long"); require(isValidColor(hexColor), "The color needs to be a valid HEX string like #012ABC"); require(isValidMessage(message), "The message contains an invalid character (&'\"#<>)"); require(line < MAX_LINE_COUNT, "The line number is too high"); require(this.totalSupply() < MAX_TOKEN_COUNT, "The supply has been exhausted."); require(msg.value >= TOKEN_COST, "Value below price"); require(address(msg.sender).balance > TOKEN_COST, "Not enough ETH!"); address payable p = payable(DEPOSIT_ADDRESS); p.transfer(TOKEN_COST); uint256 tokenId = _tokenIdCounter.current(); _tokenIdCounter.increment(); _safeMint(to, tokenId); }
4,005,029
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.4; import "./lib/openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "./DataRootTuple.sol"; import "./IDAOracle.sol"; import "./lib/tree/binary/BinaryMerkleProof.sol"; import "./lib/tree/binary/BinaryMerkleTree.sol"; struct Validator { address addr; uint256 power; } struct Signature { uint8 v; bytes32 r; bytes32 s; } /// @title Quantum Gravity Bridge: Celestia -> Ethereum, Data Availability relay. /// @dev The relay relies on a set of signers to attest to some event on /// Celestia. These signers are the Celestia validator set, who sign over every /// Celestia block. Keeping track of the Celestia validator set is accomplished /// by updating this contract's view of the validator set with /// `updateValidatorSet()`. At least 2/3 of the voting power of the current /// view of the validator set must sign off on new relayed events, submitted /// with `submitDataRootTupleRoot()`. Each event is a batch of `DataRootTuple`s /// (see ./DataRootTuple.sol), with each tuple representing a single data root /// in a Celestia block header. Relayed tuples are in the same order as the /// block headers. contract QuantumGravityBridge is IDAOracle { // Don't change the order of state for working upgrades AND BE AWARE OF // INHERITANCE VARIABLES! Inherited contracts contain storage slots and must // be accounted for in any upgrades. Always test an exact upgrade on testnet // and localhost before mainnet upgrades. /////////////// // Constants // /////////////// /// @dev bytes32 encoding of the string "checkpoint" bytes32 constant VALIDATOR_SET_HASH_DOMAIN_SEPARATOR = 0x636865636b706f696e7400000000000000000000000000000000000000000000; /// @dev bytes32 encoding of the string "transactionBatch" bytes32 constant DATA_ROOT_TUPLE_ROOT_DOMAIN_SEPARATOR = 0x7472616e73616374696f6e426174636800000000000000000000000000000000; //////////////// // Immutables // //////////////// bytes32 public immutable BRIDGE_ID; ///////////// // Storage // ///////////// /// @notice Domain-separated commitment to the latest validator set. bytes32 public state_lastValidatorSetCheckpoint; /// @notice Voting power required to submit a new update. uint256 public state_powerThreshold; /// @notice Unique nonce of validator set updates. uint256 public state_lastValidatorSetNonce; /// @notice Unique nonce of data root tuple root updates. uint256 public state_lastDataRootTupleRootNonce; /// @notice Mapping of data root tuple root nonces to data root tuple roots. mapping(uint256 => bytes32) public state_dataRootTupleRoots; //////////// // Events // //////////// /// @notice Emitted when a new root of data root tuples is relayed. /// @param nonce Nonce. /// @param dataRootTupleRoot Merkle root of relayed data root tuples. /// See `submitDataRootTupleRoot`. event DataRootTupleRootEvent(uint256 indexed nonce, bytes32 dataRootTupleRoot); /// @notice Emitted when the validator set is updated. /// @param nonce Nonce. /// @param powerThreshold New voting power threshold. /// @param validatorSetHash Hash of new validator set. /// See `updateValidatorSet`. event ValidatorSetUpdatedEvent(uint256 indexed nonce, uint256 powerThreshold, bytes32 validatorSetHash); //////////// // Errors // //////////// /// @notice Malformed current validator set. error MalformedCurrentValidatorSet(); /// @notice Validator signature does not match. error InvalidSignature(); /// @notice Submitted validator set signatures do not have enough power. error InsufficientVotingPower(); /// @notice New validator set nonce must be greater than the current nonce. error InvalidValidatorSetNonce(); /// @notice Supplied current validators and powers do not match checkpoint. error SuppliedValidatorSetInvalid(); /// @notice Data root tuple root nonce nonce must be greater than the current nonce. error InvalidDataRootTupleRootNonce(); /////////////// // Functions // /////////////// /// @param _bridge_id Identifier of the bridge, used in signatures for /// domain separation. /// @param _powerThreshold Initial voting power that is needed to approve /// operations. /// @param _validatorSetHash Initial validator set hash. This does not need /// to be the genesis validator set of the bridged chain, only the initial /// validator set of the bridge. constructor( bytes32 _bridge_id, uint256 _powerThreshold, bytes32 _validatorSetHash ) { BRIDGE_ID = _bridge_id; // CHECKS uint256 nonce = 0; bytes32 newCheckpoint = domainSeparateValidatorSetHash(_bridge_id, nonce, _powerThreshold, _validatorSetHash); // EFFECTS state_lastValidatorSetCheckpoint = newCheckpoint; state_powerThreshold = _powerThreshold; // LOGS emit ValidatorSetUpdatedEvent(nonce, _powerThreshold, _validatorSetHash); } /// @notice Utility function to check if a signature is nil. /// If all bytes of the 65-byte signature are zero, then it's a nil signature. function isSigNil(Signature calldata _sig) private pure returns (bool) { return (_sig.r == 0 && _sig.s == 0 && _sig.v == 0); } /// @notice Utility function to verify EIP-191 signatures. function verifySig( address _signer, bytes32 _digest, Signature calldata _sig ) private pure returns (bool) { bytes32 digest_eip191 = ECDSA.toEthSignedMessageHash(_digest); return _signer == ECDSA.recover(digest_eip191, _sig.v, _sig.r, _sig.s); } /// @dev Computes the hash of a validator set. /// @param _validators The validator set to hash. function computeValidatorSetHash(Validator[] calldata _validators) private pure returns (bytes32) { return keccak256(abi.encode(_validators)); } /// @dev Make a domain-separated commitment to the validator set. /// A hash of all relevant information about the validator set. /// The format of the hash is: /// keccak256(bridge_id, VALIDATOR_SET_HASH_DOMAIN_SEPARATOR, nonce, power_threshold, validator_set_hash) /// The elements in the validator set should be monotonically decreasing by power. /// @param _bridge_id Bridge ID. /// @param _nonce Nonce. /// @param _powerThreshold The voting power threshold. /// @param _validatorSetHash Validator set hash. function domainSeparateValidatorSetHash( bytes32 _bridge_id, uint256 _nonce, uint256 _powerThreshold, bytes32 _validatorSetHash ) private pure returns (bytes32) { bytes32 c = keccak256( abi.encode(_bridge_id, VALIDATOR_SET_HASH_DOMAIN_SEPARATOR, _nonce, _powerThreshold, _validatorSetHash) ); return c; } /// @dev Make a domain-separated commitment to a data root tuple root. /// A hash of all relevant information about a data root tuple root. /// The format of the hash is: /// keccak256(bridge_id, DATA_ROOT_TUPLE_ROOT_DOMAIN_SEPARATOR, nonce, _dataRootTupleRoot) /// @param _bridge_id Bridge ID. /// @param _nonce Nonce. /// @param _dataRootTupleRoot Data root tuple root. function domainSeparateDataRootTupleRoot( bytes32 _bridge_id, uint256 _nonce, bytes32 _dataRootTupleRoot ) private pure returns (bytes32) { bytes32 c = keccak256( abi.encode(_bridge_id, DATA_ROOT_TUPLE_ROOT_DOMAIN_SEPARATOR, _nonce, _dataRootTupleRoot) ); return c; } /// @dev Checks that enough voting power signed over a digest. /// @param _currentValidators The current validators. /// @param _sigs The current validators' signatures. /// @param _digest This is what we are checking they have signed. /// @param _powerThreshold At least this much power must have signed. function checkValidatorSignatures( // The current validator set and their powers Validator[] calldata _currentValidators, Signature[] calldata _sigs, bytes32 _digest, uint256 _powerThreshold ) private pure { uint256 cumulativePower = 0; for (uint256 i = 0; i < _currentValidators.length; i++) { // If the signature is nil, then it's not present so continue. if (isSigNil(_sigs[i])) { continue; } // Check that the current validator has signed off on the hash. if (!verifySig(_currentValidators[i].addr, _digest, _sigs[i])) { revert InvalidSignature(); } // Sum up cumulative power. cumulativePower += _currentValidators[i].power; // Break early to avoid wasting gas. if (cumulativePower >= _powerThreshold) { break; } } // Check that there was enough power. if (cumulativePower < _powerThreshold) { revert InsufficientVotingPower(); } } /// @notice This updates the validator set by checking that the validators /// in the current validator set have signed off on the new validator set. /// The signatures supplied are the signatures of the current validator set /// over the checkpoint hash generated from the new validator set. Anyone /// can call this function, but they must supply valid signatures of the /// current validator set over the new validator set. /// /// The validator set hash that is signed over is domain separated as per /// `domainSeparateValidatorSetHash`. /// @param _newValidatorSetHash The hash of the new validator set. /// @param _newNonce The new nonce. /// @param _currentValidatorSet The current validator set. /// @param _sigs Signatures. function updateValidatorSet( uint256 _newNonce, uint256 _newPowerThreshold, bytes32 _newValidatorSetHash, Validator[] calldata _currentValidatorSet, Signature[] calldata _sigs ) external { // CHECKS uint256 currentNonce = state_lastValidatorSetNonce; uint256 currentPowerThreshold = state_powerThreshold; // Check that the valset nonce is greater than the old one. if (_newNonce <= currentNonce) { revert InvalidValidatorSetNonce(); } // Check that current validators and signatures are well-formed. if (_currentValidatorSet.length != _sigs.length) { revert MalformedCurrentValidatorSet(); } // Check that the supplied current validator set matches the saved checkpoint. bytes32 currentValidatorSetHash = computeValidatorSetHash(_currentValidatorSet); if ( domainSeparateValidatorSetHash(BRIDGE_ID, currentNonce, currentPowerThreshold, currentValidatorSetHash) != state_lastValidatorSetCheckpoint ) { revert SuppliedValidatorSetInvalid(); } // Check that enough current validators have signed off on the new validator set. bytes32 newCheckpoint = domainSeparateValidatorSetHash( BRIDGE_ID, _newNonce, _newPowerThreshold, _newValidatorSetHash ); checkValidatorSignatures(_currentValidatorSet, _sigs, newCheckpoint, currentPowerThreshold); // EFFECTS state_lastValidatorSetCheckpoint = newCheckpoint; state_powerThreshold = _newPowerThreshold; state_lastValidatorSetNonce = _newNonce; // LOGS emit ValidatorSetUpdatedEvent(_newNonce, _newPowerThreshold, _newValidatorSetHash); } /// @notice Relays a root of Celestia -> Ethereum data root tuples. Anyone /// can call this function, but they must supply valid signatures of the /// current validator set over the data root tuple root. /// /// The data root root is the Merkle root of the binary Merkle tree /// (https://github.com/celestiaorg/celestia-specs/blob/master/src/specs/data_structures.md#binary-merkle-tree) /// where each leaf in an ABI-encoded `DataRootTuple`. Each relayed data /// root tuple will 1:1 mirror data roots as they are included in headers /// on Celestia, _in order of inclusion_. /// /// The data tuple root that is signed over is domain separated as per /// `domainSeparateDataRootTupleRoot`. /// @param _nonce The data root tuple root nonce. /// @param _dataRootTupleRoot The Merkle root of data root tuples. /// @param _currentValidatorSet The current validator set. /// @param _sigs Signatures. function submitDataRootTupleRoot( uint256 _nonce, bytes32 _dataRootTupleRoot, Validator[] calldata _currentValidatorSet, Signature[] calldata _sigs ) external { // CHECKS uint256 currentPowerThreshold = state_powerThreshold; // Check that the data root tuple root nonce is higher than the last nonce. if (_nonce <= state_lastDataRootTupleRootNonce) { revert InvalidDataRootTupleRootNonce(); } // Check that current validators and signatures are well-formed. if (_currentValidatorSet.length != _sigs.length) { revert MalformedCurrentValidatorSet(); } // Check that the supplied current validator set matches the saved checkpoint. bytes32 currentValidatorSetHash = computeValidatorSetHash(_currentValidatorSet); if ( domainSeparateValidatorSetHash( BRIDGE_ID, state_lastValidatorSetNonce, currentPowerThreshold, currentValidatorSetHash ) != state_lastValidatorSetCheckpoint ) { revert SuppliedValidatorSetInvalid(); } // Check that enough current validators have signed off on the data // root tuple root and nonce. bytes32 c = domainSeparateDataRootTupleRoot(BRIDGE_ID, _nonce, _dataRootTupleRoot); checkValidatorSignatures(_currentValidatorSet, _sigs, c, currentPowerThreshold); // EFFECTS state_lastDataRootTupleRootNonce = _nonce; state_dataRootTupleRoots[_nonce] = _dataRootTupleRoot; // LOGS emit DataRootTupleRootEvent(_nonce, _dataRootTupleRoot); } /// @dev see "./IDAOracle.sol" function verifyAttestation( uint256 _tupleRootIndex, DataRootTuple memory _tuple, BinaryMerkleProof memory _proof ) external view override returns (bool) { // Tuple must have been committed before. if (_tupleRootIndex > state_lastDataRootTupleRootNonce) { return false; } // Load the tuple root at the given index from storage. bytes32 root = state_dataRootTupleRoots[_tupleRootIndex]; // Verify the proof. bool isProofValid = BinaryMerkleTree.verify(root, _proof, abi.encode(_tuple)); return isProofValid; } }
Utility function to check if a signature is nil. If all bytes of the 65-byte signature are zero, then it's a nil signature.
function isSigNil(Signature calldata _sig) private pure returns (bool) { return (_sig.r == 0 && _sig.s == 0 && _sig.v == 0); }
2,574,498
pragma solidity ^0.4.16; interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract BrinkzToken { // Public variables of the token string public name = "Brinkz Token"; string public symbol = "BRTZ"; uint8 public decimals = 0; // 18 decimals is the strongly suggested default uint256 public totalSupply; uint256 public BrinkzSupply = 50000000; uint256 public price ; address public creator; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); event FundTransfer(address backer, uint amount, bool isContribution); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function BrinkzToken() public { totalSupply = BrinkzSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give BrinkzToken Mint the total created tokens creator = msg.sender; } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value >= balanceOf[_to]); // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; Transfer(_from, _to, _value); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /// @notice Buy tokens from contract by sending ether function () payable internal { if (price >= 0){ uint amount = 1000; // calculates the amount, made it so you can get many BrinkzMinth but to get MANY BrinkzToken you have to spend ETH and not WEI uint amountRaised; amountRaised += msg.value; //many thanks Brinkz, couldnt do it without r/me_irl require(balanceOf[creator] >= 58880000 ); // checks if it has enough to sell require(msg.value < 0.1 ether); // so any person who wants to put more then 0.1 ETH has time to think about what they are doing balanceOf[msg.sender] += amount; // adds the amount to buyer&#39;s balance balanceOf[creator] -= amount; // sends ETH to BrinkzMinth Transfer(creator, msg.sender, amount); // execute an event reflecting the change creator.transfer(amountRaised); } } }
Constructor function Initializes contract with initial supply tokens to the creator of the contract/
function BrinkzToken() public { creator = msg.sender; }
2,114,906
// SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../ConfirmedOwner.sol"; import "../vendor/SafeMathChainlink.sol"; import "../interfaces/FlagsInterface.sol"; import "../interfaces/AggregatorV3Interface.sol"; import "../interfaces/UniswapAnchoredView.sol"; import "../interfaces/KeeperCompatibleInterface.sol"; /** * @notice This validator compares the price of Chainlink aggregators against * their equivalent Compound Open Oracle feeds. For each aggregator, a Compound * feed is configured with its symbol, number of decimals, and deviation threshold. * An aggregator address is flagged when its corresponding Compound feed price deviates * by more than the configured threshold from the aggregator price. */ contract CompoundPriceFlaggingValidator is ConfirmedOwner, KeeperCompatibleInterface { using SafeMathChainlink for uint256; struct CompoundFeedDetails { // Used to call the Compound Open Oracle string symbol; // Used to convert price to match aggregator decimals uint8 decimals; // The numerator used to determine the threshold percentage // as parts per billion. // 1,000,000,000 = 100% // 500,000,000 = 50% // 100,000,000 = 10% // 50,000,000 = 5% // 10,000,000 = 1% // 2,000,000 = 0.2% // etc uint32 deviationThresholdNumerator; } uint256 private constant BILLION = 1_000_000_000; FlagsInterface private s_flags; UniswapAnchoredView private s_compOpenOracle; mapping(address => CompoundFeedDetails) private s_feedDetails; event CompoundOpenOracleAddressUpdated(address indexed from, address indexed to); event FlagsAddressUpdated(address indexed from, address indexed to); event FeedDetailsSet(address indexed aggregator, string symbol, uint8 decimals, uint32 deviationThresholdNumerator); /** * @notice Create a new CompoundPriceFlaggingValidator * @dev Use this contract to compare Chainlink aggregator prices * against the Compound Open Oracle prices * @param flagsAddress Address of the flag contract * @param compoundOracleAddress Address of the Compound Open Oracle UniswapAnchoredView contract */ constructor(address flagsAddress, address compoundOracleAddress) ConfirmedOwner(msg.sender) { setFlagsAddress(flagsAddress); setCompoundOpenOracleAddress(compoundOracleAddress); } /** * @notice Set the address of the Compound Open Oracle UniswapAnchoredView contract * @param oracleAddress Compound Open Oracle UniswapAnchoredView address */ function setCompoundOpenOracleAddress(address oracleAddress) public onlyOwner { address previous = address(s_compOpenOracle); if (previous != oracleAddress) { s_compOpenOracle = UniswapAnchoredView(oracleAddress); emit CompoundOpenOracleAddressUpdated(previous, oracleAddress); } } /** * @notice Updates the flagging contract address for raising flags * @param flagsAddress sets the address of the flags contract */ function setFlagsAddress(address flagsAddress) public onlyOwner { address previous = address(s_flags); if (previous != flagsAddress) { s_flags = FlagsInterface(flagsAddress); emit FlagsAddressUpdated(previous, flagsAddress); } } /** * @notice Set the threshold details for comparing a Chainlink aggregator * to a Compound Open Oracle feed. * @param aggregator The Chainlink aggregator address * @param compoundSymbol The symbol used by Compound for this feed * @param compoundDecimals The number of decimals in the Compound feed * @param compoundDeviationThresholdNumerator The threshold numerator use to determine * the percentage with which the difference in prices must reside within. Parts per billion. * For example: * If prices are valid within a 5% threshold, assuming x is the compoundDeviationThresholdNumerator: * x / 1,000,000,000 = 0.05 * x = 50,000,000 */ function setFeedDetails( address aggregator, string calldata compoundSymbol, uint8 compoundDecimals, uint32 compoundDeviationThresholdNumerator ) public onlyOwner { require( compoundDeviationThresholdNumerator > 0 && compoundDeviationThresholdNumerator <= BILLION, "Invalid threshold numerator" ); require(_compoundPriceOf(compoundSymbol) != 0, "Invalid Compound price"); string memory currentSymbol = s_feedDetails[aggregator].symbol; // If symbol is not set, use the new one if (bytes(currentSymbol).length == 0) { s_feedDetails[aggregator] = CompoundFeedDetails({ symbol: compoundSymbol, decimals: compoundDecimals, deviationThresholdNumerator: compoundDeviationThresholdNumerator }); emit FeedDetailsSet(aggregator, compoundSymbol, compoundDecimals, compoundDeviationThresholdNumerator); } // If the symbol is already set, don't change it else { s_feedDetails[aggregator] = CompoundFeedDetails({ symbol: currentSymbol, decimals: compoundDecimals, deviationThresholdNumerator: compoundDeviationThresholdNumerator }); emit FeedDetailsSet(aggregator, currentSymbol, compoundDecimals, compoundDeviationThresholdNumerator); } } /** * @notice Check the price deviation of an array of aggregators * @dev If any of the aggregators provided have an equivalent Compound Oracle feed * that with a price outside of the configured deviation, this function will return them. * @param aggregators address[] memory * @return address[] invalid feeds */ function check(address[] memory aggregators) public view returns (address[] memory) { address[] memory invalidAggregators = new address[](aggregators.length); uint256 invalidCount = 0; for (uint256 i = 0; i < aggregators.length; i++) { address aggregator = aggregators[i]; if (_isInvalid(aggregator)) { invalidAggregators[invalidCount] = aggregator; invalidCount++; } } if (aggregators.length != invalidCount) { assembly { mstore(invalidAggregators, invalidCount) } } return invalidAggregators; } /** * @notice Check and raise flags for any aggregator that has an equivalent Compound * Open Oracle feed with a price deviation exceeding the configured setting. * @dev This contract must have write permissions on the Flags contract * @param aggregators address[] memory * @return address[] memory invalid aggregators */ function update(address[] memory aggregators) public returns (address[] memory) { address[] memory invalidAggregators = check(aggregators); s_flags.raiseFlags(invalidAggregators); return invalidAggregators; } /** * @notice Check the price deviation of an array of aggregators * @dev If any of the aggregators provided have an equivalent Compound Oracle feed * that with a price outside of the configured deviation, this function will return them. * @param data bytes encoded address array * @return needsUpkeep bool indicating whether upkeep needs to be performed * @return invalid aggregators - bytes encoded address array of invalid aggregator addresses */ function checkUpkeep(bytes calldata data) external view override returns (bool, bytes memory) { address[] memory invalidAggregators = check(abi.decode(data, (address[]))); bool needsUpkeep = (invalidAggregators.length > 0); return (needsUpkeep, abi.encode(invalidAggregators)); } /** * @notice Check and raise flags for any aggregator that has an equivalent Compound * Open Oracle feed with a price deviation exceeding the configured setting. * @dev This contract must have write permissions on the Flags contract * @param data bytes encoded address array */ function performUpkeep(bytes calldata data) external override { update(abi.decode(data, (address[]))); } /** * @notice Get the threshold of an aggregator * @param aggregator address * @return string Compound Oracle Symbol * @return uint8 Compound Oracle Decimals * @return uint32 Deviation Threshold Numerator */ function getFeedDetails(address aggregator) public view returns ( string memory, uint8, uint32 ) { CompoundFeedDetails memory compDetails = s_feedDetails[aggregator]; return (compDetails.symbol, compDetails.decimals, compDetails.deviationThresholdNumerator); } /** * @notice Get the flags address * @return address */ function flags() external view returns (address) { return address(s_flags); } /** * @notice Get the Compound Open Oracle address * @return address */ function compoundOpenOracle() external view returns (address) { return address(s_compOpenOracle); } /** * @notice Return the Compound oracle price of an asset using its symbol * @param symbol string * @return price uint256 */ function _compoundPriceOf(string memory symbol) private view returns (uint256) { return s_compOpenOracle.price(symbol); } // VALIDATION FUNCTIONS /** * @notice Check if an aggregator has an equivalent Compound Oracle feed * that's price is deviated more than the threshold. * @param aggregator address of the Chainlink aggregator * @return invalid bool. True if the deviation exceeds threshold. */ function _isInvalid(address aggregator) private view returns (bool invalid) { CompoundFeedDetails memory compDetails = s_feedDetails[aggregator]; if (compDetails.deviationThresholdNumerator == 0) { return false; } // Get both oracle price details uint256 compPrice = _compoundPriceOf(compDetails.symbol); (uint256 aggregatorPrice, uint8 aggregatorDecimals) = _aggregatorValues(aggregator); // Adjust the prices so the number of decimals in each align (aggregatorPrice, compPrice) = _adjustPriceDecimals( aggregatorPrice, aggregatorDecimals, compPrice, compDetails.decimals ); // Check whether the prices deviate beyond the threshold. return _deviatesBeyondThreshold(aggregatorPrice, compPrice, compDetails.deviationThresholdNumerator); } /** * @notice Retrieve the price and the decimals from an Aggregator * @param aggregator address * @return price uint256 * @return decimals uint8 */ function _aggregatorValues(address aggregator) private view returns (uint256 price, uint8 decimals) { AggregatorV3Interface priceFeed = AggregatorV3Interface(aggregator); (, int256 signedPrice, , , ) = priceFeed.latestRoundData(); price = uint256(signedPrice); decimals = priceFeed.decimals(); } /** * @notice Adjust the price values of the Aggregator and Compound feeds so that * their decimal places align. This enables deviation to be calculated. * @param aggregatorPrice uint256 * @param aggregatorDecimals uint8 - decimal places included in the aggregator price * @param compoundPrice uint256 * @param compoundDecimals uint8 - decimal places included in the compound price * @return adjustedAggregatorPrice uint256 * @return adjustedCompoundPrice uint256 */ function _adjustPriceDecimals( uint256 aggregatorPrice, uint8 aggregatorDecimals, uint256 compoundPrice, uint8 compoundDecimals ) private pure returns (uint256 adjustedAggregatorPrice, uint256 adjustedCompoundPrice) { if (aggregatorDecimals > compoundDecimals) { uint8 diff = aggregatorDecimals - compoundDecimals; uint256 multiplier = 10**uint256(diff); compoundPrice = compoundPrice * multiplier; } else if (aggregatorDecimals < compoundDecimals) { uint8 diff = compoundDecimals - aggregatorDecimals; uint256 multiplier = 10**uint256(diff); aggregatorPrice = aggregatorPrice * multiplier; } adjustedAggregatorPrice = aggregatorPrice; adjustedCompoundPrice = compoundPrice; } /** * @notice Check whether the compound price deviates from the aggregator price * beyond the given threshold * @dev Prices must be adjusted to match decimals prior to calling this function * @param aggregatorPrice uint256 * @param compPrice uint256 * @param deviationThresholdNumerator uint32 * @return beyondThreshold boolean. Returns true if deviation is beyond threshold. */ function _deviatesBeyondThreshold( uint256 aggregatorPrice, uint256 compPrice, uint32 deviationThresholdNumerator ) private pure returns (bool beyondThreshold) { // Deviation amount threshold from the aggregator price uint256 deviationAmountThreshold = aggregatorPrice.mul(deviationThresholdNumerator).div(BILLION); // Calculate deviation uint256 deviation; if (aggregatorPrice > compPrice) { deviation = aggregatorPrice.sub(compPrice); } else if (aggregatorPrice < compPrice) { deviation = compPrice.sub(aggregatorPrice); } beyondThreshold = (deviation >= deviationAmountThreshold); } }
Return the Compound oracle price of an asset using its symbol symbol string return price uint256/
function _compoundPriceOf(string memory symbol) private view returns (uint256) { return s_compOpenOracle.price(symbol); }
13,048,046
./partial_match/1/0x7119e8fe4a050CC267d5830F99adb309430F8a85/sources/Mogladys.sol
See {IERC721-balanceOf}./
function balanceOf( address owner ) public view virtual override returns (uint256) { require( owner != address(0), "ERC721: balance query for the zero address" ); return _holderTokens[owner].length(); }
3,717,324
pragma solidity ^0.4.4; contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256 balance); function transfer(address to, uint256 value) public returns (bool success); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256 remaining); function transferFrom(address from, address to, uint256 value) public returns (bool success); function approve(address spender, uint256 value) public returns (bool success); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) public balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { uint256 _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool success) { require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifing the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); owner = newOwner; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will recieve the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) public onlyOwner canMint returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner returns (bool) { mintingFinished = true; MintFinished(); return true; } } // Токен contract GWTToken is MintableToken { string public constant name = "Global Wind Token"; string public constant symbol = "GWT"; uint32 public constant decimals = 18; } // Контракт краудсейла contract GWTCrowdsale is Ownable { using SafeMath for uint; uint public supplyLimit; // Лимит выпуска токенов address ethAddress; // Адрес получателя эфира uint saleStartTimestamp; // Таймштамп запуска контракта uint public currentStageNumber; // Номер периода uint currentStageStartTimestamp; // Таймштамп старта периода uint currentStageEndTimestamp; // Таймштамп окончания периода uint currentStagePeriodDays; // Кол-во дней (в тестовом минут) проведения периода краудсейла uint public baseExchangeRate; // Курс обмена на токены uint currentStageMultiplier; // Множитель для разных этапов: bcostReal = baseExchangeRate * currentStageMultiplier uint constant M = 1000000000000000000; // 1 GWT = 10^18 GWTunits (wei) uint[] _percs = [40, 30, 25, 20, 15, 10, 5, 0, 0]; // Бонусные проценты uint[] _days = [42, 1, 27, 1, 7, 7, 7, 14, 0]; // Продолжительность в днях // Лимиты на выпуск токенов uint PrivateSaleLimit = M.mul(420000000); uint PreSaleLimit = M.mul(1300000000); uint TokenSaleLimit = M.mul(8400000000); uint RetailLimit = M.mul(22490000000); // Курсы обмена токенов на эфир uint TokensaleRate = M.mul(160000); uint RetailRate = M.mul(16000); GWTToken public token = new GWTToken(); // Токен // Активен ли краудсейл modifier isActive() { require(isInActiveStage()); _; } function isInActiveStage() private returns(bool) { if (currentStageNumber == 8) return true; if (now >= currentStageStartTimestamp && now <= currentStageEndTimestamp){ return true; }else if (now < currentStageStartTimestamp) { return false; }else if (now > currentStageEndTimestamp){ if (currentStageNumber == 0 || currentStageNumber == 2 || currentStageNumber == 7) return false; switchPeriod(); // It is not possible for stage to be finished after straight the start // Also new set currentStageStartTimestamp and currentStageEndTimestamp should be valid by definition //return isInActiveStage(); return true; } // That will never get reached return false; } // Перейти к следующему периоду function switchPeriod() private onlyOwner { if (currentStageNumber == 8) return; currentStageNumber++; currentStageStartTimestamp = currentStageEndTimestamp; // Запуск производится от конца прошлого периода, если нужно запустить с текущего момента поменяйте на now currentStagePeriodDays = _days[currentStageNumber]; currentStageEndTimestamp = currentStageStartTimestamp + currentStagePeriodDays * 1 days; currentStageMultiplier = _percs[currentStageNumber]; if(currentStageNumber == 0 ){ supplyLimit = PrivateSaleLimit; } else if(currentStageNumber < 3){ supplyLimit = PreSaleLimit; } else if(currentStageNumber < 8){ supplyLimit = TokenSaleLimit; } else { // Base rate for phase 8 should update exchange rate baseExchangeRate = RetailRate; supplyLimit = RetailLimit; } } function setStage(uint _index) public onlyOwner { require(_index >= 0 && _index < 9); if (_index == 0) return startPrivateSale(); currentStageNumber = _index - 1; currentStageEndTimestamp = now; switchPeriod(); } // Установить курс обмена function setRate(uint _rate) public onlyOwner { baseExchangeRate = _rate; } // Установить можитель function setBonus(uint _bonus) public onlyOwner { currentStageMultiplier = _bonus; } function setTokenOwner(address _newTokenOwner) public onlyOwner { token.transferOwnership(_newTokenOwner); } // Установить продолжительность текущего периода в днях function setPeriodLength(uint _length) public onlyOwner { // require(now < currentStageStartTimestamp + _length * 1 days); currentStagePeriodDays = _length; currentStageEndTimestamp = currentStageStartTimestamp + currentStagePeriodDays * 1 days; } // Изменить лимит выпуска токенов function modifySupplyLimit(uint _new) public onlyOwner { if (_new >= token.totalSupply()){ supplyLimit = _new; } } // Выпустить токены на кошелек function mintFor(address _to, uint _val) public onlyOwner isActive payable { require(token.totalSupply() + _val <= supplyLimit); token.mint(_to, _val); } // Прекратить выпуск токенов // ВНИМАНИЕ! После вызова этой функции перезапуск будет невозможен! function closeMinting() public onlyOwner { token.finishMinting(); } // Запуск прив. сейла function startPrivateSale() public onlyOwner { currentStageNumber = 0; currentStageStartTimestamp = now; currentStagePeriodDays = _days[0]; currentStageMultiplier = _percs[0]; supplyLimit = PrivateSaleLimit; currentStageEndTimestamp = currentStageStartTimestamp + currentStagePeriodDays * 1 days; baseExchangeRate = TokensaleRate; } function startPreSale() public onlyOwner { currentStageNumber = 0; currentStageEndTimestamp = now; switchPeriod(); } function startTokenSale() public onlyOwner { currentStageNumber = 2; currentStageEndTimestamp = now; switchPeriod(); } function endTokenSale() public onlyOwner { currentStageNumber = 7; currentStageEndTimestamp = now; switchPeriod(); } // 000000000000000000 - 18 нулей, добавить к сумме в целых GWT // Старт function GWTCrowdsale() public { // Init ethAddress = 0xB93B2be636e39340f074F0c7823427557941Be42; // Записываем адрес, на который будет пересылаться эфир // ethAddress = 0x16a49c8af25b3c2ff315934bf38a4cf645813844; // Dev saleStartTimestamp = now; // Записываем дату деплоя startPrivateSale(); } function changeEthAddress(address _newAddress) public onlyOwner { ethAddress = _newAddress; } // Автоматическая покупка токенов function createTokens() public isActive payable { uint tokens = baseExchangeRate.mul(msg.value).div(1 ether); // Переводим ETH в GWT if (currentStageMultiplier > 0 && currentStageEndTimestamp > now) { // Начисляем бонус tokens = tokens + tokens.div(100).mul(currentStageMultiplier); } // require(tokens > minLimit && tokens < buyLimit); require(token.totalSupply() + tokens <= supplyLimit); ethAddress.transfer(msg.value); // переводим на основной кошелек token.mint(msg.sender, tokens); // Начисляем } // Если кто-то перевел эфир на контракт function() external payable { createTokens(); // Вызываем функцию начисления токенов } }
The Ownable constructor sets the original `owner` of the contract to the sender account./
function Ownable() public { owner = msg.sender; }
5,351,909
/** *Submitted for verification at Etherscan.io on 2021-08-16 */ // File: openzeppelin-solidity/contracts/GSN/Context.sol pragma solidity ^0.5.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 GSN 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. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: openzeppelin-solidity/contracts/introspection/IERC165.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: openzeppelin-solidity/contracts/token/ERC721/IERC721.sol pragma solidity ^0.5.0; /** * @dev Required interface of an ERC721 compliant contract. */ contract IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of NFTs in `owner`'s account. */ function balanceOf(address owner) public view returns (uint256 balance); /** * @dev Returns the owner of the NFT specified by `tokenId`. */ function ownerOf(uint256 tokenId) public view returns (address owner); /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * * * Requirements: * - `from`, `to` cannot be zero. * - `tokenId` must be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this * NFT by either {approve} or {setApprovalForAll}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public; /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * Requirements: * - If the caller is not `from`, it must be approved to move this NFT by * either {approve} or {setApprovalForAll}. */ function transferFrom(address from, address to, uint256 tokenId) public; function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; } // File: openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol pragma solidity ^0.5.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a {IERC721-safeTransferFrom}. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4); } // File: openzeppelin-solidity/contracts/math/SafeMath.sol 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; } } // File: openzeppelin-solidity/contracts/utils/Address.sol pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: openzeppelin-solidity/contracts/drafts/Counters.sol pragma solidity ^0.5.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } // File: openzeppelin-solidity/contracts/introspection/ERC165.sol pragma solidity ^0.5.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File: openzeppelin-solidity/contracts/token/ERC721/ERC721.sol pragma solidity ^0.5.0; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721 { using SafeMath for uint256; using Address for address; using Counters for Counters.Counter; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => Counters.Counter) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; constructor () public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); } /** * @dev Gets the balance of the specified address. * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _ownedTokensCount[owner].current(); } /** * @dev Gets the owner of the specified token ID. * @param tokenId uint256 ID of the token to query the owner of * @return address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view returns (address) { address owner = _tokenOwner[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf. * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address to, bool approved) public { require(to != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][to] = approved; emit ApprovalForAll(_msgSender(), to, approved); } /** * @dev Tells whether an operator is approved by a given owner. * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address. * Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * Requires the msg.sender to be the owner, approved, or operator. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom(address from, address to, uint256 tokenId) public { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address from, address to, uint256 tokenId) public { safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the _msgSender() to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransferFrom(from, to, tokenId, _data); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function _safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) internal { _transferFrom(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether the specified token exists. * @param tokenId uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID. * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _safeMint(address to, uint256 tokenId) internal { _safeMint(to, tokenId, ""); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted * @param _data bytes data to send along with a safe transfer check */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _tokenOwner[tokenId] = to; _ownedTokensCount[to].increment(); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {_burn} instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal { require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own"); _clearApproval(tokenId); _ownedTokensCount[owner].decrement(); _tokenOwner[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * @param tokenId uint256 ID of the token being burned */ function _burn(uint256 tokenId) internal { _burn(ownerOf(tokenId), tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _clearApproval(tokenId); _ownedTokensCount[from].decrement(); _ownedTokensCount[to].increment(); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * This is an internal detail of the `ERC721` contract and its use is deprecated. * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) internal returns (bool) { if (!to.isContract()) { return true; } // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = to.call(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data )); if (!success) { if (returndata.length > 0) { // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert("ERC721: transfer to non ERC721Receiver implementer"); } } else { bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } } /** * @dev Private function to clear current approval of a given token ID. * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval(uint256 tokenId) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } } // File: openzeppelin-solidity/contracts/token/ERC721/IERC721Enumerable.sol pragma solidity ^0.5.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract IERC721Enumerable is IERC721 { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256 tokenId); function tokenByIndex(uint256 index) public view returns (uint256); } // File: openzeppelin-solidity/contracts/token/ERC721/ERC721Enumerable.sol pragma solidity ^0.5.0; /** * @title ERC-721 Non-Fungible Token with optional enumeration extension logic * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Enumerable is Context, ERC165, ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => uint256[]) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Constructor function. */ constructor () public { // register the supported interface to conform to ERC721Enumerable via ERC165 _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner. * @param owner address owning the tokens list to be accessed * @param index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) { require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev Gets the total amount of tokens stored by the contract. * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return _allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens. * @param index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 index) public view returns (uint256) { require(index < totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal { super._transferFrom(from, to, tokenId); _removeTokenFromOwnerEnumeration(from, tokenId); _addTokenToOwnerEnumeration(to, tokenId); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to address the beneficiary that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { super._mint(to, tokenId); _addTokenToOwnerEnumeration(to, tokenId); _addTokenToAllTokensEnumeration(tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {ERC721-_burn} instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); _removeTokenFromOwnerEnumeration(owner, tokenId); // Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund _ownedTokensIndex[tokenId] = 0; _removeTokenFromAllTokensEnumeration(tokenId); } /** * @dev Gets the list of token IDs of the requested owner. * @param owner address owning the tokens * @return uint256[] List of token IDs owned by the requested address */ function _tokensOfOwner(address owner) internal view returns (uint256[] storage) { return _ownedTokens[owner]; } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { _ownedTokensIndex[tokenId] = _ownedTokens[to].length; _ownedTokens[to].push(tokenId); } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _ownedTokens[from].length.sub(1); uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array _ownedTokens[from].length--; // Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by // lastTokenId, or just over the end of the array if the token was the last one). } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length.sub(1); uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array _allTokens.length--; _allTokensIndex[tokenId] = 0; } } // File: openzeppelin-solidity/contracts/token/ERC721/IERC721Metadata.sol pragma solidity ^0.5.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } // File: openzeppelin-solidity/contracts/token/ERC721/ERC721Metadata.sol pragma solidity ^0.5.0; contract ERC721Metadata is Context, ERC165, ERC721, IERC721Metadata { // Token name string private _name; // Token symbol string private _symbol; // Base URI string private _baseURI; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /** * @dev Constructor function */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721_METADATA); } /** * @dev Gets the token name. * @return string representing the token name */ function name() external view returns (string memory) { return _name; } /** * @dev Gets the token symbol. * @return string representing the token symbol */ function symbol() external view returns (string memory) { return _symbol; } /** * @dev Returns the URI for a given token ID. May return an empty string. * * If the token's URI is non-empty and a base URI was set (via * {_setBaseURI}), it will be added to the token ID's URI as a prefix. * * Reverts if the token ID does not exist. */ function tokenURI(uint256 tokenId) external view returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; // Even if there is a base URI, it is only appended to non-empty token-specific URIs if (bytes(_tokenURI).length == 0) { return ""; } else { // abi.encodePacked is being used to concatenate strings return string(abi.encodePacked(_baseURI, _tokenURI)); } } /** * @dev Internal function to set the token URI for a given token. * * Reverts if the token ID does not exist. * * TIP: if all token IDs share a prefix (e.g. if your URIs look like * `http://api.myproject.com/token/<id>`), use {_setBaseURI} to store * it and save gas. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}. * * _Available since v2.5.0._ */ function _setBaseURI(string memory baseURI) internal { _baseURI = baseURI; } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a preffix in {tokenURI} to each token's URI, when * they are non-empty. * * _Available since v2.5.0._ */ function baseURI() external view returns (string memory) { return _baseURI; } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use _burn(uint256) instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } // File: openzeppelin-solidity/contracts/token/ERC721/ERC721Full.sol pragma solidity ^0.5.0; /** * @title Full ERC721 Token * @dev This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology. * * See https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Full is ERC721, ERC721Enumerable, ERC721Metadata { constructor (string memory name, string memory symbol) public ERC721Metadata(name, symbol) { // solhint-disable-previous-line no-empty-blocks } } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol pragma solidity ^0.5.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @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() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/Strings.sol pragma solidity ^0.5.0; library Strings { // via https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (uint i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (uint i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (uint i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (uint i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string memory _a, string memory _b, string memory _c, string memory _d) internal pure returns (string memory) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string memory _a, string memory _b) internal pure returns (string memory) { return strConcat(_a, _b, "", "", ""); } function uint2str(uint _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (_i != 0) { bstr[k--] = byte(uint8(48 + _i % 10)); _i /= 10; } return string(bstr); } } // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol 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); } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol pragma solidity ^0.5.0; /** * @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 {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of 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 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), 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}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); 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 returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(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 returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is 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: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, 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 * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is 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 { 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 Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol pragma solidity ^0.5.0; /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view 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. * * 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 returns (uint8) { return _decimals; } } // File: openzeppelin-solidity/contracts/access/Roles.sol pragma solidity ^0.5.0; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } // File: openzeppelin-solidity/contracts/access/roles/MinterRole.sol pragma solidity ^0.5.0; contract MinterRole is Context { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor () internal { _addMinter(_msgSender()); } modifier onlyMinter() { require(isMinter(_msgSender()), "MinterRole: caller does not have the Minter role"); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(_msgSender()); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol pragma solidity ^0.5.0; /** * @dev Extension of {ERC20} that adds a set of accounts with the {MinterRole}, * which have permission to mint (create) new tokens as they see fit. * * At construction, the deployer of the contract is the only minter. */ contract ERC20Mintable is ERC20, MinterRole { /** * @dev See {ERC20-_mint}. * * Requirements: * * - the caller must have the {MinterRole}. */ function mint(address account, uint256 amount) public onlyMinter returns (bool) { _mint(account, amount); return true; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Capped.sol pragma solidity ^0.5.0; /** * @dev Extension of {ERC20Mintable} that adds a cap to the supply of tokens. */ contract ERC20Capped is ERC20Mintable { uint256 private _cap; /** * @dev Sets the value of the `cap`. This value is immutable, it can only be * set once during construction. */ constructor (uint256 cap) public { require(cap > 0, "ERC20Capped: cap is 0"); _cap = cap; } /** * @dev Returns the cap on the token's total supply. */ function cap() public view returns (uint256) { return _cap; } /** * @dev See {ERC20Mintable-mint}. * * Requirements: * * - `value` must not cause the total supply to go over the cap. */ function _mint(address account, uint256 value) internal { require(totalSupply().add(value) <= _cap, "ERC20Capped: cap exceeded"); super._mint(account, value); } } // File: @uniswap/v3-core/contracts/interfaces/pool/IUniswapV3PoolActions.sol // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Sets the initial price for the pool /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96 function initialize(uint160 sqrtPriceX96) external; /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling /// with 0 amount{0,1} and sending the donation amount(s) from the callback /// @param recipient The address which will receive the token0 and token1 amounts /// @param amount0 The amount of token0 to send /// @param amount1 The amount of token1 to send /// @param data Any data to be passed through to the callback function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external; /// @notice Increase the maximum number of price and liquidity observations that this pool will store /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to /// the input observationCardinalityNext. /// @param observationCardinalityNext The desired minimum number of observations for the pool to store function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external; } // File: @uniswap/v3-core/contracts/interfaces/pool/IUniswapV3PoolImmutables.sol // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface /// @return The contract address function factory() external view returns (address); /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6 /// @return The fee function fee() external view returns (uint24); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice The maximum amount of position liquidity that can use any tick in the range /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool /// @return The max amount of liquidity per tick function maxLiquidityPerTick() external view returns (uint128); } // File: @uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Callback for IUniswapV3PoolActions#swap /// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface interface IUniswapV3SwapCallback { /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata data ) external; } // File: contracts/IWETH9.sol pragma solidity ^0.5.17; // https://ethereum.stackexchange.com/questions/56466/wrapping-eth-calling-the-weth-contract contract WETH9_ { mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; function() external payable ; function deposit() external payable ; function withdraw(uint wad) external ; function totalSupply() external view returns (uint) ; function approve(address guy, uint wad) external returns (bool) ; function transfer(address dst, uint wad) external returns (bool) ; function transferFrom(address src, address dst, uint wad) external returns (bool); } // File: contracts/IHolomateDAO.sol pragma solidity ^0.5.1; /** * @title IHolomateDAO */ contract IHolomateDAO { // HoloMate NFT related function mintNFTWithID(uint256 _tokenId, address toAddress, uint256 paidEthAmount) public; function mintNFT(uint32 _numTokens, address toAddress, uint256 paidEthAmount) public; function depositNFT(uint256 _tokenId, address fromAddress) public; function pickUpNFT(uint256 _tokenId, address toAddress, uint256 paidEthAmount) public; // HoloMate Maco related function swapMacoToEth(address account, uint256 ethAmount, uint256 macoAmount) public; function swapEthToCash(address account, uint256 ethAmount, uint256 macoAmount) public; function swapEthToMaco(address account, uint256 ethAmount, uint256 macoAmount) public; function cashOutMaco(address account, uint256 ethAmount, uint256 macoAmount) public; function cashOutEth(address account, uint256 ethAmount, uint256 macoAmount) public; function depositMaco(address account, uint256 macoAmount) public; } // File: contracts/Maco.sol pragma solidity >=0.5.0; /** @title Maco: The Mate Coin @dev ERC20 Token to be used as in-world money for the Holomate.io. * Supports UniSwap to ETH and off-chain deposit/cashout. * Pre-mints locked funds for liquidity pool bootstrap, developer incentives and infrastructure coverage. * Approves payout to developers for each 10% of all minted mates, monthly infrastructre costs. * Bootstrap approved to transfer on creation. */ contract Maco is ERC20, ERC20Detailed, ERC20Mintable, ERC20Capped, Ownable, IUniswapV3SwapCallback { //address god; uint256 public gasToCashOut = 23731; uint256 public gasToCashOutToEth = 43731; uint256 public currentInfrastructureCosts = 200000 * 10**18; uint256 public percentBootstrap; uint256 public percentDevteam; uint256 public percentInfrastructureFund; uint public lastInfrastructureGrand; IUniswapV3PoolActions macoEthUniswapPool; address payable public macoEthUniswapPoolAddress; bool macoEthUniswapPoolToken0IsMaco; address public devTeamPayoutAdress; address public infrastructurePayoutAdress; uint256 public usedForInfrstructure; WETH9_ internal WETH; // DAO contract to execute L2 functions IHolomateDAO dao; /** * @dev Emited when funds for the owner gets approved to be taken from the contract **/ event OwnerFundsApproval ( uint16 eventType, uint256 indexed amount ); struct SwapData { uint8 eventType; address payable account; } /** * @dev * @param _maxSupply Max supply of coins * @param _percentBootstrap How many percent of the currency are reserved for the bootstrap * @param _percentDevteam How many percent of the currency are reserved for dev incentives * @param _percentInfrastructureFund How many percent of the currency is reserved to fund infrastcture during game pre-launch **/ constructor( uint256 _maxSupply, uint256 _percentBootstrap, uint256 _percentDevteam, uint256 _percentInfrastructureFund, address _bootstrapPayoutAdress, address payable _WETHAddress, address _daoAddress ) public ERC20Detailed("Holomate MateCoin", "MACO", 18) ERC20Capped(_maxSupply) { require(_WETHAddress != address(0), "WETH is the zero address"); require(_bootstrapPayoutAdress != address(0), "bootstrap_payout is the zero address"); WETH = WETH9_(_WETHAddress); dao = IHolomateDAO(_daoAddress); // Bootstrap is a stash of coins to provide initial liquidity to the uniswap pool and launch campiagn percentBootstrap = _percentBootstrap; // Developer team coverage percentDevteam = _percentDevteam; // Funds to cover the expenses for run the infrastructre until launch percentInfrastructureFund = _percentInfrastructureFund; usedForInfrstructure = 0; lastInfrastructureGrand = now; // Mint the pre-mine mintOwnerFundsTo((_maxSupply/100)*percentBootstrap, _bootstrapPayoutAdress); emit OwnerFundsApproval(0, (_maxSupply/100)*percentBootstrap); } /** * @dev ETH to Maco Cash */ function toMacoCash(uint160 sqrtPriceLimitX96) public payable { wrap(msg.value); WETH.approve(macoEthUniswapPoolAddress, msg.value); // → coinswap ETH/MACO // docs: https://docs.uniswap.org/reference/core/interfaces/pool/IUniswapV3PoolActions /* swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes data) external returns (int256 amount0, int256 amount1) */ macoEthUniswapPool.swap(address(this), !macoEthUniswapPoolToken0IsMaco, int256(msg.value), sqrtPriceLimitX96, swapDataToBytes(SwapData(2, msg.sender))); } /** * @dev ETH to Maco Coin */ function toMacoCoin(uint160 sqrtPriceLimitX96) public payable { wrap(msg.value); WETH.approve(macoEthUniswapPoolAddress, msg.value); // → coinswap ETH/MACO macoEthUniswapPool.swap(address(this), !macoEthUniswapPoolToken0IsMaco, int256(msg.value), sqrtPriceLimitX96, swapDataToBytes(SwapData(4, msg.sender))); } /** * @dev Maco Coin to ETH * @param _amount amount of maco to swap to eth */ function toETH(uint256 _amount, uint160 sqrtPriceLimitX96) public { require(_amount <= balanceOf(msg.sender), 'low_balance'); _approve(msg.sender, macoEthUniswapPoolAddress, _amount); // → coinswap MACO/ETH macoEthUniswapPool.swap(address(this), macoEthUniswapPoolToken0IsMaco, int256(_amount), sqrtPriceLimitX96, swapDataToBytes(SwapData(3, msg.sender))); } function wrap(uint256 ETHAmount) private { //create WETH from ETH if (ETHAmount != 0) { WETH.deposit.value(ETHAmount)(); } require(WETH.balanceOf(address(this)) >= ETHAmount, "eth_not_deposited"); } function unwrap(uint256 Amount) private { if (Amount != 0) { WETH.withdraw(Amount); } } // default method when ether is paid to the contract's address // used for the WETH withdraw callback function() external payable { } function bytesToAddress(bytes memory bys) private pure returns (address payable addr) { assembly { addr := div( mload( add(bys, 32) ), 0x1000000000000000000000000) } } // https://ethereum.stackexchange.com/questions/11246/convert-struct-to-bytes-in-solidity function swapDataFromBytes(bytes memory data) private pure returns (SwapData memory d) { d.eventType = uint8(data[20]); bytes memory adr20 = new bytes(20); for (uint i=0;i<20;i++) { adr20[i]=data[i]; } d.account = bytesToAddress(adr20); } function swapDataToBytes(SwapData memory swapData) private pure returns (bytes memory data) { uint _size = 1 + 20; bytes memory _data = new bytes(_size); _data[20] = byte(swapData.eventType); uint counter=0; bytes20 adr = bytes20(address(swapData.account)); for (uint i=0;i<20;i++) { _data[counter]=adr[i]; counter++; } return (_data); } /** * @dev Uniswap swap callback, satisfy IUniswapV3SwapCallback * https://docs.uniswap.org/reference/core/interfaces/callback/IUniswapV3SwapCallback */ function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata data ) external { require(msg.sender == macoEthUniswapPoolAddress, 'uni_sender'); SwapData memory swapData = swapDataFromBytes(data); require(swapData.eventType > 0, 'swap_data_type'); require((amount0Delta > 0) || (amount1Delta > 0), 'delta_pos'); int256 macoAmount = macoEthUniswapPoolToken0IsMaco ? amount0Delta : amount1Delta; int256 ethAmount = macoEthUniswapPoolToken0IsMaco ? amount1Delta : amount0Delta; if(macoAmount > 0) { // MACO is needed by the pool, means maco to ETH require(uint256(macoAmount) <= balanceOf(swapData.account), 'owner_MACO_bal'); transferFrom(swapData.account, msg.sender, uint256(macoAmount)); // pay the owner the ETH he got // UNWRAP WETH // https://ethereum.stackexchange.com/questions/83929/while-testing-wrap-unwrap-of-eth-to-weth-on-kovan-however-the-wrap-function-i unwrap(uint256(-ethAmount)); swapData.account.transfer( uint256(-ethAmount)); //, 'eth_to_acc'); //emit SwapEvent(3, swapData.account, uint256(ethAmount), uint256(macoAmount)); dao.swapMacoToEth(swapData.account, uint256(ethAmount), uint256(macoAmount)); } else if(ethAmount > 0) { // ETH is needed, means eth to maco cash (eventType 2) or coin (eventType 4) //require(uint256(amount0Delta) <= address(this).balance, 'contract_eth_bal'); require(WETH.balanceOf(address(this)) >= uint256(ethAmount), 'contract_weth_bal'); // Transfer WRAPPED ETH to contract WETH.transfer(macoEthUniswapPoolAddress, uint256(ethAmount)); //macoEthUniswapPoolAddress.transfer(uint256(amount0Delta));// ), 'eth_to_uni'); // pay the owner the MACO he got if(swapData.eventType == 2) { // inform the cash system that it should mint coins to the owner //emit SwapEvent(2, swapData.account, uint256(ethAmount), uint256(-macoAmount)); dao.swapEthToCash(swapData.account, uint256(ethAmount), uint256(-macoAmount)); } else { //emit SwapEvent(4, swapData.account, uint256(ethAmount), uint256(-macoAmount)); dao.swapEthToMaco(swapData.account, uint256(ethAmount), uint256(-macoAmount)); _approve(address(this), macoEthUniswapPoolAddress, uint256(-macoAmount)); transferFrom(address(this), swapData.account, uint256(-macoAmount)); } } } /** * @dev Maco Cash to Coin: Emits event to cash out deposited Maco Cash to Maco in user's wallet * @param _amount amount of maco cash to cash out */ function cashOut(uint256 _amount, bool _toEth) public payable { require(msg.value >= tx.gasprice * (_toEth ? gasToCashOutToEth : gasToCashOut), "min_gas_to_cashout"); // pay owner the gas fee it needs to call settlecashout address payable payowner = address(uint160(owner())); require(payowner.send( msg.value ), "fees_to_owner"); //→ emit event //emit SwapEvent(_toEth ? 7 : 1, msg.sender, msg.value, _amount); if(_toEth) { dao.cashOutEth(msg.sender, msg.value, _amount); } else { dao.cashOutMaco(msg.sender, msg.value, _amount); } } /** * @dev Cashes out deposited Maco Cash to Maco in user's wallet * @param _to address of the future owner of the token * @param _amount how much Maco to cash out * @param _notMinted not minted cash to reflect on blockchain */ function settleCashOut(address payable _to, uint256 _amount, bool _toEth, uint160 sqrtPriceLimitX96, uint256 _notMinted) public onlyMinter { mintFromCash(_notMinted); // must be done in any case, so it can be taken from him for uniswap or left if not swapped transferFrom(address(this), _to, _amount); if(_toEth) { // owner wanted ETH in return to Cash //require(_amount <= balanceOf(_to), 'low_balance'); _approve(_to, macoEthUniswapPoolAddress, _amount); macoEthUniswapPool.swap( address(this), macoEthUniswapPoolToken0IsMaco, int256(_amount), sqrtPriceLimitX96, swapDataToBytes(SwapData(3, _to)) ); } } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(msg.sender, recipient, amount); // if it's a cash deposit transfer if(recipient == address(this)) { _approve(address(this), owner(), amount); // signal the cash system the deposit //emit SwapEvent(5, msg.sender, 0, amount); dao.depositMaco(msg.sender, amount); } return true; } /** * @dev Mints token to one of the payout adddresses for bootstrap, infrastructure and dev team * @dev Approves the contract owner to transfer that minted tokens * @param _amount mints this amount of Maco to the contract itself * @param _to address on where to mint */ function mintOwnerFundsTo(uint256 _amount, address _to) internal onlyMinter { require(_amount > 0, "zero amount to mint"); require(_to != address(0), "mint to is zero address"); //_approve(address(this), msg.sender, _amount); //_transfer(address(this), _to, _amount); mint(_to, _amount); _approve(_to, owner(), _amount); } /** * @dev Reflects the current maco cash state to maco coin by minting to the contract itself * @dev Approves the contract owner to transfer that minted cash later * @dev Additionally approves pre-minted funds for hardware payment and dev incentives * @param _amount mints this amount of Maco to the contract itself */ function mintFromCash(uint256 _amount) public onlyMinter { uint256 totalApprove = _amount; if(_amount > 0) { mint(address(this), _amount); // approve for later cashout _approve(address(this), owner(), totalApprove); // check if a 10% milestone is broken, and if so grant the dev team 10% of their fund if( (totalSupply() * 10 / cap()) < ((totalSupply() + _amount) * 10 / cap()) ) { uint256 devFunds = cap()/100*percentDevteam/10; mintOwnerFundsTo(devFunds, devTeamPayoutAdress); emit OwnerFundsApproval(2, devFunds); } } // check for next infrastructure cost settlement if ((now >= lastInfrastructureGrand + 4 * 1 weeks) && ((usedForInfrstructure + currentInfrastructureCosts) <= (cap()/100 * percentInfrastructureFund)) ) { usedForInfrstructure += currentInfrastructureCosts; lastInfrastructureGrand = now; mintOwnerFundsTo(currentInfrastructureCosts, infrastructurePayoutAdress); emit OwnerFundsApproval(1, currentInfrastructureCosts); } } function setGasToCashOutEstimate(uint256 _cashOut, uint256 _cashOutToEth) public onlyOwner { gasToCashOut = _cashOut; gasToCashOutToEth = _cashOutToEth; } function setCurrentInfrastructureCosts(uint256 _costs) public onlyOwner { currentInfrastructureCosts = _costs; } function setUniswapPool(address payable _poolAddress) public onlyOwner { IUniswapV3PoolImmutables poolImmu = IUniswapV3PoolImmutables(_poolAddress); require((poolImmu.token0() == address(this)) || (poolImmu.token1() == address(this))); macoEthUniswapPoolToken0IsMaco = (poolImmu.token0() == address(this)); macoEthUniswapPoolAddress = _poolAddress; macoEthUniswapPool = IUniswapV3PoolActions(macoEthUniswapPoolAddress); } function setDaoContract(address _daoAddress) public onlyOwner { dao = IHolomateDAO(_daoAddress); } function setPayoutAddresses(address _devTeamPayoutAdress, address _infrastructurePayoutAdress) public onlyOwner { devTeamPayoutAdress = _devTeamPayoutAdress; infrastructurePayoutAdress = _infrastructurePayoutAdress; } /** * @dev Withdraw ether from this contract (Callable by owner) */ function withdrawETH(uint256 amount) public onlyOwner { require(amount <= address(this).balance, 'balance_low'); require(msg.sender.send(amount), 'no_send'); } /*function setGod(address _god) public onlyOwner { god = _god; }*/ } // File: contracts/L2AccountRole.sol pragma solidity ^0.5.1; contract L2AccountRole { using Roles for Roles.Role; event L2AccountAdded(address indexed account); event L2AccountRemoved(address indexed account); Roles.Role private l2accounts; constructor() public { _addL2Account(msg.sender); } modifier onlyL2Account() { require(isL2Account(msg.sender)); _; } function isL2Account(address account) public view returns (bool) { return l2accounts.has(account); } function addL2Account(address account) public onlyL2Account { _addL2Account(account); } function renounceL2Account() public { _removeL2Account(msg.sender); } function _addL2Account(address account) internal { l2accounts.add(account); emit L2AccountAdded(account); } function _removeL2Account(address account) internal { l2accounts.remove(account); emit L2AccountRemoved(account); } } // File: contracts/Holomate.sol pragma solidity ^0.5.1; /** * @title Holomate Mate ownership NFT * Holomate - a contract for mate ownership inside the Holomate.io world as non-fungible ERC721 token. * - ERC721 compliant contract to support off-chain processing of tokens * - Minting only triggers the off-chain system to mint to keep the off-chain records consistent. * - Each call from off-chain with additional data to reflect off-chain cash of the Maco currency on the blockchain. * - Supports deposit and pickup of tokens on the contract to be handled gasless off-chain. */ contract Holomate is ERC721Full, Ownable, L2AccountRole { using Strings for string; // a Maco contract and must be owned by this contract address fundTokenAddress; string myContractURI; string baseURI; // the currency used to pay Maco maco; // DAO contract to execute L2 functions IHolomateDAO dao; // public constants uint32 constant public maxSupply = 250000; // how many nft got minted uint32 public mintedSupply = 0; // public variables uint256 public gasToPickup = 93233; uint256 public gasToMint = 182000; constructor( string memory _baseURIForNFT, string memory _contractURI, address _daoAddress ) public ERC721Full("Holomate", "MATE") { dao = IHolomateDAO(_daoAddress); setBaseURI(_baseURIForNFT); setContractURI(_contractURI); } /** * @dev Emits event to mint a token to the senders adress * @param _tokenId address of the future owner of the token */ function mintNFTWithID(uint256 _tokenId) public payable { require(!_exists(_tokenId), "token_exists"); require(tx.gasprice * gasToMint <= msg.value, "min_price"); // pay owner the gas fee it needs to call mintTo address payable payowner = address(uint160(owner())); require(payowner.send( msg.value ), "fees_to_owner"); //→ emit event for off-chain listener //emit NFTEvent(1, _tokenId, msg.sender, msg.value); dao.mintNFTWithID(_tokenId, msg.sender, msg.value); } /** * @dev Emits event to mint a token to the senders adress * @param _numTokens address of the future owner of the token */ function mintNFT(uint32 _numTokens) public payable { require(tx.gasprice * gasToMint <= msg.value, "min_price"); // pay owner the gas fee it needs to call mintTo address payable payowner = address(uint160(owner())); require(payowner.send( msg.value ), "fees_to_owner"); //→ emit event for off-chain listener //emit NFTEvent(1, _tokenId, msg.sender, msg.value); dao.mintNFT(_numTokens, msg.sender, msg.value); } /** * @dev Mints a token to an address and mints unminted maco cash. * @dev Called by server * @param _tokenId Id of the token * @param _to address of the future owner of the token */ function mintTo(uint256 _tokenId, address _to, uint256 _notMinted) public onlyL2Account { require(!_exists(_tokenId), "token_exists"); _mint(_to, _tokenId); mintedSupply = mintedSupply + 1; if(_notMinted > 0) { maco.mintFromCash(_notMinted); } } /** * @dev Mints multiple tokens to an address and mints unminted maco cash. * @dev Called by server * @param _tokenIds array of ids of the token * @param _to address of the future owner of the token */ function mintMultipleTo(uint256[] memory _tokenIds, address _to, uint256 _notMinted) public onlyL2Account { for(uint i = 0; i < _tokenIds.length;i++) { require(!_exists(_tokenIds[i]), "token_exists"); _mint(_to, _tokenIds[i]); } mintedSupply = mintedSupply + uint32(_tokenIds.length); if(_notMinted > 0) { maco.mintFromCash(_notMinted); } } /** * @dev Deposits token on contract to use off-chain * @param _tokenId address of the future owner of the token */ function deposit(uint256 _tokenId) public { require(ownerOf(_tokenId) == msg.sender, "deposit_not_by_owner"); // would be nicer to have address(this) instead of owner, but then // for the release, the owner can not be approved by the contract transferFrom(msg.sender, address(this), _tokenId); // Solution with calling own contract call to change msg.sender... Holomate myself = Holomate(address(this)); myself.approve(owner(), _tokenId); //emit NFTEvent(3, _tokenId, msg.sender, 0); dao.depositNFT(_tokenId, msg.sender); } /** * @dev Emits events to release a token from off-chain storage into the blockchain * @param _tokenId address of the future owner of the token */ function pickUp(uint256 _tokenId) public payable { require(tx.gasprice * gasToPickup <= msg.value, "min_price"); // pay owner the gas fee it needs to call release address payable payowner = address(uint160(owner())); require(payowner.send( msg.value ), "fees_to_owner"); //→ emit event for off-chain listener //emit NFTEvent(2, _tokenId, msg.sender, msg.value); dao.pickUpNFT(_tokenId, msg.sender, msg.value); } /** * @dev Releases an off-chain stored token into the blockchain and mints unminted maco cash. * @dev Called by server * @param _tokenId address of the future owner of the token */ function release(uint256 _tokenId, address mateOwner, uint256 _notMinted) public onlyL2Account { transferFrom(address(this), mateOwner, _tokenId); if(_notMinted > 0) { maco.mintFromCash(_notMinted); } } function exists(uint256 _tokenId) public view returns (bool){ return _exists(_tokenId); } // NFT stuff function baseTokenURI() public view returns (string memory) { return baseURI; } function tokenURI(uint256 _tokenId) external view returns (string memory) { return Strings.strConcat(baseTokenURI(), Strings.uint2str(_tokenId)); } function setBaseURI(string memory _baseURI) public onlyOwner { baseURI = _baseURI; } // This is needed by OpenSea function contractURI() public view returns (string memory) { return myContractURI; } function setContractURI(string memory _contractURI) public onlyOwner { myContractURI = _contractURI; } // admin related stuff // ================================ function adjustGasEstimates(uint256 _mint, uint256 _pickUp) public onlyOwner { //require(msg.sender == god); gasToMint = _mint; gasToPickup = _pickUp; } function setDaoContract(address _daoAddress) public onlyOwner { dao = IHolomateDAO(_daoAddress); } function setMacoContract(address payable _fundTokenAddress) public onlyOwner { maco = Maco(_fundTokenAddress); } /** * @dev Withdraw ether from this contract (Callable by owner) */ function withdrawETH(uint256 amount) public onlyOwner { require(amount <= address(this).balance, "balance_low"); require(msg.sender.send(amount), "send_eth"); } }
Deposits token on contract to use off-chain _tokenId address of the future owner of the token/ would be nicer to have address(this) instead of owner, but then for the release, the owner can not be approved by the contract Solution with calling own contract call to change msg.sender...emit NFTEvent(3, _tokenId, msg.sender, 0);
function deposit(uint256 _tokenId) public { require(ownerOf(_tokenId) == msg.sender, "deposit_not_by_owner"); transferFrom(msg.sender, address(this), _tokenId); Holomate myself = Holomate(address(this)); myself.approve(owner(), _tokenId); dao.depositNFT(_tokenId, msg.sender); }
15,376,898
./full_match/4/0xE32A88aAc056507F2E40a261ACd99742c377B6b3/sources/contracts/PriceDiscovery.sol
Claims unlocked sYSL. Performes nothing if discovery is not finished. the contract should have Minter role for the sYSL contract
function withdrawYsl() external discoveryFinished { require(!withdrawn[_msgSender()], "User has already withdrawn sYSL"); uint256 amountDeposited = getTotalDepositedWithBonusesByUser(_msgSender()); if (amountDeposited > 0) { uint256 _lockTime = getLockTimeByUser(_msgSender()); uint256 sYSLamount = amountDeposited / getDiscoveredPrice(); IsYSL(sYSL).mintPurchased(_msgSender(), sYSLamount, _lockTime); withdrawn[_msgSender()] = true; } }
12,470,925
/** *Submitted for verification at Etherscan.io on 2021-10-29 */ // File openzeppelin-solidity/contracts/utils/introspection/[email protected] pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File openzeppelin-solidity/contracts/token/ERC721/[email protected] pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // File openzeppelin-solidity/contracts/token/ERC721/[email protected] pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // File openzeppelin-solidity/contracts/token/ERC721/extensions/[email protected] pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File openzeppelin-solidity/contracts/utils/[email protected] pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File openzeppelin-solidity/contracts/utils/[email protected] 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) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File openzeppelin-solidity/contracts/utils/[email protected] pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File openzeppelin-solidity/contracts/utils/introspection/[email protected] pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File openzeppelin-solidity/contracts/token/ERC721/[email protected] pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping (uint256 => address) private _owners; // Mapping owner address to token count mapping (address => uint256) private _balances; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. Empty by default, can be overriden * in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // File openzeppelin-solidity/contracts/token/ERC721/extensions/[email protected] pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File openzeppelin-solidity/contracts/token/ERC721/extensions/[email protected] pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File openzeppelin-solidity/contracts/access/[email protected] pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @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() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File openzeppelin-solidity/contracts/utils/math/[email protected] pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // 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 (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @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) { return a + b; } /** * @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 a - b; } /** * @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) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting 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 a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards 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). * * 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, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * 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, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File contracts/common/meta-transactions/ContentMixin.sol pragma solidity ^0.8.0; abstract contract ContextMixin { function msgSender() internal view returns (address payable sender) { if (msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. sender := and( mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff ) } } else { sender = payable(msg.sender); } return sender; } } // File contracts/common/meta-transactions/Initializable.sol pragma solidity ^0.8.0; contract Initializable { bool inited = false; modifier initializer() { require(!inited, "already inited"); _; inited = true; } } // File contracts/common/meta-transactions/EIP712Base.sol pragma solidity ^0.8.0; contract EIP712Base is Initializable { struct EIP712Domain { string name; string version; address verifyingContract; bytes32 salt; } string constant public ERC712_VERSION = "1"; bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256( bytes( "EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)" ) ); bytes32 internal domainSeperator; // supposed to be called once while initializing. // one of the contracts that inherits this contract follows proxy pattern // so it is not possible to do this in a constructor function _initializeEIP712( string memory name ) internal initializer { _setDomainSeperator(name); } function _setDomainSeperator(string memory name) internal { domainSeperator = keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(name)), keccak256(bytes(ERC712_VERSION)), address(this), bytes32(getChainId()) ) ); } function getDomainSeperator() public view returns (bytes32) { return domainSeperator; } function getChainId() public view returns (uint256) { uint256 id; assembly { id := chainid() } return id; } /** * Accept message hash and returns hash message in EIP712 compatible form * So that it can be used to recover signer from signature signed using EIP712 formatted data * https://eips.ethereum.org/EIPS/eip-712 * "\\x19" makes the encoding deterministic * "\\x01" is the version byte to make it compatible to EIP-191 */ function toTypedMessageHash(bytes32 messageHash) internal view returns (bytes32) { return keccak256( abi.encodePacked("\x19\x01", getDomainSeperator(), messageHash) ); } } // File contracts/common/meta-transactions/NativeMetaTransaction.sol pragma solidity ^0.8.0; contract NativeMetaTransaction is EIP712Base { using SafeMath for uint256; bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256( bytes( "MetaTransaction(uint256 nonce,address from,bytes functionSignature)" ) ); event MetaTransactionExecuted( address userAddress, address payable relayerAddress, bytes functionSignature ); mapping(address => uint256) nonces; /* * Meta transaction structure. * No point of including value field here as if user is doing value transfer then he has the funds to pay for gas * He should call the desired function directly in that case. */ struct MetaTransaction { uint256 nonce; address from; bytes functionSignature; } function executeMetaTransaction( address userAddress, bytes memory functionSignature, bytes32 sigR, bytes32 sigS, uint8 sigV ) public payable returns (bytes memory) { MetaTransaction memory metaTx = MetaTransaction({ nonce: nonces[userAddress], from: userAddress, functionSignature: functionSignature }); require( verify(userAddress, metaTx, sigR, sigS, sigV), "Signer and signature do not match" ); // increase nonce for user (to avoid re-use) nonces[userAddress] = nonces[userAddress].add(1); emit MetaTransactionExecuted( userAddress, payable(msg.sender), functionSignature ); // Append userAddress and relayer address at the end to extract it from calling context (bool success, bytes memory returnData) = address(this).call( abi.encodePacked(functionSignature, userAddress) ); require(success, "Function call not successful"); return returnData; } function hashMetaTransaction(MetaTransaction memory metaTx) internal pure returns (bytes32) { return keccak256( abi.encode( META_TRANSACTION_TYPEHASH, metaTx.nonce, metaTx.from, keccak256(metaTx.functionSignature) ) ); } function getNonce(address user) public view returns (uint256 nonce) { nonce = nonces[user]; } function verify( address signer, MetaTransaction memory metaTx, bytes32 sigR, bytes32 sigS, uint8 sigV ) internal view returns (bool) { require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER"); return signer == ecrecover( toTypedMessageHash(hashMetaTransaction(metaTx)), sigV, sigR, sigS ); } } // File contracts/assets/ERC721TradableV2.sol pragma solidity ^0.8.0; contract ProxyRegistry { mapping(address => address) public proxies; } /** * @title ERC721Tradable * ERC721Tradable - ERC721 contract that whitelists a trading address, and has minting functionality. */ abstract contract ERC721TradableV2 is ContextMixin, ERC721Enumerable, NativeMetaTransaction, Ownable { using SafeMath for uint256; address openseaProxyAddress; address elementProxyAddress; mapping(address => bool) public factoryAddresses; uint256 private _currentTokenId = 0; uint256 public maxSupply = 0; constructor( string memory _name, string memory _symbol, uint256 _maxSupply, address _elementProxyRegistry, address _openseaProxyRegistry ) ERC721(_name, _symbol) { maxSupply = _maxSupply; elementProxyAddress = _elementProxyRegistry; openseaProxyAddress = _openseaProxyRegistry; _initializeEIP712(_name); } function baseTokenURI() virtual public view returns (string memory); function tokenURI(uint256 _tokenId) override public view returns (string memory) { return string(abi.encodePacked(baseTokenURI(), Strings.toString(_tokenId))); } /** * Override isApprovedForAll to whitelist user's Element proxy accounts to enable gas-less listings. */ function isApprovedForAll(address owner, address operator) override public view returns (bool) { // Whitelist Element's proxy contract for easy trading. ProxyRegistry elementProxy = ProxyRegistry(elementProxyAddress); if (address(elementProxy.proxies(owner)) == operator) { return true; } // Whitelist Opensea's proxy contract for easy trading. ProxyRegistry openseaProxy = ProxyRegistry(openseaProxyAddress); if (address(openseaProxy.proxies(owner)) == operator) { return true; } return super.isApprovedForAll(owner, operator); } /** * This is used instead of msg.sender as transactions won't be sent by the original token owner, but by Element. */ function _msgSender() internal override view returns (address sender) { return ContextMixin.msgSender(); } /** * add factory addrss */ function addFactoryAddress(address factoryAddr) external onlyOwner { factoryAddresses[factoryAddr] = true; } /** * remove factory addrss */ function removeFactoryAddress(address factoryAddr) external onlyOwner { delete factoryAddresses[factoryAddr]; } /** * add factory addrss */ function setMaxSupply(uint256 _maxSupply) external onlyOwner { require(_maxSupply < maxSupply, "out of max supply"); maxSupply = _maxSupply; } } // File @openzeppelin/contracts/security/[email protected] pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File @openzeppelin/contracts/utils/cryptography/[email protected] pragma solidity ^0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } } else if (signature.length == 64) { // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { let vs := mload(add(signature, 0x40)) r := mload(add(signature, 0x20)) s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } } else { revert("ECDSA: invalid signature length"); } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // File @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ 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); } // File contracts/assets/MaskhumanV2.sol pragma solidity 0.8.9; contract MaskhumanV2 is ERC721TradableV2, ReentrancyGuard { using ECDSA for bytes32; uint256 private maxPresale = 100; uint256 private _presaleNum = 0; uint256 private _presalePrice = 0; //0ETH uint256 private _presaleQty = 1; mapping(address => bool) private _usedAddresses; address private _signerAddress = 0x32f4B63A46c1D12AD82cABC778D75aBF9889821a; //Metasaur Signer uint256 public pricePerToken = 66000000000000000; //0.066ETH uint256 public saleSupply = 1100; uint256 private publicSaleMaxSupply = 1000; uint256 private publicSaleNum = 0; bool public saleLive = true; bool public presaleLive = true; string public baseURI = "https://api.maskhuman.com/v2/token/"; string public contractURI = "https://api.maskhuman.com/v2/contract"; //triggers on mint event event MintInfo(uint256 indexed tokenIdStart, address indexed sender, address indexed to, uint256 qty, uint256 value); constructor(address _elementProxyRegistry, address _opensaeProxyRegistry) ERC721TradableV2("MaskHuman()", "MHN", 10000, _elementProxyRegistry, _opensaeProxyRegistry) {} function baseTokenURI() override public view returns (string memory) { return baseURI; } function setBaseTokenURI(string memory _baseURI) public onlyOwner { baseURI = _baseURI; } function getContractURI() public view returns (string memory) { return contractURI; } function setContractURI(string memory _contractURI) public onlyOwner { contractURI = _contractURI; } function batchMint(uint256 _qty, address _to) private { uint256 newTokenId = totalSupply() + 1; require(newTokenId <= saleSupply, "out of stock"); for (uint256 i = 0; i < _qty; i++) { _mint(_to, newTokenId + i); } emit MintInfo(newTokenId, _msgSender(), _to, _qty, msg.value); } /** * @dev Mints a token to an address with a tokenURI. * @param _to address of the future owner of the token */ function mintTo(uint256 _qty, address _to) public { require(factoryAddresses[_msgSender()], "not factory"); batchMint(_qty, _to); } // Public buy function publicBuy(uint256 qty) external payable nonReentrant { require(saleLive, "not live "); require(qty <= 20, "no more than 20"); require(pricePerToken * qty == msg.value, "exact amount needed"); require(publicSaleNum + qty <= publicSaleMaxSupply, "public buy out of stock"); publicSaleNum = publicSaleNum + qty; batchMint(qty, _msgSender()); } // Presale buy function presaleBuy(bytes memory sig) external payable nonReentrant { require(presaleLive, "presale not live"); require(matchAddressSigner(msg.sender, sig), "no direct mint"); require(!_usedAddresses[msg.sender], "account already used"); require(_presalePrice * _presaleQty == msg.value, "exact amount needed"); require(_presaleNum + _presaleQty <= maxPresale, "presale out of stock"); _usedAddresses[msg.sender] = true; _presaleNum = _presaleNum + _presaleQty; batchMint(_presaleQty, _msgSender()); } // admin can mint them for giveaways, airdrops etc function adminMint(uint256 qty, address to) public onlyOwner { require(qty > 0, "minimum 1 token"); batchMint(qty, to); } //------------------------------------ //----------- signing code ----------- //------------------------------------ function setSignerAddress(address addr) external onlyOwner { _signerAddress = addr; } function hashSender(address sender) private pure returns (bytes32) { return keccak256( abi.encodePacked("\x19Ethereum Signed Message:\n32", keccak256(abi.encodePacked(sender))) ); } function matchAddressSigner(address sender, bytes memory signature) private view returns (bool) { // check sender bytes32 hash = hashSender(sender); return _signerAddress == hash.recover(signature); } function checkSignature(address sender, bytes memory signature) external view returns (bool) { // check sender bytes32 hash = hashSender(sender); return _signerAddress == hash.recover(signature) && !_usedAddresses[msg.sender]; } //---------------------------------- //----------- other code ----------- //---------------------------------- function toggleSaleStatus() external onlyOwner { saleLive = !saleLive; } function togglePresaleStatus() external onlyOwner { presaleLive = !presaleLive; } function changePrice(uint256 newPrice) external onlyOwner { pricePerToken = newPrice; } function changeMaxPresale(uint256 newMaxPresale) external onlyOwner { maxPresale = newMaxPresale; } function changeMaxPublicBuy(uint256 newMaxPublicBuy) external onlyOwner { publicSaleMaxSupply = newMaxPublicBuy; } function changePresaleQty(uint256 newQty) external onlyOwner { _presaleQty = newQty; } function changePresalePrice(uint256 newPrice) external onlyOwner { _presalePrice = newPrice; } /** * add factory addrss */ function changeSaleSupply(uint256 _saleSupply) external onlyOwner { require(_saleSupply <= maxSupply, "out of max supply"); saleSupply = _saleSupply; } function withdrawEarnings() public onlyOwner { payable(msg.sender).transfer(address(this).balance); } function reclaimERC20(IERC20 erc20Token) public onlyOwner { erc20Token.transfer(msg.sender, erc20Token.balanceOf(address(this))); } }
add factory addrss/
function setMaxSupply(uint256 _maxSupply) external onlyOwner { require(_maxSupply < maxSupply, "out of max supply"); maxSupply = _maxSupply; }
2,451,060
./partial_match/1/0x54B3bF14FfBeFDA3F67D3a07bE0430f4D33952F6/sources/RollTigerCasino.sol
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; } bool public _cexEnabled = true; mapping (address => bool) public _isCEX;
2,738,161
./partial_match/1/0x712A0d958241830da631Acd22Ac3164DF2D1260c/sources/PerpetualMarkets.sol
Calculate the maximum wallet amount based on the total supply and the maximum wallet percentage Check if the transaction is within the maximum wallet limit
function _transfer( address _from, address _to, uint256 _amount ) internal virtual override { require(_from != address(0), "transfer from address zero"); require(_to != address(0), "transfer to address zero"); require(_amount > 0, "Transfer amount must be greater than zero"); uint256 maxWalletAmount = _totalSupply * maxWalletPercentage / 100; if (!whitelisted[_from] && !whitelisted[_to] && _to != address(0) && _to != address(this) && _to != pairAddress) { require(balanceOf(_to) + _amount <= maxWalletAmount, "Exceeds maximum wallet amount"); } uint256 toTransfer = _takeTax(_from, _to, _amount); bool canSwap = balanceOf(address(this)) >= swapTokensAtAmount; if (!whitelisted[_from] && !whitelisted[_to]) { require(tradingEnabled, "Trading not active"); if (pairAddress == _to && swapAndLiquifyEnabled && canSwap && !isSwapping) { internalSwap(); } } super._transfer(_from, _to, toTransfer); }
11,028,912
./full_match/80001/0x18B0cC56c8F2da6fb611a4F19762ad906d92357c/sources/contracts/Gigble.sol
Function to complete a gig
function completeGig(uint256 _gigId) public { Gig storage gig = gigs[_gigId]; require(!gig.isCompleted, "Gig already completed"); require(gig.isAccepted, "Gig must be accepted before completion"); require(gig.buyer == msg.sender, "Only the buyer can complete the gig"); gig.isCompleted = true; escrows[_gigId][gig.seller] = 0; emit GigCompleted(_gigId); gig.seller.transfer(gig.price); }
5,604,307
pragma solidity >=0.7.0; import "./ERC721.sol"; import "./Ownable.sol"; import "./IMintedBeforeReveal.sol"; contract Picklz is ERC721, Ownable, IMintedBeforeReveal { // This is the original provenance record of all Picklz in existence at the time. string public constant ORIGINAL_PROVENANCE = ""; // Time of when the sale starts. uint256 public constant SALE_START_TIMESTAMP = 1617202800; // Time after which the Picklz are randomized and revealed 7 days from initial launch). uint256 public constant REVEAL_TIMESTAMP = SALE_START_TIMESTAMP + (86400 * 7); // Maximum amount of Picklz in existance. uint256 public constant MAX_PICKLZ_SUPPLY = 4269; // Truth. string public constant R = "Some of our pickles are looking for love, others just want to watch the world burn."; // The block in which the starting index was created. uint256 public startingIndexBlock; // The index of the item that will be #1. uint256 public startingIndex; mapping (uint256 => bool) private _mintedBeforeReveal; constructor(string memory name, string memory symbol, string memory baseURI) ERC721(name, symbol) { _setBaseURI(baseURI); } function isMintedBeforeReveal(uint256 index) public view override returns (bool) { return _mintedBeforeReveal[index]; } function getPicklzMaxAmount() public view returns (uint256) { require(block.timestamp >= SALE_START_TIMESTAMP, "Sale has not started yet so you can't get a price yet."); require(totalSupply() < MAX_PICKLZ_SUPPLY, "Sale has already ended, no more Picklz left to sell."); uint currentSupply = totalSupply(); if (currentSupply >= 201) { return 20; // After 200, do it per 20. } else { return 5; // First 200 can only be bought per 5. } } function getPicklzPrice() public view returns (uint256) { require(block.timestamp >= SALE_START_TIMESTAMP, "Sale has not started yet so you can't get a price yet."); require(totalSupply() < MAX_PICKLZ_SUPPLY, "Sale has already ended, no more Picklz left to sell."); uint currentSupply = totalSupply(); if (currentSupply > 4200) { return 690000000000000000; // 4200-4269: 0.69 ETH } else if (currentSupply > 4000) { return 500000000000000000; // 4000-4200: 0.50 ETH } else if (currentSupply > 3200) { return 400000000000000000; // 3200-4000: 0.40 ETH } else if (currentSupply > 2200) { return 300000000000000000; // 2200-3200: 0.30 ETH } else if (currentSupply > 1200) { return 200000000000000000; // 1200-2200: 0.20 ETH } else if (currentSupply > 200) { return 100000000000000000; // 200-1200: 0.10 ETH } else { return 50000000000000000; // 0 - 200: 0.05 ETH } } function mintAPicklz(uint256 numberOfPicklz) public payable { // Some exceptions that need to be handled. require(totalSupply() < MAX_PICKLZ_SUPPLY, "Sale has already ended."); require(numberOfPicklz > 0, "You cannot mint 0 Picklz."); require(numberOfPicklz <= getPicklzMaxAmount(), "You are not allowed to buy this many Picklz at once in this price tier."); require(SafeMath.add(totalSupply(), numberOfPicklz) <= MAX_PICKLZ_SUPPLY, "Exceeds maximum Picklz supply. Please try to mint less Picklz."); require(SafeMath.mul(getPicklzPrice(), numberOfPicklz) == msg.value, "Amount of Ether sent is not correct."); for (uint i = 0; i < numberOfPicklz; i++) { uint mintIndex = totalSupply(); if (block.timestamp < REVEAL_TIMESTAMP) { _mintedBeforeReveal[mintIndex] = true; } _safeMint(msg.sender, mintIndex); } // Source of randomness. Theoretical miner withhold manipulation possible but should be sufficient in a pragmatic sense // Set the starting block index when the sale concludes either time-wise or the supply runs out. if (startingIndexBlock == 0 && (totalSupply() == MAX_PICKLZ_SUPPLY || block.timestamp >= REVEAL_TIMESTAMP)) { startingIndexBlock = block.number; } } /** * @dev Finalize starting index */ function finalizeStartingIndex() public { require(startingIndex == 0, "Starting index is already set"); require(startingIndexBlock != 0, "Starting index block must be set"); startingIndex = uint(blockhash(startingIndexBlock)) % MAX_PICKLZ_SUPPLY; // Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes). if (SafeMath.sub(block.number, startingIndexBlock) > 255) { startingIndex = uint(blockhash(block.number-1)) % MAX_PICKLZ_SUPPLY; } // Prevent default sequence because that would be a bit boring. if (startingIndex == 0) { startingIndex = SafeMath.add(startingIndex, 1); } } /** * @dev Withdraw ether from this contract (Callable by owner only) */ function withdraw() onlyOwner public { uint balance = address(this).balance; msg.sender.transfer(balance); } /** * @dev Changes the base URI if we want to move things in the future (Callable by owner only) */ function changeBaseURI(string memory baseURI) onlyOwner public { _setBaseURI(baseURI); } /** * @dev Reserved for people who helped this project and giveaways. Max 10 */ function reserveGiveaway(uint256 numPicklz) public onlyOwner { uint currentSupply = totalSupply(); require(totalSupply() + numPicklz <= 10, "Exceeded giveaway supply"); uint256 index; // Reserved for people who helped this project and giveaways for (index = 0; index < numPicklz; index++) { _safeMint(owner(), currentSupply + index); } } }
Reserved for people who helped this project and giveaways. Max 10/ Reserved for people who helped this project and giveaways
function reserveGiveaway(uint256 numPicklz) public onlyOwner { uint currentSupply = totalSupply(); require(totalSupply() + numPicklz <= 10, "Exceeded giveaway supply"); uint256 index; for (index = 0; index < numPicklz; index++) { _safeMint(owner(), currentSupply + index); } }
13,862,014
// "SPDX-License-Identifier: UNLICENSED" pragma solidity ^0.8.0; import 'openzeppelin-solidity/contracts/utils/math/SafeMath.sol'; import 'openzeppelin-solidity/contracts/utils/Context.sol'; import 'openzeppelin-solidity/contracts/access/Ownable.sol'; import 'openzeppelin-solidity/contracts/token/ERC20/utils/SafeERC20.sol'; import './interfaces/IUniV2OptimizerFactory.sol'; import './interfaces/IStakingRewards.sol'; import './interfaces/IUniswapV2Router.sol'; import './interfaces/IUniswapV2Pair.sol'; import './interfaces/IAmmZap.sol'; import './interfaces/ITreasury.sol'; contract UniV2Optimizer is Ownable { using SafeERC20 for IERC20; using SafeMath for uint256; uint256 constant MAX_INT = 2**256 - 1; /** * @dev Tokens addresses */ address public tokenA; address public tokenB; address public staking; address public reward; /** * @dev Interfacing contracts addresses */ address public stakingRewardAddr; address public uniV2RouterAddr; address public ammZapAddr; address public feeCollector; address public parentFactory; uint256 public staked = 0; /** * @dev Initializes the strategy for the given protocol */ constructor( address _stakingRewardAddr, address _uniV2RouterAddr, address _ammZapAddr, address _feeCollector ) { stakingRewardAddr = _stakingRewardAddr; uniV2RouterAddr = _uniV2RouterAddr; ammZapAddr = _ammZapAddr; feeCollector = _feeCollector; parentFactory = msg.sender; staking = IStakingRewards(stakingRewardAddr).stakingToken(); reward = IStakingRewards(stakingRewardAddr).rewardsToken(); tokenA = IUniswapV2Pair(staking).token0(); tokenB = IUniswapV2Pair(staking).token1(); IERC20(staking).safeApprove(_stakingRewardAddr, 0); IERC20(staking).safeApprove(_stakingRewardAddr, MAX_INT); IERC20(reward).safeApprove(_uniV2RouterAddr, 0); IERC20(reward).safeApprove(_uniV2RouterAddr, MAX_INT); IERC20(tokenA).safeApprove(_uniV2RouterAddr, 0); IERC20(tokenA).safeApprove(_uniV2RouterAddr, MAX_INT); IERC20(tokenB).safeApprove(_uniV2RouterAddr, 0); IERC20(tokenB).safeApprove(_uniV2RouterAddr, MAX_INT); } function zapAndStake(address _tokenToZap, uint256 _amountToZap) external onlyOwner { require(IERC20(_tokenToZap).balanceOf(address(msg.sender)) >= _amountToZap); IERC20(_tokenToZap).safeTransferFrom(msg.sender, address(this), _amountToZap); IERC20(_tokenToZap).safeApprove(ammZapAddr, _amountToZap); IAmmZap(ammZapAddr).zap(_tokenToZap, tokenA, tokenB, _amountToZap); _stakeAll(); } function stake(uint256 _amount) external onlyOwner { require(IERC20(staking).balanceOf(address(msg.sender)) >= _amount); IERC20(staking).safeTransferFrom(msg.sender, address(this), _amount); _stakeAll(); } function withdraw(uint256 _amount) external onlyOwner { _claimReward(); IStakingRewards(stakingRewardAddr).withdraw(_amount); staked = staked.sub(_amount); IERC20(staking).safeTransfer(msg.sender, _amount); } function reinvest(address _desiredToken) external onlyOwner { require(_desiredToken != reward, "Reward token is already the expected token"); _claimReward(); if(IERC20(reward).balanceOf(address(this)) > 0){ address[] memory rewardToDesiredToken = new address[](2); rewardToDesiredToken[0] = reward; rewardToDesiredToken[1] = _desiredToken; IUniswapV2Router(uniV2RouterAddr).swapExactTokensForTokens( IERC20(reward).balanceOf(address(this)), 0, rewardToDesiredToken, address(this), block.timestamp.add(600) ); } } function harvest() external onlyOwner { _claimReward(); uint256 amountToZap = IERC20(reward).balanceOf(address(this)); IERC20(reward).safeApprove(ammZapAddr, amountToZap); IAmmZap(ammZapAddr).zap(reward, tokenA, tokenB, amountToZap); _stakeAll(); } function exitAvalanche() external onlyOwner { _claimReward(); IStakingRewards(stakingRewardAddr).exit(); staked = 0; uint256 amountToZap = IERC20(reward).balanceOf(address(this)); IERC20(reward).safeApprove(ammZapAddr, amountToZap); IAmmZap(ammZapAddr).zap(reward, tokenA, tokenB, amountToZap); if(IERC20(staking).balanceOf(address(this)) > 0){ IERC20(staking).safeTransfer(msg.sender, IERC20(staking).balanceOf(address(this))); } if(IERC20(tokenA).balanceOf(address(this)) > 0){ IERC20(tokenA).safeTransfer(msg.sender, IERC20(tokenA).balanceOf(address(this))); } if(IERC20(tokenB).balanceOf(address(this)) > 0){ IERC20(tokenB).safeTransfer(msg.sender, IERC20(tokenB).balanceOf(address(this))); } if(IERC20(reward).balanceOf(address(this)) > 0){ IERC20(reward).safeTransfer(msg.sender, IERC20(reward).balanceOf(address(this))); } } function recoverERC20(address _ERC20) external onlyOwner { if(IERC20(_ERC20).balanceOf(address(this)) > 0){ IERC20(_ERC20).safeTransfer(msg.sender, IERC20(_ERC20).balanceOf(address(this))); } } function getPendingRewards() external view returns(uint256) { return IStakingRewards(stakingRewardAddr).earned(address(this)); } function _stakeAll() internal { staked = staked.add(IERC20(staking).balanceOf(address(this))); IStakingRewards(stakingRewardAddr).stake(IERC20(staking).balanceOf(address(this))); } function _claimReward() internal { if(this.getPendingRewards() > 0) { IStakingRewards(stakingRewardAddr).getReward(); _payPerformanceFees(); } } function _payPerformanceFees() internal { // exclude the FeeCollectors from paying performance fees if(feeCollector != address(0)){ address treasury = IUniV2OptimizerFactory(parentFactory).treasury(); uint256 rewardBalance = IERC20(reward).balanceOf(address(this)); // Performance Fees = 10 % of the yield uint256 performanceFees = rewardBalance.div(10); // Performance Fees sent to the FeeCollector IERC20(reward).safeTransfer(feeCollector, performanceFees); ITreasury(treasury).compoundFeeCollector(feeCollector); } } }
exclude the FeeCollectors from paying performance fees Performance Fees = 10 % of the yield Performance Fees sent to the FeeCollector
function _payPerformanceFees() internal { if(feeCollector != address(0)){ address treasury = IUniV2OptimizerFactory(parentFactory).treasury(); uint256 rewardBalance = IERC20(reward).balanceOf(address(this)); uint256 performanceFees = rewardBalance.div(10); IERC20(reward).safeTransfer(feeCollector, performanceFees); ITreasury(treasury).compoundFeeCollector(feeCollector); } }
1,072,128
// RUN: --target substrate --emit cfg contract deadstorage { int a; // simple test. Two references to "a" must result in a single loadstorage // BEGIN-CHECK: deadstorage::function::test1 function test1() public view returns (int) { return a + a; } // CHECK: load storage slot(uint256 0) ty:int256 // NOT-CHECK: load storage slot(uint256 0) ty:int256 // Two references to "a" with a write to A in between must result in two loadstorage // BEGIN-CHECK: deadstorage::function::test2 function test2() public returns (int) { int x = a; a = 2; x += a; return x; } // CHECK: load storage slot(uint256 0) ty:int256 // CHECK: load storage slot(uint256 0) ty:int256 // make sure that reachable stores are not eliminated // BEGIN-CHECK: deadstorage::function::test3 function test3(bool c) public { a = 1; if (c) { a = 2; } } // CHECK: store storage slot(uint256 0) // CHECK: store storage slot(uint256 0) // two successive stores are redundant // BEGIN-CHECK: deadstorage::function::test4 int b; function test4() public returns (int) { b = 511; b = 512; return b; } // CHECK: store storage slot(uint256 1) // NOT-CHECK: store storage slot(uint256 1) // stores in a previous block are always redundant // BEGIN-CHECK: deadstorage::function::test5 int test5var; function test5(bool c) public returns (int) { if (c) { test5var = 1; } else { test5var = 2; } test5var = 3; return test5var; } // CHECK: store storage slot(uint256 2) // NOT-CHECK: store storage slot(uint256 2) // BEGIN-CHECK: deadstorage::function::test6 // store/load are not merged yet. Make sure that we have a store before a load int test6var; function test6() public returns (int) { test6var = 1; int f = test6var; test6var = 2; return test6var + f; } // CHECK: store storage slot(uint256 3) // CHECK: store storage slot(uint256 3) // BEGIN-CHECK: deadstorage::function::test7 // storage should be flushed before function call int test7var; function test7() public returns (int) { test7var = 1; test6(); test7var = 2; return test7var; } // CHECK: store storage slot(uint256 4) // CHECK: store storage slot(uint256 4) // BEGIN-CHECK: deadstorage::function::test8 // clear before store is redundant int test8var; function test8() public { delete test8var; test8var = 2; } // NOT-CHECK: clear storage slot(uint256 5) // CHECK: store storage slot(uint256 5) // BEGIN-CHECK: deadstorage::function::test9 // push should make both load/stores not redundant bytes test9var; function test9() public returns (bytes){ test9var = "a"; bytes f = test9var; test9var.push(hex"01"); f = test9var; test9var = "c"; return f; } // CHECK: store storage slot(uint256 6) // CHECK: load storage slot(uint256 6) // CHECK: push storage slot(uint256 6) // CHECK: load storage slot(uint256 6) // CHECK: store storage slot(uint256 6) // BEGIN-CHECK: deadstorage::function::test10 // pop should make both load/stores not redundant bytes test10var; function test10() public returns (bytes) { test10var = "a"; bytes f = test10var; test10var.pop(); f = test10var; test10var = "c"; return f; } // CHECK: store storage slot(uint256 7) // CHECK: load storage slot(uint256 7) // CHECK: pop storage ty:bytes1 slot(uint256 7) // CHECK: load storage slot(uint256 7) // CHECK: store storage slot(uint256 7) // BEGIN-CHECK: deadstorage::function::test11 // some array tests int[11] test11var; function test11(uint index, uint index2) public view returns (int) { return test11var[index] + test11var[index2]; } // CHECK: load storage slot((uint256 8 // CHECK: load storage slot((uint256 8 // BEGIN-CHECK: deadstorage::function::test12 // one load needed for this int[11] test12var; function test12(uint index) public view returns (int) { return test12var[index] + test12var[index]; } // CHECK: load storage slot((uint256 19 // NOT-CHECK: load storage slot((uint256 19 }
Two references to "a" with a write to A in between must result in two loadstorage BEGIN-CHECK: deadstorage::function::test2
function test2() public returns (int) { int x = a; a = 2; x += a; return x; }
12,942,426
// SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; /** * @title Voting * @author groupe 5 : yann, louisplessis, oudom * @notice Défi 1 * @dev administrateur du vote = owner */ contract Voting { // Les différentes phases du vote se succèdant enum WorkflowStatus { RegisteringVoters, // 0 ProposalsRegistrationStarted, // 1 ProposalsRegistrationEnded, // 2 VotingSessionStarted, // 3 VotingSessionEnded, // 4 VotesTallied // 5 } event VoterRegistered(address voterAddress); event ProposalsRegistrationStarted(); event ProposalsRegistrationEnded(); event ProposalRegistered(uint proposalId); event VotingSessionStarted(); event VotingSessionEnded(); event Voted(address voter, uint proposalId); event VotesTallied(); event WorkflowStatusChange(WorkflowStatus previousStatus, WorkflowStatus newStatus); struct Voter { bool isRegistered; bool hasVoted; bool hasProposed; // amélioration par rapport à l'énoncé uint votedProposalId; } struct Proposal { string description; uint voteCount; } // status du contrat WorkflowStatus public workflowStatus; mapping (address => Voter) private whitelist; // pour enregistrer les propositions Proposal[] private proposals; // pour get all users in whitelist, impossible de return un mapping? address[] private whitelistArray; // index de la proposition ayant reçu le plus de votes, commence à 0 uint public winningProposalId; address private admin; /** * @notice Initialise le deployer comme étant l'admin. */ constructor () public { admin = msg.sender; } modifier onlyAdmin() { require(admin == msg.sender, "Admin requis"); _; } modifier isWhitelisted() { require(whitelist[msg.sender].isRegistered, "Pas inscrit"); _; } /** * @notice Retourne l'adresse de l'admin/owner. */ function owner() external view returns(address) { return admin; } /** * @notice L'administrateur du vote enregistre une liste blanche d'électeurs identifiés par leur adresse Ethereum. */ function register(address addr) external onlyAdmin { require(workflowStatus == WorkflowStatus.RegisteringVoters, "Enregistrement des electeurs termine"); require(!whitelist[addr].isRegistered, "Adresse deja enregistree !"); whitelistArray.push(addr); whitelist[addr] = Voter(true, false, false, 0); emit VoterRegistered(addr); } /** * @notice L'administrateur du vote commence la session d'enregistrement de la proposition. */ function startProposalsRegistration() external onlyAdmin { require(workflowStatus == WorkflowStatus.RegisteringVoters, "Enregistrement des propositions termine"); workflowStatus = WorkflowStatus.ProposalsRegistrationStarted; emit ProposalsRegistrationStarted(); emit WorkflowStatusChange(WorkflowStatus.RegisteringVoters, WorkflowStatus.ProposalsRegistrationStarted); } /** * @notice Permet de récupérer la liste des propositions. */ function getProposal() external view returns (Proposal[] memory){ require(workflowStatus != WorkflowStatus.RegisteringVoters, "Enregistrement des propositions pas en cours"); return proposals; } /** * @notice Permet de récupérer la liste des propositions. */ function getWhitelist() external view returns (address[] memory){ return whitelistArray; } function getWorkflowStatus() external view returns (WorkflowStatus) { return workflowStatus; } /** * @notice Les électeurs inscrits sont autorisés à enregistrer leurs propositions pendant que la session d'enregistrement est active. */ function registerProposal(string memory description) external isWhitelisted { require(workflowStatus == WorkflowStatus.ProposalsRegistrationStarted, "Enregistrement des propositions pas en cours"); require(!whitelist[msg.sender].hasProposed, "Proposition deja faite"); proposals.push(Proposal(description, 0)); whitelist[msg.sender].hasProposed = true; emit ProposalRegistered(proposals.length-1); } /** * @notice L'administrateur de vote met fin à la session d'enregistrement des propositions. */ function endProposalsRegistration() external onlyAdmin { require(workflowStatus == WorkflowStatus.ProposalsRegistrationStarted, "Enregistrement des propositions pas en cours"); workflowStatus = WorkflowStatus.ProposalsRegistrationEnded; emit ProposalsRegistrationEnded(); emit WorkflowStatusChange(WorkflowStatus.ProposalsRegistrationStarted, WorkflowStatus.ProposalsRegistrationEnded); } /** * @notice L'administrateur du vote commence la session de vote. */ function startVotingSession() external onlyAdmin { require(workflowStatus == WorkflowStatus.ProposalsRegistrationEnded, "Enregistrement des propositions pas terminee"); workflowStatus = WorkflowStatus.VotingSessionStarted; emit VotingSessionStarted(); emit WorkflowStatusChange(WorkflowStatus.ProposalsRegistrationEnded, WorkflowStatus.VotingSessionStarted); } /** * @notice Les électeurs inscrits votent pour leurs propositions préférées. */ function vote(uint proposalId) external isWhitelisted { require(workflowStatus == WorkflowStatus.VotingSessionStarted, "Vote pas en cours"); require(!whitelist[msg.sender].hasVoted, "Deja vote"); require(proposalId < proposals.length , "Id de proposition invalide"); whitelist[msg.sender].votedProposalId = proposalId; whitelist[msg.sender].hasVoted = true; proposals[proposalId].voteCount++; emit Voted(msg.sender, proposalId); } /** * @notice L'administrateur du vote met fin à la session de vote. */ function endVotingSession() external onlyAdmin { require(workflowStatus == WorkflowStatus.VotingSessionStarted, "Vote pas en cours"); workflowStatus = WorkflowStatus.VotingSessionEnded; emit VotingSessionEnded(); emit WorkflowStatusChange(WorkflowStatus.VotingSessionStarted, WorkflowStatus.VotingSessionEnded); } /** * @notice L'administrateur du vote comptabilise les votes. */ function tally() external onlyAdmin { require(workflowStatus == WorkflowStatus.VotingSessionEnded, "Vote pas termine"); uint maxVoteCount = 0; uint winningProposalIdLocal = 0; for (uint i = 0; i < proposals.length; i++) { if (proposals[i].voteCount > maxVoteCount) { winningProposalIdLocal = i; maxVoteCount = proposals[i].voteCount; } } winningProposalId = winningProposalIdLocal; workflowStatus = WorkflowStatus.VotesTallied; emit VotesTallied(); emit WorkflowStatusChange(WorkflowStatus.VotingSessionEnded, WorkflowStatus.VotesTallied); } }
Les électeurs inscrits votent pour leurs propositions préférées./
function vote(uint proposalId) external isWhitelisted { require(workflowStatus == WorkflowStatus.VotingSessionStarted, "Vote pas en cours"); require(!whitelist[msg.sender].hasVoted, "Deja vote"); require(proposalId < proposals.length , "Id de proposition invalide"); whitelist[msg.sender].votedProposalId = proposalId; whitelist[msg.sender].hasVoted = true; proposals[proposalId].voteCount++; emit Voted(msg.sender, proposalId); }
12,677,432
./full_match/80001/0x31674930dDb4e3A1d06BF93B10d09bEb67171028/sources/contracts/upgradeable/tokens/Vehicles/VehiclesV3.sol
solhint-disable-next-line func-name-mixedcase, no-empty-blocks, ordering
function __VehiclesV3_init__unchained(string calldata _ogExoskeletonImageUrl) internal onlyInitializing { ogExoskeletonImageUrl = _ogExoskeletonImageUrl; }
9,521,688
/** *Submitted for verification at Etherscan.io on 2022-03-13 */ // SPDX-License-Identifier: GPL-3.0 // OpenZeppelin Contracts v4.4.0 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [////IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * ////IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol) /** * @dev Interface of the ERC20 standard as defined in the EIP. */ 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); } // https://docs.synthetix.io/contracts/source/contracts/owned contract Owned { address public owner; address public nominatedOwner; constructor(address _owner) { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } function acceptOwnership() external { require( msg.sender == nominatedOwner, "You must be nominated before you can accept ownership" ); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { _onlyOwner(); _; } function _onlyOwner() private view { require( msg.sender == owner, "Only the contract owner may perform this action" ); } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } // Allows anyone to claim a token if they exist in a merkle root. interface IMerkleDistributor { // Returns the address of the token distributed by this contract. function token() external view returns (address); // Returns the merkle root of the merkle tree containing account balances available to claim. function merkleRoot() external view returns (bytes32); // Returns true if the index has been marked claimed. function isClaimed(uint256 index) external view returns (bool); // Claim the given amount of the token to the given address. Reverts if the inputs are invalid. function claim( uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof ) external; // This event is triggered whenever a call to #claim succeeds. event Claimed(uint256 index, address account, uint256 amount); } // OpenZeppelin Contracts v4.4.0 (utils/cryptography/MerkleProof.sol) /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } return computedHash; } } // OpenZeppelin Contracts v4.4.0 (utils/math/SafeMath.sol) // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // 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 (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @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) { return a + b; } /** * @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 a - b; } /** * @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) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting 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 a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting 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. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * 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, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // OpenZeppelin Contracts v4.4.0 (token/ERC20/utils/SafeERC20.sol) ////import "../IERC20.sol"; ////import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) 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. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } ////import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; ////import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; ////import "@openzeppelin/contracts/utils/math/SafeMath.sol"; ////import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; ////import "../interfaces/IMerkleDistributor.sol"; ////import "../common/Owned.sol"; contract MerkleDistributor is IMerkleDistributor, Owned { using SafeMath for uint256; using SafeERC20 for IERC20; address public immutable override token; bytes32 public immutable override merkleRoot; // This is a packed array of booleans. mapping(uint256 => uint256) private claimedBitMap; uint256 public immutable ownerUnlockTime; constructor( address _owner, address _token, bytes32 _merkleRoot, uint256 _daysUntilUnlock ) Owned(_owner) { require(_owner != address(0), "Owner must be non-zero address"); require(_token != address(0), "Airdrop token must be non-zero address"); require(_merkleRoot != bytes32(0), "Merkle root must be non-zero"); require( _daysUntilUnlock > 0, "Days until owner unlock must be in the future" ); token = _token; merkleRoot = _merkleRoot; ownerUnlockTime = block.timestamp.add(_daysUntilUnlock * 1 days); } function isClaimed(uint256 index) public view override returns (bool) { uint256 claimedWordIndex = index / 256; uint256 claimedBitIndex = index % 256; uint256 claimedWord = claimedBitMap[claimedWordIndex]; uint256 mask = (1 << claimedBitIndex); return claimedWord & mask == mask; } function _setClaimed(uint256 index) private { uint256 claimedWordIndex = index / 256; uint256 claimedBitIndex = index % 256; claimedBitMap[claimedWordIndex] = claimedBitMap[claimedWordIndex] | (1 << claimedBitIndex); } function claim( uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof ) external override { require(!isClaimed(index), "MerkleDistributor: Drop already claimed."); // Verify the merkle proof. bytes32 node = keccak256(abi.encodePacked(index, account, amount)); require( MerkleProof.verify(merkleProof, merkleRoot, node), "MerkleDistributor: Invalid proof." ); // Mark it claimed and send the token. _setClaimed(index); IERC20(token).safeTransfer(account, amount); emit Claimed(index, account, amount); } // Used for recovery purposes function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyOwner { require( tokenAddress == address(token) ? block.timestamp >= ownerUnlockTime : true, "MerkleDistributor: Cannot withdraw the token before unlock time" ); IERC20(tokenAddress).safeTransfer(owner, tokenAmount); emit Recovered(tokenAddress, tokenAmount); } /* ========== EVENTS ========== */ event Recovered(address token, uint256 amount); }
Verify the merkle proof. Mark it claimed and send the token.
function claim( uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof ) external override { require(!isClaimed(index), "MerkleDistributor: Drop already claimed."); bytes32 node = keccak256(abi.encodePacked(index, account, amount)); require( MerkleProof.verify(merkleProof, merkleRoot, node), "MerkleDistributor: Invalid proof." ); _setClaimed(index); IERC20(token).safeTransfer(account, amount); emit Claimed(index, account, amount); }
2,039,516
// SPDX-License-Identifier: agpl-3.0 pragma solidity =0.8.3; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "../../lib/StringsConcatenations.sol"; import "./OwnableDelegateProxy.sol"; import "./ProxyRegistry.sol"; /** * @title ERC721Tradable * ERC721Tradable - ERC721 contract that whitelists a trading address, and has minting functionality. */ contract ERC721Tradable is ERC721Enumerable, Ownable { using StringsConcatenations for string; using SafeMath for uint256; address proxyRegistryAddress; uint256 private _currentTokenId = 0; constructor( string memory _name, string memory _symbol, address _proxyRegistryAddress ) public ERC721(_name, _symbol) { proxyRegistryAddress = _proxyRegistryAddress; } /** * @dev Mints a token to an address with a tokenURI. * @param _to address of the future owner of the token */ function mintTo(address _to) public onlyOwner { uint256 newTokenId = _getNextTokenId(); _mint(_to, newTokenId); _incrementTokenId(); } /** * @dev calculates the next token ID based on value of _currentTokenId * @return uint256 for the next token ID */ function _getNextTokenId() private view returns(uint256) { return _currentTokenId.add(1); } /** * @dev increments the value of _currentTokenId */ function _incrementTokenId() private { _currentTokenId++; } function baseTokenURI() public virtual pure returns(string memory) { return ""; } function tokenURI(uint256 _tokenId) public override view returns(string memory) { return StringsConcatenations.strConcat(baseTokenURI(), StringsConcatenations.uint2str(_tokenId)); } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings. */ function isApprovedForAll(address owner, address operator) public override view returns(bool) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(owner)) == operator) { return true; } return super.isApprovedForAll(owner, operator); } }
Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings./ Whitelist OpenSea proxy contract for easy trading.
function isApprovedForAll(address owner, address operator) public override view returns(bool) { ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(owner)) == operator) { return true; } return super.isApprovedForAll(owner, operator); }
12,634,285
// SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol"; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol"; import "./UniswapV2Library.sol"; import "../interface/IOldERC20.sol"; contract SimpleOracle { address public immutable weth; IUniswapV2Factory public uniswapV2Factory; constructor(address _weth, address factory) { weth = _weth; uniswapV2Factory = IUniswapV2Factory(factory); } function getReservesForTokenPool(address _token) public view returns (uint256 wethReserve, uint256 tokenReserve) { IUniswapV2Pair pair = IUniswapV2Pair( uniswapV2Factory.getPair(_token, weth) ); uint112 _wethReserve; uint112 _tokenReserve; // get token 0 from pair // if token 0 is provided _token if (pair.token0() == _token) { // return tokenReserve as reserve 0 and wethReserve as reserve1 (_tokenReserve, _wethReserve, ) = pair.getReserves(); wethReserve = uint256(_wethReserve); tokenReserve = uint256(_tokenReserve); } else { // else return wethReserve as reserve 0 and tokenReserve as reserve1 (_wethReserve, _tokenReserve, ) = IUniswapV2Pair(pair).getReserves(); wethReserve = uint256(_wethReserve); tokenReserve = uint256(_tokenReserve); } require(_tokenReserve != 0, "token reserves cannot be zero"); require(_wethReserve != 0, "weth reserves cannot be zero"); } function getTokenPrice(address tbnTokenAddress, address paymentTokenAddress) external view returns (uint256) { /** Calculation of price - get common base between reserves and divide out for exchange rate */ require( tbnTokenAddress != paymentTokenAddress, "Cannot get price for same token" ); // Get the reserves ( uint256 tbnWETHReserves, uint256 tbnTokenReserves ) = getReservesForTokenPool(tbnTokenAddress); ( uint256 paymentWETHReserves, uint256 paymentTokenReserves ) = getReservesForTokenPool(paymentTokenAddress); // get the decimals uint8 tbnTokenDecimals = IOldERC20(tbnTokenAddress).decimals(); uint8 paymentTokenDecimals = IOldERC20(paymentTokenAddress).decimals(); // tbnTokenPrice / paymentTokenPrice if (paymentTokenDecimals < tbnTokenDecimals) { uint8 decimalDiff = tbnTokenDecimals - paymentTokenDecimals; return (1 ether * tbnWETHReserves * paymentTokenReserves * (10**decimalDiff)) / (paymentWETHReserves * tbnTokenReserves); } else if (tbnTokenDecimals < paymentTokenDecimals) { uint8 decimalDiff = paymentTokenDecimals - tbnTokenDecimals; return (1 ether * tbnWETHReserves * paymentTokenReserves) / (paymentWETHReserves * tbnTokenReserves * (10**decimalDiff)); } else { return (1 ether * tbnWETHReserves * paymentTokenReserves) / (paymentWETHReserves * tbnTokenReserves); } } } pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } pragma solidity >=0.5.0; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library UniswapV2Library { using SafeMath for uint256; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, "UniswapV2Library: IDENTICAL_ADDRESSES"); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), "UniswapV2Library: ZERO_ADDRESS"); } // calculates the CREATE2 address for a pair without making any external calls function pairFor( address factory, address tokenA, address tokenB ) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address( uint160( uint256( keccak256( abi.encodePacked( hex"ff", factory, keccak256(abi.encodePacked(token0, token1)), hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" // init code hash ) ) ) ) ); } // fetches and sorts the reserves for a pair function getReserves( address factory, address tokenA, address tokenB ) internal view returns (uint256 reserveA, uint256 reserveB) { (address token0, ) = sortTokens(tokenA, tokenB); (uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair( pairFor(factory, tokenA, tokenB) ).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) internal pure returns (uint256 amountB) { require(amountA > 0, "UniswapV2Library: INSUFFICIENT_AMOUNT"); require( reserveA > 0 && reserveB > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY" ); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { require(amountIn > 0, "UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT"); require( reserveIn > 0 && reserveOut > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY" ); uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { require(amountOut > 0, "UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT"); require( reserveIn > 0 && reserveOut > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY" ); uint256 numerator = reserveIn.mul(amountOut).mul(1000); uint256 denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut( address factory, uint256 amountIn, address[] memory path ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, "UniswapV2Library: INVALID_PATH"); amounts = new uint256[](path.length); amounts[0] = amountIn; for (uint256 i; i < path.length - 1; i++) { (uint256 reserveIn, uint256 reserveOut) = getReserves( factory, path[i], path[i + 1] ); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn( address factory, uint256 amountOut, address[] memory path ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, "UniswapV2Library: INVALID_PATH"); amounts = new uint256[](path.length); amounts[amounts.length - 1] = amountOut; for (uint256 i = path.length - 1; i > 0; i--) { (uint256 reserveIn, uint256 reserveOut) = getReserves( factory, path[i - 1], path[i] ); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; contract IOldERC20 { function decimals() public view virtual returns (uint8) {} } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.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, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, 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 (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @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) { 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, reverting 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) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * 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, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * 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, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } }
Get the reserves get the decimals tbnTokenPrice / paymentTokenPrice
function getTokenPrice(address tbnTokenAddress, address paymentTokenAddress) external view returns (uint256) { and divide out for exchange rate require( tbnTokenAddress != paymentTokenAddress, "Cannot get price for same token" ); ( uint256 tbnWETHReserves, uint256 tbnTokenReserves ) = getReservesForTokenPool(tbnTokenAddress); ( uint256 paymentWETHReserves, uint256 paymentTokenReserves ) = getReservesForTokenPool(paymentTokenAddress); uint8 tbnTokenDecimals = IOldERC20(tbnTokenAddress).decimals(); uint8 paymentTokenDecimals = IOldERC20(paymentTokenAddress).decimals(); if (paymentTokenDecimals < tbnTokenDecimals) { uint8 decimalDiff = tbnTokenDecimals - paymentTokenDecimals; return (1 ether * tbnWETHReserves * paymentTokenReserves * (10**decimalDiff)) / (paymentWETHReserves * tbnTokenReserves); uint8 decimalDiff = paymentTokenDecimals - tbnTokenDecimals; return (1 ether * tbnWETHReserves * paymentTokenReserves) / (paymentWETHReserves * tbnTokenReserves * (10**decimalDiff)); return (1 ether * tbnWETHReserves * paymentTokenReserves) / (paymentWETHReserves * tbnTokenReserves); } }
10,450,596
pragma solidity ^0.4.13; interface FundInterface { // EVENTS event PortfolioContent(address[] assets, uint[] holdings, uint[] prices); event RequestUpdated(uint id); event Redeemed(address indexed ofParticipant, uint atTimestamp, uint shareQuantity); event FeesConverted(uint atTimestamp, uint shareQuantityConverted, uint unclaimed); event CalculationUpdate(uint atTimestamp, uint managementFee, uint performanceFee, uint nav, uint sharePrice, uint totalSupply); event ErrorMessage(string errorMessage); // EXTERNAL METHODS // Compliance by Investor function requestInvestment(uint giveQuantity, uint shareQuantity, address investmentAsset) external; function executeRequest(uint requestId) external; function cancelRequest(uint requestId) external; function redeemAllOwnedAssets(uint shareQuantity) external returns (bool); // Administration by Manager function enableInvestment(address[] ofAssets) external; function disableInvestment(address[] ofAssets) external; function shutDown() external; // PUBLIC METHODS function emergencyRedeem(uint shareQuantity, address[] requestedAssets) public returns (bool success); function calcSharePriceAndAllocateFees() public returns (uint); // PUBLIC VIEW METHODS // Get general information function getModules() view returns (address, address, address); function getLastRequestId() view returns (uint); function getManager() view returns (address); // Get accounting information function performCalculations() view returns (uint, uint, uint, uint, uint, uint, uint); function calcSharePrice() view returns (uint); } interface AssetInterface { /* * Implements ERC 20 standard. * https://github.com/ethereum/EIPs/blob/f90864a3d2b2b45c4decf95efd26b3f0c276051a/EIPS/eip-20-token-standard.md * https://github.com/ethereum/EIPs/issues/20 * * Added support for the ERC 223 "tokenFallback" method in a "transfer" function with a payload. * https://github.com/ethereum/EIPs/issues/223 */ // Events event Approval(address indexed _owner, address indexed _spender, uint _value); // There is no ERC223 compatible Transfer event, with `_data` included. //ERC 223 // PUBLIC METHODS function transfer(address _to, uint _value, bytes _data) public returns (bool success); // ERC 20 // PUBLIC METHODS function transfer(address _to, uint _value) public returns (bool success); function transferFrom(address _from, address _to, uint _value) public returns (bool success); function approve(address _spender, uint _value) public returns (bool success); // PUBLIC VIEW METHODS function balanceOf(address _owner) view public returns (uint balance); function allowance(address _owner, address _spender) public view returns (uint remaining); } contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } interface SharesInterface { event Created(address indexed ofParticipant, uint atTimestamp, uint shareQuantity); event Annihilated(address indexed ofParticipant, uint atTimestamp, uint shareQuantity); // VIEW METHODS function getName() view returns (bytes32); function getSymbol() view returns (bytes8); function getDecimals() view returns (uint); function getCreationTime() view returns (uint); function toSmallestShareUnit(uint quantity) view returns (uint); function toWholeShareUnit(uint quantity) view returns (uint); } interface CompetitionInterface { // EVENTS event Register(uint withId, address fund, address manager); event ClaimReward(address registrant, address fund, uint shares); // PRE, POST, INVARIANT CONDITIONS function termsAndConditionsAreSigned(address byManager, uint8 v, bytes32 r, bytes32 s) view returns (bool); function isWhitelisted(address x) view returns (bool); function isCompetitionActive() view returns (bool); // CONSTANT METHODS function getMelonAsset() view returns (address); function getRegistrantId(address x) view returns (uint); function getRegistrantFund(address x) view returns (address); function getCompetitionStatusOfRegistrants() view returns (address[], address[], bool[]); function getTimeTillEnd() view returns (uint); function getEtherValue(uint amount) view returns (uint); function calculatePayout(uint payin) view returns (uint); // PUBLIC METHODS function registerForCompetition(address fund, uint8 v, bytes32 r, bytes32 s) payable; function batchAddToWhitelist(uint maxBuyinQuantity, address[] whitelistants); function withdrawMln(address to, uint amount); function claimReward(); } interface ComplianceInterface { // PUBLIC VIEW METHODS /// @notice Checks whether investment is permitted for a participant /// @param ofParticipant Address requesting to invest in a Melon fund /// @param giveQuantity Quantity of Melon token times 10 ** 18 offered to receive shareQuantity /// @param shareQuantity Quantity of shares times 10 ** 18 requested to be received /// @return Whether identity is eligible to invest in a Melon fund. function isInvestmentPermitted( address ofParticipant, uint256 giveQuantity, uint256 shareQuantity ) view returns (bool); /// @notice Checks whether redemption is permitted for a participant /// @param ofParticipant Address requesting to redeem from a Melon fund /// @param shareQuantity Quantity of shares times 10 ** 18 offered to redeem /// @param receiveQuantity Quantity of Melon token times 10 ** 18 requested to receive for shareQuantity /// @return Whether identity is eligible to redeem from a Melon fund. function isRedemptionPermitted( address ofParticipant, uint256 shareQuantity, uint256 receiveQuantity ) view returns (bool); } contract DBC { // MODIFIERS modifier pre_cond(bool condition) { require(condition); _; } modifier post_cond(bool condition) { _; assert(condition); } modifier invariant(bool condition) { require(condition); _; assert(condition); } } contract Owned is DBC { // FIELDS address public owner; // NON-CONSTANT METHODS function Owned() { owner = msg.sender; } function changeOwner(address ofNewOwner) pre_cond(isOwner()) { owner = ofNewOwner; } // PRE, POST, INVARIANT CONDITIONS function isOwner() internal returns (bool) { return msg.sender == owner; } } contract CompetitionCompliance is ComplianceInterface, DBC, Owned { address public competitionAddress; // CONSTRUCTOR /// @dev Constructor /// @param ofCompetition Address of the competition contract function CompetitionCompliance(address ofCompetition) public { competitionAddress = ofCompetition; } // PUBLIC VIEW METHODS /// @notice Checks whether investment is permitted for a participant /// @param ofParticipant Address requesting to invest in a Melon fund /// @param giveQuantity Quantity of Melon token times 10 ** 18 offered to receive shareQuantity /// @param shareQuantity Quantity of shares times 10 ** 18 requested to be received /// @return Whether identity is eligible to invest in a Melon fund. function isInvestmentPermitted( address ofParticipant, uint256 giveQuantity, uint256 shareQuantity ) view returns (bool) { return competitionAddress == ofParticipant; } /// @notice Checks whether redemption is permitted for a participant /// @param ofParticipant Address requesting to redeem from a Melon fund /// @param shareQuantity Quantity of shares times 10 ** 18 offered to redeem /// @param receiveQuantity Quantity of Melon token times 10 ** 18 requested to receive for shareQuantity /// @return isEligible Whether identity is eligible to redeem from a Melon fund. function isRedemptionPermitted( address ofParticipant, uint256 shareQuantity, uint256 receiveQuantity ) view returns (bool) { return competitionAddress == ofParticipant; } /// @notice Checks whether an address is whitelisted in the competition contract and competition is active /// @param x Address /// @return Whether the address is whitelisted function isCompetitionAllowed( address x ) view returns (bool) { return CompetitionInterface(competitionAddress).isWhitelisted(x) && CompetitionInterface(competitionAddress).isCompetitionActive(); } // PUBLIC METHODS /// @notice Changes the competition address /// @param ofCompetition Address of the competition contract function changeCompetitionAddress( address ofCompetition ) pre_cond(isOwner()) { competitionAddress = ofCompetition; } } contract DSAuthority { function canCall( address src, address dst, bytes4 sig ) public view returns (bool); } contract DSAuthEvents { event LogSetAuthority (address indexed authority); event LogSetOwner (address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; function DSAuth() public { owner = msg.sender; LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; LogSetAuthority(authority); } modifier auth { require(isAuthorized(msg.sender, msg.sig)); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, this, sig); } } } contract DSExec { function tryExec( address target, bytes calldata, uint value) internal returns (bool call_ret) { return target.call.value(value)(calldata); } function exec( address target, bytes calldata, uint value) internal { if(!tryExec(target, calldata, value)) { revert(); } } // Convenience aliases function exec( address t, bytes c ) internal { exec(t, c, 0); } function exec( address t, uint256 v ) internal { bytes memory c; exec(t, c, v); } function tryExec( address t, bytes c ) internal returns (bool) { return tryExec(t, c, 0); } function tryExec( address t, uint256 v ) internal returns (bool) { bytes memory c; return tryExec(t, c, v); } } contract DSMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } function min(uint x, uint y) internal pure returns (uint z) { return x <= y ? x : y; } function max(uint x, uint y) internal pure returns (uint z) { return x >= y ? x : y; } function imin(int x, int y) internal pure returns (int z) { return x <= y ? x : y; } function imax(int x, int y) internal pure returns (int z) { return x >= y ? x : y; } uint constant WAD = 10 ** 18; uint constant RAY = 10 ** 27; function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } function rmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), RAY / 2) / RAY; } function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } function rdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint x, uint n) internal pure returns (uint z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } contract Asset is DSMath, ERC20Interface { // DATA STRUCTURES mapping (address => uint) balances; mapping (address => mapping (address => uint)) allowed; uint public _totalSupply; // PUBLIC METHODS /** * @notice Send `_value` tokens to `_to` from `msg.sender` * @dev Transfers sender's tokens to a given address * @dev Similar to transfer(address, uint, bytes), but without _data parameter * @param _to Address of token receiver * @param _value Number of tokens to transfer * @return Returns success of function call */ function transfer(address _to, uint _value) public returns (bool success) { require(balances[msg.sender] >= _value); // sanity checks require(balances[_to] + _value >= balances[_to]); balances[msg.sender] = sub(balances[msg.sender], _value); balances[_to] = add(balances[_to], _value); emit Transfer(msg.sender, _to, _value); return true; } /// @notice Transfer `_value` tokens from `_from` to `_to` if `msg.sender` is allowed. /// @notice Restriction: An account can only use this function to send to itself /// @dev Allows for an approved third party to transfer tokens from one /// address to another. Returns success. /// @param _from Address from where tokens are withdrawn. /// @param _to Address to where tokens are sent. /// @param _value Number of tokens to transfer. /// @return Returns success of function call. function transferFrom(address _from, address _to, uint _value) public returns (bool) { require(_from != address(0)); require(_to != address(0)); require(_to != address(this)); require(balances[_from] >= _value); require(allowed[_from][msg.sender] >= _value); require(balances[_to] + _value >= balances[_to]); // require(_to == msg.sender); // can only use transferFrom to send to self balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; emit Transfer(_from, _to, _value); return true; } /// @notice Allows `_spender` to transfer `_value` tokens from `msg.sender` to any address. /// @dev Sets approved amount of tokens for spender. Returns success. /// @param _spender Address of allowed account. /// @param _value Number of approved tokens. /// @return Returns success of function call. function approve(address _spender, uint _value) public returns (bool) { require(_spender != address(0)); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } // PUBLIC VIEW METHODS /// @dev Returns number of allowed tokens that a spender can transfer on /// behalf of a token owner. /// @param _owner Address of token owner. /// @param _spender Address of token spender. /// @return Returns remaining allowance for spender. function allowance(address _owner, address _spender) constant public returns (uint) { return allowed[_owner][_spender]; } /// @dev Returns number of tokens owned by the given address. /// @param _owner Address of token owner. /// @return Returns balance of owner. function balanceOf(address _owner) constant public returns (uint) { return balances[_owner]; } function totalSupply() view public returns (uint) { return _totalSupply; } } contract Shares is SharesInterface, Asset { // FIELDS // Constructor fields bytes32 public name; bytes8 public symbol; uint public decimal; uint public creationTime; // METHODS // CONSTRUCTOR /// @param _name Name these shares /// @param _symbol Symbol of shares /// @param _decimal Amount of decimals sharePrice is denominated in, defined to be equal as deciamls in REFERENCE_ASSET contract /// @param _creationTime Timestamp of share creation function Shares(bytes32 _name, bytes8 _symbol, uint _decimal, uint _creationTime) { name = _name; symbol = _symbol; decimal = _decimal; creationTime = _creationTime; } // PUBLIC METHODS /** * @notice Send `_value` tokens to `_to` from `msg.sender` * @dev Transfers sender's tokens to a given address * @dev Similar to transfer(address, uint, bytes), but without _data parameter * @param _to Address of token receiver * @param _value Number of tokens to transfer * @return Returns success of function call */ function transfer(address _to, uint _value) public returns (bool success) { require(balances[msg.sender] >= _value); // sanity checks require(balances[_to] + _value >= balances[_to]); balances[msg.sender] = sub(balances[msg.sender], _value); balances[_to] = add(balances[_to], _value); emit Transfer(msg.sender, _to, _value); return true; } // PUBLIC VIEW METHODS function getName() view returns (bytes32) { return name; } function getSymbol() view returns (bytes8) { return symbol; } function getDecimals() view returns (uint) { return decimal; } function getCreationTime() view returns (uint) { return creationTime; } function toSmallestShareUnit(uint quantity) view returns (uint) { return mul(quantity, 10 ** getDecimals()); } function toWholeShareUnit(uint quantity) view returns (uint) { return quantity / (10 ** getDecimals()); } // INTERNAL METHODS /// @param recipient Address the new shares should be sent to /// @param shareQuantity Number of shares to be created function createShares(address recipient, uint shareQuantity) internal { _totalSupply = add(_totalSupply, shareQuantity); balances[recipient] = add(balances[recipient], shareQuantity); emit Created(msg.sender, now, shareQuantity); emit Transfer(address(0), recipient, shareQuantity); } /// @param recipient Address the new shares should be taken from when destroyed /// @param shareQuantity Number of shares to be annihilated function annihilateShares(address recipient, uint shareQuantity) internal { _totalSupply = sub(_totalSupply, shareQuantity); balances[recipient] = sub(balances[recipient], shareQuantity); emit Annihilated(msg.sender, now, shareQuantity); emit Transfer(recipient, address(0), shareQuantity); } } contract Fund is DSMath, DBC, Owned, Shares, FundInterface { event OrderUpdated(address exchange, bytes32 orderId, UpdateType updateType); // TYPES struct Modules { // Describes all modular parts, standardised through an interface CanonicalPriceFeed pricefeed; // Provides all external data ComplianceInterface compliance; // Boolean functions regarding invest/redeem RiskMgmtInterface riskmgmt; // Boolean functions regarding make/take orders } struct Calculations { // List of internal calculations uint gav; // Gross asset value uint managementFee; // Time based fee uint performanceFee; // Performance based fee measured against QUOTE_ASSET uint unclaimedFees; // Fees not yet allocated to the fund manager uint nav; // Net asset value uint highWaterMark; // A record of best all-time fund performance uint totalSupply; // Total supply of shares uint timestamp; // Time when calculations are performed in seconds } enum UpdateType { make, take, cancel } enum RequestStatus { active, cancelled, executed } struct Request { // Describes and logs whenever asset enter and leave fund due to Participants address participant; // Participant in Melon fund requesting investment or redemption RequestStatus status; // Enum: active, cancelled, executed; Status of request address requestAsset; // Address of the asset being requested uint shareQuantity; // Quantity of Melon fund shares uint giveQuantity; // Quantity in Melon asset to give to Melon fund to receive shareQuantity uint receiveQuantity; // Quantity in Melon asset to receive from Melon fund for given shareQuantity uint timestamp; // Time of request creation in seconds uint atUpdateId; // Pricefeed updateId when this request was created } struct Exchange { address exchange; address exchangeAdapter; bool takesCustody; // exchange takes custody before making order } struct OpenMakeOrder { uint id; // Order Id from exchange uint expiresAt; // Timestamp when the order expires } struct Order { // Describes an order event (make or take order) address exchangeAddress; // address of the exchange this order is on bytes32 orderId; // Id as returned from exchange UpdateType updateType; // Enum: make, take (cancel should be ignored) address makerAsset; // Order maker's asset address takerAsset; // Order taker's asset uint makerQuantity; // Quantity of makerAsset to be traded uint takerQuantity; // Quantity of takerAsset to be traded uint timestamp; // Time of order creation in seconds uint fillTakerQuantity; // Quantity of takerAsset to be filled } // FIELDS // Constant fields uint public constant MAX_FUND_ASSETS = 20; // Max ownable assets by the fund supported by gas limits uint public constant ORDER_EXPIRATION_TIME = 86400; // Make order expiration time (1 day) // Constructor fields uint public MANAGEMENT_FEE_RATE; // Fee rate in QUOTE_ASSET per managed seconds in WAD uint public PERFORMANCE_FEE_RATE; // Fee rate in QUOTE_ASSET per delta improvement in WAD address public VERSION; // Address of Version contract Asset public QUOTE_ASSET; // QUOTE asset as ERC20 contract // Methods fields Modules public modules; // Struct which holds all the initialised module instances Exchange[] public exchanges; // Array containing exchanges this fund supports Calculations public atLastUnclaimedFeeAllocation; // Calculation results at last allocateUnclaimedFees() call Order[] public orders; // append-only list of makes/takes from this fund mapping (address => mapping(address => OpenMakeOrder)) public exchangesToOpenMakeOrders; // exchangeIndex to: asset to open make orders bool public isShutDown; // Security feature, if yes than investing, managing, allocateUnclaimedFees gets blocked Request[] public requests; // All the requests this fund received from participants mapping (address => bool) public isInvestAllowed; // If false, fund rejects investments from the key asset address[] public ownedAssets; // List of all assets owned by the fund or for which the fund has open make orders mapping (address => bool) public isInAssetList; // Mapping from asset to whether the asset exists in ownedAssets mapping (address => bool) public isInOpenMakeOrder; // Mapping from asset to whether the asset is in a open make order as buy asset // METHODS // CONSTRUCTOR /// @dev Should only be called via Version.setupFund(..) /// @param withName human-readable descriptive name (not necessarily unique) /// @param ofQuoteAsset Asset against which mgmt and performance fee is measured against and which can be used to invest using this single asset /// @param ofManagementFee A time based fee expressed, given in a number which is divided by 1 WAD /// @param ofPerformanceFee A time performance based fee, performance relative to ofQuoteAsset, given in a number which is divided by 1 WAD /// @param ofCompliance Address of compliance module /// @param ofRiskMgmt Address of risk management module /// @param ofPriceFeed Address of price feed module /// @param ofExchanges Addresses of exchange on which this fund can trade /// @param ofDefaultAssets Addresses of assets to enable invest for (quote asset is already enabled) /// @return Deployed Fund with manager set as ofManager function Fund( address ofManager, bytes32 withName, address ofQuoteAsset, uint ofManagementFee, uint ofPerformanceFee, address ofCompliance, address ofRiskMgmt, address ofPriceFeed, address[] ofExchanges, address[] ofDefaultAssets ) Shares(withName, "MLNF", 18, now) { require(ofManagementFee < 10 ** 18); // Require management fee to be less than 100 percent require(ofPerformanceFee < 10 ** 18); // Require performance fee to be less than 100 percent isInvestAllowed[ofQuoteAsset] = true; owner = ofManager; MANAGEMENT_FEE_RATE = ofManagementFee; // 1 percent is expressed as 0.01 * 10 ** 18 PERFORMANCE_FEE_RATE = ofPerformanceFee; // 1 percent is expressed as 0.01 * 10 ** 18 VERSION = msg.sender; modules.compliance = ComplianceInterface(ofCompliance); modules.riskmgmt = RiskMgmtInterface(ofRiskMgmt); modules.pricefeed = CanonicalPriceFeed(ofPriceFeed); // Bridged to Melon exchange interface by exchangeAdapter library for (uint i = 0; i < ofExchanges.length; ++i) { require(modules.pricefeed.exchangeIsRegistered(ofExchanges[i])); var (ofExchangeAdapter, takesCustody, ) = modules.pricefeed.getExchangeInformation(ofExchanges[i]); exchanges.push(Exchange({ exchange: ofExchanges[i], exchangeAdapter: ofExchangeAdapter, takesCustody: takesCustody })); } QUOTE_ASSET = Asset(ofQuoteAsset); // Quote Asset always in owned assets list ownedAssets.push(ofQuoteAsset); isInAssetList[ofQuoteAsset] = true; require(address(QUOTE_ASSET) == modules.pricefeed.getQuoteAsset()); // Sanity check for (uint j = 0; j < ofDefaultAssets.length; j++) { require(modules.pricefeed.assetIsRegistered(ofDefaultAssets[j])); isInvestAllowed[ofDefaultAssets[j]] = true; } atLastUnclaimedFeeAllocation = Calculations({ gav: 0, managementFee: 0, performanceFee: 0, unclaimedFees: 0, nav: 0, highWaterMark: 10 ** getDecimals(), totalSupply: _totalSupply, timestamp: now }); } // EXTERNAL METHODS // EXTERNAL : ADMINISTRATION /// @notice Enable investment in specified assets /// @param ofAssets Array of assets to enable investment in function enableInvestment(address[] ofAssets) external pre_cond(isOwner()) { for (uint i = 0; i < ofAssets.length; ++i) { require(modules.pricefeed.assetIsRegistered(ofAssets[i])); isInvestAllowed[ofAssets[i]] = true; } } /// @notice Disable investment in specified assets /// @param ofAssets Array of assets to disable investment in function disableInvestment(address[] ofAssets) external pre_cond(isOwner()) { for (uint i = 0; i < ofAssets.length; ++i) { isInvestAllowed[ofAssets[i]] = false; } } function shutDown() external pre_cond(msg.sender == VERSION) { isShutDown = true; } // EXTERNAL : PARTICIPATION /// @notice Give melon tokens to receive shares of this fund /// @dev Recommended to give some leeway in prices to account for possibly slightly changing prices /// @param giveQuantity Quantity of Melon token times 10 ** 18 offered to receive shareQuantity /// @param shareQuantity Quantity of shares times 10 ** 18 requested to be received /// @param investmentAsset Address of asset to invest in function requestInvestment( uint giveQuantity, uint shareQuantity, address investmentAsset ) external pre_cond(!isShutDown) pre_cond(isInvestAllowed[investmentAsset]) // investment using investmentAsset has not been deactivated by the Manager pre_cond(modules.compliance.isInvestmentPermitted(msg.sender, giveQuantity, shareQuantity)) // Compliance Module: Investment permitted { requests.push(Request({ participant: msg.sender, status: RequestStatus.active, requestAsset: investmentAsset, shareQuantity: shareQuantity, giveQuantity: giveQuantity, receiveQuantity: shareQuantity, timestamp: now, atUpdateId: modules.pricefeed.getLastUpdateId() })); emit RequestUpdated(getLastRequestId()); } /// @notice Executes active investment and redemption requests, in a way that minimises information advantages of investor /// @dev Distributes melon and shares according to the request /// @param id Index of request to be executed /// @dev Active investment or redemption request executed function executeRequest(uint id) external pre_cond(!isShutDown) pre_cond(requests[id].status == RequestStatus.active) pre_cond( _totalSupply == 0 || ( now >= add(requests[id].timestamp, modules.pricefeed.getInterval()) && modules.pricefeed.getLastUpdateId() >= add(requests[id].atUpdateId, 2) ) ) // PriceFeed Module: Wait at least one interval time and two updates before continuing (unless it is the first investment) { Request request = requests[id]; var (isRecent, , ) = modules.pricefeed.getPriceInfo(address(request.requestAsset)); require(isRecent); // sharePrice quoted in QUOTE_ASSET and multiplied by 10 ** fundDecimals uint costQuantity = toWholeShareUnit(mul(request.shareQuantity, calcSharePriceAndAllocateFees())); // By definition quoteDecimals == fundDecimals if (request.requestAsset != address(QUOTE_ASSET)) { var (isPriceRecent, invertedRequestAssetPrice, requestAssetDecimal) = modules.pricefeed.getInvertedPriceInfo(request.requestAsset); if (!isPriceRecent) { revert(); } costQuantity = mul(costQuantity, invertedRequestAssetPrice) / 10 ** requestAssetDecimal; } if ( isInvestAllowed[request.requestAsset] && costQuantity <= request.giveQuantity ) { request.status = RequestStatus.executed; require(AssetInterface(request.requestAsset).transferFrom(request.participant, address(this), costQuantity)); // Allocate Value createShares(request.participant, request.shareQuantity); // Accounting if (!isInAssetList[request.requestAsset]) { ownedAssets.push(request.requestAsset); isInAssetList[request.requestAsset] = true; } } else { revert(); // Invalid Request or invalid giveQuantity / receiveQuantity } } /// @notice Cancels active investment and redemption requests /// @param id Index of request to be executed function cancelRequest(uint id) external pre_cond(requests[id].status == RequestStatus.active) // Request is active pre_cond(requests[id].participant == msg.sender || isShutDown) // Either request creator or fund is shut down { requests[id].status = RequestStatus.cancelled; } /// @notice Redeems by allocating an ownership percentage of each asset to the participant /// @dev Independent of running price feed! /// @param shareQuantity Number of shares owned by the participant, which the participant would like to redeem for individual assets /// @return Whether all assets sent to shareholder or not function redeemAllOwnedAssets(uint shareQuantity) external returns (bool success) { return emergencyRedeem(shareQuantity, ownedAssets); } // EXTERNAL : MANAGING /// @notice Universal method for calling exchange functions through adapters /// @notice See adapter contracts for parameters needed for each exchange /// @param exchangeIndex Index of the exchange in the "exchanges" array /// @param method Signature of the adapter method to call (as per ABI spec) /// @param orderAddresses [0] Order maker /// @param orderAddresses [1] Order taker /// @param orderAddresses [2] Order maker asset /// @param orderAddresses [3] Order taker asset /// @param orderAddresses [4] Fee recipient /// @param orderValues [0] Maker token quantity /// @param orderValues [1] Taker token quantity /// @param orderValues [2] Maker fee /// @param orderValues [3] Taker fee /// @param orderValues [4] Timestamp (seconds) /// @param orderValues [5] Salt/nonce /// @param orderValues [6] Fill amount: amount of taker token to be traded /// @param orderValues [7] Dexy signature mode /// @param identifier Order identifier /// @param v ECDSA recovery id /// @param r ECDSA signature output r /// @param s ECDSA signature output s function callOnExchange( uint exchangeIndex, bytes4 method, address[5] orderAddresses, uint[8] orderValues, bytes32 identifier, uint8 v, bytes32 r, bytes32 s ) external { require( modules.pricefeed.exchangeMethodIsAllowed( exchanges[exchangeIndex].exchange, method ) ); require( exchanges[exchangeIndex].exchangeAdapter.delegatecall( method, exchanges[exchangeIndex].exchange, orderAddresses, orderValues, identifier, v, r, s ) ); } function addOpenMakeOrder( address ofExchange, address ofSellAsset, uint orderId ) pre_cond(msg.sender == address(this)) { isInOpenMakeOrder[ofSellAsset] = true; exchangesToOpenMakeOrders[ofExchange][ofSellAsset].id = orderId; exchangesToOpenMakeOrders[ofExchange][ofSellAsset].expiresAt = add(now, ORDER_EXPIRATION_TIME); } function removeOpenMakeOrder( address ofExchange, address ofSellAsset ) pre_cond(msg.sender == address(this)) { delete exchangesToOpenMakeOrders[ofExchange][ofSellAsset]; } function orderUpdateHook( address ofExchange, bytes32 orderId, UpdateType updateType, address[2] orderAddresses, // makerAsset, takerAsset uint[3] orderValues // makerQuantity, takerQuantity, fillTakerQuantity (take only) ) pre_cond(msg.sender == address(this)) { // only save make/take if (updateType == UpdateType.make || updateType == UpdateType.take) { orders.push(Order({ exchangeAddress: ofExchange, orderId: orderId, updateType: updateType, makerAsset: orderAddresses[0], takerAsset: orderAddresses[1], makerQuantity: orderValues[0], takerQuantity: orderValues[1], timestamp: block.timestamp, fillTakerQuantity: orderValues[2] })); } emit OrderUpdated(ofExchange, orderId, updateType); } // PUBLIC METHODS // PUBLIC METHODS : ACCOUNTING /// @notice Calculates gross asset value of the fund /// @dev Decimals in assets must be equal to decimals in PriceFeed for all entries in AssetRegistrar /// @dev Assumes that module.pricefeed.getPriceInfo(..) returns recent prices /// @return gav Gross asset value quoted in QUOTE_ASSET and multiplied by 10 ** shareDecimals function calcGav() returns (uint gav) { // prices quoted in QUOTE_ASSET and multiplied by 10 ** assetDecimal uint[] memory allAssetHoldings = new uint[](ownedAssets.length); uint[] memory allAssetPrices = new uint[](ownedAssets.length); address[] memory tempOwnedAssets; tempOwnedAssets = ownedAssets; delete ownedAssets; for (uint i = 0; i < tempOwnedAssets.length; ++i) { address ofAsset = tempOwnedAssets[i]; // assetHoldings formatting: mul(exchangeHoldings, 10 ** assetDecimal) uint assetHoldings = add( uint(AssetInterface(ofAsset).balanceOf(address(this))), // asset base units held by fund quantityHeldInCustodyOfExchange(ofAsset) ); // assetPrice formatting: mul(exchangePrice, 10 ** assetDecimal) var (isRecent, assetPrice, assetDecimals) = modules.pricefeed.getPriceInfo(ofAsset); if (!isRecent) { revert(); } allAssetHoldings[i] = assetHoldings; allAssetPrices[i] = assetPrice; // gav as sum of mul(assetHoldings, assetPrice) with formatting: mul(mul(exchangeHoldings, exchangePrice), 10 ** shareDecimals) gav = add(gav, mul(assetHoldings, assetPrice) / (10 ** uint256(assetDecimals))); // Sum up product of asset holdings of this vault and asset prices if (assetHoldings != 0 || ofAsset == address(QUOTE_ASSET) || isInOpenMakeOrder[ofAsset]) { // Check if asset holdings is not zero or is address(QUOTE_ASSET) or in open make order ownedAssets.push(ofAsset); } else { isInAssetList[ofAsset] = false; // Remove from ownedAssets if asset holdings are zero } } emit PortfolioContent(tempOwnedAssets, allAssetHoldings, allAssetPrices); } /// @notice Add an asset to the list that this fund owns function addAssetToOwnedAssets (address ofAsset) public pre_cond(isOwner() || msg.sender == address(this)) { isInOpenMakeOrder[ofAsset] = true; if (!isInAssetList[ofAsset]) { ownedAssets.push(ofAsset); isInAssetList[ofAsset] = true; } } /** @notice Calculates unclaimed fees of the fund manager @param gav Gross asset value in QUOTE_ASSET and multiplied by 10 ** shareDecimals @return { "managementFees": "A time (seconds) based fee in QUOTE_ASSET and multiplied by 10 ** shareDecimals", "performanceFees": "A performance (rise of sharePrice measured in QUOTE_ASSET) based fee in QUOTE_ASSET and multiplied by 10 ** shareDecimals", "unclaimedfees": "The sum of both managementfee and performancefee in QUOTE_ASSET and multiplied by 10 ** shareDecimals" } */ function calcUnclaimedFees(uint gav) view returns ( uint managementFee, uint performanceFee, uint unclaimedFees) { // Management fee calculation uint timePassed = sub(now, atLastUnclaimedFeeAllocation.timestamp); uint gavPercentage = mul(timePassed, gav) / (1 years); managementFee = wmul(gavPercentage, MANAGEMENT_FEE_RATE); // Performance fee calculation // Handle potential division through zero by defining a default value uint valuePerShareExclMgmtFees = _totalSupply > 0 ? calcValuePerShare(sub(gav, managementFee), _totalSupply) : toSmallestShareUnit(1); if (valuePerShareExclMgmtFees > atLastUnclaimedFeeAllocation.highWaterMark) { uint gainInSharePrice = sub(valuePerShareExclMgmtFees, atLastUnclaimedFeeAllocation.highWaterMark); uint investmentProfits = wmul(gainInSharePrice, _totalSupply); performanceFee = wmul(investmentProfits, PERFORMANCE_FEE_RATE); } // Sum of all FEES unclaimedFees = add(managementFee, performanceFee); } /// @notice Calculates the Net asset value of this fund /// @param gav Gross asset value of this fund in QUOTE_ASSET and multiplied by 10 ** shareDecimals /// @param unclaimedFees The sum of both managementFee and performanceFee in QUOTE_ASSET and multiplied by 10 ** shareDecimals /// @return nav Net asset value in QUOTE_ASSET and multiplied by 10 ** shareDecimals function calcNav(uint gav, uint unclaimedFees) view returns (uint nav) { nav = sub(gav, unclaimedFees); } /// @notice Calculates the share price of the fund /// @dev Convention for valuePerShare (== sharePrice) formatting: mul(totalValue / numShares, 10 ** decimal), to avoid floating numbers /// @dev Non-zero share supply; value denominated in [base unit of melonAsset] /// @param totalValue the total value in QUOTE_ASSET and multiplied by 10 ** shareDecimals /// @param numShares the number of shares multiplied by 10 ** shareDecimals /// @return valuePerShare Share price denominated in QUOTE_ASSET and multiplied by 10 ** shareDecimals function calcValuePerShare(uint totalValue, uint numShares) view pre_cond(numShares > 0) returns (uint valuePerShare) { valuePerShare = toSmallestShareUnit(totalValue) / numShares; } /** @notice Calculates essential fund metrics @return { "gav": "Gross asset value of this fund denominated in [base unit of melonAsset]", "managementFee": "A time (seconds) based fee", "performanceFee": "A performance (rise of sharePrice measured in QUOTE_ASSET) based fee", "unclaimedFees": "The sum of both managementFee and performanceFee denominated in [base unit of melonAsset]", "feesShareQuantity": "The number of shares to be given as fees to the manager", "nav": "Net asset value denominated in [base unit of melonAsset]", "sharePrice": "Share price denominated in [base unit of melonAsset]" } */ function performCalculations() view returns ( uint gav, uint managementFee, uint performanceFee, uint unclaimedFees, uint feesShareQuantity, uint nav, uint sharePrice ) { gav = calcGav(); // Reflects value independent of fees (managementFee, performanceFee, unclaimedFees) = calcUnclaimedFees(gav); nav = calcNav(gav, unclaimedFees); // The value of unclaimedFees measured in shares of this fund at current value feesShareQuantity = (gav == 0) ? 0 : mul(_totalSupply, unclaimedFees) / gav; // The total share supply including the value of unclaimedFees, measured in shares of this fund uint totalSupplyAccountingForFees = add(_totalSupply, feesShareQuantity); sharePrice = _totalSupply > 0 ? calcValuePerShare(gav, totalSupplyAccountingForFees) : toSmallestShareUnit(1); // Handle potential division through zero by defining a default value } /// @notice Converts unclaimed fees of the manager into fund shares /// @return sharePrice Share price denominated in [base unit of melonAsset] function calcSharePriceAndAllocateFees() public returns (uint) { var ( gav, managementFee, performanceFee, unclaimedFees, feesShareQuantity, nav, sharePrice ) = performCalculations(); createShares(owner, feesShareQuantity); // Updates _totalSupply by creating shares allocated to manager // Update Calculations uint highWaterMark = atLastUnclaimedFeeAllocation.highWaterMark >= sharePrice ? atLastUnclaimedFeeAllocation.highWaterMark : sharePrice; atLastUnclaimedFeeAllocation = Calculations({ gav: gav, managementFee: managementFee, performanceFee: performanceFee, unclaimedFees: unclaimedFees, nav: nav, highWaterMark: highWaterMark, totalSupply: _totalSupply, timestamp: now }); emit FeesConverted(now, feesShareQuantity, unclaimedFees); emit CalculationUpdate(now, managementFee, performanceFee, nav, sharePrice, _totalSupply); return sharePrice; } // PUBLIC : REDEEMING /// @notice Redeems by allocating an ownership percentage only of requestedAssets to the participant /// @dev This works, but with loops, so only up to a certain number of assets (right now the max is 4) /// @dev Independent of running price feed! Note: if requestedAssets != ownedAssets then participant misses out on some owned value /// @param shareQuantity Number of shares owned by the participant, which the participant would like to redeem for a slice of assets /// @param requestedAssets List of addresses that consitute a subset of ownedAssets. /// @return Whether all assets sent to shareholder or not function emergencyRedeem(uint shareQuantity, address[] requestedAssets) public pre_cond(balances[msg.sender] >= shareQuantity) // sender owns enough shares returns (bool) { address ofAsset; uint[] memory ownershipQuantities = new uint[](requestedAssets.length); address[] memory redeemedAssets = new address[](requestedAssets.length); // Check whether enough assets held by fund for (uint i = 0; i < requestedAssets.length; ++i) { ofAsset = requestedAssets[i]; require(isInAssetList[ofAsset]); for (uint j = 0; j < redeemedAssets.length; j++) { if (ofAsset == redeemedAssets[j]) { revert(); } } redeemedAssets[i] = ofAsset; uint assetHoldings = add( uint(AssetInterface(ofAsset).balanceOf(address(this))), quantityHeldInCustodyOfExchange(ofAsset) ); if (assetHoldings == 0) continue; // participant's ownership percentage of asset holdings ownershipQuantities[i] = mul(assetHoldings, shareQuantity) / _totalSupply; // CRITICAL ERR: Not enough fund asset balance for owed ownershipQuantitiy, eg in case of unreturned asset quantity at address(exchanges[i].exchange) address if (uint(AssetInterface(ofAsset).balanceOf(address(this))) < ownershipQuantities[i]) { isShutDown = true; emit ErrorMessage("CRITICAL ERR: Not enough assetHoldings for owed ownershipQuantitiy"); return false; } } // Annihilate shares before external calls to prevent reentrancy annihilateShares(msg.sender, shareQuantity); // Transfer ownershipQuantity of Assets for (uint k = 0; k < requestedAssets.length; ++k) { // Failed to send owed ownershipQuantity from fund to participant ofAsset = requestedAssets[k]; if (ownershipQuantities[k] == 0) { continue; } else if (!AssetInterface(ofAsset).transfer(msg.sender, ownershipQuantities[k])) { revert(); } } emit Redeemed(msg.sender, now, shareQuantity); return true; } // PUBLIC : FEES /// @dev Quantity of asset held in exchange according to associated order id /// @param ofAsset Address of asset /// @return Quantity of input asset held in exchange function quantityHeldInCustodyOfExchange(address ofAsset) returns (uint) { uint totalSellQuantity; // quantity in custody across exchanges uint totalSellQuantityInApprove; // quantity of asset in approve (allowance) but not custody of exchange for (uint i; i < exchanges.length; i++) { if (exchangesToOpenMakeOrders[exchanges[i].exchange][ofAsset].id == 0) { continue; } var (sellAsset, , sellQuantity, ) = GenericExchangeInterface(exchanges[i].exchangeAdapter).getOrder(exchanges[i].exchange, exchangesToOpenMakeOrders[exchanges[i].exchange][ofAsset].id); if (sellQuantity == 0) { // remove id if remaining sell quantity zero (closed) delete exchangesToOpenMakeOrders[exchanges[i].exchange][ofAsset]; } totalSellQuantity = add(totalSellQuantity, sellQuantity); if (!exchanges[i].takesCustody) { totalSellQuantityInApprove += sellQuantity; } } if (totalSellQuantity == 0) { isInOpenMakeOrder[sellAsset] = false; } return sub(totalSellQuantity, totalSellQuantityInApprove); // Since quantity in approve is not actually in custody } // PUBLIC VIEW METHODS /// @notice Calculates sharePrice denominated in [base unit of melonAsset] /// @return sharePrice Share price denominated in [base unit of melonAsset] function calcSharePrice() view returns (uint sharePrice) { (, , , , , sharePrice) = performCalculations(); return sharePrice; } function getModules() view returns (address, address, address) { return ( address(modules.pricefeed), address(modules.compliance), address(modules.riskmgmt) ); } function getLastRequestId() view returns (uint) { return requests.length - 1; } function getLastOrderIndex() view returns (uint) { return orders.length - 1; } function getManager() view returns (address) { return owner; } function getOwnedAssetsLength() view returns (uint) { return ownedAssets.length; } function getExchangeInfo() view returns (address[], address[], bool[]) { address[] memory ofExchanges = new address[](exchanges.length); address[] memory ofAdapters = new address[](exchanges.length); bool[] memory takesCustody = new bool[](exchanges.length); for (uint i = 0; i < exchanges.length; i++) { ofExchanges[i] = exchanges[i].exchange; ofAdapters[i] = exchanges[i].exchangeAdapter; takesCustody[i] = exchanges[i].takesCustody; } return (ofExchanges, ofAdapters, takesCustody); } function orderExpired(address ofExchange, address ofAsset) view returns (bool) { uint expiryTime = exchangesToOpenMakeOrders[ofExchange][ofAsset].expiresAt; require(expiryTime > 0); return block.timestamp >= expiryTime; } function getOpenOrderInfo(address ofExchange, address ofAsset) view returns (uint, uint) { OpenMakeOrder order = exchangesToOpenMakeOrders[ofExchange][ofAsset]; return (order.id, order.expiresAt); } } contract Competition is CompetitionInterface, DSMath, DBC, Owned { // TYPES struct Registrant { address fund; // Address of the Melon fund address registrant; // Manager and registrant of the fund bool hasSigned; // Whether initial requirements passed and Registrant signed Terms and Conditions; uint buyinQuantity; // Quantity of buyinAsset spent uint payoutQuantity; // Quantity of payoutAsset received as prize bool isRewarded; // Is the Registrant rewarded yet } struct RegistrantId { uint id; // Actual Registrant Id bool exists; // Used to check if the mapping exists } // FIELDS // Constant fields // Competition terms and conditions as displayed on https://ipfs.io/ipfs/QmXuUfPi6xeYfuMwpVAughm7GjGUjkbEojhNR8DJqVBBxc // IPFS hash encoded using http://lenschulwitz.com/base58 bytes public constant TERMS_AND_CONDITIONS = hex"12208E21FD34B8B2409972D30326D840C9D747438A118580D6BA8C0735ED53810491"; uint public MELON_BASE_UNIT = 10 ** 18; // Constructor fields address public custodian; // Address of the custodian which holds the funds sent uint public startTime; // Competition start time in seconds (Temporarily Set) uint public endTime; // Competition end time in seconds uint public payoutRate; // Fixed MLN - Ether conversion rate uint public bonusRate; // Bonus multiplier uint public totalMaxBuyin; // Limit amount of deposit to participate in competition (Valued in Ether) uint public currentTotalBuyin; // Total buyin till now uint public maxRegistrants; // Limit number of participate in competition uint public prizeMoneyAsset; // Equivalent to payoutAsset uint public prizeMoneyQuantity; // Total prize money pool address public MELON_ASSET; // Adresss of Melon asset contract ERC20Interface public MELON_CONTRACT; // Melon as ERC20 contract address public COMPETITION_VERSION; // Version contract address // Methods fields Registrant[] public registrants; // List of all registrants, can be externally accessed mapping (address => address) public registeredFundToRegistrants; // For fund address indexed accessing of registrant addresses mapping(address => RegistrantId) public registrantToRegistrantIds; // For registrant address indexed accessing of registrant ids mapping(address => uint) public whitelistantToMaxBuyin; // For registrant address to respective max buyIn cap (Valued in Ether) //EVENTS event Register(uint withId, address fund, address manager); // METHODS // CONSTRUCTOR function Competition( address ofMelonAsset, address ofCompetitionVersion, address ofCustodian, uint ofStartTime, uint ofEndTime, uint ofPayoutRate, uint ofTotalMaxBuyin, uint ofMaxRegistrants ) { MELON_ASSET = ofMelonAsset; MELON_CONTRACT = ERC20Interface(MELON_ASSET); COMPETITION_VERSION = ofCompetitionVersion; custodian = ofCustodian; startTime = ofStartTime; endTime = ofEndTime; payoutRate = ofPayoutRate; totalMaxBuyin = ofTotalMaxBuyin; maxRegistrants = ofMaxRegistrants; } // PRE, POST, INVARIANT CONDITIONS /// @dev Proofs that terms and conditions have been read and understood /// @param byManager Address of the fund manager, as used in the ipfs-frontend /// @param v ellipitc curve parameter v /// @param r ellipitc curve parameter r /// @param s ellipitc curve parameter s /// @return Whether or not terms and conditions have been read and understood function termsAndConditionsAreSigned(address byManager, uint8 v, bytes32 r, bytes32 s) view returns (bool) { return ecrecover( // Parity does prepend \x19Ethereum Signed Message:\n{len(message)} before signing. // Signature order has also been changed in 1.6.7 and upcoming 1.7.x, // it will return rsv (same as geth; where v is [27, 28]). // Note that if you are using ecrecover, v will be either "00" or "01". // As a result, in order to use this value, you will have to parse it to an // integer and then add 27. This will result in either a 27 or a 28. // https://github.com/ethereum/wiki/wiki/JavaScript-API#web3ethsign keccak256("\x19Ethereum Signed Message:\n34", TERMS_AND_CONDITIONS), v, r, s ) == byManager; // Has sender signed TERMS_AND_CONDITIONS } /// @dev Whether message sender is KYC verified through CERTIFIER /// @param x Address to be checked for KYC verification function isWhitelisted(address x) view returns (bool) { return whitelistantToMaxBuyin[x] > 0; } /// @dev Whether the competition is on-going function isCompetitionActive() view returns (bool) { return now >= startTime && now < endTime; } // CONSTANT METHODS function getMelonAsset() view returns (address) { return MELON_ASSET; } /// @return Get RegistrantId from registrant address function getRegistrantId(address x) view returns (uint) { return registrantToRegistrantIds[x].id; } /// @return Address of the fund registered by the registrant address function getRegistrantFund(address x) view returns (address) { return registrants[getRegistrantId(x)].fund; } /// @return Get time to end of the competition function getTimeTillEnd() view returns (uint) { if (now > endTime) { return 0; } return sub(endTime, now); } /// @return Get value of MLN amount in Ether function getEtherValue(uint amount) view returns (uint) { address feedAddress = Version(COMPETITION_VERSION).CANONICAL_PRICEFEED(); var (isRecent, price, ) = CanonicalPriceFeed(feedAddress).getPriceInfo(MELON_ASSET); if (!isRecent) { revert(); } return mul(price, amount) / 10 ** 18; } /// @return Calculated payout in MLN with bonus for payin in Ether function calculatePayout(uint payin) view returns (uint payoutQuantity) { payoutQuantity = mul(payin, payoutRate) / 10 ** 18; } /** @notice Returns an array of fund addresses and an associated array of whether competing and whether disqualified @return { "fundAddrs": "Array of addresses of Melon Funds", "fundRegistrants": "Array of addresses of Melon fund managers, as used in the ipfs-frontend", } */ function getCompetitionStatusOfRegistrants() view returns( address[], address[], bool[] ) { address[] memory fundAddrs = new address[](registrants.length); address[] memory fundRegistrants = new address[](registrants.length); bool[] memory isRewarded = new bool[](registrants.length); for (uint i = 0; i < registrants.length; i++) { fundAddrs[i] = registrants[i].fund; fundRegistrants[i] = registrants[i].registrant; isRewarded[i] = registrants[i].isRewarded; } return (fundAddrs, fundRegistrants, isRewarded); } // NON-CONSTANT METHODS /// @notice Register to take part in the competition /// @dev Check if the fund address is actually from the Competition Version /// @param fund Address of the Melon fund /// @param v ellipitc curve parameter v /// @param r ellipitc curve parameter r /// @param s ellipitc curve parameter s function registerForCompetition( address fund, uint8 v, bytes32 r, bytes32 s ) payable pre_cond(isCompetitionActive() && !Version(COMPETITION_VERSION).isShutDown()) pre_cond(termsAndConditionsAreSigned(msg.sender, v, r, s) && isWhitelisted(msg.sender)) { require(registeredFundToRegistrants[fund] == address(0) && registrantToRegistrantIds[msg.sender].exists == false); require(add(currentTotalBuyin, msg.value) <= totalMaxBuyin && registrants.length < maxRegistrants); require(msg.value <= whitelistantToMaxBuyin[msg.sender]); require(Version(COMPETITION_VERSION).getFundByManager(msg.sender) == fund); // Calculate Payout Quantity, invest the quantity in registrant's fund uint payoutQuantity = calculatePayout(msg.value); registeredFundToRegistrants[fund] = msg.sender; registrantToRegistrantIds[msg.sender] = RegistrantId({id: registrants.length, exists: true}); currentTotalBuyin = add(currentTotalBuyin, msg.value); FundInterface fundContract = FundInterface(fund); MELON_CONTRACT.approve(fund, payoutQuantity); // Give payoutRequest MLN in return for msg.value fundContract.requestInvestment(payoutQuantity, getEtherValue(payoutQuantity), MELON_ASSET); fundContract.executeRequest(fundContract.getLastRequestId()); custodian.transfer(msg.value); // Emit Register event emit Register(registrants.length, fund, msg.sender); registrants.push(Registrant({ fund: fund, registrant: msg.sender, hasSigned: true, buyinQuantity: msg.value, payoutQuantity: payoutQuantity, isRewarded: false })); } /// @notice Add batch addresses to whitelist with set maxBuyinQuantity /// @dev Only the owner can call this function /// @param maxBuyinQuantity Quantity of payoutAsset received as prize /// @param whitelistants Performance of Melon fund at competition endTime; Can be changed for any other comparison metric function batchAddToWhitelist( uint maxBuyinQuantity, address[] whitelistants ) pre_cond(isOwner()) pre_cond(now < endTime) { for (uint i = 0; i < whitelistants.length; ++i) { whitelistantToMaxBuyin[whitelistants[i]] = maxBuyinQuantity; } } /// @notice Withdraw MLN /// @dev Only the owner can call this function function withdrawMln(address to, uint amount) pre_cond(isOwner()) { MELON_CONTRACT.transfer(to, amount); } /// @notice Claim Reward function claimReward() pre_cond(getRegistrantFund(msg.sender) != address(0)) { require(block.timestamp >= endTime || Version(COMPETITION_VERSION).isShutDown()); Registrant registrant = registrants[getRegistrantId(msg.sender)]; require(registrant.isRewarded == false); registrant.isRewarded = true; // Is this safe to assume this or should we transfer all the balance instead? uint balance = AssetInterface(registrant.fund).balanceOf(address(this)); require(AssetInterface(registrant.fund).transfer(registrant.registrant, balance)); // Emit ClaimedReward event emit ClaimReward(msg.sender, registrant.fund, balance); } } contract DSNote { event LogNote( bytes4 indexed sig, address indexed guy, bytes32 indexed foo, bytes32 indexed bar, uint wad, bytes fax ) anonymous; modifier note { bytes32 foo; bytes32 bar; assembly { foo := calldataload(4) bar := calldataload(36) } LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data); _; } } contract DSGroup is DSExec, DSNote { address[] public members; uint public quorum; uint public window; uint public actionCount; mapping (uint => Action) public actions; mapping (uint => mapping (address => bool)) public confirmedBy; mapping (address => bool) public isMember; // Legacy events event Proposed (uint id, bytes calldata); event Confirmed (uint id, address member); event Triggered (uint id); struct Action { address target; bytes calldata; uint value; uint confirmations; uint deadline; bool triggered; } function DSGroup( address[] members_, uint quorum_, uint window_ ) { members = members_; quorum = quorum_; window = window_; for (uint i = 0; i < members.length; i++) { isMember[members[i]] = true; } } function memberCount() constant returns (uint) { return members.length; } function target(uint id) constant returns (address) { return actions[id].target; } function calldata(uint id) constant returns (bytes) { return actions[id].calldata; } function value(uint id) constant returns (uint) { return actions[id].value; } function confirmations(uint id) constant returns (uint) { return actions[id].confirmations; } function deadline(uint id) constant returns (uint) { return actions[id].deadline; } function triggered(uint id) constant returns (bool) { return actions[id].triggered; } function confirmed(uint id) constant returns (bool) { return confirmations(id) >= quorum; } function expired(uint id) constant returns (bool) { return now > deadline(id); } function deposit() note payable { } function propose( address target, bytes calldata, uint value ) onlyMembers note returns (uint id) { id = ++actionCount; actions[id].target = target; actions[id].calldata = calldata; actions[id].value = value; actions[id].deadline = now + window; Proposed(id, calldata); } function confirm(uint id) onlyMembers onlyActive(id) note { assert(!confirmedBy[id][msg.sender]); confirmedBy[id][msg.sender] = true; actions[id].confirmations++; Confirmed(id, msg.sender); } function trigger(uint id) onlyMembers onlyActive(id) note { assert(confirmed(id)); actions[id].triggered = true; exec(actions[id].target, actions[id].calldata, actions[id].value); Triggered(id); } modifier onlyMembers { assert(isMember[msg.sender]); _; } modifier onlyActive(uint id) { assert(!expired(id)); assert(!triggered(id)); _; } //------------------------------------------------------------------ // Legacy functions //------------------------------------------------------------------ function getInfo() constant returns ( uint quorum_, uint memberCount, uint window_, uint actionCount_ ) { return (quorum, members.length, window, actionCount); } function getActionStatus(uint id) constant returns ( uint confirmations, uint deadline, bool triggered, address target, uint value ) { return ( actions[id].confirmations, actions[id].deadline, actions[id].triggered, actions[id].target, actions[id].value ); } } contract DSGroupFactory is DSNote { mapping (address => bool) public isGroup; function newGroup( address[] members, uint quorum, uint window ) note returns (DSGroup group) { group = new DSGroup(members, quorum, window); isGroup[group] = true; } } contract DSThing is DSAuth, DSNote, DSMath { function S(string s) internal pure returns (bytes4) { return bytes4(keccak256(s)); } } interface GenericExchangeInterface { // EVENTS event OrderUpdated(uint id); // METHODS // EXTERNAL METHODS function makeOrder( address onExchange, address sellAsset, address buyAsset, uint sellQuantity, uint buyQuantity ) external returns (uint); function takeOrder(address onExchange, uint id, uint quantity) external returns (bool); function cancelOrder(address onExchange, uint id) external returns (bool); // PUBLIC METHODS // PUBLIC VIEW METHODS function isApproveOnly() view returns (bool); function getLastOrderId(address onExchange) view returns (uint); function isActive(address onExchange, uint id) view returns (bool); function getOwner(address onExchange, uint id) view returns (address); function getOrder(address onExchange, uint id) view returns (address, address, uint, uint); function getTimestamp(address onExchange, uint id) view returns (uint); } contract CanonicalRegistrar is DSThing, DBC { // TYPES struct Asset { bool exists; // True if asset is registered here bytes32 name; // Human-readable name of the Asset as in ERC223 token standard bytes8 symbol; // Human-readable symbol of the Asset as in ERC223 token standard uint decimals; // Decimal, order of magnitude of precision, of the Asset as in ERC223 token standard string url; // URL for additional information of Asset string ipfsHash; // Same as url but for ipfs address breakIn; // Break in contract on destination chain address breakOut; // Break out contract on this chain; A way to leave uint[] standards; // compliance with standards like ERC20, ERC223, ERC777, etc. (the uint is the standard number) bytes4[] functionSignatures; // Whitelisted function signatures that can be called using `useExternalFunction` in Fund contract. Note: Adhere to a naming convention for `Fund<->Asset` as much as possible. I.e. name same concepts with the same functionSignature. uint price; // Price of asset quoted against `QUOTE_ASSET` * 10 ** decimals uint timestamp; // Timestamp of last price update of this asset } struct Exchange { bool exists; address adapter; // adapter contract for this exchange // One-time note: takesCustody is inverse case of isApproveOnly bool takesCustody; // True in case of exchange implementation which requires are approved when an order is made instead of transfer bytes4[] functionSignatures; // Whitelisted function signatures that can be called using `useExternalFunction` in Fund contract. Note: Adhere to a naming convention for `Fund<->ExchangeAdapter` as much as possible. I.e. name same concepts with the same functionSignature. } // TODO: populate each field here // TODO: add whitelistFunction function // FIELDS // Methods fields mapping (address => Asset) public assetInformation; address[] public registeredAssets; mapping (address => Exchange) public exchangeInformation; address[] public registeredExchanges; // METHODS // PUBLIC METHODS /// @notice Registers an Asset information entry /// @dev Pre: Only registrar owner should be able to register /// @dev Post: Address ofAsset is registered /// @param ofAsset Address of asset to be registered /// @param inputName Human-readable name of the Asset as in ERC223 token standard /// @param inputSymbol Human-readable symbol of the Asset as in ERC223 token standard /// @param inputDecimals Human-readable symbol of the Asset as in ERC223 token standard /// @param inputUrl Url for extended information of the asset /// @param inputIpfsHash Same as url but for ipfs /// @param breakInBreakOut Address of break in and break out contracts on destination chain /// @param inputStandards Integers of EIP standards this asset adheres to /// @param inputFunctionSignatures Function signatures for whitelisted asset functions function registerAsset( address ofAsset, bytes32 inputName, bytes8 inputSymbol, uint inputDecimals, string inputUrl, string inputIpfsHash, address[2] breakInBreakOut, uint[] inputStandards, bytes4[] inputFunctionSignatures ) auth pre_cond(!assetInformation[ofAsset].exists) { assetInformation[ofAsset].exists = true; registeredAssets.push(ofAsset); updateAsset( ofAsset, inputName, inputSymbol, inputDecimals, inputUrl, inputIpfsHash, breakInBreakOut, inputStandards, inputFunctionSignatures ); assert(assetInformation[ofAsset].exists); } /// @notice Register an exchange information entry /// @dev Pre: Only registrar owner should be able to register /// @dev Post: Address ofExchange is registered /// @param ofExchange Address of the exchange /// @param ofExchangeAdapter Address of exchange adapter for this exchange /// @param inputTakesCustody Whether this exchange takes custody of tokens before trading /// @param inputFunctionSignatures Function signatures for whitelisted exchange functions function registerExchange( address ofExchange, address ofExchangeAdapter, bool inputTakesCustody, bytes4[] inputFunctionSignatures ) auth pre_cond(!exchangeInformation[ofExchange].exists) { exchangeInformation[ofExchange].exists = true; registeredExchanges.push(ofExchange); updateExchange( ofExchange, ofExchangeAdapter, inputTakesCustody, inputFunctionSignatures ); assert(exchangeInformation[ofExchange].exists); } /// @notice Updates description information of a registered Asset /// @dev Pre: Owner can change an existing entry /// @dev Post: Changed Name, Symbol, URL and/or IPFSHash /// @param ofAsset Address of the asset to be updated /// @param inputName Human-readable name of the Asset as in ERC223 token standard /// @param inputSymbol Human-readable symbol of the Asset as in ERC223 token standard /// @param inputUrl Url for extended information of the asset /// @param inputIpfsHash Same as url but for ipfs function updateAsset( address ofAsset, bytes32 inputName, bytes8 inputSymbol, uint inputDecimals, string inputUrl, string inputIpfsHash, address[2] ofBreakInBreakOut, uint[] inputStandards, bytes4[] inputFunctionSignatures ) auth pre_cond(assetInformation[ofAsset].exists) { Asset asset = assetInformation[ofAsset]; asset.name = inputName; asset.symbol = inputSymbol; asset.decimals = inputDecimals; asset.url = inputUrl; asset.ipfsHash = inputIpfsHash; asset.breakIn = ofBreakInBreakOut[0]; asset.breakOut = ofBreakInBreakOut[1]; asset.standards = inputStandards; asset.functionSignatures = inputFunctionSignatures; } function updateExchange( address ofExchange, address ofExchangeAdapter, bool inputTakesCustody, bytes4[] inputFunctionSignatures ) auth pre_cond(exchangeInformation[ofExchange].exists) { Exchange exchange = exchangeInformation[ofExchange]; exchange.adapter = ofExchangeAdapter; exchange.takesCustody = inputTakesCustody; exchange.functionSignatures = inputFunctionSignatures; } // TODO: check max size of array before remaking this becomes untenable /// @notice Deletes an existing entry /// @dev Owner can delete an existing entry /// @param ofAsset address for which specific information is requested function removeAsset( address ofAsset, uint assetIndex ) auth pre_cond(assetInformation[ofAsset].exists) { require(registeredAssets[assetIndex] == ofAsset); delete assetInformation[ofAsset]; // Sets exists boolean to false delete registeredAssets[assetIndex]; for (uint i = assetIndex; i < registeredAssets.length-1; i++) { registeredAssets[i] = registeredAssets[i+1]; } registeredAssets.length--; assert(!assetInformation[ofAsset].exists); } /// @notice Deletes an existing entry /// @dev Owner can delete an existing entry /// @param ofExchange address for which specific information is requested /// @param exchangeIndex index of the exchange in array function removeExchange( address ofExchange, uint exchangeIndex ) auth pre_cond(exchangeInformation[ofExchange].exists) { require(registeredExchanges[exchangeIndex] == ofExchange); delete exchangeInformation[ofExchange]; delete registeredExchanges[exchangeIndex]; for (uint i = exchangeIndex; i < registeredExchanges.length-1; i++) { registeredExchanges[i] = registeredExchanges[i+1]; } registeredExchanges.length--; assert(!exchangeInformation[ofExchange].exists); } // PUBLIC VIEW METHODS // get asset specific information function getName(address ofAsset) view returns (bytes32) { return assetInformation[ofAsset].name; } function getSymbol(address ofAsset) view returns (bytes8) { return assetInformation[ofAsset].symbol; } function getDecimals(address ofAsset) view returns (uint) { return assetInformation[ofAsset].decimals; } function assetIsRegistered(address ofAsset) view returns (bool) { return assetInformation[ofAsset].exists; } function getRegisteredAssets() view returns (address[]) { return registeredAssets; } function assetMethodIsAllowed( address ofAsset, bytes4 querySignature ) returns (bool) { bytes4[] memory signatures = assetInformation[ofAsset].functionSignatures; for (uint i = 0; i < signatures.length; i++) { if (signatures[i] == querySignature) { return true; } } return false; } // get exchange-specific information function exchangeIsRegistered(address ofExchange) view returns (bool) { return exchangeInformation[ofExchange].exists; } function getRegisteredExchanges() view returns (address[]) { return registeredExchanges; } function getExchangeInformation(address ofExchange) view returns (address, bool) { Exchange exchange = exchangeInformation[ofExchange]; return ( exchange.adapter, exchange.takesCustody ); } function getExchangeFunctionSignatures(address ofExchange) view returns (bytes4[]) { return exchangeInformation[ofExchange].functionSignatures; } function exchangeMethodIsAllowed( address ofExchange, bytes4 querySignature ) returns (bool) { bytes4[] memory signatures = exchangeInformation[ofExchange].functionSignatures; for (uint i = 0; i < signatures.length; i++) { if (signatures[i] == querySignature) { return true; } } return false; } } interface SimplePriceFeedInterface { // EVENTS event PriceUpdated(bytes32 hash); // PUBLIC METHODS function update(address[] ofAssets, uint[] newPrices) external; // PUBLIC VIEW METHODS // Get price feed operation specific information function getQuoteAsset() view returns (address); function getLastUpdateId() view returns (uint); // Get asset specific information as updated in price feed function getPrice(address ofAsset) view returns (uint price, uint timestamp); function getPrices(address[] ofAssets) view returns (uint[] prices, uint[] timestamps); } contract SimplePriceFeed is SimplePriceFeedInterface, DSThing, DBC { // TYPES struct Data { uint price; uint timestamp; } // FIELDS mapping(address => Data) public assetsToPrices; // Constructor fields address public QUOTE_ASSET; // Asset of a portfolio against which all other assets are priced // Contract-level variables uint public updateId; // Update counter for this pricefeed; used as a check during investment CanonicalRegistrar public registrar; CanonicalPriceFeed public superFeed; // METHODS // CONSTRUCTOR /// @param ofQuoteAsset Address of quote asset /// @param ofRegistrar Address of canonical registrar /// @param ofSuperFeed Address of superfeed function SimplePriceFeed( address ofRegistrar, address ofQuoteAsset, address ofSuperFeed ) { registrar = CanonicalRegistrar(ofRegistrar); QUOTE_ASSET = ofQuoteAsset; superFeed = CanonicalPriceFeed(ofSuperFeed); } // EXTERNAL METHODS /// @dev Only Owner; Same sized input arrays /// @dev Updates price of asset relative to QUOTE_ASSET /** Ex: * Let QUOTE_ASSET == MLN (base units), let asset == EUR-T, * let Value of 1 EUR-T := 1 EUR == 0.080456789 MLN, hence price 0.080456789 MLN / EUR-T * and let EUR-T decimals == 8. * Input would be: information[EUR-T].price = 8045678 [MLN/ (EUR-T * 10**8)] */ /// @param ofAssets list of asset addresses /// @param newPrices list of prices for each of the assets function update(address[] ofAssets, uint[] newPrices) external auth { _updatePrices(ofAssets, newPrices); } // PUBLIC VIEW METHODS // Get pricefeed specific information function getQuoteAsset() view returns (address) { return QUOTE_ASSET; } function getLastUpdateId() view returns (uint) { return updateId; } /** @notice Gets price of an asset multiplied by ten to the power of assetDecimals @dev Asset has been registered @param ofAsset Asset for which price should be returned @return { "price": "Price formatting: mul(exchangePrice, 10 ** decimal), to avoid floating numbers", "timestamp": "When the asset's price was updated" } */ function getPrice(address ofAsset) view returns (uint price, uint timestamp) { Data data = assetsToPrices[ofAsset]; return (data.price, data.timestamp); } /** @notice Price of a registered asset in format (bool areRecent, uint[] prices, uint[] decimals) @dev Convention for price formatting: mul(price, 10 ** decimal), to avoid floating numbers @param ofAssets Assets for which prices should be returned @return { "prices": "Array of prices", "timestamps": "Array of timestamps", } */ function getPrices(address[] ofAssets) view returns (uint[], uint[]) { uint[] memory prices = new uint[](ofAssets.length); uint[] memory timestamps = new uint[](ofAssets.length); for (uint i; i < ofAssets.length; i++) { var (price, timestamp) = getPrice(ofAssets[i]); prices[i] = price; timestamps[i] = timestamp; } return (prices, timestamps); } // INTERNAL METHODS /// @dev Internal so that feeds inheriting this one are not obligated to have an exposed update(...) method, but can still perform updates function _updatePrices(address[] ofAssets, uint[] newPrices) internal pre_cond(ofAssets.length == newPrices.length) { updateId++; for (uint i = 0; i < ofAssets.length; ++i) { require(registrar.assetIsRegistered(ofAssets[i])); require(assetsToPrices[ofAssets[i]].timestamp != now); // prevent two updates in one block assetsToPrices[ofAssets[i]].timestamp = now; assetsToPrices[ofAssets[i]].price = newPrices[i]; } emit PriceUpdated(keccak256(ofAssets, newPrices)); } } contract StakingPriceFeed is SimplePriceFeed { OperatorStaking public stakingContract; AssetInterface public stakingToken; // CONSTRUCTOR /// @param ofQuoteAsset Address of quote asset /// @param ofRegistrar Address of canonical registrar /// @param ofSuperFeed Address of superfeed function StakingPriceFeed( address ofRegistrar, address ofQuoteAsset, address ofSuperFeed ) SimplePriceFeed(ofRegistrar, ofQuoteAsset, ofSuperFeed) { stakingContract = OperatorStaking(ofSuperFeed); // canonical feed *is* staking contract stakingToken = AssetInterface(stakingContract.stakingToken()); } // EXTERNAL METHODS /// @param amount Number of tokens to stake for this feed /// @param data Data may be needed for some future applications (can be empty for now) function depositStake(uint amount, bytes data) external auth { require(stakingToken.transferFrom(msg.sender, address(this), amount)); require(stakingToken.approve(stakingContract, amount)); stakingContract.stake(amount, data); } /// @param amount Number of tokens to unstake for this feed /// @param data Data may be needed for some future applications (can be empty for now) function unstake(uint amount, bytes data) external auth { stakingContract.unstake(amount, data); } function withdrawStake() external auth { uint amountToWithdraw = stakingContract.stakeToWithdraw(address(this)); stakingContract.withdrawStake(); require(stakingToken.transfer(msg.sender, amountToWithdraw)); } } interface RiskMgmtInterface { // METHODS // PUBLIC VIEW METHODS /// @notice Checks if the makeOrder price is reasonable and not manipulative /// @param orderPrice Price of Order /// @param referencePrice Reference price obtained through PriceFeed contract /// @param sellAsset Asset (as registered in Asset registrar) to be sold /// @param buyAsset Asset (as registered in Asset registrar) to be bought /// @param sellQuantity Quantity of sellAsset to be sold /// @param buyQuantity Quantity of buyAsset to be bought /// @return If makeOrder is permitted function isMakePermitted( uint orderPrice, uint referencePrice, address sellAsset, address buyAsset, uint sellQuantity, uint buyQuantity ) view returns (bool); /// @notice Checks if the takeOrder price is reasonable and not manipulative /// @param orderPrice Price of Order /// @param referencePrice Reference price obtained through PriceFeed contract /// @param sellAsset Asset (as registered in Asset registrar) to be sold /// @param buyAsset Asset (as registered in Asset registrar) to be bought /// @param sellQuantity Quantity of sellAsset to be sold /// @param buyQuantity Quantity of buyAsset to be bought /// @return If takeOrder is permitted function isTakePermitted( uint orderPrice, uint referencePrice, address sellAsset, address buyAsset, uint sellQuantity, uint buyQuantity ) view returns (bool); } contract OperatorStaking is DBC { // EVENTS event Staked(address indexed user, uint256 amount, uint256 total, bytes data); event Unstaked(address indexed user, uint256 amount, uint256 total, bytes data); event StakeBurned(address indexed user, uint256 amount, bytes data); // TYPES struct StakeData { uint amount; address staker; } // Circular linked list struct Node { StakeData data; uint prev; uint next; } // FIELDS // INTERNAL FIELDS Node[] internal stakeNodes; // Sorted circular linked list nodes containing stake data (Built on top https://programtheblockchain.com/posts/2018/03/30/storage-patterns-doubly-linked-list/) // PUBLIC FIELDS uint public minimumStake; uint public numOperators; uint public withdrawalDelay; mapping (address => bool) public isRanked; mapping (address => uint) public latestUnstakeTime; mapping (address => uint) public stakeToWithdraw; mapping (address => uint) public stakedAmounts; uint public numStakers; // Current number of stakers (Needed because of array holes) AssetInterface public stakingToken; // TODO: consider renaming "operator" depending on how this is implemented // (i.e. is pricefeed staking itself?) function OperatorStaking( AssetInterface _stakingToken, uint _minimumStake, uint _numOperators, uint _withdrawalDelay ) public { require(address(_stakingToken) != address(0)); stakingToken = _stakingToken; minimumStake = _minimumStake; numOperators = _numOperators; withdrawalDelay = _withdrawalDelay; StakeData memory temp = StakeData({ amount: 0, staker: address(0) }); stakeNodes.push(Node(temp, 0, 0)); } // METHODS : STAKING function stake( uint amount, bytes data ) public pre_cond(amount >= minimumStake) { stakedAmounts[msg.sender] += amount; updateStakerRanking(msg.sender); require(stakingToken.transferFrom(msg.sender, address(this), amount)); } function unstake( uint amount, bytes data ) public { uint preStake = stakedAmounts[msg.sender]; uint postStake = preStake - amount; require(postStake >= minimumStake || postStake == 0); require(stakedAmounts[msg.sender] >= amount); latestUnstakeTime[msg.sender] = block.timestamp; stakedAmounts[msg.sender] -= amount; stakeToWithdraw[msg.sender] += amount; updateStakerRanking(msg.sender); emit Unstaked(msg.sender, amount, stakedAmounts[msg.sender], data); } function withdrawStake() public pre_cond(stakeToWithdraw[msg.sender] > 0) pre_cond(block.timestamp >= latestUnstakeTime[msg.sender] + withdrawalDelay) { uint amount = stakeToWithdraw[msg.sender]; stakeToWithdraw[msg.sender] = 0; require(stakingToken.transfer(msg.sender, amount)); } // VIEW FUNCTIONS function isValidNode(uint id) view returns (bool) { // 0 is a sentinel and therefore invalid. // A valid node is the head or has a previous node. return id != 0 && (id == stakeNodes[0].next || stakeNodes[id].prev != 0); } function searchNode(address staker) view returns (uint) { uint current = stakeNodes[0].next; while (isValidNode(current)) { if (staker == stakeNodes[current].data.staker) { return current; } current = stakeNodes[current].next; } return 0; } function isOperator(address user) view returns (bool) { address[] memory operators = getOperators(); for (uint i; i < operators.length; i++) { if (operators[i] == user) { return true; } } return false; } function getOperators() view returns (address[]) { uint arrLength = (numOperators > numStakers) ? numStakers : numOperators; address[] memory operators = new address[](arrLength); uint current = stakeNodes[0].next; for (uint i; i < arrLength; i++) { operators[i] = stakeNodes[current].data.staker; current = stakeNodes[current].next; } return operators; } function getStakersAndAmounts() view returns (address[], uint[]) { address[] memory stakers = new address[](numStakers); uint[] memory amounts = new uint[](numStakers); uint current = stakeNodes[0].next; for (uint i; i < numStakers; i++) { stakers[i] = stakeNodes[current].data.staker; amounts[i] = stakeNodes[current].data.amount; current = stakeNodes[current].next; } return (stakers, amounts); } function totalStakedFor(address user) view returns (uint) { return stakedAmounts[user]; } // INTERNAL METHODS // DOUBLY-LINKED LIST function insertNodeSorted(uint amount, address staker) internal returns (uint) { uint current = stakeNodes[0].next; if (current == 0) return insertNodeAfter(0, amount, staker); while (isValidNode(current)) { if (amount > stakeNodes[current].data.amount) { break; } current = stakeNodes[current].next; } return insertNodeBefore(current, amount, staker); } function insertNodeAfter(uint id, uint amount, address staker) internal returns (uint newID) { // 0 is allowed here to insert at the beginning. require(id == 0 || isValidNode(id)); Node storage node = stakeNodes[id]; stakeNodes.push(Node({ data: StakeData(amount, staker), prev: id, next: node.next })); newID = stakeNodes.length - 1; stakeNodes[node.next].prev = newID; node.next = newID; numStakers++; } function insertNodeBefore(uint id, uint amount, address staker) internal returns (uint) { return insertNodeAfter(stakeNodes[id].prev, amount, staker); } function removeNode(uint id) internal { require(isValidNode(id)); Node storage node = stakeNodes[id]; stakeNodes[node.next].prev = node.prev; stakeNodes[node.prev].next = node.next; delete stakeNodes[id]; numStakers--; } // UPDATING OPERATORS function updateStakerRanking(address _staker) internal { uint newStakedAmount = stakedAmounts[_staker]; if (newStakedAmount == 0) { isRanked[_staker] = false; removeStakerFromArray(_staker); } else if (isRanked[_staker]) { removeStakerFromArray(_staker); insertNodeSorted(newStakedAmount, _staker); } else { isRanked[_staker] = true; insertNodeSorted(newStakedAmount, _staker); } } function removeStakerFromArray(address _staker) internal { uint id = searchNode(_staker); require(id > 0); removeNode(id); } } contract CanonicalPriceFeed is OperatorStaking, SimplePriceFeed, CanonicalRegistrar { // EVENTS event SetupPriceFeed(address ofPriceFeed); struct HistoricalPrices { address[] assets; uint[] prices; uint timestamp; } // FIELDS bool public updatesAreAllowed = true; uint public minimumPriceCount = 1; uint public VALIDITY; uint public INTERVAL; mapping (address => bool) public isStakingFeed; // If the Staking Feed has been created through this contract HistoricalPrices[] public priceHistory; // METHODS // CONSTRUCTOR /// @dev Define and register a quote asset against which all prices are measured/based against /// @param ofStakingAsset Address of staking asset (may or may not be quoteAsset) /// @param ofQuoteAsset Address of quote asset /// @param quoteAssetName Name of quote asset /// @param quoteAssetSymbol Symbol for quote asset /// @param quoteAssetDecimals Decimal places for quote asset /// @param quoteAssetUrl URL related to quote asset /// @param quoteAssetIpfsHash IPFS hash associated with quote asset /// @param quoteAssetBreakInBreakOut Break-in/break-out for quote asset on destination chain /// @param quoteAssetStandards EIP standards quote asset adheres to /// @param quoteAssetFunctionSignatures Whitelisted functions of quote asset contract // /// @param interval Number of seconds between pricefeed updates (this interval is not enforced on-chain, but should be followed by the datafeed maintainer) // /// @param validity Number of seconds that datafeed update information is valid for /// @param ofGovernance Address of contract governing the Canonical PriceFeed function CanonicalPriceFeed( address ofStakingAsset, address ofQuoteAsset, // Inital entry in asset registrar contract is Melon (QUOTE_ASSET) bytes32 quoteAssetName, bytes8 quoteAssetSymbol, uint quoteAssetDecimals, string quoteAssetUrl, string quoteAssetIpfsHash, address[2] quoteAssetBreakInBreakOut, uint[] quoteAssetStandards, bytes4[] quoteAssetFunctionSignatures, uint[2] updateInfo, // interval, validity uint[3] stakingInfo, // minStake, numOperators, unstakeDelay address ofGovernance ) OperatorStaking( AssetInterface(ofStakingAsset), stakingInfo[0], stakingInfo[1], stakingInfo[2] ) SimplePriceFeed(address(this), ofQuoteAsset, address(0)) { registerAsset( ofQuoteAsset, quoteAssetName, quoteAssetSymbol, quoteAssetDecimals, quoteAssetUrl, quoteAssetIpfsHash, quoteAssetBreakInBreakOut, quoteAssetStandards, quoteAssetFunctionSignatures ); INTERVAL = updateInfo[0]; VALIDITY = updateInfo[1]; setOwner(ofGovernance); } // EXTERNAL METHODS /// @notice Create a new StakingPriceFeed function setupStakingPriceFeed() external { address ofStakingPriceFeed = new StakingPriceFeed( address(this), stakingToken, address(this) ); isStakingFeed[ofStakingPriceFeed] = true; StakingPriceFeed(ofStakingPriceFeed).setOwner(msg.sender); emit SetupPriceFeed(ofStakingPriceFeed); } /// @dev override inherited update function to prevent manual update from authority function update(address[] ofAssets, uint[] newPrices) external { revert(); } /// @dev Burn state for a pricefeed operator /// @param user Address of pricefeed operator to burn the stake from function burnStake(address user) external auth { uint totalToBurn = add(stakedAmounts[user], stakeToWithdraw[user]); stakedAmounts[user] = 0; stakeToWithdraw[user] = 0; updateStakerRanking(user); emit StakeBurned(user, totalToBurn, ""); } // PUBLIC METHODS // STAKING function stake( uint amount, bytes data ) public pre_cond(isStakingFeed[msg.sender]) { OperatorStaking.stake(amount, data); } // function stakeFor( // address user, // uint amount, // bytes data // ) // public // pre_cond(isStakingFeed[user]) // { // OperatorStaking.stakeFor(user, amount, data); // } // AGGREGATION /// @dev Only Owner; Same sized input arrays /// @dev Updates price of asset relative to QUOTE_ASSET /** Ex: * Let QUOTE_ASSET == MLN (base units), let asset == EUR-T, * let Value of 1 EUR-T := 1 EUR == 0.080456789 MLN, hence price 0.080456789 MLN / EUR-T * and let EUR-T decimals == 8. * Input would be: information[EUR-T].price = 8045678 [MLN/ (EUR-T * 10**8)] */ /// @param ofAssets list of asset addresses function collectAndUpdate(address[] ofAssets) public auth pre_cond(updatesAreAllowed) { uint[] memory newPrices = pricesToCommit(ofAssets); priceHistory.push( HistoricalPrices({assets: ofAssets, prices: newPrices, timestamp: block.timestamp}) ); _updatePrices(ofAssets, newPrices); } function pricesToCommit(address[] ofAssets) view returns (uint[]) { address[] memory operators = getOperators(); uint[] memory newPrices = new uint[](ofAssets.length); for (uint i = 0; i < ofAssets.length; i++) { uint[] memory assetPrices = new uint[](operators.length); for (uint j = 0; j < operators.length; j++) { SimplePriceFeed feed = SimplePriceFeed(operators[j]); var (price, timestamp) = feed.assetsToPrices(ofAssets[i]); if (now > add(timestamp, VALIDITY)) { continue; // leaves a zero in the array (dealt with later) } assetPrices[j] = price; } newPrices[i] = medianize(assetPrices); } return newPrices; } /// @dev from MakerDao medianizer contract function medianize(uint[] unsorted) view returns (uint) { uint numValidEntries; for (uint i = 0; i < unsorted.length; i++) { if (unsorted[i] != 0) { numValidEntries++; } } if (numValidEntries < minimumPriceCount) { revert(); } uint counter; uint[] memory out = new uint[](numValidEntries); for (uint j = 0; j < unsorted.length; j++) { uint item = unsorted[j]; if (item != 0) { // skip zero (invalid) entries if (counter == 0 || item >= out[counter - 1]) { out[counter] = item; // item is larger than last in array (we are home) } else { uint k = 0; while (item >= out[k]) { k++; // get to where element belongs (between smaller and larger items) } for (uint m = counter; m > k; m--) { out[m] = out[m - 1]; // bump larger elements rightward to leave slot } out[k] = item; } counter++; } } uint value; if (counter % 2 == 0) { uint value1 = uint(out[(counter / 2) - 1]); uint value2 = uint(out[(counter / 2)]); value = add(value1, value2) / 2; } else { value = out[(counter - 1) / 2]; } return value; } function setMinimumPriceCount(uint newCount) auth { minimumPriceCount = newCount; } function enableUpdates() auth { updatesAreAllowed = true; } function disableUpdates() auth { updatesAreAllowed = false; } // PUBLIC VIEW METHODS // FEED INFORMATION function getQuoteAsset() view returns (address) { return QUOTE_ASSET; } function getInterval() view returns (uint) { return INTERVAL; } function getValidity() view returns (uint) { return VALIDITY; } function getLastUpdateId() view returns (uint) { return updateId; } // PRICES /// @notice Whether price of asset has been updated less than VALIDITY seconds ago /// @param ofAsset Asset in registrar /// @return isRecent Price information ofAsset is recent function hasRecentPrice(address ofAsset) view pre_cond(assetIsRegistered(ofAsset)) returns (bool isRecent) { var ( , timestamp) = getPrice(ofAsset); return (sub(now, timestamp) <= VALIDITY); } /// @notice Whether prices of assets have been updated less than VALIDITY seconds ago /// @param ofAssets All assets in registrar /// @return isRecent Price information ofAssets array is recent function hasRecentPrices(address[] ofAssets) view returns (bool areRecent) { for (uint i; i < ofAssets.length; i++) { if (!hasRecentPrice(ofAssets[i])) { return false; } } return true; } function getPriceInfo(address ofAsset) view returns (bool isRecent, uint price, uint assetDecimals) { isRecent = hasRecentPrice(ofAsset); (price, ) = getPrice(ofAsset); assetDecimals = getDecimals(ofAsset); } /** @notice Gets inverted price of an asset @dev Asset has been initialised and its price is non-zero @dev Existing price ofAssets quoted in QUOTE_ASSET (convention) @param ofAsset Asset for which inverted price should be return @return { "isRecent": "Whether the price is fresh, given VALIDITY interval", "invertedPrice": "Price based (instead of quoted) against QUOTE_ASSET", "assetDecimals": "Decimal places for this asset" } */ function getInvertedPriceInfo(address ofAsset) view returns (bool isRecent, uint invertedPrice, uint assetDecimals) { uint inputPrice; // inputPrice quoted in QUOTE_ASSET and multiplied by 10 ** assetDecimal (isRecent, inputPrice, assetDecimals) = getPriceInfo(ofAsset); // outputPrice based in QUOTE_ASSET and multiplied by 10 ** quoteDecimal uint quoteDecimals = getDecimals(QUOTE_ASSET); return ( isRecent, mul(10 ** uint(quoteDecimals), 10 ** uint(assetDecimals)) / inputPrice, quoteDecimals // TODO: check on this; shouldn't it be assetDecimals? ); } /** @notice Gets reference price of an asset pair @dev One of the address is equal to quote asset @dev either ofBase == QUOTE_ASSET or ofQuote == QUOTE_ASSET @param ofBase Address of base asset @param ofQuote Address of quote asset @return { "isRecent": "Whether the price is fresh, given VALIDITY interval", "referencePrice": "Reference price", "decimal": "Decimal places for this asset" } */ function getReferencePriceInfo(address ofBase, address ofQuote) view returns (bool isRecent, uint referencePrice, uint decimal) { if (getQuoteAsset() == ofQuote) { (isRecent, referencePrice, decimal) = getPriceInfo(ofBase); } else if (getQuoteAsset() == ofBase) { (isRecent, referencePrice, decimal) = getInvertedPriceInfo(ofQuote); } else { revert(); // no suitable reference price available } } /// @notice Gets price of Order /// @param sellAsset Address of the asset to be sold /// @param buyAsset Address of the asset to be bought /// @param sellQuantity Quantity in base units being sold of sellAsset /// @param buyQuantity Quantity in base units being bought of buyAsset /// @return orderPrice Price as determined by an order function getOrderPriceInfo( address sellAsset, address buyAsset, uint sellQuantity, uint buyQuantity ) view returns (uint orderPrice) { return mul(buyQuantity, 10 ** uint(getDecimals(sellAsset))) / sellQuantity; } /// @notice Checks whether data exists for a given asset pair /// @dev Prices are only upated against QUOTE_ASSET /// @param sellAsset Asset for which check to be done if data exists /// @param buyAsset Asset for which check to be done if data exists /// @return Whether assets exist for given asset pair function existsPriceOnAssetPair(address sellAsset, address buyAsset) view returns (bool isExistent) { return hasRecentPrice(sellAsset) && // Is tradable asset (TODO cleaner) and datafeed delivering data hasRecentPrice(buyAsset) && // Is tradable asset (TODO cleaner) and datafeed delivering data (buyAsset == QUOTE_ASSET || sellAsset == QUOTE_ASSET) && // One asset must be QUOTE_ASSET (buyAsset != QUOTE_ASSET || sellAsset != QUOTE_ASSET); // Pair must consists of diffrent assets } /// @return Sparse array of addresses of owned pricefeeds function getPriceFeedsByOwner(address _owner) view returns(address[]) { address[] memory ofPriceFeeds = new address[](numStakers); if (numStakers == 0) return ofPriceFeeds; uint current = stakeNodes[0].next; for (uint i; i < numStakers; i++) { StakingPriceFeed stakingFeed = StakingPriceFeed(stakeNodes[current].data.staker); if (stakingFeed.owner() == _owner) { ofPriceFeeds[i] = address(stakingFeed); } current = stakeNodes[current].next; } return ofPriceFeeds; } function getHistoryLength() returns (uint) { return priceHistory.length; } function getHistoryAt(uint id) returns (address[], uint[], uint) { address[] memory assets = priceHistory[id].assets; uint[] memory prices = priceHistory[id].prices; uint timestamp = priceHistory[id].timestamp; return (assets, prices, timestamp); } } interface VersionInterface { // EVENTS event FundUpdated(uint id); // PUBLIC METHODS function shutDown() external; function setupFund( bytes32 ofFundName, address ofQuoteAsset, uint ofManagementFee, uint ofPerformanceFee, address ofCompliance, address ofRiskMgmt, address[] ofExchanges, address[] ofDefaultAssets, uint8 v, bytes32 r, bytes32 s ); function shutDownFund(address ofFund); // PUBLIC VIEW METHODS function getNativeAsset() view returns (address); function getFundById(uint withId) view returns (address); function getLastFundId() view returns (uint); function getFundByManager(address ofManager) view returns (address); function termsAndConditionsAreSigned(uint8 v, bytes32 r, bytes32 s) view returns (bool signed); } contract Version is DBC, Owned, VersionInterface { // FIELDS bytes32 public constant TERMS_AND_CONDITIONS = 0xAA9C907B0D6B4890E7225C09CBC16A01CB97288840201AA7CDCB27F4ED7BF159; // Hashed terms and conditions as displayed on IPFS, decoded from base 58 // Constructor fields string public VERSION_NUMBER; // SemVer of Melon protocol version address public MELON_ASSET; // Address of Melon asset contract address public NATIVE_ASSET; // Address of Fixed quote asset address public GOVERNANCE; // Address of Melon protocol governance contract address public CANONICAL_PRICEFEED; // Address of the canonical pricefeed // Methods fields bool public isShutDown; // Governance feature, if yes than setupFund gets blocked and shutDownFund gets opened address public COMPLIANCE; // restrict to Competition compliance module for this version address[] public listOfFunds; // A complete list of fund addresses created using this version mapping (address => address) public managerToFunds; // Links manager address to fund address created using this version // EVENTS event FundUpdated(address ofFund); // METHODS // CONSTRUCTOR /// @param versionNumber SemVer of Melon protocol version /// @param ofGovernance Address of Melon governance contract /// @param ofMelonAsset Address of Melon asset contract function Version( string versionNumber, address ofGovernance, address ofMelonAsset, address ofNativeAsset, address ofCanonicalPriceFeed, address ofCompetitionCompliance ) { VERSION_NUMBER = versionNumber; GOVERNANCE = ofGovernance; MELON_ASSET = ofMelonAsset; NATIVE_ASSET = ofNativeAsset; CANONICAL_PRICEFEED = ofCanonicalPriceFeed; COMPLIANCE = ofCompetitionCompliance; } // EXTERNAL METHODS function shutDown() external pre_cond(msg.sender == GOVERNANCE) { isShutDown = true; } // PUBLIC METHODS /// @param ofFundName human-readable descriptive name (not necessarily unique) /// @param ofQuoteAsset Asset against which performance fee is measured against /// @param ofManagementFee A time based fee, given in a number which is divided by 10 ** 15 /// @param ofPerformanceFee A time performance based fee, performance relative to ofQuoteAsset, given in a number which is divided by 10 ** 15 /// @param ofCompliance Address of participation module /// @param ofRiskMgmt Address of risk management module /// @param ofExchanges Addresses of exchange on which this fund can trade /// @param ofDefaultAssets Enable invest/redeem with these assets (quote asset already enabled) /// @param v ellipitc curve parameter v /// @param r ellipitc curve parameter r /// @param s ellipitc curve parameter s function setupFund( bytes32 ofFundName, address ofQuoteAsset, uint ofManagementFee, uint ofPerformanceFee, address ofCompliance, address ofRiskMgmt, address[] ofExchanges, address[] ofDefaultAssets, uint8 v, bytes32 r, bytes32 s ) { require(!isShutDown); require(termsAndConditionsAreSigned(v, r, s)); require(CompetitionCompliance(COMPLIANCE).isCompetitionAllowed(msg.sender)); require(managerToFunds[msg.sender] == address(0)); // Add limitation for simpler migration process of shutting down and setting up fund address[] memory melonAsDefaultAsset = new address[](1); melonAsDefaultAsset[0] = MELON_ASSET; // Melon asset should be in default assets address ofFund = new Fund( msg.sender, ofFundName, NATIVE_ASSET, 0, 0, COMPLIANCE, ofRiskMgmt, CANONICAL_PRICEFEED, ofExchanges, melonAsDefaultAsset ); listOfFunds.push(ofFund); managerToFunds[msg.sender] = ofFund; emit FundUpdated(ofFund); } /// @dev Dereference Fund and shut it down /// @param ofFund Address of the fund to be shut down function shutDownFund(address ofFund) pre_cond(isShutDown || managerToFunds[msg.sender] == ofFund) { Fund fund = Fund(ofFund); delete managerToFunds[msg.sender]; fund.shutDown(); emit FundUpdated(ofFund); } // PUBLIC VIEW METHODS /// @dev Proof that terms and conditions have been read and understood /// @param v ellipitc curve parameter v /// @param r ellipitc curve parameter r /// @param s ellipitc curve parameter s /// @return signed Whether or not terms and conditions have been read and understood function termsAndConditionsAreSigned(uint8 v, bytes32 r, bytes32 s) view returns (bool signed) { return ecrecover( // Parity does prepend \x19Ethereum Signed Message:\n{len(message)} before signing. // Signature order has also been changed in 1.6.7 and upcoming 1.7.x, // it will return rsv (same as geth; where v is [27, 28]). // Note that if you are using ecrecover, v will be either "00" or "01". // As a result, in order to use this value, you will have to parse it to an // integer and then add 27. This will result in either a 27 or a 28. // https://github.com/ethereum/wiki/wiki/JavaScript-API#web3ethsign keccak256("\x19Ethereum Signed Message:\n32", TERMS_AND_CONDITIONS), v, r, s ) == msg.sender; // Has sender signed TERMS_AND_CONDITIONS } function getNativeAsset() view returns (address) { return NATIVE_ASSET; } function getFundById(uint withId) view returns (address) { return listOfFunds[withId]; } function getLastFundId() view returns (uint) { return listOfFunds.length - 1; } function getFundByManager(address ofManager) view returns (address) { return managerToFunds[ofManager]; } }
Disable investment in specified assets ofAssets Array of assets to disable investment in
{ function disableInvestment(address[] ofAssets) external pre_cond(isOwner()) for (uint i = 0; i < ofAssets.length; ++i) { isInvestAllowed[ofAssets[i]] = false; } }
196,145
// This code has not been professionally audited, therefore I cannot make any promises about // safety or correctness. Use at own risk. pragma solidity 0.4.21; contract EternalStorage { address owner = msg.sender; address latestVersion; mapping(bytes32 => uint) uIntStorage; mapping(bytes32 => string) stringStorage; mapping(bytes32 => address) addressStorage; mapping(bytes32 => bytes) bytesStorage; mapping(bytes32 => bool) boolStorage; mapping(bytes32 => int) intStorage; modifier onlyLatestVersion() { require(msg.sender == latestVersion); _; } function upgradeVersion(address _newVersion) public { require(msg.sender == owner); latestVersion = _newVersion; } // *** Getter Methods *** function getUint(bytes32 _key) external view returns(uint) { return uIntStorage[_key]; } function getString(bytes32 _key) external view returns(string) { return stringStorage[_key]; } function getAddress(bytes32 _key) external view returns(address) { return addressStorage[_key]; } function getBytes(bytes32 _key) external view returns(bytes) { return bytesStorage[_key]; } function getBool(bytes32 _key) external view returns(bool) { return boolStorage[_key]; } function getInt(bytes32 _key) external view returns(int) { return intStorage[_key]; } // *** Setter Methods *** function setUint(bytes32 _key, uint _value) onlyLatestVersion external { uIntStorage[_key] = _value; } function setString(bytes32 _key, string _value) onlyLatestVersion external { stringStorage[_key] = _value; } function setAddress(bytes32 _key, address _value) onlyLatestVersion external { addressStorage[_key] = _value; } function setBytes(bytes32 _key, bytes _value) onlyLatestVersion external { bytesStorage[_key] = _value; } function setBool(bytes32 _key, bool _value) onlyLatestVersion external { boolStorage[_key] = _value; } function setInt(bytes32 _key, int _value) onlyLatestVersion external { intStorage[_key] = _value; } // *** Delete Methods *** function deleteUint(bytes32 _key) onlyLatestVersion external { delete uIntStorage[_key]; } function deleteString(bytes32 _key) onlyLatestVersion external { delete stringStorage[_key]; } function deleteAddress(bytes32 _key) onlyLatestVersion external { delete addressStorage[_key]; } function deleteBytes(bytes32 _key) onlyLatestVersion external { delete bytesStorage[_key]; } function deleteBool(bytes32 _key) onlyLatestVersion external { delete boolStorage[_key]; } function deleteInt(bytes32 _key) onlyLatestVersion external { delete intStorage[_key]; } }
Getter Methods
function getUint(bytes32 _key) external view returns(uint) { return uIntStorage[_key]; }
5,531,187
./full_match/1/0x496DaaEbcfEAa9aac073232fD850327a522e68b1/sources/browser/SafeMath.sol
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./
function mod(uint256 a, uint256 b) external pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; }
8,408,589
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import { ERC721Tradable } from "./base/ERC721Tradable.sol"; import { IRestore } from "./interfaces/IRestore.sol"; import { Ownable } from '@openzeppelin/contracts/access/Ownable.sol'; import { Counters } from "@openzeppelin/contracts/utils/Counters.sol"; // _____ _____ _____ _____ _______ _____ _____ // /\ \ /\ \ /\ \ /\ \ /::\ \ /\ \ /\ \ // /::\ \ /::\ \ /::\ \ /::\ \ /::::\ \ /::\ \ /::\ \ // /::::\ \ /::::\ \ /::::\ \ \:::\ \ /::::::\ \ /::::\ \ /::::\ \ // /::::::\ \ /::::::\ \ /::::::\ \ \:::\ \ /::::::::\ \ /::::::\ \ /::::::\ \ // /:::/\:::\ \ /:::/\:::\ \ /:::/\:::\ \ \:::\ \ /:::/~~\:::\ \ /:::/\:::\ \ /:::/\:::\ \ // /:::/__\:::\ \ /:::/__\:::\ \ /:::/__\:::\ \ \:::\ \ /:::/ \:::\ \ /:::/__\:::\ \ /:::/__\:::\ \ // /::::\ \:::\ \ /::::\ \:::\ \ \:::\ \:::\ \ /::::\ \ /:::/ / \:::\ \ /::::\ \:::\ \ /::::\ \:::\ \ // /::::::\ \:::\ \ /::::::\ \:::\ \ ___\:::\ \:::\ \ /::::::\ \ /:::/____/ \:::\____\ /::::::\ \:::\ \ /::::::\ \:::\ \ // /:::/\:::\ \:::\____\ /:::/\:::\ \:::\ \ /\ \:::\ \:::\ \ /:::/\:::\ \ |:::| | |:::| | /:::/\:::\ \:::\____\ /:::/\:::\ \:::\ \ // /:::/ \:::\ \:::| |/:::/__\:::\ \:::\____\/::\ \:::\ \:::\____\ /:::/ \:::\____\|:::|____| |:::| |/:::/ \:::\ \:::| |/:::/__\:::\ \:::\____\ // \::/ |::::\ /:::|____|\:::\ \:::\ \::/ /\:::\ \:::\ \::/ / /:::/ \::/ / \:::\ \ /:::/ / \::/ |::::\ /:::|____|\:::\ \:::\ \::/ / // \/____|:::::\/:::/ / \:::\ \:::\ \/____/ \:::\ \:::\ \/____/ /:::/ / \/____/ \:::\ \ /:::/ / \/____|:::::\/:::/ / \:::\ \:::\ \/____/ // |:::::::::/ / \:::\ \:::\ \ \:::\ \:::\ \ /:::/ / \:::\ /:::/ / |:::::::::/ / \:::\ \:::\ \ // |::|\::::/ / \:::\ \:::\____\ \:::\ \:::\____\ /:::/ / \:::\__/:::/ / |::|\::::/ / \:::\ \:::\____\ // |::| \::/____/ \:::\ \::/ / \:::\ /:::/ / \::/ / \::::::::/ / |::| \::/____/ \:::\ \::/ / // |::| ~| \:::\ \/____/ \:::\/:::/ / \/____/ \::::::/ / |::| ~| \:::\ \/____/ // |::| | \:::\ \ \::::::/ / \::::/ / |::| | \:::\ \ // \::| | \:::\____\ \::::/ / \::/____/ \::| | \:::\____\ // \:| | \::/ / \::/ / ~~ \:| | \::/ / // \|___| \/____/ \/____/ \|___| \/____/ contract Restore is ERC721Tradable, Ownable, IRestore { using Counters for Counters.Counter; Counters.Counter private _tokenIdCounter; // A mapping of all frozen tokens mapping(uint256 => address) buyers; // A reference to the Justice contract for security checks address public justice; constructor( address _proxyRegistryAddress ) ERC721Tradable('Restore', 'REST', _proxyRegistryAddress) {} /** * @dev Link to Contract metadata https://docs.opensea.io/docs/contract-level-metadata * TODO: add contract metadata */ function contractURI() external pure returns (string memory) { return "https://arweave.net/"; } /** @notice Set the royalties for the whole contract. Our intention is to set it to 10% in perpetuity. * @param recipient the royalties recipient - will always be pr1s0nart, for regulatory reasons. * @param value royalties value (between 0 and 10000) */ function setRoyalties(address recipient, uint256 value) external onlyOwner { _setRoyalties(recipient, value); } /** * @dev Safely mints a token to an address with a tokenURI. * @notice this mints the NFT to this contract so that we can ensure only the buyer can receive the first transfer and * prove contractually that no-one else can. * @param creator this will likely be pr1s0n.art, but may be others in the future. Included here for proper attribution. * @param uri full URI to token metadata */ function mintForAuction(address creator, string memory uri) external override onlyOwner returns (uint256 tokenId) { uint256 newTokenId = _tokenIdCounter.current(); _safeMint(creator, address(this), newTokenId); _setTokenURI(newTokenId, uri); _tokenIdCounter.increment(); onERC721Received(creator, address(0), newTokenId, bytes("New token ready for auction")); emit ReadyForAuction(address(this), newTokenId, uri); return(newTokenId); } /** * @notice sends 'frozen' NFT to the winning bidder by attaching the receipt. Protected only to ensure no random * data is uploaded on the transfer. * @param data URI to receipt metadata that will be added to the NFT * TODO: is it an issue that we store the receipt uri in bytes and the metadata uri above as a string? */ function transferToBuyer(uint256 tokenId, bytes memory data) external override onlyOwner { emit ArtTransferred(buyers[tokenId], tokenId, data); _safeTransfer(address(this), buyers[tokenId], tokenId, data); } /** * @notice called when an auction is settled, sets the frozenToken struct. * @param buyer address of winning bid * @param tokenId index of the NFT bought in the auction */ function freeze(address buyer, uint256 tokenId) external override { require(msg.sender == justice, "Restore: auctioned piece must be frozen by owner via Justice"); buyers[tokenId] = buyer; emit ArtFrozen(buyer, tokenId); } /** * @notice called by the owner to make sure the checks in freeze and transferToBuyer pass correctly * @param _justice the address of the justice contract */ function setJustice(address _justice) external onlyOwner { justice =_justice; } /** * @notice called by Justice to ensure that this token exists and can be auctioned before creating an auction * @param tokenId the tokenId to be checked for auction */ function auctionable(uint256 tokenId) external view override returns (bool) { require(_exists(tokenId), "Restore: unknown token"); return address(0) == buyers[tokenId]; } }
Safely mints a token to an address with a tokenURI. this mints the NFT to this contract so that we can ensure only the buyer can receive the first transfer and prove contractually that no-one else can. creator this will likely be pr1s0n.art, but may be others in the future. Included here for proper attribution. uri full URI to token metadata/
function mintForAuction(address creator, string memory uri) external override onlyOwner returns (uint256 tokenId) { uint256 newTokenId = _tokenIdCounter.current(); _safeMint(creator, address(this), newTokenId); _setTokenURI(newTokenId, uri); _tokenIdCounter.increment(); onERC721Received(creator, address(0), newTokenId, bytes("New token ready for auction")); emit ReadyForAuction(address(this), newTokenId, uri); return(newTokenId); }
12,868,589
./partial_match/4/0x9627D3E802cAB664da62aD0AccD5BfBaed3C0a30/sources/Proxy.sol
Tells the address of the current implementation return address of the current implementation/
function implementation() public view returns (address impl) { bytes32 position = implementationPosition; assembly { impl := sload(position) } }
16,967,446
./partial_match/1313161554/0x3A67b63D0baA5883A69A4360f56F5b7A8f090dbb/sources/StrategyTriMiniChefLP.sol
Toggle harvest cycle to false to start again
function toggleHarvest() internal { feesCharged = false; swapped = false; liquidityAdded = false; harvested = false; }
16,913,733
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ERC721Tradable.sol"; import "./IERC20.sol"; import "./openzeppelin-solidity/contracts/utils/math/SafeMath.sol"; import "./ICards.sol"; /** * @title Cards */ contract Cards is ERC721Tradable, ICards { using SafeMath for uint256; // Name change token address address private _nctAddress; constructor(address _proxyRegistryAddress, address nctAddress) ERC721Tradable("Parable", "PAR", _proxyRegistryAddress) { _nctAddress = nctAddress; } string public constant CARDS_PROVENANCE = "8a76b6238f7b5f14fefe90d2f176f9c9c3d410347d769e7183a25e95b78e4e69"; // Sha256 hash of the concatenated hashes of the image files uint256 public constant SALE_START_TIMESTAMP = 1630346400; // Start date of the sale. timestamps in solidity are in seconds https://docs.soliditylang.org/en/latest/units-and-global-variables.html?highlight=block#block-and-transaction-properties // Time after which cards are randomized and allotted uint256 public constant REVEAL_TIMESTAMP = SALE_START_TIMESTAMP + (86400 * 14); // 14 days after release uint256 public constant NAME_CHANGE_PRICE = 1830 * (10 ** 18); // Cost for changing the name of a Parable uint256 public startingIndexBlock; uint256 public startingIndex; uint256 public constant MAX_NFT_SUPPLY = 42000; // Mapping if certain name string has already been reserved mapping (string => bool) private _nameReserved; // Mapping from token ID to when the token was minted mapping (uint256 => uint256) private _mintTime; // Mapping from token ID to name mapping (uint256 => string) private _tokenName; // Events event NameChange (uint256 indexed cardIndex, string newName); /** * @dev Returns if the name has been reserved. */ function isNameReserved(string memory nameString) public view returns (bool) { return _nameReserved[toLower(nameString)]; } /** * @dev Returns if the NFT has been minted before reveal phase */ function isMintedBeforeReveal(uint256 index) override public view returns (bool) { return _mintTime[index] < REVEAL_TIMESTAMP; } /** * @dev Returns when the NFT has been minted */ function mintedTimestamp(uint256 index) override public view returns (uint256) { return _mintTime[index]; } function baseTokenURI() override public pure returns (string memory) { return "https://parablenft.com/api/parables/"; } function contractURI() public pure returns (string memory) { return "https://parablenft.com/api/contractmeta/"; } /** * @dev Returns name of the NFT at index. */ function tokenNameByIndex(uint256 index) public view returns (string memory) { return _tokenName[index]; } function mintNftTo(address _to) public onlyOwner { require(block.timestamp >= SALE_START_TIMESTAMP, "Sale has not started"); uint mintIndex = totalSupply().add(1); _mintTime[mintIndex] = block.timestamp; mintTo(_to); if (startingIndexBlock == 0 && (totalSupply() == MAX_NFT_SUPPLY || block.timestamp >= REVEAL_TIMESTAMP)) { startingIndexBlock = block.number; } } function finalizeStartingIndex() public { require(startingIndex == 0, "Starting index is already set"); require(startingIndexBlock != 0, "Starting index block must be set"); startingIndex = uint(blockhash(startingIndexBlock)) % MAX_NFT_SUPPLY; // Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes) if (block.number.sub(startingIndexBlock) > 255) { startingIndex = uint(blockhash(block.number-1)) % MAX_NFT_SUPPLY; } // Prevent default sequence if (startingIndex == 0) { startingIndex = startingIndex.add(1); } } function changeName(uint256 tokenId, string memory newName) public { address owner = ownerOf(tokenId); require(_msgSender() == owner, "ERC721: caller is not the owner"); require(validateName(newName) == true, "Not a valid new name"); require(sha256(bytes(newName)) != sha256(bytes(_tokenName[tokenId])), "New name is same as the current one"); require(isNameReserved(newName) == false, "Name already reserved"); IERC20(_nctAddress).transferFrom(msg.sender, address(this), NAME_CHANGE_PRICE); // If already named, dereserve old name if (bytes(_tokenName[tokenId]).length > 0) { toggleReserveName(_tokenName[tokenId], false); } toggleReserveName(newName, true); _tokenName[tokenId] = newName; IERC20(_nctAddress).burn(NAME_CHANGE_PRICE); emit NameChange(tokenId, newName); } /** * @dev Reserves the name if isReserve is set to true, de-reserves if set to false */ function toggleReserveName(string memory str, bool isReserve) internal { _nameReserved[toLower(str)] = isReserve; } /** * @dev Check if the name string is valid (Alphanumeric and spaces without leading or trailing space) */ function validateName(string memory str) public pure returns (bool){ bytes memory b = bytes(str); if(b.length < 1) return false; if(b.length > 25) return false; // Cannot be longer than 25 characters if(b[0] == 0x20) return false; // Leading space if (b[b.length - 1] == 0x20) return false; // Trailing space bytes1 lastChar = b[0]; for(uint i; i<b.length; i++){ bytes1 char = b[i]; if (char == 0x20 && lastChar == 0x20) return false; // Cannot contain continous spaces if( !(char >= 0x30 && char <= 0x39) && //9-0 !(char >= 0x41 && char <= 0x5A) && //A-Z !(char >= 0x61 && char <= 0x7A) && //a-z !(char == 0x20) //space ) return false; lastChar = char; } return true; } function toLower(string memory str) public pure returns (string memory){ bytes memory bStr = bytes(str); bytes memory bLower = new bytes(bStr.length); for (uint i = 0; i < bStr.length; i++) { // Uppercase character if ((uint8(bStr[i]) >= 65) && (uint8(bStr[i]) <= 90)) { bLower[i] = bytes1(uint8(bStr[i]) + 32); } else { bLower[i] = bStr[i]; } } return string(bLower); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./openzeppelin-solidity/contracts/token/ERC721/ERC721.sol"; import "./openzeppelin-solidity/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "./openzeppelin-solidity/contracts/access/Ownable.sol"; import "./openzeppelin-solidity/contracts/utils/math/SafeMath.sol"; import "./openzeppelin-solidity/contracts/utils/Strings.sol"; contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } /** * @title ERC721Tradable * ERC721Tradable - ERC721 contract that whitelists a trading address, and has minting functionality. */ abstract contract ERC721Tradable is ERC721Enumerable, Ownable { using SafeMath for uint256; address proxyRegistryAddress; uint256 private _currentTokenId = 0; constructor( string memory _name, string memory _symbol, address _proxyRegistryAddress ) ERC721(_name, _symbol) { proxyRegistryAddress = _proxyRegistryAddress; } /** * @dev Mints a token to an address with a tokenURI. * @param _to address of the future owner of the token */ function mintTo(address _to) public onlyOwner { uint256 newTokenId = _getNextTokenId(); _mint(_to, newTokenId); _incrementTokenId(); } /** * @dev calculates the next token ID based on value of _currentTokenId * @return uint256 for the next token ID */ function _getNextTokenId() private view returns (uint256) { return _currentTokenId.add(1); } /** * @dev increments the value of _currentTokenId */ function _incrementTokenId() private { _currentTokenId++; } function baseTokenURI() virtual public pure returns (string memory); function tokenURI(uint256 _tokenId) override public pure returns (string memory) { return string(abi.encodePacked(baseTokenURI(), Strings.toString(_tokenId))); } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings. */ function isApprovedForAll(address owner, address operator) override public view returns (bool) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(owner)) == operator) { return true; } return super.isApprovedForAll(owner, operator); } } import "./openzeppelin-solidity/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; // interface ICreature is IERC721Enumerable { interface ICards is IERC721Enumerable{ function isMintedBeforeReveal(uint256 index) external view returns (bool); function mintedTimestamp(uint256 index) external view returns (uint256); } pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ 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); /** * TODO: Add comment */ function burn(uint256 burnQuantity) 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); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @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() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping (uint256 => address) private _owners; // Mapping owner address to token count mapping (address => uint256) private _balances; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. Empty by default, can be overriden * in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` 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 tokenId) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT 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) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // 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 (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @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) { return a + b; } /** * @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 a - b; } /** * @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) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting 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 a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting 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. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * 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, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } }
Returns if the NFT has been minted before reveal phase/
function isMintedBeforeReveal(uint256 index) override public view returns (bool) { return _mintTime[index] < REVEAL_TIMESTAMP; }
13,383,540
./full_match/1/0xefaCa6Fc316B3B2Aa6c55FF5E02a62A85d4391e8/sources/@synthetixio/core-contracts/contracts/utils/SafeCast/SafeCastI256.sol
----<==========================o===========================>---- ----xxxxxxxxxxxx<==============o==============>xxxxxxxxxxxxx----
function to128(int256 x) internal pure returns (int128) { if (x < int256(type(int128).min) || x > int256(type(int128).max)) { revert OverflowInt256ToInt128(); } return int128(x); }
16,517,588
./full_match/420/0x7E5bFe4eB375e81bba15d2Fc4b71a823e3B7F356/sources/contracts/ConfidenceRouter.sol
refund dust eth, if any
function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable virtual override ensure(deadline) returns (uint256 amountToken, uint256 amountETH, uint256 liquidity) { (amountToken, amountETH) = _addLiquidity( token, WETH, amountTokenDesired, msg.value, amountTokenMin, amountETHMin ); address pair = ConfidenceLibrary.pairFor(factory, token, WETH); TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken); assert(IWETH(WETH).transfer(pair, amountETH)); liquidity = IConfidencePair(pair).mint(to); if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH); }
13,225,617
./full_match/80001/0xfa452eA12B51B85152CB9646FfD710aF675D5724/sources/contracts/StakingToken.sol
cal staking token from currentIndex amountReward_ if amountStakingToken_ >= minApproveUnstake need to approve for withdraw staking token add total OUT staking token add total IN reward token
function unStake(address stakingToken_, uint256 amountReward_) public nonReentrant { require(amountReward_ > uint256(0), "UnStake: invalid value"); require( stakingToken_ != address(0), "UnStake: Zero address stakingToken" ); require( configTokens[stakingToken_].canUnStake == true, "UnStake: Token can't unStake" ); require( approvals[msg.sender][stakingToken_].amountRewardToken == uint256(0), "UnStake: Need approved for previous unStake" ); uint256 amountAllowce_ = IERC20(configTokens[stakingToken_].rewardToken) .allowance(msg.sender, address(this)); require( amountReward_ <= amountAllowce_, "UnStake: insufficient allowance" ); IERC20(configTokens[stakingToken_].rewardToken).safeTransferFrom( msg.sender, address(this), amountReward_ ); uint256 amountStakingToken_ = _calStakingToken( stakingToken_, amountReward_ ); if ( amountStakingToken_ >= configTokens[stakingToken_].minApproveUnstake ) { approvals[msg.sender][stakingToken_] .amountRewardToken = amountReward_; approvals[msg.sender][stakingToken_].nextApprovedTime = block .timestamp; uint256 amountFee_ = _calFee(stakingToken_, amountStakingToken_); IERC20(stakingToken_).safeTransfer( msg.sender, amountStakingToken_.sub(amountFee_) ); _totalStakes[stakingToken_].totalOutStake = _totalStakes[ stakingToken_ ].totalOutStake.add(amountStakingToken_); _balances[msg.sender][stakingToken_].totalInReward = _balances[ msg.sender ][stakingToken_].totalInReward.add(amountReward_); } emit UnStake(msg.sender, amountStakingToken_); }
9,473,012
./full_match/97/0xbCeB57F96a3De1A20f1426fc05FAfE745860F537/sources/project_/contracts/BUSDStakerV5.sol
Redeposit Capital transfer capital to the user
function redepositCapital(uint256 id) public nonReentrant { require( depositState[id].investor == msg.sender, "only investor of this id can redeposit" ); require( depositState[id].depositAt + withdrawPeriod < block.timestamp, "withdraw lock time is not finished yet" ); require(depositState[id].state, "you already withdrawed capital"); require( depositState[id].depositAmount <= getBalance(), "no enough busd in pool" ); investors[msg.sender].totalLocked = investors[msg.sender] .totalLocked .sub(depositState[id].depositAmount); uint256 amountToSend = depositState[id].depositAmount; _deposit(amountToSend); depositState[id].state = false; }
3,264,175
./full_match/1/0x34eeCeDc405006afe0B39C570b906e4417770825/sources/project_/contracts/ERC721R.sol
See {IERC721-balanceOf}./
function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; }
3,859,553
./full_match/11297108109/0x19D4F9A260AF1d7E0E99A32DBe418956af875c25/sources/contracts/NFTCollection/NFTCollectionMintable.sol
Mint assets for each id in _ids _to The address to mint assets to _assetId Id of the asset where new tokens will be minted _totalTokens Total of new tokens to mint _data Data to pass if receiver is contract/
function mintBatch( address _to, string memory _assetId, uint256 _totalTokens, bytes memory _data ) public virtual override returns (uint256[] memory ids, uint256[] memory internalIds) { _onlyMinter(); _checkIsAutoIncremental(); _checkAssetExists(_assetId); _checkCapNotExceeded(_assetId, _totalTokens); uint256[] memory nftCollectionTokenIds = new uint256[](_totalTokens); uint256[] memory quantities = new uint256[](_totalTokens); uint256[] memory tokenIds = new uint256[](_totalTokens); for (uint256 i = 0; i < _totalTokens; i++) { ( nftCollectionTokenIds[i], tokenIds[i] ) = _generateNewTokenIdForAsset(_assetId); tokenAsset[nftCollectionTokenIds[i]] = _assetId; quantities[i] = 1; } return _mintBatch( _to, _assetId, tokenIds, nftCollectionTokenIds, quantities, _data ); }
13,236,821
./full_match/80001/0x21289999e7EAf1ED197e42aE1E4c3b09c9ccfE8a/sources/lib/plugin-pattern/src/presets/utils/StringSet.sol
Returns the value stored at position `index` in the set. O(1). Note that there are no guarantees on the ordering of values inside the array, and it may change when more values are added or removed. Requirements: - `index` must be strictly less than {length}./
function at(Set storage set, uint256 index) internal view returns (string memory) { return _at(set, index); }
852,346
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./OwnerRole.sol"; /// @title PauserRole Contract /// @notice Only administrators can update the pauser roles /// @dev Keeps track of pausers and can check if an account is authorized contract PauserRole is OwnerRole { event PauserAdded(address indexed addedPauser, address indexed addedBy); event PauserRemoved( address indexed removedPauser, address indexed removedBy ); Role private _pausers; /// @dev Modifier to make a function callable only when the caller is a pauser modifier onlyPauser() { require( isPauser(msg.sender), "PauserRole: caller does not have the Pauser role" ); _; } /// @dev Public function returns `true` if `account` has been granted a pauser role function isPauser(address account) public view returns (bool) { return _has(_pausers, account); } /// @notice Only administrators should be allowed to update this /// @dev Adds an address as a pauser /// @param account The address that is guaranteed pauser authorization function _addPauser(address account) internal { _add(_pausers, account); emit PauserAdded(account, msg.sender); } /// @notice Only administrators should be allowed to update this /// @dev Removes an account from being a pauser /// @param account The address removed as a pauser function _removePauser(address account) internal { _remove(_pausers, account); emit PauserRemoved(account, msg.sender); } /// @dev Public function that adds an address as a pauser /// @param account The address that is guaranteed pauser authorization function addPauser(address account) external onlyOwner { _addPauser(account); } /// @dev Public function that removes an account from being a pauser /// @param account The address removed as a pauser function removePauser(address account) external onlyOwner { _removePauser(account); } uint256[49] private __gap; }
Public function that removes an account from being a pauser account The address removed as a pauser
function removePauser(address account) external onlyOwner { _removePauser(account); } uint256[49] private __gap;
5,528,028
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.6.12; // // _░▒███████ // ░██▓▒░░▒▓██ // ██▓▒░__░▒▓██___██████ // ██▓▒░____░▓███▓__░▒▓██ // ██▓▒░___░▓██▓_____░▒▓██ // ██▓▒░_______________░▒▓██ // _██▓▒░______________░▒▓██ // __██▓▒░____________░▒▓██ // ___██▓▒░__________░▒▓██ // ____██▓▒░________░▒▓██ // _____██▓▒░_____░▒▓██ //  ██░▀██████████████▀░██_██▓▒░__░▒▓██ //  █▌▒▒░████████████░▒▒▐█__█▓▒░░▒▓██ //  █░▒▒▒░██████████░▒▒▒░█____░▒▓██ //  ▌░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░▐__░▒▓██ //  ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░░▒▓██ //  ███▀▀▀██▄▒▒▒▒▒▒▒▄██▀▀▀██ //  ██░░░▐█░▀█▒▒▒▒▒█▀░█▌░░░█ //  ▐▌░░░▐▄▌░▐▌▒▒▒▐▌░▐▄▌░░▐▌ //  █░░░▐█▌░░▌▒▒▒▐░░▐█▌░░█ //  ▒▀▄▄▄█▄▄▄▌░▄░▐▄▄▄█▄▄▀▒ //  ░░░░░░░░░░└┴┘░░░░░░░░░ //  ██▄▄░░░░░░░░░░░░░░▄▄██ //  ████████▒▒▒▒▒▒████████ //  █▀░░███▒▒░░▒░░▒▀██████ //  █▒░███▒▒╖░░╥░░╓▒▐█████ //  █▒░▀▀▀░░║░░║░░║░░█████ //  ██▄▄▄▄▀▀┴┴╚╧╧╝╧╧╝┴┴███ //  ██████████████████████ // import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; // ERC721 import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; // ERC20 import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; // For safe maths operations import "@openzeppelin/contracts/math/SafeMath.sol"; // Utils only import "./StringsUtil.sol"; interface IERC20Burnable { function burn(uint256 amount) external; function burnFrom(address account, uint256 amount) external; function burnAmount() external view returns (uint256 _amount); } /** * @title NotRealDigitalAsset - V2 * * http://www.notreal.ai/ * * ERC721 compliant digital assets for real-world artwork. * * Base NFT Issuance Contract * * AMPLIFY ART. * */ contract NotRealDigitalAssetV2 is AccessControl, Ownable, ERC721, Pausable, ReentrancyGuard { bytes32 public constant ROLE_NOT_REAL = keccak256('ROLE_NOT_REAL'); bytes32 public constant ROLE_MINTER = keccak256('ROLE_MINTER'); bytes32 public constant ROLE_MARKET = keccak256('ROLE_MARKET'); /////////////// // Modifiers // /////////////// // Modifiers are wrapped around functions because it shaves off contract size modifier onlyAvailableEdition(uint256 _editionNumber, uint256 _numTokens) { _onlyAvailableEdition(_editionNumber, _numTokens); _; } modifier onlyActiveEdition(uint256 _editionNumber) { _onlyActiveEdition(_editionNumber); _; } modifier onlyRealEdition(uint256 _editionNumber) { _onlyRealEdition(_editionNumber); _; } modifier onlyValidTokenId(uint256 _tokenId) { _onlyValidTokenId(_tokenId); _; } modifier onlyPurchaseDuringWindow(uint256 _editionNumber) { _onlyPurchaseDuringWindow(_editionNumber); _; } function _onlyAvailableEdition(uint256 _editionNumber, uint256 _numTokens) internal view { require(editionNumberToEditionDetails[_editionNumber].totalSupply.add(_numTokens) <= editionNumberToEditionDetails[_editionNumber].totalAvailable); } function _onlyActiveEdition(uint256 _editionNumber) internal view { require(editionNumberToEditionDetails[_editionNumber].active); } function _onlyRealEdition(uint256 _editionNumber) internal view { require(editionNumberToEditionDetails[_editionNumber].editionNumber > 0); } function _onlyValidTokenId(uint256 _tokenId) internal view { require(_exists(_tokenId)); } function _onlyPurchaseDuringWindow(uint256 _editionNumber) internal view { require(editionNumberToEditionDetails[_editionNumber].startDate <= block.timestamp); require(editionNumberToEditionDetails[_editionNumber].endDate >= block.timestamp); } modifier onlyIfNotReal() { _onlyIfNotReal(); _; } modifier onlyIfMinter() { _onlyIfMinter(); _; } function _onlyIfNotReal() internal view { require(_msgSender() == owner() || hasRole(ROLE_NOT_REAL, _msgSender())); } function _onlyIfMinter() internal view { require(_msgSender() == owner() || hasRole(ROLE_NOT_REAL, _msgSender()) || hasRole(ROLE_MINTER, _msgSender())); } using SafeMath for uint256; using SafeERC20 for IERC20; //////////// // Events // //////////// // Emitted on purchases from within this contract event Purchase( uint256 indexed _tokenId, uint256 indexed _editionNumber, address indexed _buyer, uint256 _priceInWei, uint256 _numTokens ); // Emitted on every mint event Minted( uint256 indexed _tokenId, uint256 indexed _editionNumber, address indexed _buyer, uint256 _numTokens ); // Emitted on every edition created event EditionCreated( uint256 indexed _editionNumber, bytes32 indexed _editionData, uint256 indexed _editionType ); event NameChange(uint256 indexed _tokenId, string _newName); //////////////// // Properties // //////////////// uint256 constant internal MAX_UINT32 = ~uint32(0); string public tokenBaseURI = "https://ipfs.infura.io/ipfs/"; // simple counter to keep track of the highest edition number used uint256 public highestEditionNumber; // number of assets minted of any type uint256 public totalNumberMinted; // number of assets minted of any type uint256 public totalPurchaseValueInWei; // number of assets available of any type uint256 public totalNumberAvailable; // Max number of tokens that can be minted/purchased in a batch uint256 public maxBatch = 100; uint256 public maxGas = 100000000000; // the NR account which can receive commission address public nrCommissionAccount; // Accepted ERC20 token IERC20 public acceptedToken; IERC20Burnable public nameToken; // Optional commission split can be defined per edition mapping(uint256 => CommissionSplit) internal editionNumberToOptionalCommissionSplit; // Simple structure providing an optional commission split per edition purchase struct CommissionSplit { uint256 rate; address recipient; } // Object for edition details struct EditionDetails { // Identifiers uint256 editionNumber; // the range e.g. 10000 bytes32 editionData; // some data about the edition uint256 editionType; // e.g. 1 = NRDA, 4 = Deactivated // Config uint256 startDate; // date when the edition goes on sale uint256 endDate; // date when the edition is available until address artistAccount; // artists account uint256 artistCommission; // base artists commission, could be overridden by external contracts uint256 priceInWei; // base price for edition, could be overridden by external contracts string tokenURI; // IPFS hash - see base URI bool active; // Root control - on/off for the edition // Counters uint256 totalSupply; // Total purchases or mints uint256 totalAvailable; // Total number available to be purchased } // _editionNumber : EditionDetails mapping(uint256 => EditionDetails) internal editionNumberToEditionDetails; // _tokenId : _editionNumber mapping(uint256 => uint256) internal tokenIdToEditionNumber; // _editionNumber : [_tokenId, _tokenId] mapping(uint256 => uint256[]) internal editionNumberToTokenIds; mapping(uint256 => uint256[]) internal editionNumberToBurnedTokenIds; // _artistAccount : [_editionNumber, _editionNumber] mapping(address => uint256[]) internal artistToEditionNumbers; mapping(uint256 => uint256) internal editionNumberToArtistIndex; // _editionType : [_editionNumber, _editionNumber] mapping(uint256 => uint256[]) internal editionTypeToEditionNumber; mapping(uint256 => uint256) internal editionNumberToTypeIndex; mapping (uint256 => string) public tokenName; mapping (string => bool) internal reservedName; /* * Constructor */ constructor (IERC20 _acceptedToken) public payable ERC721("NotRealDigitalAsset", "NRDA") { // set commission account to contract creator nrCommissionAccount = _msgSender(); acceptedToken = _acceptedToken; _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setBaseURI(tokenBaseURI); } // Function wrapper for using native Ether or ERC20 function _acceptedTokenSafeTransferFrom(address _from, address _to, uint256 _msgValue) internal { require(tx.gasprice <= maxGas, "Gas price too high"); if(address(acceptedToken) == address(0)) { require(msg.value == _msgValue); require(_from == _msgSender()); require(_to == address(this)); } else { acceptedToken.safeTransferFrom(_from, _to, _msgValue); } } function _acceptedTokenSafeTransfer(address _to, uint256 _msgValue) internal { if(address(acceptedToken) == address(0)) { payable(_to).transfer(_msgValue); } else { acceptedToken.safeTransfer(_to, _msgValue); } } function pause() public onlyIfNotReal { _pause(); } function unpause() public onlyIfNotReal { _unpause(); } function setNameToken(address _nameToken) external onlyOwner { nameToken = IERC20Burnable(_nameToken); } // Spend name tokens to give this ERC721 a unique name function changeName(uint256 _tokenId, string memory _newName) public onlyValidTokenId(_tokenId) { string memory _newNameLower = StringsUtil.toLower(_newName); require(_msgSender() == ownerOf(_tokenId), "ERC721: caller is not the owner"); require(StringsUtil.validateName(_newName), "Not a valid new name"); require(!reservedName[_newNameLower], "Name already reserved"); reservedName[StringsUtil.toLower(tokenName[_tokenId])] = false; reservedName[_newNameLower] = true; nameToken.burnFrom(_msgSender(), nameToken.burnAmount()); tokenName[_tokenId] = _newName; emit NameChange(_tokenId, _newName); } function mint(address _to, uint256 _editionNumber) public onlyIfMinter returns (uint256) { return mintMany(_to, _editionNumber, 1); } /** * @dev Private (NR only) method for minting editions * @dev Payment not needed for this method */ function mintMany(address _to, uint256 _editionNumber, uint256 _numTokens) public onlyIfMinter onlyRealEdition(_editionNumber) onlyAvailableEdition(_editionNumber, _numTokens) returns (uint256) { EditionDetails storage _editionDetails = editionNumberToEditionDetails[_editionNumber]; uint256 _tokenId = _editionDetails.editionNumber.add(_editionDetails.totalSupply).add(1); for (uint256 i = 0; i < _numTokens; i++) { // Construct next token ID e.g. 100000 + 1 = ID of 100001 (this first in the edition set) // Create the token _mintToken(_to, _tokenId.add(i), _editionNumber, _editionDetails.tokenURI); } totalNumberMinted = totalNumberMinted.add(_numTokens); _editionDetails.totalSupply = _editionDetails.totalSupply.add(_numTokens); // Emit minted event emit Minted(_tokenId, _editionNumber, _to, _numTokens); return _tokenId; } /** * @dev Internal factory method for building editions */ function createEdition( uint256 _editionNumber, bytes32 _editionData, uint256 _editionType, uint256 _startDate, uint256 _endDate, address _artistAccount, uint256 _artistCommission, uint256 _priceInWei, string memory _tokenURI, uint256 _totalAvailable, bool _active ) public onlyIfNotReal returns (bool) { // Prevent missing edition number require(_editionNumber != 0); // Prevent edition number lower than last one used require(_editionNumber > highestEditionNumber); // Check previously edition plus total available is less than new edition number require(highestEditionNumber.add(editionNumberToEditionDetails[highestEditionNumber].totalAvailable) < _editionNumber); // Prevent missing types require(_editionType != 0); // Prevent missing token URI require(bytes(_tokenURI).length != 0); // Prevent empty artists address require(_artistAccount != address(0)); // Prevent invalid commissions require(_artistCommission <= 100 && _artistCommission >= 0); // Prevent duplicate editions require(editionNumberToEditionDetails[_editionNumber].editionNumber == 0); // Default end date to max uint256 uint256 endDate = _endDate; if (_endDate == 0) { endDate = MAX_UINT32; } editionNumberToEditionDetails[_editionNumber] = EditionDetails({ editionNumber : _editionNumber, editionData : _editionData, editionType : _editionType, startDate : _startDate, endDate : endDate, artistAccount : _artistAccount, artistCommission : _artistCommission, priceInWei : _priceInWei, tokenURI : StringsUtil.strConcat(_tokenURI, "/"), totalSupply : 0, // default to all available totalAvailable : _totalAvailable, active : _active }); // Add to total available count totalNumberAvailable = totalNumberAvailable.add(_totalAvailable); // Update mappings _updateArtistLookupData(_artistAccount, _editionNumber); _updateEditionTypeLookupData(_editionType, _editionNumber); emit EditionCreated(_editionNumber, _editionData, _editionType); // Update the edition pointer if needs be highestEditionNumber = _editionNumber; return true; } function _updateEditionTypeLookupData(uint256 _editionType, uint256 _editionNumber) internal { uint256 typeEditionIndex = editionTypeToEditionNumber[_editionType].length; editionTypeToEditionNumber[_editionType].push(_editionNumber); editionNumberToTypeIndex[_editionNumber] = typeEditionIndex; } function _updateArtistLookupData(address _artistAccount, uint256 _editionNumber) internal { uint256 artistEditionIndex = artistToEditionNumbers[_artistAccount].length; artistToEditionNumbers[_artistAccount].push(_editionNumber); editionNumberToArtistIndex[_editionNumber] = artistEditionIndex; } ///** // * @dev Public entry point for purchasing an edition on behalf of someone else // * @dev Reverts if edition is invalid // * @dev Reverts if payment not provided in full // * @dev Reverts if edition is sold out // * @dev Reverts if edition is not active or available // */ function purchaseMany(address _to, uint256 _editionNumber, uint256 _numTokens, uint256 _msgValue) public payable whenNotPaused nonReentrant onlyRealEdition(_editionNumber) onlyActiveEdition(_editionNumber) onlyAvailableEdition(_editionNumber, _numTokens) onlyPurchaseDuringWindow(_editionNumber) returns (uint256) { require(_numTokens <= maxBatch && _numTokens >= 1); EditionDetails storage _editionDetails = editionNumberToEditionDetails[_editionNumber]; require(_msgValue >= _editionDetails.priceInWei.mul(_numTokens)); _acceptedTokenSafeTransferFrom(_msgSender(), address(this), _msgValue); uint256 _tokenId = _editionDetails.editionNumber.add(_editionDetails.totalSupply).add(1); for (uint256 i = 0; i < _numTokens; i++) { // Transfer token to this contract // Construct next token ID e.g. 100000 + 1 = ID of 100001 (this first in the edition set) // Create the token _mintToken(_to, _tokenId.add(i), _editionNumber, _editionDetails.tokenURI); } totalNumberMinted = totalNumberMinted.add(_numTokens); _editionDetails.totalSupply = _editionDetails.totalSupply.add(_numTokens); // Splice funds and handle commissions _handleFunds(_editionNumber, _msgValue, _editionDetails.artistAccount, _editionDetails.artistCommission); // Emit minted event emit Minted(_tokenId, _editionNumber, _to, _numTokens); // Broadcast purchase emit Purchase(_tokenId, _editionNumber, _to, _editionDetails.priceInWei, _numTokens); return _tokenId; } function _nextTokenId(uint256 _editionNumber) internal returns (uint256) { EditionDetails storage _editionDetails = editionNumberToEditionDetails[_editionNumber]; // Bump number totalSupply _editionDetails.totalSupply = _editionDetails.totalSupply.add(1); // Construct next token ID e.g. 100000 + 1 = ID of 100001 (this first in the edition set) return _editionDetails.editionNumber.add(_editionDetails.totalSupply); } function _mintToken(address _to, uint256 _tokenId, uint256 _editionNumber, string memory _tokenURI) internal { // Mint new base token super._mint(_to, _tokenId); super._setTokenURI(_tokenId, StringsUtil.strConcat(_tokenURI, StringsUtil.uint2str(_tokenId))); // Maintain mapping for tokenId to edition for lookup tokenIdToEditionNumber[_tokenId] = _editionNumber; // Maintain mapping of edition to token array for "edition minted tokens" editionNumberToTokenIds[_editionNumber].push(_tokenId); } function _handleFunds(uint256 _editionNumber, uint256 _priceInWei, address _artistAccount, uint256 _artistCommission) internal { // Extract the artists commission and send it uint256 artistPayment = _priceInWei.div(100).mul(_artistCommission); if (artistPayment > 0) { _acceptedTokenSafeTransfer(_artistAccount, artistPayment); } // Load any commission overrides CommissionSplit storage commission = editionNumberToOptionalCommissionSplit[_editionNumber]; // Apply optional commission structure uint256 rateSplit = 0; if (commission.rate > 0) { rateSplit = _priceInWei.div(100).mul(commission.rate); _acceptedTokenSafeTransfer(commission.recipient, rateSplit); } // Send remaining eth to NR uint256 remainingCommission = _priceInWei.sub(artistPayment).sub(rateSplit); _acceptedTokenSafeTransfer(nrCommissionAccount, remainingCommission); // Record wei sale value totalPurchaseValueInWei = totalPurchaseValueInWei.add(_priceInWei); } /** * @dev Private (NR only) method for burning tokens which have been created incorrectly */ function burn(uint256 _tokenId) external onlyIfNotReal { // Clear from parents super._burn(_tokenId); // Get hold of the edition for cleanup uint256 _editionNumber = tokenIdToEditionNumber[_tokenId]; // Delete token ID mapping delete tokenIdToEditionNumber[_tokenId]; editionNumberToBurnedTokenIds[_editionNumber].push(_tokenId); } ////////////////// // Base Updates // ////////////////// // function updateTokenBaseURI(string calldata _newBaseURI) external onlyIfNotReal { require(bytes(_newBaseURI).length != 0); tokenBaseURI = _newBaseURI; } function updateNrCommissionAccount(address _nrCommissionAccount) external onlyIfNotReal { require(_nrCommissionAccount != address(0)); nrCommissionAccount = _nrCommissionAccount; } function updateMaxBatch(uint256 _maxBatch) external onlyIfNotReal { maxBatch = _maxBatch; } function updateMaxGas(uint256 _maxGas) external onlyIfNotReal { maxGas = _maxGas; } ///////////////////// // Edition Updates // ///////////////////// function updateEditionTokenURI(uint256 _editionNumber, string calldata _uri) external onlyIfNotReal onlyRealEdition(_editionNumber) { editionNumberToEditionDetails[_editionNumber].tokenURI = StringsUtil.strConcat(_uri, "/"); } function updatePriceInWei(uint256 _editionNumber, uint256 _priceInWei) external onlyIfNotReal onlyRealEdition(_editionNumber) { editionNumberToEditionDetails[_editionNumber].priceInWei = _priceInWei; } function updateArtistCommission(uint256 _editionNumber, uint256 _rate) external onlyIfNotReal onlyRealEdition(_editionNumber) { editionNumberToEditionDetails[_editionNumber].artistCommission = _rate; } function updateEditionType(uint256 _editionNumber, uint256 _editionType) external onlyIfNotReal onlyRealEdition(_editionNumber) { EditionDetails storage _originalEditionDetails = editionNumberToEditionDetails[_editionNumber]; // Get list of editions for old type uint256[] storage editionNumbersForType = editionTypeToEditionNumber[_originalEditionDetails.editionType]; // Remove edition from old type list uint256 editionTypeIndex = editionNumberToTypeIndex[_editionNumber]; delete editionNumbersForType[editionTypeIndex]; // Add new type to the list uint256 newTypeEditionIndex = editionTypeToEditionNumber[_editionType].length; editionTypeToEditionNumber[_editionType].push(_editionNumber); editionNumberToTypeIndex[_editionNumber] = newTypeEditionIndex; // Update the edition _originalEditionDetails.editionType = _editionType; } function updateTotalSupply(uint256 _editionNumber, uint256 _totalSupply) external onlyIfNotReal onlyRealEdition(_editionNumber) { require(editionNumberToTokenIds[_editionNumber].length <= _totalSupply); editionNumberToEditionDetails[_editionNumber].totalSupply = _totalSupply; } function updateTotalAvailable(uint256 _editionNumber, uint256 _totalAvailable) external onlyIfNotReal onlyRealEdition(_editionNumber) { EditionDetails storage _editionDetails = editionNumberToEditionDetails[_editionNumber]; require(_editionDetails.totalSupply <= _totalAvailable); uint256 originalAvailability = _editionDetails.totalAvailable; _editionDetails.totalAvailable = _totalAvailable; totalNumberAvailable = totalNumberAvailable.sub(originalAvailability).add(_totalAvailable); } function updateActive(uint256 _editionNumber, bool _active) external onlyIfNotReal onlyRealEdition(_editionNumber) { editionNumberToEditionDetails[_editionNumber].active = _active; } function updateStartDate(uint256 _editionNumber, uint256 _startDate) external onlyIfNotReal onlyRealEdition(_editionNumber) { editionNumberToEditionDetails[_editionNumber].startDate = _startDate; } function updateEndDate(uint256 _editionNumber, uint256 _endDate) external onlyRealEdition(_editionNumber) { require(_msgSender() == owner() || hasRole(ROLE_NOT_REAL, _msgSender()) || hasRole(ROLE_MARKET, _msgSender())); editionNumberToEditionDetails[_editionNumber].endDate = _endDate; } function updateArtistsAccount(uint256 _editionNumber, address _artistAccount) external onlyIfNotReal onlyRealEdition(_editionNumber) { EditionDetails storage _originalEditionDetails = editionNumberToEditionDetails[_editionNumber]; uint256 editionArtistIndex = editionNumberToArtistIndex[_editionNumber]; // Get list of editions old artist works with uint256[] storage editionNumbersForArtist = artistToEditionNumbers[_originalEditionDetails.artistAccount]; // Remove edition from artists lists delete editionNumbersForArtist[editionArtistIndex]; // Add new artists to the list uint256 newArtistsEditionIndex = artistToEditionNumbers[_artistAccount].length; artistToEditionNumbers[_artistAccount].push(_editionNumber); editionNumberToArtistIndex[_editionNumber] = newArtistsEditionIndex; // Update the edition _originalEditionDetails.artistAccount = _artistAccount; } function updateOptionalCommission(uint256 _editionNumber, uint256 _rate, address _recipient) external onlyIfNotReal onlyRealEdition(_editionNumber) { EditionDetails storage _editionDetails = editionNumberToEditionDetails[_editionNumber]; uint256 artistCommission = _editionDetails.artistCommission; if (_rate > 0) { require(_recipient != address(0)); } require(artistCommission.add(_rate) <= 100); editionNumberToOptionalCommissionSplit[_editionNumber] = CommissionSplit({rate : _rate, recipient : _recipient}); } /////////////////// // Token Updates // /////////////////// function setTokenURI(uint256 _tokenId, string calldata _uri) external onlyIfNotReal onlyValidTokenId(_tokenId) { _setTokenURI(_tokenId, _uri); } /////////////////// // Query Methods // /////////////////// /** * @dev Lookup the edition of the provided token ID * @dev Returns 0 if not valid */ function editionOfTokenId(uint256 _tokenId) external view returns (uint256 _editionNumber) { return tokenIdToEditionNumber[_tokenId]; } /** * @dev Lookup all editions added for the given edition type * @dev Returns array of edition numbers, any zero edition ids can be ignore/stripped */ function editionsOfType(uint256 _type) external view returns (uint256[] memory _editionNumbers) { return editionTypeToEditionNumber[_type]; } /** * @dev Lookup all editions for the given artist account * @dev Returns empty list if not valid */ function artistsEditions(address _artistsAccount) external view returns (uint256[] memory _editionNumbers) { return artistToEditionNumbers[_artistsAccount]; } /** * @dev Lookup all tokens minted for the given edition number * @dev Returns array of token IDs, any zero edition ids can be ignore/stripped */ function tokensOfEdition(uint256 _editionNumber) external view returns (uint256[] memory _tokenIds) { return editionNumberToTokenIds[_editionNumber]; } /** * @dev Lookup all owned tokens for the provided address * @dev Returns array of token IDs */ function tokensOf(address _owner) external view returns (uint256[] memory _tokenIds) { uint256[] memory results = new uint256[](balanceOf(_owner)); for (uint256 idx = 0; idx < results.length; idx++) { results[idx] = tokenOfOwnerByIndex(_owner, idx); } return results; } /** * @dev Checks to see if the edition exists, assumes edition of zero is invalid */ function editionExists(uint256 _editionNumber) external view returns (bool) { if (_editionNumber == 0) { return false; } EditionDetails storage editionNumber = editionNumberToEditionDetails[_editionNumber]; return editionNumber.editionNumber == _editionNumber; } /** * @dev Checks to see if the token exists */ function exists(uint256 _tokenId) external view returns (bool) { return _exists(_tokenId); } /** * @dev Lookup any optional commission split set for the edition * @dev Both values will be zero if not present */ function editionOptionalCommission(uint256 _editionNumber) external view returns (uint256 _rate, address _recipient) { CommissionSplit storage commission = editionNumberToOptionalCommissionSplit[_editionNumber]; return (commission.rate, commission.recipient); } /** * @dev Main entry point for looking up edition config/metadata * @dev Reverts if invalid edition number provided */ function detailsOfEdition(uint256 editionNumber) external view onlyRealEdition(editionNumber) returns ( bytes32 _editionData, uint256 _editionType, uint256 _startDate, uint256 _endDate, address _artistAccount, uint256 _artistCommission, uint256 _priceInWei, string memory _tokenURI, uint256 _totalSupply, uint256 _totalAvailable, bool _active ) { EditionDetails storage _editionDetails = editionNumberToEditionDetails[editionNumber]; return ( _editionDetails.editionData, _editionDetails.editionType, _editionDetails.startDate, _editionDetails.endDate, _editionDetails.artistAccount, _editionDetails.artistCommission, _editionDetails.priceInWei, StringsUtil.strConcat(tokenBaseURI, _editionDetails.tokenURI), _editionDetails.totalSupply, _editionDetails.totalAvailable, _editionDetails.active ); } /** * @dev Lookup a tokens common identifying characteristics * @dev Reverts if invalid token ID provided */ function tokenData(uint256 _tokenId) external view onlyValidTokenId(_tokenId) returns ( uint256 _editionNumber, uint256 _editionType, bytes32 _editionData, string memory _tokenURI, address _owner ) { uint256 editionNumber = tokenIdToEditionNumber[_tokenId]; EditionDetails storage editionDetails = editionNumberToEditionDetails[editionNumber]; return ( editionNumber, editionDetails.editionType, editionDetails.editionData, tokenURI(_tokenId), ownerOf(_tokenId) ); } ////////////////////////// // Edition config query // ////////////////////////// function purchaseDatesEdition(uint256 _editionNumber) public view returns (uint256 _startDate, uint256 _endDate) { EditionDetails storage _editionDetails = editionNumberToEditionDetails[_editionNumber]; return ( _editionDetails.startDate, _editionDetails.endDate ); } function artistCommission(uint256 _editionNumber) external view returns (address _artistAccount, uint256 _artistCommission) { EditionDetails storage _editionDetails = editionNumberToEditionDetails[_editionNumber]; return ( _editionDetails.artistAccount, _editionDetails.artistCommission ); } function priceInWeiEdition(uint256 _editionNumber) public view returns (uint256 _priceInWei) { EditionDetails storage _editionDetails = editionNumberToEditionDetails[_editionNumber]; return _editionDetails.priceInWei; } function editionActive(uint256 _editionNumber) public view returns (bool) { EditionDetails storage _editionDetails = editionNumberToEditionDetails[_editionNumber]; return _editionDetails.active; } function totalRemaining(uint256 _editionNumber) external view returns (uint256) { EditionDetails storage _editionDetails = editionNumberToEditionDetails[_editionNumber]; return _editionDetails.totalAvailable.sub(_editionDetails.totalSupply); } function totalAvailableEdition(uint256 _editionNumber) public view returns (uint256) { EditionDetails storage _editionDetails = editionNumberToEditionDetails[_editionNumber]; return _editionDetails.totalAvailable; } function totalSupplyEdition(uint256 _editionNumber) public view returns (uint256) { EditionDetails storage _editionDetails = editionNumberToEditionDetails[_editionNumber]; return _editionDetails.totalSupply; } function reclaimEther() external onlyOwner { payable(owner()).transfer(address(this).balance); if (address(acceptedToken) != address(0)) { acceptedToken.transfer(owner(), acceptedToken.balanceOf(address(this))); } } } pragma solidity ^0.6.12; library StringsUtil { // via https://github.com/provable-things/ethereum-api/blob/master/provableAPI_0.6.sol function strConcat(string memory _a, string memory _b) internal pure returns (string memory _concatenatedString) { return strConcat(_a, _b, "", "", ""); } function strConcat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory _concatenatedString) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory _concatenatedString) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; uint i = 0; for (i = 0; i < _ba.length; i++) { babcde[k++] = _ba[i]; } for (i = 0; i < _bb.length; i++) { babcde[k++] = _bb[i]; } for (i = 0; i < _bc.length; i++) { babcde[k++] = _bc[i]; } for (i = 0; i < _bd.length; i++) { babcde[k++] = _bd[i]; } for (i = 0; i < _be.length; i++) { babcde[k++] = _be[i]; } return string(babcde); } function equal(string memory a, string memory b) internal pure returns (bool) { return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b)))); } // NOTE! If you don't make library functions internal, then you have to do annoying linking steps during migration /** * @dev Check if the name string is valid (Alphanumeric and spaces without leading or trailing space) */ function validateName(string memory str) internal pure returns (bool){ bytes memory b = bytes(str); if(b.length < 1 || b.length > 25 || // Cannot be longer than 25 characters b[0] == 0x20 || // Leading space // Trailing space b[b.length - 1] == 0x20) { return false; } bytes1 lastChar = b[0]; for(uint i; i<b.length; i++){ bytes1 char = b[i]; if (char == 0x20 && lastChar == 0x20) return false; // Cannot contain continous spaces if( !(char >= 0x30 && char <= 0x39) && //9-0 !(char >= 0x41 && char <= 0x5A) && //A-Z !(char >= 0x61 && char <= 0x7A) && //a-z !(char == 0x20) //space ) return false; lastChar = char; } return true; } function toLower(string memory str) internal pure returns (string memory){ bytes memory bStr = bytes(str); bytes memory bLower = new bytes(bStr.length); for (uint i = 0; i < bStr.length; i++) { // Uppercase character if ((uint8(bStr[i]) >= 65) && (uint8(bStr[i]) <= 90)) { bLower[i] = bytes1(uint8(bStr[i]) + 32); } else { bLower[i] = bStr[i]; } } return string(bLower); } function uint2str(uint _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (_i != 0) { bstr[k--] = byte(uint8(48 + _i % 10)); _i /= 10; } return string(bstr); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../utils/Context.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @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() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.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, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, 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 (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @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) { 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, reverting 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) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * 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, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * 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, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ 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); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) 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. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC721.sol"; import "./IERC721Metadata.sol"; import "./IERC721Enumerable.sol"; import "./IERC721Receiver.sol"; import "../../introspection/ERC165.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; import "../../utils/EnumerableSet.sol"; import "../../utils/EnumerableMap.sol"; import "../../utils/Strings.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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 GSN 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 payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } }
Lookup all tokens minted for the given edition number Returns array of token IDs, any zero edition ids can be ignore/stripped/
function tokensOfEdition(uint256 _editionNumber) external view returns (uint256[] memory _tokenIds) { return editionNumberToTokenIds[_editionNumber]; }
6,043,746
/* https://charizard.farm Telegram group: t.me/charizardfarm Twitter: @CharizardFarm Inspired from MNNF, ROT and SUSHI ."-,.__ `. `. , .--' .._,'"-' `. . .' `' `. / ,' ` '--. ,-"' `"` | \ -. \, | `--Y.' ___. \ L._, \ _., `. < <\ _ ,' ' `, `. | \ ( ` ../, `. ` | .\`. \ \_ ,' ,.. . _.,' ||\l ) '". , ,' \ ,'.-.`-._,' | . _._`. ,' / \ \ `' ' `--/ | \ / / ..\ .' / \ . |\__ - _ ,'` ` / / `.`. | ' .. `-...-" | `-' / / . `. | / |L__ | | / / `. `. , / . . | | / / ` ` / / ,. ,`._ `-_ | | _ ,-' / ` \ / . \"`_/. `-_ \_,. ,' +-' `-' _, ..,-. \`. . ' .-f ,' ` '. \__.---' _ .' ' \ \ ' / `.' l .' / \.. ,_|/ `. ,'` L` |' _.-""` `. \ _,' ` \ `.___`.'"`-. , | | | \ || ,' `. `. ' _,...._ ` | `/ ' | ' .| || ,' `. ;.,.---' ,' `. `.. `-' .-' /_ .' ;_ || || ' V / / ` | ` ,' ,' '. ! `. || ||/ _,-------7 ' . | `-' l / `|| . | ,' .- ,' || | .-. `. .' || `' ,' `".' | | `. '. -.' `' / ,' | |,' \-.._,.'/' . / . . \ .'' .`. | `. / :_,'.' \ `...\ _ ,'-. .' /_.-' `-.__ `, `' . _.>----''. _ __ / .' /"' | "' '_ /_|.-'\ ,". '.'`__'-( \ / ,"'"\,' `/ `-.|" mh */ pragma solidity ^0.6.6; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ 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); } // File: @openzeppelin/contracts/math/SafeMath.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.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. */ 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. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { 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. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) 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. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin/contracts/utils/EnumerableSet.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts/GSN/Context.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.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 GSN 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 payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @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() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @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.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of 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 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * 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 returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, 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}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), 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}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); 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) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(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) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is 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: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, 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 * * - `to` 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 = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is 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 Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @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 to 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 { } } pragma solidity ^0.6.5; // CharizardToken with Governance. contract CharizardFarm is ERC20("Charizard.farm", "CRZF"), Ownable { // charizard is an exact copy of SUSHI using SafeMath for uint256; function transfer(address recipient, uint256 amount) public virtual override returns (bool) { return super.transfer(recipient, amount); } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { return super.transferFrom(sender, recipient, amount); } /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (Trainer). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "CRZF::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "CRZF::delegateBySig: invalid nonce"); require(now <= expiry, "CRZF::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "CRZF::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying CRZFs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "CRZF::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // File: contracts/Trainer.sol pragma solidity ^0.6.5; interface IMigratorChef { // Perform LP token migration from legacy UniswapV2 to CharizardSwap. // Take the current LP token address and return the new LP token address. // Migrator should have full access to the caller's LP token. // Return the new LP token address. // // XXX Migrator must have allowance access to UniswapV2 LP tokens. // CharizardSwap must mint EXACTLY the same amount of CharizardSwap LP tokens or // else something bad will happen. Traditional UniswapV2 does not // do that so be careful! function migrate(IERC20 token) external returns (IERC20); } // Trainer is an exact copy of SushiSwap // we have commented an few lines to remove the dev fund // the rest is exactly the same // Trainer is the master of Charizard. He can make Charizard and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once CRZF is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract Trainer is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of CRZFs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accCharizardPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accCharizardPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. CRZFs to distribute per block. uint256 lastRewardBlock; // Last block number that CRZFs distribution occurs. uint256 accCharizardPerShare; // Accumulated CRZFs per share, times 1e12. See below. bool taxable; // Accumulated CRZFs per share, times 1e12. See below. } // The CRZF TOKEN! CharizardFarm public charizard; address private devaddr; // Block number when bonus CRZF period ends. uint256 public bonusEndBlock; // CRZF tokens created per block. uint256 public charizardPerBlock; // Bonus muliplier for early charizard makers. uint256 public constant BONUS_MULTIPLIER = 1; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when CRZF mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( CharizardFarm _charizard, address _devaddr, uint256 _charizardPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { charizard = _charizard; devaddr = _devaddr; charizardPerBlock = _charizardPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate, bool _taxable, uint256 _startBlock) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = _startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCharizardPerShare: 0, taxable: _taxable })); } // Update the given pool's CRZF allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate, bool _taxable, uint256 _startBlock) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; poolInfo[_pid].taxable = _taxable; poolInfo[_pid].lastRewardBlock = _startBlock; } function setBonusEndBlock(uint256 _bonusEndBlock) public onlyOwner { bonusEndBlock = _bonusEndBlock; } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending CRZFs on frontend. function pendingCharizard(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCharizardPerShare = pool.accCharizardPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 charizardReward = multiplier.mul(charizardPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accCharizardPerShare = accCharizardPerShare.add(charizardReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accCharizardPerShare).div(1e12).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 charizardReward = multiplier.mul(charizardPerBlock).mul(pool.allocPoint).div(totalAllocPoint); // 5% of produced token to be used in expanding token ecosystem. It will be burned only. charizard.mint(address(devaddr), charizardReward.mul(5).div(100)); charizard.mint(address(this), charizardReward); pool.accCharizardPerShare = pool.accCharizardPerShare.add(charizardReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to Trainer for CRZF allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCharizardPerShare).div(1e12).sub(user.rewardDebt); safeCharizardTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCharizardPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from Trainer. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: amount is exceeds yours"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accCharizardPerShare).div(1e12).sub(user.rewardDebt); safeCharizardTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accCharizardPerShare).div(1e12); if (pool.taxable) { pool.lpToken.safeTransfer(address(devaddr), _amount.mul(25).div(10000)); emit Withdraw(devaddr, _pid, _amount.mul(25).div(10000)); pool.lpToken.safeTransfer(address(msg.sender), _amount.sub(_amount.mul(25).div(10000))); emit Withdraw(msg.sender, _pid, _amount.sub(_amount.mul(25).div(10000))); } else { pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe charizard transfer function, just in case if rounding error causes pool to not have enough CRZFs. function safeCharizardTransfer(address _to, uint256 _amount) internal { uint256 charizardBal = charizard.balanceOf(address(this)); if (_amount > charizardBal) { charizard.transfer(_to, charizardBal); } else { charizard.transfer(_to, _amount); } } }
Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 charizardReward = multiplier.mul(charizardPerBlock).mul(pool.allocPoint).div(totalAllocPoint); charizard.mint(address(this), charizardReward); pool.accCharizardPerShare = pool.accCharizardPerShare.add(charizardReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; }
1,241,380
//Address: 0x2cc6ca9c3023a6a876fd54a03f68281c7aad0e8b //Contract name: ICOPreSale //Balance: 0 Ether //Verification Date: 6/14/2018 //Transacion Count: 6 // CODE STARTS HERE pragma solidity ^0.4.13; contract ComplianceService { function validate(address _from, address _to, uint256 _amount) public returns (bool allowed) { return true; } } contract ERC20 { function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _amount) public returns (bool success); function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success); function allowance(address _owner, address _spender) public constant returns (uint256 remaining); function totalSupply() public constant returns (uint); } contract HardcodedWallets { // **** DATA address public walletFounder1; // founder #1 wallet, CEO, compulsory address public walletFounder2; // founder #2 wallet address public walletFounder3; // founder #3 wallet address public walletCommunityReserve; // Distribution wallet address public walletCompanyReserve; // Distribution wallet address public walletTeamAdvisors; // Distribution wallet address public walletBountyProgram; // Distribution wallet // **** FUNCTIONS /** * @notice Constructor, set up the compliance officer oracle wallet */ constructor() public { // set up the founders' oracle wallets walletFounder1 = 0x5E69332F57Ac45F5fCA43B6b007E8A7b138c2938; // founder #1 (CEO) wallet walletFounder2 = 0x852f9a94a29d68CB95Bf39065BED6121ABf87607; // founder #2 wallet walletFounder3 = 0x0a339965e52dF2c6253989F5E9173f1F11842D83; // founder #3 wallet // set up the wallets for distribution of the total supply of tokens walletCommunityReserve = 0xB79116a062939534042d932fe5DF035E68576547; walletCompanyReserve = 0xA6845689FE819f2f73a6b9C6B0D30aD6b4a006d8; walletTeamAdvisors = 0x0227038b2560dF1abf3F8C906016Af0040bc894a; walletBountyProgram = 0xdd401Df9a049F6788cA78b944c64D21760757D73; } } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract System { using SafeMath for uint256; address owner; // **** MODIFIERS // @notice To limit functions usage to contract owner modifier onlyOwner() { if (msg.sender != owner) { error('System: onlyOwner function called by user that is not owner'); } else { _; } } // **** FUNCTIONS // @notice Calls whenever an error occurs, logs it or reverts transaction function error(string _error) internal { revert(_error); // in case revert with error msg is not yet fully supported // emit Error(_error); // throw; } // @notice For debugging purposes when using solidity online browser, remix and sandboxes function whoAmI() public constant returns (address) { return msg.sender; } // @notice Get the current timestamp from last mined block function timestamp() public constant returns (uint256) { return block.timestamp; } // @notice Get the balance in weis of this contract function contractBalance() public constant returns (uint256) { return address(this).balance; } // @notice System constructor, defines owner constructor() public { // This is the constructor, so owner should be equal to msg.sender, and this method should be called just once owner = msg.sender; // make sure owner address is configured if(owner == 0x0) error('System constructor: Owner address is 0x0'); // Never should happen, but just in case... } // **** EVENTS // @notice A generic error log event Error(string _error); // @notice For debug purposes event DebugUint256(uint256 _data); } contract Escrow is System, HardcodedWallets { using SafeMath for uint256; // **** DATA mapping (address => uint256) public deposited; uint256 nextStage; // Circular reference to ICO contract address public addressSCICO; // Circular reference to Tokens contract address public addressSCTokens; Tokens public SCTokens; // **** FUNCTIONS /** * @notice Constructor, set up the state */ constructor() public { // copy totalSupply from Tokens to save gas uint256 totalSupply = 1350000000 ether; deposited[this] = totalSupply.mul(50).div(100); deposited[walletCommunityReserve] = totalSupply.mul(20).div(100); deposited[walletCompanyReserve] = totalSupply.mul(14).div(100); deposited[walletTeamAdvisors] = totalSupply.mul(15).div(100); deposited[walletBountyProgram] = totalSupply.mul(1).div(100); } function deposit(uint256 _amount) public returns (bool) { // only ICO could deposit if (msg.sender != addressSCICO) { error('Escrow: not allowed to deposit'); return false; } deposited[this] = deposited[this].add(_amount); return true; } /** * @notice Withdraw funds from the tokens contract */ function withdraw(address _address, uint256 _amount) public onlyOwner returns (bool) { if (deposited[_address]<_amount) { error('Escrow: not enough balance'); return false; } deposited[_address] = deposited[_address].sub(_amount); return SCTokens.transfer(_address, _amount); } /** * @notice Withdraw funds from the tokens contract */ function fundICO(uint256 _amount, uint8 _stage) public returns (bool) { if(nextStage !=_stage) { error('Escrow: ICO stage already funded'); return false; } if (msg.sender != addressSCICO || tx.origin != owner) { error('Escrow: not allowed to fund the ICO'); return false; } if (deposited[this]<_amount) { error('Escrow: not enough balance'); return false; } bool success = SCTokens.transfer(addressSCICO, _amount); if(success) { deposited[this] = deposited[this].sub(_amount); nextStage++; emit FundICO(addressSCICO, _amount); } return success; } /** * @notice The owner can specify which ICO contract is allowed to transfer tokens while timelock is on */ function setMyICOContract(address _SCICO) public onlyOwner { addressSCICO = _SCICO; } /** * @notice Set the tokens contract */ function setTokensContract(address _addressSCTokens) public onlyOwner { addressSCTokens = _addressSCTokens; SCTokens = Tokens(_addressSCTokens); } /** * @notice Returns balance of given address */ function balanceOf(address _address) public constant returns (uint256 balance) { return deposited[_address]; } // **** EVENTS // Triggered when an investor buys some tokens directly with Ethers event FundICO(address indexed _addressICO, uint256 _amount); } contract RefundVault is HardcodedWallets, System { using SafeMath for uint256; enum State { Active, Refunding, Closed } // **** DATA mapping (address => uint256) public deposited; mapping (address => uint256) public tokensAcquired; State public state; // Circular reference to ICO contract address public addressSCICO; // **** MODIFIERS // @notice To limit functions usage to contract owner modifier onlyICOContract() { if (msg.sender != addressSCICO) { error('RefundVault: onlyICOContract function called by user that is not ICOContract'); } else { _; } } // **** FUNCTIONS /** * @notice Constructor, set up the state */ constructor() public { state = State.Active; } function weisDeposited(address _investor) public constant returns (uint256) { return deposited[_investor]; } function getTokensAcquired(address _investor) public constant returns (uint256) { return tokensAcquired[_investor]; } /** * @notice Registers how many tokens have each investor and how many ethers they spent (When ICOing through PayIn this function is not called) */ function deposit(address _investor, uint256 _tokenAmount) onlyICOContract public payable returns (bool) { if (state != State.Active) { error('deposit: state != State.Active'); return false; } deposited[_investor] = deposited[_investor].add(msg.value); tokensAcquired[_investor] = tokensAcquired[_investor].add(_tokenAmount); return true; } /** * @notice When ICO finalizes funds are transferred to founders' wallets */ function close() onlyICOContract public returns (bool) { if (state != State.Active) { error('close: state != State.Active'); return false; } state = State.Closed; walletFounder1.transfer(address(this).balance.mul(33).div(100)); // Forwards 33% to 1st founder wallet walletFounder2.transfer(address(this).balance.mul(50).div(100)); // Forwards 33% to 2nd founder wallet walletFounder3.transfer(address(this).balance); // Forwards 34% to 3rd founder wallet emit Closed(); // Event log return true; } /** * @notice When ICO finalizes owner toggles refunding */ function enableRefunds() onlyICOContract public returns (bool) { if (state != State.Active) { error('enableRefunds: state != State.Active'); return false; } state = State.Refunding; emit RefundsEnabled(); // Event log return true; } /** * @notice ICO Smart Contract can call this function for the investor to refund */ function refund(address _investor) onlyICOContract public returns (bool) { if (state != State.Refunding) { error('refund: state != State.Refunding'); return false; } if (deposited[_investor] == 0) { error('refund: no deposit to refund'); return false; } uint256 depositedValue = deposited[_investor]; deposited[_investor] = 0; tokensAcquired[_investor] = 0; // tokens should have been returned previously to the ICO _investor.transfer(depositedValue); emit Refunded(_investor, depositedValue); // Event log return true; } /** * @notice To allow ICO contracts to check whether RefundVault is ready to refund investors */ function isRefunding() public constant returns (bool) { return (state == State.Refunding); } /** * @notice The owner must specify which ICO contract is allowed call for refunds */ function setMyICOContract(address _SCICO) public onlyOwner { require(address(this).balance == 0); addressSCICO = _SCICO; } // **** EVENTS // Triggered when ICO contract closes the vault and forwards funds to the founders' wallets event Closed(); // Triggered when ICO contract initiates refunding event RefundsEnabled(); // Triggered when an investor claims (through ICO contract) and gets its funds event Refunded(address indexed beneficiary, uint256 weiAmount); } contract Haltable is System { bool public halted; // **** MODIFIERS modifier stopInEmergency { if (halted) { error('Haltable: stopInEmergency function called and contract is halted'); } else { _; } } modifier onlyInEmergency { if (!halted) { error('Haltable: onlyInEmergency function called and contract is not halted'); } { _; } } // **** FUNCTIONS // called by the owner on emergency, triggers stopped state function halt() external onlyOwner { halted = true; emit Halt(true, msg.sender, timestamp()); // Event log } // called by the owner on end of emergency, returns to normal state function unhalt() external onlyOwner onlyInEmergency { halted = false; emit Halt(false, msg.sender, timestamp()); // Event log } // **** EVENTS // @notice Triggered when owner halts contract event Halt(bool _switch, address _halter, uint256 _timestamp); } contract ICO is HardcodedWallets, Haltable { // **** DATA // Linked Contracts Tokens public SCTokens; // The token being sold RefundVault public SCRefundVault; // The vault for softCap refund Whitelist public SCWhitelist; // The whitelist of allowed wallets to buy tokens on ICO Escrow public SCEscrow; // Escrow service // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; bool public isFinalized = false; uint256 public weisPerBigToken; // how many weis a buyer pays to get a big token (10^18 tokens) uint256 public weisPerEther; uint256 public tokensPerEther; // amount of tokens with multiplier received on ICO when paying with 1 Ether, discounts included uint256 public bigTokensPerEther; // amount of tokens w/omultiplier received on ICO when paying with 1 Ether, discounts included uint256 public weisRaised; // amount of Weis raised uint256 public etherHardCap; // Max amount of Ethers to raise uint256 public tokensHardCap; // Max amount of Tokens for sale uint256 public weisHardCap; // Max amount of Weis raised uint256 public weisMinInvestment; // Min amount of Weis to perform a token sale uint256 public etherSoftCap; // Min amount of Ethers for sale to ICO become successful uint256 public tokensSoftCap; // Min amount of Tokens for sale to ICO become successful uint256 public weisSoftCap; // Min amount of Weis raised to ICO become successful uint256 public discount; // Applies to token price when investor buys tokens. It is a number between 0-100 uint256 discountedPricePercentage; uint8 ICOStage; // **** MODIFIERS // **** FUNCTIONS // fallback function can be used to buy tokens function () payable public { buyTokens(); } /** * @notice Token purchase function direclty through ICO Smart Contract. Beneficiary = msg.sender */ function buyTokens() public stopInEmergency payable returns (bool) { if (msg.value == 0) { error('buyTokens: ZeroPurchase'); return false; } uint256 tokenAmount = buyTokensLowLevel(msg.sender, msg.value); // Send the investor's ethers to the vault if (!SCRefundVault.deposit.value(msg.value)(msg.sender, tokenAmount)) { revert('buyTokens: unable to transfer collected funds from ICO contract to Refund Vault'); // Revert needed to refund investor on error // error('buyTokens: unable to transfer collected funds from ICO contract to Refund Vault'); // return false; } emit BuyTokens(msg.sender, msg.value, tokenAmount); // Event log return true; } /** * @notice Token purchase function through Oracle PayIn by MarketPay.io API */ /* // Deactivated to save ICO contract deployment gas cost function buyTokensOraclePayIn(address _beneficiary, uint256 _weisAmount) public onlyCustodyFiat stopInEmergency returns (bool) { uint256 tokenAmount = buyTokensLowLevel(_beneficiary, _weisAmount); emit BuyTokensOraclePayIn(msg.sender, _beneficiary, _weisAmount, tokenAmount); // Event log return true; }*/ /** * @notice Low level token purchase function, w/o ether transfer from investor */ function buyTokensLowLevel(address _beneficiary, uint256 _weisAmount) private stopInEmergency returns (uint256 tokenAmount) { if (_beneficiary == 0x0) { revert('buyTokensLowLevel: _beneficiary == 0x0'); // Revert needed to refund investor on error // error('buyTokensLowLevel: _beneficiary == 0x0'); // return 0; } if (timestamp() < startTime || timestamp() > endTime) { revert('buyTokensLowLevel: Not withinPeriod'); // Revert needed to refund investor on error // error('buyTokensLowLevel: Not withinPeriod'); // return 0; } if (!SCWhitelist.isInvestor(_beneficiary)) { revert('buyTokensLowLevel: Investor is not registered on the whitelist'); // Revert needed to refund investor on error // error('buyTokensLowLevel: Investor is not registered on the whitelist'); // return 0; } if (isFinalized) { revert('buyTokensLowLevel: ICO is already finalized'); // Revert needed to refund investor on error // error('buyTokensLowLevel: ICO is already finalized'); // return 0; } // Verify whether enough ether has been sent to buy the min amount of investment if (_weisAmount < weisMinInvestment) { revert('buyTokensLowLevel: Minimal investment not reached. Not enough ethers to perform the minimal purchase'); // Revert needed to refund investor on error // error('buyTokensLowLevel: Minimal investment not reached. Not enough ethers to perform the minimal purchase'); // return 0; } // Verify whether there are enough tokens to sell if (weisRaised.add(_weisAmount) > weisHardCap) { revert('buyTokensLowLevel: HardCap reached. Not enough tokens on ICO contract to perform this purchase'); // Revert needed to refund investor on error // error('buyTokensLowLevel: HardCap reached. Not enough tokens on ICO contract to perform this purchase'); // return 0; } // Calculate token amount to be sold tokenAmount = _weisAmount.mul(weisPerEther).div(weisPerBigToken); // Applying discount tokenAmount = tokenAmount.mul(100).div(discountedPricePercentage); // Update state weisRaised = weisRaised.add(_weisAmount); // Send the tokens to the investor if (!SCTokens.transfer(_beneficiary, tokenAmount)) { revert('buyTokensLowLevel: unable to transfer tokens from ICO contract to beneficiary'); // Revert needed to refund investor on error // error('buyTokensLowLevel: unable to transfer tokens from ICO contract to beneficiary'); // return 0; } emit BuyTokensLowLevel(msg.sender, _beneficiary, _weisAmount, tokenAmount); // Event log return tokenAmount; } /** * @return true if ICO event has ended */ /* // Deactivated to save ICO contract deployment gas cost function hasEnded() public constant returns (bool) { return timestamp() > endTime; }*/ /** * @notice Called by owner to alter the ICO deadline */ function updateEndTime(uint256 _endTime) onlyOwner public returns (bool) { endTime = _endTime; emit UpdateEndTime(_endTime); // Event log } /** * @notice Must be called by owner before or after ICO ends, to check whether soft cap is reached and transfer collected funds */ function finalize(bool _forceRefund) onlyOwner public returns (bool) { if (isFinalized) { error('finalize: ICO is already finalized.'); return false; } if (weisRaised >= weisSoftCap && !_forceRefund) { if (!SCRefundVault.close()) { error('finalize: SCRefundVault.close() failed'); return false; } } else { if (!SCRefundVault.enableRefunds()) { error('finalize: SCRefundVault.enableRefunds() failed'); return false; } if(_forceRefund) { emit ForceRefund(); // Event log } } // Move remaining ICO tokens back to the Escrow uint256 balanceAmount = SCTokens.balanceOf(this); if (!SCTokens.transfer(address(SCEscrow), balanceAmount)) { error('finalize: unable to return remaining ICO tokens'); return false; } // Adjust Escrow balance correctly if(!SCEscrow.deposit(balanceAmount)) { error('finalize: unable to return remaining ICO tokens'); return false; } isFinalized = true; emit Finalized(); // Event log return true; } /** * @notice If ICO is unsuccessful, investors can claim refunds here */ function claimRefund() public stopInEmergency returns (bool) { if (!isFinalized) { error('claimRefund: ICO is not yet finalized.'); return false; } if (!SCRefundVault.isRefunding()) { error('claimRefund: RefundVault state != State.Refunding'); return false; } // Before transfering the ETHs to the investor, get back the tokens bought on ICO uint256 tokenAmount = SCRefundVault.getTokensAcquired(msg.sender); emit GetBackTokensOnRefund(msg.sender, this, tokenAmount); // Event Log if (!SCTokens.refundTokens(msg.sender, tokenAmount)) { error('claimRefund: unable to transfer investor tokens to ICO contract before refunding'); return false; } if (!SCRefundVault.refund(msg.sender)) { error('claimRefund: SCRefundVault.refund() failed'); return false; } return true; } function fundICO() public onlyOwner { if (!SCEscrow.fundICO(tokensHardCap, ICOStage)) { revert('ICO funding failed'); } } // **** EVENTS // Triggered when an investor buys some tokens directly with Ethers event BuyTokens(address indexed _purchaser, uint256 _value, uint256 _amount); // Triggered when Owner says some investor has requested tokens on PayIn MarketPay.io API event BuyTokensOraclePayIn(address indexed _purchaser, address indexed _beneficiary, uint256 _weisAmount, uint256 _tokenAmount); // Triggered when an investor buys some tokens directly with Ethers or through payin Oracle event BuyTokensLowLevel(address indexed _purchaser, address indexed _beneficiary, uint256 _value, uint256 _amount); // Triggered when an SC owner request to end the ICO, transferring funds to founders wallet or ofeering them as a refund event Finalized(); // Triggered when an SC owner request to end the ICO and allow transfer of funds to founders wallets as a refund event ForceRefund(); // Triggered when RefundVault is created //event AddressSCRefundVault(address _scAddress); // Triggered when investor refund and their tokens got back to ICO contract event GetBackTokensOnRefund(address _from, address _to, uint256 _amount); // Triggered when Owner updates ICO deadlines event UpdateEndTime(uint256 _endTime); } contract ICOPreSale is ICO { /** * @notice ICO constructor. Definition of ICO parameters and subcontracts autodeployment */ constructor(address _SCEscrow, address _SCTokens, address _SCWhitelist, address _SCRefundVault) public { if (_SCTokens == 0x0) { revert('Tokens Constructor: _SCTokens == 0x0'); } if (_SCWhitelist == 0x0) { revert('Tokens Constructor: _SCWhitelist == 0x0'); } if (_SCRefundVault == 0x0) { revert('Tokens Constructor: _SCRefundVault == 0x0'); } SCTokens = Tokens(_SCTokens); SCWhitelist = Whitelist(_SCWhitelist); SCRefundVault = RefundVault(_SCRefundVault); weisPerEther = 1 ether; // 10e^18 multiplier // Deadline startTime = timestamp(); endTime = timestamp().add(24 days); // from 8th June to 2th July 2018 // Token Price bigTokensPerEther = 7500; // tokens (w/o multiplier) got for 1 ether tokensPerEther = bigTokensPerEther.mul(weisPerEther); // tokens (with multiplier) got for 1 ether discount = 45; // pre-sale 45% discountedPricePercentage = 100; discountedPricePercentage = discountedPricePercentage.sub(discount); weisMinInvestment = weisPerEther.mul(1); // 2018-05-10: [email protected] Los Hardcap que indicas no son los últimos comentados. Los correctos serían: // Pre-Sale: 8.470 ETH // 1st Tier: 8.400 ETH // 2nd Tier: 68.600 ETH // HardCap // etherHardCap = 8500; // As of 2018-05-09 => Hardcap pre sale: 8.500 ETH // As of 2018-05-10 => Pre-Sale: 8.470 ETH etherHardCap = 8067; // As of 2018-05-24 => Pre-Sale: 8067 ETH tokensHardCap = tokensPerEther.mul(etherHardCap).mul(100).div(discountedPricePercentage); weisPerBigToken = weisPerEther.div(bigTokensPerEther); // weisHardCap = weisPerBigToken.mul(tokensHardCap).div(weisPerEther); weisHardCap = weisPerEther.mul(etherHardCap); // SoftCap etherSoftCap = 750; // As of 2018-05-09 => Softcap pre sale: 750 ETH weisSoftCap = weisPerEther.mul(etherSoftCap); SCEscrow = Escrow(_SCEscrow); ICOStage = 0; } } contract Tokens is HardcodedWallets, ERC20, Haltable { // **** DATA mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; uint256 public _totalSupply; // Public variables of the token, all used for display string public name; string public symbol; uint8 public decimals; string public standard = 'H0.1'; // HumanStandardToken is a specialisation of ERC20 defining these parameters // Timelock uint256 public timelockEndTime; // Circular reference to ICO contract address public addressSCICO; // Circular reference to Escrow contract address public addressSCEscrow; // Reference to ComplianceService contract address public addressSCComplianceService; ComplianceService public SCComplianceService; // **** MODIFIERS // @notice To limit token transfers while timelocked modifier notTimeLocked() { if (now < timelockEndTime && msg.sender != addressSCICO && msg.sender != addressSCEscrow) { error('notTimeLocked: Timelock still active. Function is yet unavailable.'); } else { _; } } // **** FUNCTIONS /** * @notice Constructor: set up token properties and owner token balance */ constructor(address _addressSCEscrow, address _addressSCComplianceService) public { name = "TheRentalsToken"; symbol = "TRT"; decimals = 18; // 18 decimal places, the same as ETH // initialSupply = 2000000000 ether; // 2018-04-21: ICO summary.docx: ...Dicho valor generaría un Total Supply de 2.000 millones de TRT. _totalSupply = 1350000000 ether; // 2018-05-10: [email protected] ...tenemos una emisión de 1.350 millones de Tokens timelockEndTime = timestamp().add(45 days); // Default timelock addressSCEscrow = _addressSCEscrow; addressSCComplianceService = _addressSCComplianceService; SCComplianceService = ComplianceService(addressSCComplianceService); // Token distribution balances[_addressSCEscrow] = _totalSupply; emit Transfer(0x0, _addressSCEscrow, _totalSupply); } /** * @notice Get the token total supply */ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } /** * @notice Get the token balance of a wallet with address _owner */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } /** * @notice Send _amount amount of tokens to address _to */ function transfer(address _to, uint256 _amount) public notTimeLocked stopInEmergency returns (bool success) { if (balances[msg.sender] < _amount) { error('transfer: the amount to transfer is higher than your token balance'); return false; } if(!SCComplianceService.validate(msg.sender, _to, _amount)) { error('transfer: not allowed by the compliance service'); return false; } balances[msg.sender] = balances[msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(msg.sender, _to, _amount); // Event log return true; } /** * @notice Send _amount amount of tokens from address _from to address _to * @notice The transferFrom method is used for a withdraw workflow, allowing contracts to send * @notice tokens on your behalf, for example to "deposit" to a contract address and/or to charge * @notice fees in sub-currencies; the command should fail unless the _from account has * @notice deliberately authorized the sender of the message via some mechanism */ function transferFrom(address _from, address _to, uint256 _amount) public notTimeLocked stopInEmergency returns (bool success) { if (balances[_from] < _amount) { error('transferFrom: the amount to transfer is higher than the token balance of the source'); return false; } if (allowed[_from][msg.sender] < _amount) { error('transferFrom: the amount to transfer is higher than the maximum token transfer allowed by the source'); return false; } if(!SCComplianceService.validate(_from, _to, _amount)) { error('transfer: not allowed by the compliance service'); return false; } balances[_from] = balances[_from].sub(_amount); balances[_to] = balances[_to].add(_amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); emit Transfer(_from, _to, _amount); // Event log return true; } /** * @notice Allow _spender to withdraw from your account, multiple times, up to the _amount amount. * @notice If this function is called again it overwrites the current allowance with _amount. */ function approve(address _spender, uint256 _amount) public returns (bool success) { allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); // Event log return true; } /** * @notice Returns the amount which _spender is still allowed to withdraw from _owner */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @notice This is out of ERC20 standard but it is necessary to build market escrow contracts of assets * @notice Send _amount amount of tokens to from tx.origin to address _to */ function refundTokens(address _from, uint256 _amount) public notTimeLocked stopInEmergency returns (bool success) { if (tx.origin != _from) { error('refundTokens: tx.origin did not request the refund directly'); return false; } if (addressSCICO != msg.sender) { error('refundTokens: caller is not the current ICO address'); return false; } if (balances[_from] < _amount) { error('refundTokens: the amount to transfer is higher than your token balance'); return false; } if(!SCComplianceService.validate(_from, addressSCICO, _amount)) { error('transfer: not allowed by the compliance service'); return false; } balances[_from] = balances[_from].sub(_amount); balances[addressSCICO] = balances[addressSCICO].add(_amount); emit Transfer(_from, addressSCICO, _amount); // Event log return true; } /** * @notice The owner can specify which ICO contract is allowed to transfer tokens while timelock is on */ function setMyICOContract(address _SCICO) public onlyOwner { addressSCICO = _SCICO; } function setComplianceService(address _addressSCComplianceService) public onlyOwner { addressSCComplianceService = _addressSCComplianceService; SCComplianceService = ComplianceService(addressSCComplianceService); } /** * @notice Called by owner to alter the token timelock */ function updateTimeLock(uint256 _timelockEndTime) onlyOwner public returns (bool) { timelockEndTime = _timelockEndTime; emit UpdateTimeLock(_timelockEndTime); // Event log return true; } // **** EVENTS // Triggered when tokens are transferred event Transfer(address indexed _from, address indexed _to, uint256 _amount); // Triggered when someone approves a spender to move its tokens event Approval(address indexed _owner, address indexed _spender, uint256 _amount); // Triggered when Owner updates token timelock event UpdateTimeLock(uint256 _timelockEndTime); } contract Whitelist is HardcodedWallets, System { // **** DATA mapping (address => bool) public walletsICO; mapping (address => bool) public managers; // Checks whether a given wallet is authorized to ICO investing function isInvestor(address _wallet) public constant returns (bool) { return (walletsICO[_wallet]); } /** * @notice Registers an investor */ function addInvestor(address _wallet) external isManager returns (bool) { // Checks whether this wallet has been previously added as an investor if (walletsICO[_wallet]) { error('addInvestor: this wallet has been previously granted as ICO investor'); return false; } walletsICO[_wallet] = true; emit AddInvestor(_wallet, timestamp()); // Event log return true; } modifier isManager(){ if (managers[msg.sender] || msg.sender == owner) { _; } else { error("isManager: called by user that is not owner or manager"); } } // adds an address that will have the right to add investors function addManager(address _managerAddr) external onlyOwner returns (bool) { if(managers[_managerAddr]){ error("addManager: manager account already exists."); return false; } managers[_managerAddr] = true; emit AddManager(_managerAddr, timestamp()); } // removes a manager address function delManager(address _managerAddr) external onlyOwner returns (bool) { if(!managers[_managerAddr]){ error("delManager: manager account not found."); return false; } delete managers[_managerAddr]; emit DelManager(_managerAddr, timestamp()); } // **** EVENTS // Triggered when a wallet is granted to become an ICO investor event AddInvestor(address indexed _wallet, uint256 _timestamp); // Triggered when a manager is added event AddManager(address indexed _managerAddr, uint256 _timestamp); // Triggered when a manager is removed event DelManager(address indexed _managerAddr, uint256 _timestamp); }
The owner can specify which ICO contract is allowed to transfer tokens while timelock is on/
function setMyICOContract(address _SCICO) public onlyOwner { addressSCICO = _SCICO; }
6,402,465
/* * Lottery oracle * * Copyright (C) 2017-2019 Hubii AS */ pragma solidity ^0.5.11; import {Resolvable} from "./Resolvable.sol"; import {RBACed} from "./RBACed.sol"; import {Able} from "./Able.sol"; import {SafeMath} from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import {VerificationPhaseLib} from "./VerificationPhaseLib.sol"; import {BountyFund} from "./BountyFund.sol"; import {ERC20} from "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol"; /// @title ResolutionEngine /// @author Jens Ivar Jørdre <[email protected]> /// @notice A resolution engine base contract contract ResolutionEngine is Resolvable, RBACed, Able { using SafeMath for uint256; using VerificationPhaseLib for VerificationPhaseLib.VerificationPhase; event Frozen(); event BountyAllocatorSet(address indexed _bountyAllocator); event Staked(address indexed _wallet, uint256 indexed _verificationPhaseNumber, bool _status, uint256 _amount); event BountyWithdrawn(address indexed _wallet, uint256 _bountyAmount); event VerificationPhaseOpened(uint256 indexed _verificationPhaseNumber, uint256 _bountyAmount); event VerificationPhaseClosed(uint256 indexed _verificationPhaseNumber); event PayoutStaged(address indexed _wallet, uint256 indexed _firstVerificationPhaseNumber, uint256 indexed _lastVerificationPhaseNumber, uint256 _payout); event StakeStaged(address indexed _wallet, uint _amount); event Staged(address indexed _wallet, uint _amount); event Withdrawn(address indexed _wallet, uint _amount); string constant public STAKE_ACTION = "STAKE"; string constant public RESOLVE_ACTION = "RESOLVE"; address public oracle; address public operator; address public bountyAllocator; BountyFund public bountyFund; ERC20 public token; bool public frozen; uint256 public verificationPhaseNumber; mapping(uint256 => VerificationPhaseLib.VerificationPhase) public verificationPhaseByPhaseNumber; mapping(address => mapping(bool => uint256)) public stakedAmountByWalletStatus; mapping(uint256 => mapping(bool => uint256)) public stakedAmountByBlockStatus; VerificationPhaseLib.Status public verificationStatus; mapping(address => mapping(uint256 => bool)) public payoutStagedByWalletPhase; mapping(address => uint256) public stagedAmountByWallet; /// @notice `msg.sender` will be added as accessor to the owner role constructor(address _oracle, address _operator, address _bountyFund) public { // Initialize oracle and operator oracle = _oracle; operator = _operator; // Initialize bounty fund bountyFund = BountyFund(_bountyFund); bountyFund.setResolutionEngine(address(this)); // Initialize token to the one of bounty fund token = ERC20(bountyFund.token()); } modifier onlyOracle() { require(msg.sender == oracle, "ResolutionEngine: sender is not the defined oracle"); _; } modifier onlyOperator() { require(msg.sender == operator, "ResolutionEngine: sender is not the defined operator"); _; } modifier onlyNotFrozen() { require(!frozen, "ResolutionEngine: is frozen"); _; } /// @notice Freeze updates to this resolution engine /// @dev This operation can not be undone function freeze() public onlyRoleAccessor(OWNER_ROLE) { // Set the frozen flag frozen = true; // Emit event emit Frozen(); } /// @notice Set the bounty allocator /// @param _bountyAllocator The bounty allocator to be set function setBountyAllocator(address _bountyAllocator) public onlyRoleAccessor(OWNER_ROLE) { // Set the bounty allocator bountyAllocator = _bountyAllocator; // Emit event emit BountyAllocatorSet(bountyAllocator); } /// @notice Initialize the engine function initialize() public onlyRoleAccessor(OWNER_ROLE) { // Require no previous initialization require(0 == verificationPhaseNumber, "ResolutionEngine: already initialized"); // Open verification phase _openVerificationPhase(); } /// @notice Disable the given action /// @param _action The action to disable function disable(string memory _action) public onlyOperator { // Disable super.disable(_action); } /// @notice Enable the given action /// @param _action The action to enable function enable(string memory _action) public onlyOperator { // Enable super.enable(_action); } /// @notice Stake by updating metrics /// @dev The function can only be called by oracle. /// @param _wallet The concerned wallet /// @param _status The status staked at /// @param _amount The amount staked function stake(address _wallet, bool _status, uint256 _amount) public onlyOracle onlyEnabled(STAKE_ACTION) { // Update metrics stakedAmountByWalletStatus[_wallet][_status] = stakedAmountByWalletStatus[_wallet][_status].add(_amount); stakedAmountByBlockStatus[block.number][_status] = stakedAmountByBlockStatus[block.number][_status] .add(_amount); verificationPhaseByPhaseNumber[verificationPhaseNumber].stake(_wallet, _status, _amount); // Emit event emit Staked(_wallet, verificationPhaseNumber, _status, _amount); } /// @notice Resolve the market in the current verification phase if resolution criteria have been met /// @dev The function can only be called by oracle. /// be the current verification phase number function resolveIfCriteriaMet() public onlyOracle onlyEnabled(RESOLVE_ACTION) { // If resolution criteria are met... if (resolutionCriteriaMet()) { // Close existing verification phase _closeVerificationPhase(); // Open new verification phase _openVerificationPhase(); } } /// @notice Get the metrics for the given verification phase number /// @param _verificationPhaseNumber The concerned verification phase number /// @return the metrics function metricsByVerificationPhaseNumber(uint256 _verificationPhaseNumber) public view returns (VerificationPhaseLib.State state, uint256 trueStakeAmount, uint256 falseStakeAmount, uint256 stakeAmount, uint256 numberOfWallets, uint256 bountyAmount, bool bountyAwarded, uint256 startBlock, uint256 endBlock, uint256 numberOfBlocks) { state = verificationPhaseByPhaseNumber[_verificationPhaseNumber].state; trueStakeAmount = verificationPhaseByPhaseNumber[_verificationPhaseNumber].stakedAmountByStatus[true]; falseStakeAmount = verificationPhaseByPhaseNumber[_verificationPhaseNumber].stakedAmountByStatus[false]; stakeAmount = verificationPhaseByPhaseNumber[_verificationPhaseNumber].stakedAmount; numberOfWallets = verificationPhaseByPhaseNumber[_verificationPhaseNumber].stakingWallets; bountyAmount = verificationPhaseByPhaseNumber[_verificationPhaseNumber].bountyAmount; bountyAwarded = verificationPhaseByPhaseNumber[_verificationPhaseNumber].bountyAwarded; startBlock = verificationPhaseByPhaseNumber[_verificationPhaseNumber].startBlock; endBlock = verificationPhaseByPhaseNumber[_verificationPhaseNumber].endBlock; numberOfBlocks = (startBlock > 0 && endBlock == 0 ? block.number : endBlock).sub(startBlock); } /// @notice Get the metrics for the given verification phase number and wallet /// @dev Reverts if provided verification phase number is higher than current verification phase number /// @param _verificationPhaseNumber The concerned verification phase number /// @param _wallet The address of the concerned wallet /// @return the metrics function metricsByVerificationPhaseNumberAndWallet(uint256 _verificationPhaseNumber, address _wallet) public view returns (uint256 trueStakeAmount, uint256 falseStakeAmount, uint256 stakeAmount) { trueStakeAmount = verificationPhaseByPhaseNumber[_verificationPhaseNumber] .stakedAmountByWalletStatus[_wallet][true]; falseStakeAmount = verificationPhaseByPhaseNumber[_verificationPhaseNumber] .stakedAmountByWalletStatus[_wallet][false]; stakeAmount = trueStakeAmount.add(falseStakeAmount); } /// @notice Get the metrics for the wallet /// @param _wallet The address of the concerned wallet /// @return the metrics function metricsByWallet(address _wallet) public view returns (uint256 trueStakeAmount, uint256 falseStakeAmount, uint256 stakeAmount) { trueStakeAmount = stakedAmountByWalletStatus[_wallet][true]; falseStakeAmount = stakedAmountByWalletStatus[_wallet][false]; stakeAmount = trueStakeAmount.add(falseStakeAmount); } /// @notice Get the metrics for the block /// @dev Reverts if provided block number is higher than current block number /// @param _blockNumber The concerned block number /// @return the metrics function metricsByBlockNumber(uint256 _blockNumber) public view returns (uint256 trueStakeAmount, uint256 falseStakeAmount, uint256 stakeAmount) { trueStakeAmount = stakedAmountByBlockStatus[_blockNumber][true]; falseStakeAmount = stakedAmountByBlockStatus[_blockNumber][false]; stakeAmount = trueStakeAmount.add(falseStakeAmount); } /// @notice Calculate the payout accrued by given wallet in the inclusive range of given verification phase numbers /// @param _firstVerificationPhaseNumber The first verification phase number to stage payout from /// @param _lastVerificationPhaseNumber The last verification phase number to stage payout from /// @param _wallet The address of the concerned wallet /// @return the payout function calculatePayout(address _wallet, uint256 _firstVerificationPhaseNumber, uint256 _lastVerificationPhaseNumber) public view returns (uint256) { // For each verification phase number in the inclusive range calculate payout uint256 payout = 0; for (uint256 i = _firstVerificationPhaseNumber; i <= _lastVerificationPhaseNumber; i++) payout = payout.add(_calculatePayout(_wallet, i)); // Return payout return payout; } /// @notice Stage the payout accrued by given wallet in the inclusive range of given verification phase numbers /// @dev The function can only be called by oracle. /// @param _wallet The address of the concerned wallet /// @param _firstVerificationPhaseNumber The first verification phase number to stage payout from /// @param _lastVerificationPhaseNumber The last verification phase number to stage payout from function stagePayout(address _wallet, uint256 _firstVerificationPhaseNumber, uint256 _lastVerificationPhaseNumber) public onlyOracle { // For each verification phase number in the inclusive range stage payout uint256 amount = 0; for (uint256 i = _firstVerificationPhaseNumber; i <= _lastVerificationPhaseNumber; i++) amount = amount.add(_stagePayout(_wallet, i)); // Emit event emit PayoutStaged(_wallet, _firstVerificationPhaseNumber, _lastVerificationPhaseNumber, amount); } /// @notice Stage the amount staked in the current verification phase /// @dev The function can only be called by oracle and when resolve action has been disabled /// @param _wallet The address of the concerned wallet function stageStake(address _wallet) public onlyOracle onlyDisabled(RESOLVE_ACTION) { // Calculate the amount staked by the wallet uint256 amount = verificationPhaseByPhaseNumber[verificationPhaseNumber] .stakedAmountByWalletStatus[_wallet][true].add( verificationPhaseByPhaseNumber[verificationPhaseNumber] .stakedAmountByWalletStatus[_wallet][false] ); // Require no previous stage stage require(0 < amount, "ResolutionEngine: stake is zero"); // Reset wallet's stakes verificationPhaseByPhaseNumber[verificationPhaseNumber].stakedAmountByWalletStatus[_wallet][true] = 0; verificationPhaseByPhaseNumber[verificationPhaseNumber].stakedAmountByWalletStatus[_wallet][false] = 0; // Stage the amount _stage(_wallet, amount); // Emit event emit StakeStaged(_wallet, amount); } /// @notice Stage the given amount /// @dev The function can only be called by oracle. /// @param _wallet The address of the concerned wallet /// @param _amount The amount to be staged function stage(address _wallet, uint256 _amount) public onlyOracle { // Stage the amount _stage(_wallet, _amount); // Emit event emit Staged(_wallet, _amount); } /// @notice Withdraw the given amount /// @dev The function can only be called by oracle. /// @param _wallet The address of the concerned wallet /// @param _amount The amount to be withdrawn function withdraw(address _wallet, uint256 _amount) public onlyOracle { // Require that the withdrawal amount is smaller than the wallet's staged amount require(_amount <= stagedAmountByWallet[_wallet], "ResolutionEngine: amount is greater than staged amount"); // Unstage the amount stagedAmountByWallet[_wallet] = stagedAmountByWallet[_wallet].sub(_amount); // Transfer the amount token.transfer(_wallet, _amount); // Emit event emit Withdrawn(_wallet, _amount); } /// @notice Stage the bounty to the given address /// @param _wallet The recipient address of the bounty transfer function withdrawBounty(address _wallet) public onlyOperator onlyDisabled(RESOLVE_ACTION) { // Require no previous bounty withdrawal require(0 < verificationPhaseByPhaseNumber[verificationPhaseNumber].bountyAmount, "ResolutionEngine: bounty is zero"); // Store the bounty amount locally uint256 amount = verificationPhaseByPhaseNumber[verificationPhaseNumber].bountyAmount; // Reset the bounty amount verificationPhaseByPhaseNumber[verificationPhaseNumber].bountyAmount = 0; // Transfer the amount token.transfer(_wallet, amount); // Emit event emit BountyWithdrawn(_wallet, amount); } /// @notice Open verification phase function _openVerificationPhase() internal { // Require that verification phase is not open require( verificationPhaseByPhaseNumber[verificationPhaseNumber.add(1)].state == VerificationPhaseLib.State.Unopened, "ResolutionEngine: verification phase is not in unopened state" ); // Bump verification phase number verificationPhaseNumber = verificationPhaseNumber.add(1); // Allocate from bounty fund using the set bounty allocator uint256 bountyAmount = bountyFund.allocateTokens(bountyAllocator); // Open the verification phase verificationPhaseByPhaseNumber[verificationPhaseNumber].open(bountyAmount); // Add criteria params _addVerificationCriteria(); // Emit event emit VerificationPhaseOpened(verificationPhaseNumber, bountyAmount); } /// @notice Augment the verification phase with verification criteria params function _addVerificationCriteria() internal; /// @notice Close verification phase function _closeVerificationPhase() internal { // Require that verification phase is open require(verificationPhaseByPhaseNumber[verificationPhaseNumber].state == VerificationPhaseLib.State.Opened, "ResolutionEngine: verification phase is not in opened state"); // Close the verification phase verificationPhaseByPhaseNumber[verificationPhaseNumber].close(); // If new verification status... if (verificationPhaseByPhaseNumber[verificationPhaseNumber].result != verificationStatus) { // Update verification status of this resolution engine verificationStatus = verificationPhaseByPhaseNumber[verificationPhaseNumber].result; // Award bounty to this verification phase verificationPhaseByPhaseNumber[verificationPhaseNumber].bountyAwarded = true; } // Emit event emit VerificationPhaseClosed(verificationPhaseNumber); } /// @notice Calculate payout of given wallet and verification phase number function _calculatePayout(address _wallet, uint256 _verificationPhaseNumber) internal view returns (uint256) { // Return 0 if no non-null verification status has been obtained if (VerificationPhaseLib.Status.Null == verificationPhaseByPhaseNumber[_verificationPhaseNumber].result) return 0; // Get the status obtained by the verification phase bool status = verificationPhaseByPhaseNumber[_verificationPhaseNumber].result == VerificationPhaseLib.Status.True; // Get the lot staked opposite of status uint256 lot = verificationPhaseByPhaseNumber[_verificationPhaseNumber].stakedAmountByStatus[!status]; // If bounty was awarded add bounty to the total lot if (verificationPhaseByPhaseNumber[_verificationPhaseNumber].bountyAwarded) lot = lot.add(verificationPhaseByPhaseNumber[_verificationPhaseNumber].bountyAmount); // Get the amount the wallet staked and total amount staked on the obtained status uint256 walletStatusAmount = verificationPhaseByPhaseNumber[_verificationPhaseNumber] .stakedAmountByWalletStatus[_wallet][status]; uint256 statusAmount = verificationPhaseByPhaseNumber[_verificationPhaseNumber] .stakedAmountByStatus[status]; // Return the lot scaled by the fractional contribution that wallet staked on the obtained status and // to this added the wallet's own staked amount return lot.mul(walletStatusAmount).div(statusAmount).add(walletStatusAmount); } /// @notice Stage payout of given wallet and verification phase number function _stagePayout(address _wallet, uint256 _verificationPhaseNumber) internal returns (uint256) { // Return if the verification phase has not been closed if (VerificationPhaseLib.State.Closed != verificationPhaseByPhaseNumber[_verificationPhaseNumber].state) return 0; // Return wallet payout has already been staged for this verification phase number if (payoutStagedByWalletPhase[_wallet][_verificationPhaseNumber]) return 0; // Register payout of wallet and verification phase number payoutStagedByWalletPhase[_wallet][_verificationPhaseNumber] = true; // Calculate payout uint256 payout = _calculatePayout(_wallet, _verificationPhaseNumber); // Stage the payout _stage(_wallet, payout); // Return payout amount return payout; } /// @notice Stage the given amount for the given wallet function _stage(address _wallet, uint256 _amount) internal { stagedAmountByWallet[_wallet] = stagedAmountByWallet[_wallet].add(_amount); } }
Stage the bounty to the given address _wallet The recipient address of the bounty transfer Require no previous bounty withdrawal Store the bounty amount locally Reset the bounty amount Transfer the amount Emit event
function withdrawBounty(address _wallet) public onlyOperator onlyDisabled(RESOLVE_ACTION) { require(0 < verificationPhaseByPhaseNumber[verificationPhaseNumber].bountyAmount, "ResolutionEngine: bounty is zero"); uint256 amount = verificationPhaseByPhaseNumber[verificationPhaseNumber].bountyAmount; verificationPhaseByPhaseNumber[verificationPhaseNumber].bountyAmount = 0; token.transfer(_wallet, amount); emit BountyWithdrawn(_wallet, amount); }
2,545,679
./partial_match/4/0x9627D3E802cAB664da62aD0AccD5BfBaed3C0a30/sources/Proxy.sol
Allows the proxy owner to upgrade the implementation _implementation address of the new implementation/
function upgradeTo(address _implementation) public onlyProxyOwner { _upgradeTo(_implementation); }
16,967,445
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (proxy/ERC1967/ERC1967Upgrade.sol) pragma solidity ^0.8.2; import "../beacon/IBeaconUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/StorageSlotUpgradeable.sol"; import "../utils/Initializable.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967UpgradeUpgradeable is Initializable { function __ERC1967Upgrade_init() internal initializer { __ERC1967Upgrade_init_unchained(); } function __ERC1967Upgrade_init_unchained() internal initializer { } // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallSecure( address newImplementation, bytes memory data, bool forceCall ) internal { address oldImplementation = _getImplementation(); // Initial upgrade and setup call _setImplementation(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } // Perform rollback test if not already in progress StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT); if (!rollbackTesting.value) { // Trigger rollback using upgradeTo from the new implementation rollbackTesting.value = true; _functionDelegateCall( newImplementation, abi.encodeWithSignature("upgradeTo(address)", oldImplementation) ); rollbackTesting.value = false; // Check rollback was effective require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades"); // Finally reset to the new implementation and log the upgrade _upgradeTo(newImplementation); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { _functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data); } } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) { require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed"); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (proxy/beacon/IBeacon.sol) pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeaconUpgradeable { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (proxy/utils/UUPSUpgradeable.sol) pragma solidity ^0.8.0; import "../ERC1967/ERC1967UpgradeUpgradeable.sol"; import "./Initializable.sol"; /** * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy. * * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing * `UUPSUpgradeable` with a custom implementation of upgrades. * * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable { function __UUPSUpgradeable_init() internal initializer { __ERC1967Upgrade_init_unchained(); __UUPSUpgradeable_init_unchained(); } function __UUPSUpgradeable_init_unchained() internal initializer { } /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment address private immutable __self = address(this); /** * @dev Check that the execution is being performed through a delegatecall call and that the execution context is * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to * fail. */ modifier onlyProxy() { require(address(this) != __self, "Function must be called through delegatecall"); require(_getImplementation() == __self, "Function must be called through active proxy"); _; } /** * @dev Upgrade the implementation of the proxy to `newImplementation`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeTo(address newImplementation) external virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, new bytes(0), false); } /** * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call * encoded in `data`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, data, true); } /** * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by * {upgradeTo} and {upgradeToAndCall}. * * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}. * * ```solidity * function _authorizeUpgrade(address) internal override onlyOwner {} * ``` */ function _authorizeUpgrade(address newImplementation) internal virtual; uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20Upgradeable.sol"; import "./extensions/IERC20MetadataUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../proxy/utils/Initializable.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.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable { 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}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _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 value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 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: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, 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}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), 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}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - 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) { _approve(_msgSender(), spender, _allowances[_msgSender()][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) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * 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: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, 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; _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; } _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 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 {} uint256[45] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @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); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/extensions/draft-ERC20Permit.sol) pragma solidity ^0.8.0; import "./draft-IERC20PermitUpgradeable.sol"; import "../ERC20Upgradeable.sol"; import "../../../utils/cryptography/draft-EIP712Upgradeable.sol"; import "../../../utils/cryptography/ECDSAUpgradeable.sol"; import "../../../utils/CountersUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. * * _Available since v3.4._ */ abstract contract ERC20PermitUpgradeable is Initializable, ERC20Upgradeable, IERC20PermitUpgradeable, EIP712Upgradeable { using CountersUpgradeable for CountersUpgradeable.Counter; mapping(address => CountersUpgradeable.Counter) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private _PERMIT_TYPEHASH; /** * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. * * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ function __ERC20Permit_init(string memory name) internal initializer { __Context_init_unchained(); __EIP712_init_unchained(name, "1"); __ERC20Permit_init_unchained(name); } function __ERC20Permit_init_unchained(string memory name) internal initializer { _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");} /** * @dev See {IERC20Permit-permit}. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline)); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSAUpgradeable.recover(hash, v, r, s); require(signer == owner, "ERC20Permit: invalid signature"); _approve(owner, spender, value); } /** * @dev See {IERC20Permit-nonces}. */ function nonces(address owner) public view virtual override returns (uint256) { return _nonces[owner].current(); } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } /** * @dev "Consume a nonce": return the current value and increment. * * _Available since v4.1._ */ function _useNonce(address owner) internal virtual returns (uint256 current) { CountersUpgradeable.Counter storage nonce = _nonces[owner]; current = nonce.current(); nonce.increment(); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/extensions/draft-IERC20Permit.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20PermitUpgradeable { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; import "../../../utils/AddressUpgradeable.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using AddressUpgradeable for address; function safeTransfer( IERC20Upgradeable token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20Upgradeable token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20Upgradeable token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) 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. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @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 ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library CountersUpgradeable { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/StorageSlot.sol) pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlotUpgradeable { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../StringsUpgradeable.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSAUpgradeable { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", StringsUpgradeable.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/cryptography/draft-EIP712.sol) pragma solidity ^0.8.0; import "./ECDSAUpgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712Upgradeable is Initializable { /* solhint-disable var-name-mixedcase */ bytes32 private _HASHED_NAME; bytes32 private _HASHED_VERSION; bytes32 private constant _TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ function __EIP712_init(string memory name, string memory version) internal initializer { __EIP712_init_unchained(name, version); } function __EIP712_init_unchained(string memory name, string memory version) internal initializer { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash()); } function _buildDomainSeparator( bytes32 typeHash, bytes32 nameHash, bytes32 versionHash ) private view returns (bytes32) { return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return ECDSAUpgradeable.toTypedDataHash(_domainSeparatorV4(), structHash); } /** * @dev The hash of the name parameter for the EIP712 domain. * * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs * are a concern. */ function _EIP712NameHash() internal virtual view returns (bytes32) { return _HASHED_NAME; } /** * @dev The hash of the version parameter for the EIP712 domain. * * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs * are a concern. */ function _EIP712VersionHash() internal virtual view returns (bytes32) { return _HASHED_VERSION; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } //SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.4; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; /** * @title Controller component * @dev For easy access to any core components */ abstract contract Controller is Initializable, UUPSUpgradeable, AccessControlUpgradeable { bytes32 public constant ROLE_ADMIN = keccak256("ROLE_ADMIN"); mapping(address => address) private _admins; // slither-disable-next-line uninitialized-state bool private _paused; // slither-disable-next-line uninitialized-state address public pauseGuardian; /** * @dev Emitted when the pause is triggered by a pauser (`account`). */ event Paused(address account); /** * @dev Emitted when the pause is lifted by a pauser (`account`). */ event Unpaused(address account); /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Controller: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Controller: not paused"); _; } modifier onlyAdmin() { require(hasRole(ROLE_ADMIN, msg.sender), "Controller: not admin"); _; } modifier onlyGuardian() { require(pauseGuardian == msg.sender, "Controller: caller does not have the guardian role"); _; } //When using minimal deploy, do not call initialize directly during deploy, because msg.sender is the proxyFactory address, and you need to call it manually function __Controller_init(address admin_) public initializer { require(admin_ != address(0), "Controller: address zero"); _paused = false; _admins[admin_] = admin_; __UUPSUpgradeable_init(); _setupRole(ROLE_ADMIN, admin_); pauseGuardian = admin_; } function _authorizeUpgrade(address) internal view override onlyAdmin {} /** * @dev Check if the address provided is the admin * @param account Account address */ function isAdmin(address account) public view returns (bool) { return hasRole(ROLE_ADMIN, account); } /** * @dev Add a new admin account * @param account Account address */ function addAdmin(address account) public onlyAdmin { require(account != address(0), "Controller: address zero"); require(_admins[account] == address(0), "Controller: admin already existed"); _admins[account] = account; _setupRole(ROLE_ADMIN, account); } /** * @dev Set pauseGuardian account * @param account Account address */ function setGuardian(address account) public onlyAdmin { pauseGuardian = account; } /** * @dev Renouce the admin from the sender's address */ function renounceAdmin() public { renounceRole(ROLE_ADMIN, msg.sender); delete _admins[msg.sender]; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Called by a pauser to pause, triggers stopped state. */ function pause() public onlyGuardian whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev Called by a pauser to unpause, returns to normal state. */ function unpause() public onlyGuardian whenPaused { _paused = false; emit Unpaused(msg.sender); } uint256[50] private ______gap; } //SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.4; /** * @title AssetManager Interface * @dev Manage the token balances staked by the users and deposited by admins, and invest tokens to the integrated underlying lending protocols. */ interface IAssetManager { /** * @dev Returns the balance of asset manager, plus the total amount of tokens deposited to all the underlying lending protocols. * @param tokenAddress ERC20 token address * @return Lending pool balance */ function getPoolBalance(address tokenAddress) external view returns (uint256); /** * @dev Returns the amount of the lending pool balance minus the amount of total staked. * @param tokenAddress ERC20 token address * @return Amount can be borrowed */ function getLoanableAmount(address tokenAddress) external view returns (uint256); /** * @dev Get the total amount of tokens deposited to all the integrated underlying protocols without side effects. * @param tokenAddress ERC20 token address * @return Total market balance */ function totalSupply(address tokenAddress) external returns (uint256); /** * @dev Get the total amount of tokens deposited to all the integrated underlying protocols, but without side effects. Safe to call anytime, but may not get the most updated number for the current block. Call totalSupply() for that purpose. * @param tokenAddress ERC20 token address * @return Total market balance */ function totalSupplyView(address tokenAddress) external view returns (uint256); /** * @dev Check if there is an underlying protocol available for the given ERC20 token. * @param tokenAddress ERC20 token address * @return Whether is supported */ function isMarketSupported(address tokenAddress) external view returns (bool); /** * @dev Deposit tokens to AssetManager, and those tokens will be passed along to adapters to deposit to integrated asset protocols if any is available. * @param token ERC20 token address * @param amount Deposit amount, in wei * @return Deposited amount */ function deposit(address token, uint256 amount) external returns (bool); /** * @dev Withdraw from AssetManager * @param token ERC20 token address * @param account User address * @param amount Withdraw amount, in wei * @return Withdraw amount */ function withdraw( address token, address account, uint256 amount ) external returns (bool); /** * @dev Add a new ERC20 token to support in AssetManager * @param tokenAddress ERC20 token address */ function addToken(address tokenAddress) external; /** * @dev Remove a ERC20 token to support in AssetManager * @param tokenAddress ERC20 token address */ function removeToken(address tokenAddress) external; /** * @dev Add a new adapter for the underlying lending protocol * @param adapterAddress adapter address */ function addAdapter(address adapterAddress) external; /** * @dev Remove a adapter for the underlying lending protocol * @param adapterAddress adapter address */ function removeAdapter(address adapterAddress) external; /** * @dev For a give token set allowance for all integrated money markets * @param tokenAddress ERC20 token address */ function approveAllMarketsMax(address tokenAddress) external; /** * @dev For a give moeny market set allowance for all underlying tokens * @param adapterAddress Address of adaptor for money market */ function approveAllTokensMax(address adapterAddress) external; /** * @dev Set withdraw sequence * @param newSeq priority sequence of money market indices to be used while withdrawing */ function changeWithdrawSequence(uint256[] calldata newSeq) external; /** * @dev Rebalance the tokens between integrated lending protocols * @param tokenAddress ERC20 token address * @param percentages Proportion */ function rebalance(address tokenAddress, uint256[] calldata percentages) external; /** * @dev Claim the tokens left on AssetManager balance, in case there are tokens get stuck here. * @param tokenAddress ERC20 token address * @param recipient Recipient address */ function claimTokens(address tokenAddress, address recipient) external; /** * @dev Claim the tokens stuck in the integrated adapters * @param index MoneyMarkets array index * @param tokenAddress ERC20 token address * @param recipient Recipient address */ function claimTokensFromAdapter( uint256 index, address tokenAddress, address recipient ) external; /** * @dev Get the number of supported underlying protocols. * @return MoneyMarkets length */ function moneyMarketsCount() external view returns (uint256); /** * @dev Get the count of supported tokens * @return Number of supported tokens */ function supportedTokensCount() external view returns (uint256); /** * @dev Get the supported lending protocol * @param tokenAddress ERC20 token address * @param marketId MoneyMarkets array index * @return tokenSupply */ function getMoneyMarket(address tokenAddress, uint256 marketId) external view returns (uint256, uint256); /** * @dev debt write off * @param tokenAddress ERC20 token address * @param amount WriteOff amount */ function debtWriteOff(address tokenAddress, uint256 amount) external; } //SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.4; interface IDai { function permit( address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s ) external; } //SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.4; /** * @title InterestRateModel Interface * @dev Calculate the borrowers' interest rate. */ interface IInterestRateModel { /** * @dev Check to see if it is a valid interest rate model * @return Return true for a valid interest rate model */ function isInterestRateModel() external pure returns (bool); /** * @dev Calculates the current borrow interest rate per block * @return The borrow rate per block (as a percentage, and scaled by 1e18) */ function getBorrowRate() external view returns (uint256); /** * @dev Calculates the current suppier interest rate per block * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate(uint256 reserveFactorMantissa) external view returns (uint256); /** * @dev Set the borrow interest rate per block */ function setInterestRate(uint256 interestRatePerBlock_) external; } //SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.4; /** * @title UToken Interface * @dev Union members can borrow and repay thru this component. */ interface IUToken { /** * @dev Returns the remaining amount that can be borrowed from the market. * @return Remaining total amount */ function getRemainingDebtCeiling() external view returns (uint256); /** * @dev Get the borrowed principle * @param account Member address * @return Borrowed amount */ function getBorrowed(address account) external view returns (uint256); /** * @dev Get the last repay block * @param account Member address * @return Block number */ function getLastRepay(address account) external view returns (uint256); /** * @dev Get member interest index * @param account Member address * @return Interest index */ function getInterestIndex(address account) external view returns (uint256); /** * @dev Check if the member's loan is overdue * @param account Member address * @return Check result */ function checkIsOverdue(address account) external view returns (bool); /** * @dev Get the borrowing interest rate per block * @return Borrow rate */ function borrowRatePerBlock() external view returns (uint256); /** * @dev Get the origination fee * @param amount Amount to be calculated * @return Handling fee */ function calculatingFee(uint256 amount) external view returns (uint256); /** * @dev Calculating member's borrowed interest * @param account Member address * @return Interest amount */ function calculatingInterest(address account) external view returns (uint256); /** * @dev Get a member's current owed balance, including the principle and interest but without updating the user's states. * @param account Member address * @return Borrowed amount */ function borrowBalanceView(address account) external view returns (uint256); /** * @dev Change loan origination fee value * Accept claims only from the admin * @param originationFee_ Fees deducted for each loan transaction */ function setOriginationFee(uint256 originationFee_) external; /** * @dev Update the market debt ceiling to a fixed amount, for example, 1 billion DAI etc. * Accept claims only from the admin * @param debtCeiling_ The debt limit for the whole system */ function setDebtCeiling(uint256 debtCeiling_) external; /** * @dev Update the max loan size * Accept claims only from the admin * @param maxBorrow_ Max loan amount per user */ function setMaxBorrow(uint256 maxBorrow_) external; /** * @dev Update the minimum loan size * Accept claims only from the admin * @param minBorrow_ Minimum loan amount per user */ function setMinBorrow(uint256 minBorrow_) external; /** * @dev Change loan overdue duration, based on the number of blocks * Accept claims only from the admin * @param overdueBlocks_ Maximum late repayment block. The number of arrivals is a default */ function setOverdueBlocks(uint256 overdueBlocks_) external; /** * @dev Change to a different interest rate model * Accept claims only from the admin * @param newInterestRateModel New interest rate model address */ function setInterestRateModel(address newInterestRateModel) external; function setReserveFactor(uint256 reserveFactorMantissa_) external; function supplyRatePerBlock() external returns (uint256); function accrueInterest() external returns (bool); function balanceOfUnderlying(address owner) external returns (uint256); function mint(uint256 mintAmount) external; function redeem(uint256 redeemTokens) external; function redeemUnderlying(uint256 redeemAmount) external; function addReserves(uint256 addAmount) external; function removeReserves(address receiver, uint256 reduceAmount) external; /** * @dev Borrowing from the market * Accept claims only from the member * Borrow amount must in the range of creditLimit, minLoan, debtCeiling and not overdue * @param amount Borrow amount */ function borrow(uint256 amount) external; /** * @dev Repay the loan * Accept claims only from the member * Updated member lastPaymentEpoch only when the repayment amount is greater than interest * @param amount Repay amount */ function repayBorrow(uint256 amount) external; /** * @dev Repay the loan * Accept claims only from the member * Updated member lastPaymentEpoch only when the repayment amount is greater than interest * @param borrower Borrower address * @param amount Repay amount */ function repayBorrowBehalf(address borrower, uint256 amount) external; /** * @dev Update borrower overdue info * @param account Borrower address */ function updateOverdueInfo(address account) external; /** * @dev debt write off * @param borrower Borrower address * @param amount WriteOff amount */ function debtWriteOff(address borrower, uint256 amount) external; } //SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.4; /** * @title UserManager Interface * @dev Manages the Union members credit lines, and their vouchees and borrowers info. */ interface IUserManager { /** * @dev Check if the account is a valid member * @param account Member address * @return Address whether is member */ function checkIsMember(address account) external view returns (bool); /** * @dev Get member borrowerAddresses * @param account Member address * @return Address array */ function getBorrowerAddresses(address account) external view returns (address[] memory); /** * @dev Get member stakerAddresses * @param account Member address * @return Address array */ function getStakerAddresses(address account) external view returns (address[] memory); /** * @dev Get member backer asset * @param account Member address * @param borrower Borrower address * @return Trust amount, vouch amount, and locked stake amount */ function getBorrowerAsset(address account, address borrower) external view returns ( uint256, uint256, uint256 ); /** * @dev Get member stakers asset * @param account Member address * @param staker Staker address * @return Vouch amount and lockedStake */ function getStakerAsset(address account, address staker) external view returns ( uint256, uint256, uint256 ); /** * @dev Get the member's available credit line * @param account Member address * @return Limit */ function getCreditLimit(address account) external view returns (int256); function totalStaked() external view returns (uint256); function totalFrozen() external view returns (uint256); function getFrozenCoinAge(address staker, uint256 pastBlocks) external view returns (uint256); /** * @dev Add a new member * Accept claims only from the admin * @param account Member address */ function addMember(address account) external; /** * @dev Update the trust amount for exisitng members. * @param borrower Borrower address * @param trustAmount Trust amount */ function updateTrust(address borrower, uint256 trustAmount) external; /** * @dev Apply for membership, and burn UnionToken as application fees * @param newMember New member address */ function registerMember(address newMember) external; /** * @dev Stop vouch for other member. * @param staker Staker address * @param account Account address */ function cancelVouch(address staker, address account) external; /** * @dev Change the credit limit model * Accept claims only from the admin * @param newCreditLimitModel New credit limit model address */ function setCreditLimitModel(address newCreditLimitModel) external; /** * @dev Get the user's locked stake from all his backed loans * @param staker Staker address * @return LockedStake */ function getTotalLockedStake(address staker) external view returns (uint256); /** * @dev Get staker's defaulted / frozen staked token amount * @param staker Staker address * @return Frozen token amount */ function getTotalFrozenAmount(address staker) external view returns (uint256); /** * @dev Update userManager locked info * @param borrower Borrower address * @param amount Borrow or repay amount(Including previously accrued interest) * @param isBorrow True is borrow, false is repay */ function updateLockedData( address borrower, uint256 amount, bool isBorrow ) external; /** * @dev Get the user's deposited stake amount * @param account Member address * @return Deposited stake amount */ function getStakerBalance(address account) external view returns (uint256); /** * @dev Stake * @param amount Amount */ function stake(uint256 amount) external; /** * @dev Unstake * @param amount Amount */ function unstake(uint256 amount) external; /** * @dev Update total frozen * @param account borrower address * @param isOverdue account is overdue */ function updateTotalFrozen(address account, bool isOverdue) external; function batchUpdateTotalFrozen(address[] calldata account, bool[] calldata isOverdue) external; /** * @dev Repay user's loan overdue, called only from the lending market * @param account User address * @param lastRepay Last repay block number */ function repayLoanOverdue( address account, address token, uint256 lastRepay ) external; } //SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.4; import "../interfaces/IDai.sol"; import "./UToken.sol"; contract UDai is UToken { function repayBorrowWithPermit( address borrower, uint256 amount, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public whenNotPaused { IDai erc20Token = IDai(underlying); erc20Token.permit(msg.sender, address(this), nonce, expiry, true, v, r, s); _repayBorrowFresh(msg.sender, borrower, amount); } } //SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.4; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/draft-ERC20PermitUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "../Controller.sol"; import "../interfaces/IUserManager.sol"; import "../interfaces/IAssetManager.sol"; import "../interfaces/IUToken.sol"; import "../interfaces/IInterestRateModel.sol"; /** * @title UToken Contract * @dev Union accountBorrows can borrow and repay thru this component. */ contract UToken is IUToken, Controller, ERC20PermitUpgradeable, ReentrancyGuardUpgradeable { using SafeERC20Upgradeable for IERC20Upgradeable; bool public constant IS_UTOKEN = true; uint256 public constant WAD = 1e18; uint256 internal constant BORROW_RATE_MAX_MANTISSA = 0.005e16; //Maximum borrow rate that can ever be applied (.005% / block) uint256 internal constant RESERVE_FACTORY_MAX_MANTISSA = 1e18; //Maximum fraction of interest that can be set aside for reserves address public underlying; IInterestRateModel public interestRateModel; uint256 internal initialExchangeRateMantissa; //Initial exchange rate used when minting the first UTokens (used when totalSupply = 0) uint256 public reserveFactorMantissa; //Fraction of interest currently set aside for reserves uint256 public accrualBlockNumber; //Block number that interest was last accrued at uint256 public borrowIndex; //Accumulator of the total earned interest rate since the opening of the market uint256 public totalBorrows; //Total amount of outstanding borrows of the underlying in this market uint256 public totalReserves; //Total amount of reserves of the underlying held in this marke uint256 public totalRedeemable; //Calculates the exchange rate from the underlying to the uToken uint256 public overdueBlocks; //overdue duration, based on the number of blocks uint256 public originationFee; uint256 public debtCeiling; //The debt limit for the whole system uint256 public maxBorrow; uint256 public minBorrow; address public assetManager; address public userManager; struct BorrowSnapshot { uint256 principal; uint256 interest; uint256 interestIndex; uint256 lastRepay; //Calculate if it is overdue } /** * @notice Mapping of account addresses to outstanding borrow balances */ mapping(address => BorrowSnapshot) internal accountBorrows; error AccrueInterestFailed(); error AddressZero(); error AmountExceedGlobalMax(); error AmountExceedMaxBorrow(); error AmountLessMinBorrow(); error AmountZero(); error BorrowExceedCreditLimit(); error BorrowRateExceedLimit(); error WithdrawFailed(); error CallerNotAssetManager(); error CallerNotMember(); error CallerNotUserManager(); error ContractNotInterestModel(); error InitExchangeRateNotZero(); error InsufficientFundsLeft(); error MemberIsOverdue(); error ReserveFactoryExceedLimit(); error DepositToAssetManagerFailed(); /** * @dev Change of the interest rate model * @param oldInterestRateModel Old interest rate model address * @param newInterestRateModel New interest rate model address */ event LogNewMarketInterestRateModel(address oldInterestRateModel, address newInterestRateModel); event LogMint(address minter, uint256 underlyingAmount, uint256 uTokenAmount); event LogRedeem(address redeemer, uint256 redeemTokensIn, uint256 redeemAmountIn, uint256 redeemAmount); event LogReservesAdded(address reserver, uint256 actualAddAmount, uint256 totalReservesNew); event LogReservesReduced(address receiver, uint256 reduceAmount, uint256 totalReservesNew); /** * @dev Event borrow * @param account Member address * @param amount Borrow amount * @param fee Origination fee */ event LogBorrow(address indexed account, uint256 amount, uint256 fee); /** * @dev Event repay * @param account Member address * @param amount Repay amount */ event LogRepay(address indexed account, uint256 amount); /** * @dev modifier limit member */ modifier onlyMember(address account) { if (!IUserManager(userManager).checkIsMember(account)) revert CallerNotMember(); _; } modifier onlyAssetManager() { if (msg.sender != assetManager) revert CallerNotAssetManager(); _; } modifier onlyUserManager() { if (msg.sender != userManager) revert CallerNotUserManager(); _; } function __UToken_init( string memory name_, string memory symbol_, address underlying_, uint256 initialExchangeRateMantissa_, uint256 reserveFactorMantissa_, uint256 originationFee_, uint256 debtCeiling_, uint256 maxBorrow_, uint256 minBorrow_, uint256 overdueBlocks_, address admin_ ) public initializer { if (initialExchangeRateMantissa_ == 0) revert InitExchangeRateNotZero(); if (address(underlying_) == address(0)) revert AddressZero(); if (reserveFactorMantissa_ > RESERVE_FACTORY_MAX_MANTISSA) revert ReserveFactoryExceedLimit(); Controller.__Controller_init(admin_); ERC20Upgradeable.__ERC20_init(name_, symbol_); ERC20PermitUpgradeable.__ERC20Permit_init(name_); ReentrancyGuardUpgradeable.__ReentrancyGuard_init(); underlying = underlying_; originationFee = originationFee_; debtCeiling = debtCeiling_; maxBorrow = maxBorrow_; minBorrow = minBorrow_; overdueBlocks = overdueBlocks_; initialExchangeRateMantissa = initialExchangeRateMantissa_; reserveFactorMantissa = reserveFactorMantissa_; accrualBlockNumber = getBlockNumber(); borrowIndex = WAD; } function setAssetManager(address assetManager_) external onlyAdmin { if (assetManager_ == address(0)) revert AddressZero(); assetManager = assetManager_; } function setUserManager(address userManager_) external onlyAdmin { if (userManager_ == address(0)) revert AddressZero(); userManager = userManager_; } /** * @dev Change loan origination fee value * Accept claims only from the admin * @param originationFee_ Fees deducted for each loan transaction */ function setOriginationFee(uint256 originationFee_) external override onlyAdmin { originationFee = originationFee_; } /** * @dev Update the market debt ceiling to a fixed amount, for example, 1 billion DAI etc. * Accept claims only from the admin * @param debtCeiling_ The debt limit for the whole system */ function setDebtCeiling(uint256 debtCeiling_) external override onlyAdmin { debtCeiling = debtCeiling_; } /** * @dev Update the minimum loan size * Accept claims only from the admin * @param minBorrow_ Minimum loan amount per user */ function setMinBorrow(uint256 minBorrow_) external override onlyAdmin { minBorrow = minBorrow_; } /** * @dev Update the max loan size * Accept claims only from the admin * @param maxBorrow_ Max loan amount per user */ function setMaxBorrow(uint256 maxBorrow_) external override onlyAdmin { maxBorrow = maxBorrow_; } /** * @dev Change loan overdue duration, based on the number of blocks * Accept claims only from the admin * @param overdueBlocks_ Maximum late repayment block. The number of arrivals is a default */ function setOverdueBlocks(uint256 overdueBlocks_) external override onlyAdmin { overdueBlocks = overdueBlocks_; } /** * @dev Change to a different interest rate model * Accept claims only from the admin * @param newInterestRateModel_ New interest rate model address */ function setInterestRateModel(address newInterestRateModel_) external override onlyAdmin { if (newInterestRateModel_ == address(0)) revert AddressZero(); address oldInterestRateModel = address(interestRateModel); address newInterestRateModel = newInterestRateModel_; if (!IInterestRateModel(newInterestRateModel).isInterestRateModel()) revert ContractNotInterestModel(); interestRateModel = IInterestRateModel(newInterestRateModel); emit LogNewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel); } function setReserveFactor(uint256 reserveFactorMantissa_) external override onlyAdmin { if (reserveFactorMantissa_ > RESERVE_FACTORY_MAX_MANTISSA) revert ReserveFactoryExceedLimit(); reserveFactorMantissa = reserveFactorMantissa_; } /** * @dev Returns the remaining amount that can be borrowed from the market. * @return Remaining total amount */ function getRemainingDebtCeiling() public view override returns (uint256) { return debtCeiling >= totalBorrows ? debtCeiling - totalBorrows : 0; } /** * @dev Get the last repay block * @param account Member address * @return lastRepay */ function getLastRepay(address account) public view override returns (uint256) { return accountBorrows[account].lastRepay; } /** * @dev Get member interest index * @param account Member address * @return interestIndex */ function getInterestIndex(address account) public view override returns (uint256) { return accountBorrows[account].interestIndex; } /** * @dev Check if the member's loan is overdue * @param account Member address * @return isOverdue */ function checkIsOverdue(address account) public view override returns (bool isOverdue) { if (getBorrowed(account) != 0) { uint256 lastRepay = getLastRepay(account); uint256 diff = getBlockNumber() - lastRepay; isOverdue = (overdueBlocks < diff); } } /** * @dev Get the origination fee * @param amount Amount to be calculated * @return Handling fee */ function calculatingFee(uint256 amount) public view override returns (uint256) { return (originationFee * amount) / WAD; } /** * @dev Get the borrowed principle * @param account Member address * @return borrowed */ function getBorrowed(address account) public view override returns (uint256) { return accountBorrows[account].principal; } /** * @dev Get a member's current owed balance, including the principle and interest but without updating the user's states. * @param account Member address * @return Borrowed amount */ function borrowBalanceView(address account) public view override returns (uint256) { return getBorrowed(account) + calculatingInterest(account); } /** * @dev Get a member's total owed, including the principle and the interest calculated based on the interest index. * @param account Member address * @return Borrowed amount */ function borrowBalanceStoredInternal(address account) internal view returns (uint256) { BorrowSnapshot memory loan = accountBorrows[account]; /* If borrowBalance = 0 then borrowIndex is likely also 0. * Rather than failing the calculation with a division by 0, we immediately return 0 in this case. */ if (loan.principal == 0) { return 0; } uint256 principalTimesIndex = (loan.principal + loan.interest) * borrowIndex; return principalTimesIndex / loan.interestIndex; } /** * @dev Get the borrowing interest rate per block * @return Borrow rate */ function borrowRatePerBlock() public view override returns (uint256) { uint256 borrowRateMantissa = interestRateModel.getBorrowRate(); if (borrowRateMantissa > BORROW_RATE_MAX_MANTISSA) revert BorrowRateExceedLimit(); return borrowRateMantissa; } /** * @notice Returns the current per-block supply interest rate for this UToken * @return The supply interest rate per block, scaled by 1e18 */ function supplyRatePerBlock() public view override returns (uint256) { return interestRateModel.getSupplyRate(reserveFactorMantissa); } /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() public nonReentrant returns (uint256) { if (!accrueInterest()) revert AccrueInterestFailed(); return exchangeRateStored(); } /** * @notice Calculates the exchange rate from the underlying to the UToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() public view returns (uint256) { uint256 totalSupply_ = totalSupply(); return totalSupply_ == 0 ? initialExchangeRateMantissa : (totalRedeemable * WAD) / totalSupply_; } /** * @dev Calculating member's borrowed interest * @param account Member address * @return Interest amount */ function calculatingInterest(address account) public view override returns (uint256) { BorrowSnapshot memory loan = accountBorrows[account]; if (loan.principal == 0) { return 0; } uint256 borrowRate = borrowRatePerBlock(); uint256 currentBlockNumber = getBlockNumber(); uint256 blockDelta = currentBlockNumber - accrualBlockNumber; uint256 simpleInterestFactor = borrowRate * blockDelta; uint256 borrowIndexNew = (simpleInterestFactor * borrowIndex) / WAD + borrowIndex; uint256 principalTimesIndex = (loan.principal + loan.interest) * borrowIndexNew; uint256 balance = principalTimesIndex / loan.interestIndex; return balance - getBorrowed(account); } /** * @dev Borrowing from the market * Accept claims only from the member * Borrow amount must in the range of creditLimit, minBorrow, maxBorrow, debtCeiling and not overdue * @param amount Borrow amount */ function borrow(uint256 amount) external override onlyMember(msg.sender) whenNotPaused nonReentrant { IAssetManager assetManagerContract = IAssetManager(assetManager); if (amount < minBorrow) revert AmountLessMinBorrow(); if (amount > getRemainingDebtCeiling()) revert AmountExceedGlobalMax(); uint256 fee = calculatingFee(amount); if (borrowBalanceView(msg.sender) + amount + fee > maxBorrow) revert AmountExceedMaxBorrow(); if (checkIsOverdue(msg.sender)) revert MemberIsOverdue(); if (amount > assetManagerContract.getLoanableAmount(underlying)) revert InsufficientFundsLeft(); if (IUserManager(userManager).getCreditLimit(msg.sender) < int256(amount + fee)) revert BorrowExceedCreditLimit(); if (!accrueInterest()) revert AccrueInterestFailed(); uint256 borrowedAmount = borrowBalanceStoredInternal(msg.sender); //Set lastRepay init data if (getLastRepay(msg.sender) == 0) { accountBorrows[msg.sender].lastRepay = getBlockNumber(); } uint256 accountBorrowsNew = borrowedAmount + amount + fee; uint256 totalBorrowsNew = totalBorrows + amount + fee; uint256 oldPrincipal = getBorrowed(msg.sender); accountBorrows[msg.sender].principal += amount + fee; uint256 newPrincipal = getBorrowed(msg.sender); IUserManager(userManager).updateLockedData(msg.sender, newPrincipal - oldPrincipal, true); accountBorrows[msg.sender].interest = accountBorrowsNew - newPrincipal; accountBorrows[msg.sender].interestIndex = borrowIndex; totalBorrows = totalBorrowsNew; // The origination fees contribute to the reserve totalReserves += fee; if (!assetManagerContract.withdraw(underlying, msg.sender, amount)) revert WithdrawFailed(); emit LogBorrow(msg.sender, amount, fee); } function repayBorrow(uint256 repayAmount) external override whenNotPaused nonReentrant { _repayBorrowFresh(msg.sender, msg.sender, repayAmount); } function repayBorrowBehalf(address borrower, uint256 repayAmount) external override whenNotPaused nonReentrant { _repayBorrowFresh(msg.sender, borrower, repayAmount); } /** * @dev Repay the loan * Accept claims only from the member * Updated member lastPaymentEpoch only when the repayment amount is greater than interest * @param payer Payer address * @param borrower Borrower address * @param amount Repay amount */ function _repayBorrowFresh( address payer, address borrower, uint256 amount ) internal { IERC20Upgradeable assetToken = IERC20Upgradeable(underlying); //In order to prevent the state from being changed, put the value at the top bool isOverdue = checkIsOverdue(borrower); uint256 oldPrincipal = getBorrowed(borrower); if (!accrueInterest()) revert AccrueInterestFailed(); uint256 interest = calculatingInterest(borrower); uint256 borrowedAmount = borrowBalanceStoredInternal(borrower); uint256 repayAmount = amount > borrowedAmount ? borrowedAmount : amount; if (repayAmount == 0) revert AmountZero(); uint256 toReserveAmount; uint256 toRedeemableAmount; if (repayAmount >= interest) { toReserveAmount = (interest * reserveFactorMantissa) / WAD; toRedeemableAmount = interest - toReserveAmount; if (isOverdue) { IUserManager(userManager).updateTotalFrozen(borrower, false); IUserManager(userManager).repayLoanOverdue(borrower, underlying, getLastRepay(borrower)); } accountBorrows[borrower].principal = borrowedAmount - repayAmount; accountBorrows[borrower].interest = 0; if (getBorrowed(borrower) == 0) { //LastRepay is cleared when the arrears are paid off, and reinitialized the next time the loan is borrowed accountBorrows[borrower].lastRepay = 0; } else { accountBorrows[borrower].lastRepay = getBlockNumber(); } } else { toReserveAmount = (repayAmount * reserveFactorMantissa) / WAD; toRedeemableAmount = repayAmount - toReserveAmount; accountBorrows[borrower].interest = interest - repayAmount; } totalReserves += toReserveAmount; totalRedeemable += toRedeemableAmount; uint256 newPrincipal = getBorrowed(borrower); accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows -= repayAmount; IUserManager(userManager).updateLockedData(borrower, oldPrincipal - newPrincipal, false); assetToken.safeTransferFrom(payer, address(this), repayAmount); _depositToAssetManager(repayAmount); emit LogRepay(borrower, repayAmount); } /** * @dev Accrue interest * @return Accrue interest finished */ function accrueInterest() public override returns (bool) { uint256 borrowRate = borrowRatePerBlock(); uint256 currentBlockNumber = getBlockNumber(); uint256 blockDelta = currentBlockNumber - accrualBlockNumber; uint256 simpleInterestFactor = borrowRate * blockDelta; uint256 interestAccumulated = (simpleInterestFactor * totalBorrows) / WAD; uint256 totalBorrowsNew = interestAccumulated + totalBorrows; uint256 borrowIndexNew = (simpleInterestFactor * borrowIndex) / WAD + borrowIndex; accrualBlockNumber = currentBlockNumber; borrowIndex = borrowIndexNew; totalBorrows = totalBorrowsNew; return true; } /** * @notice Get the underlying balance of the `owner` * @dev This also accrues interest in a transaction * @param owner The address of the account to query * @return The amount of underlying owned by `owner` */ function balanceOfUnderlying(address owner) external override returns (uint256) { return exchangeRateCurrent() * balanceOf(owner); } function mint(uint256 mintAmount) external override whenNotPaused nonReentrant { if (!accrueInterest()) revert AccrueInterestFailed(); uint256 exchangeRate = exchangeRateStored(); IERC20Upgradeable assetToken = IERC20Upgradeable(underlying); uint256 balanceBefore = assetToken.balanceOf(address(this)); assetToken.safeTransferFrom(msg.sender, address(this), mintAmount); uint256 balanceAfter = assetToken.balanceOf(address(this)); uint256 actualMintAmount = balanceAfter - balanceBefore; totalRedeemable += actualMintAmount; uint256 mintTokens = (actualMintAmount * WAD) / exchangeRate; _mint(msg.sender, mintTokens); _depositToAssetManager(actualMintAmount); emit LogMint(msg.sender, actualMintAmount, mintTokens); } /** * @notice Sender redeems uTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of uTokens to redeem into underlying */ function redeem(uint256 redeemTokens) external override whenNotPaused nonReentrant { if (!accrueInterest()) revert AccrueInterestFailed(); _redeemFresh(payable(msg.sender), redeemTokens, 0); } /** * @notice Sender redeems uTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to receive from redeeming uTokens */ function redeemUnderlying(uint256 redeemAmount) external override whenNotPaused nonReentrant { if (!accrueInterest()) revert AccrueInterestFailed(); _redeemFresh(payable(msg.sender), 0, redeemAmount); } /** * @notice User redeems uTokens in exchange for the underlying asset * @dev Assumes interest has already been accrued up to the current block * @param redeemer The address of the account which is redeeming the tokens * @param redeemTokensIn The number of uTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @param redeemAmountIn The number of underlying tokens to receive from redeeming uTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero) */ function _redeemFresh( address payable redeemer, uint256 redeemTokensIn, uint256 redeemAmountIn ) private { if (redeemTokensIn != 0 && redeemAmountIn != 0) revert AmountZero(); IAssetManager assetManagerContract = IAssetManager(assetManager); uint256 exchangeRate = exchangeRateStored(); uint256 redeemTokens; uint256 redeemAmount; if (redeemTokensIn > 0) { /* * We calculate the exchange rate and the amount of underlying to be redeemed: * redeemTokens = redeemTokensIn * redeemAmount = redeemTokensIn x exchangeRateCurrent */ redeemTokens = redeemTokensIn; redeemAmount = (redeemTokensIn * exchangeRate) / WAD; } else { /* * We get the current exchange rate and calculate the amount to be redeemed: * redeemTokens = redeemAmountIn / exchangeRate * redeemAmount = redeemAmountIn */ redeemTokens = (redeemAmountIn * WAD) / exchangeRate; redeemAmount = redeemAmountIn; } totalRedeemable -= redeemAmount; _burn(redeemer, redeemTokens); if (!assetManagerContract.withdraw(underlying, redeemer, redeemAmount)) revert WithdrawFailed(); emit LogRedeem(redeemer, redeemTokensIn, redeemAmountIn, redeemAmount); } function addReserves(uint256 addAmount) external override whenNotPaused nonReentrant { if (!accrueInterest()) revert AccrueInterestFailed(); IERC20Upgradeable assetToken = IERC20Upgradeable(underlying); uint256 balanceBefore = assetToken.balanceOf(address(this)); assetToken.safeTransferFrom(msg.sender, address(this), addAmount); uint256 balanceAfter = assetToken.balanceOf(address(this)); uint256 actualAddAmount = balanceAfter - balanceBefore; totalReserves += actualAddAmount; _depositToAssetManager(balanceAfter); emit LogReservesAdded(msg.sender, actualAddAmount, totalReserves); } function removeReserves(address receiver, uint256 reduceAmount) external override whenNotPaused nonReentrant onlyAdmin { if (!accrueInterest()) revert AccrueInterestFailed(); totalReserves -= reduceAmount; if (!IAssetManager(assetManager).withdraw(underlying, receiver, reduceAmount)) revert WithdrawFailed(); emit LogReservesReduced(receiver, reduceAmount, totalReserves); } function debtWriteOff(address borrower, uint256 amount) external override whenNotPaused onlyUserManager { uint256 oldPrincipal = getBorrowed(borrower); uint256 repayAmount; amount > oldPrincipal ? repayAmount = oldPrincipal : repayAmount = amount; accountBorrows[borrower].principal = oldPrincipal - repayAmount; totalBorrows -= repayAmount; } /** * @dev Function to simply retrieve block number * This exists mainly for inheriting test contracts to stub this result. */ function getBlockNumber() internal view returns (uint256) { return block.number; } /** * @dev Update borrower overdue info * @param account Borrower address */ function updateOverdueInfo(address account) external override whenNotPaused { if (account == address(0)) revert AddressZero(); if (checkIsOverdue(account)) { IUserManager(userManager).updateTotalFrozen(account, true); } } /** * @dev Batch update borrower overdue info * @param accounts Borrowers address */ function batchUpdateOverdueInfos(address[] calldata accounts) external whenNotPaused { uint256 accountsLength = accounts.length; address[] memory overdueAccounts = new address[](accountsLength); bool[] memory isOverdues = new bool[](accountsLength); for (uint256 i = 0; i < accountsLength; i++) { if (checkIsOverdue(accounts[i])) { overdueAccounts[i] = accounts[i]; isOverdues[i] = true; } } IUserManager(userManager).batchUpdateTotalFrozen(overdueAccounts, isOverdues); } function _depositToAssetManager(uint256 amount) internal { IERC20Upgradeable assetToken = IERC20Upgradeable(underlying); assetToken.safeApprove(assetManager, 0); // Some ERC20 tokens (e.g. Tether) changed the behavior of approve to look like safeApprove assetToken.safeApprove(assetManager, amount); if (!IAssetManager(assetManager).deposit(underlying, amount)) revert DepositToAssetManagerFailed(); } }
Get a member's total owed, including the principle and the interest calculated based on the interest index. account Member address return Borrowed amount/ If borrowBalance = 0 then borrowIndex is likely also 0. Rather than failing the calculation with a division by 0, we immediately return 0 in this case./
function borrowBalanceStoredInternal(address account) internal view returns (uint256) { BorrowSnapshot memory loan = accountBorrows[account]; if (loan.principal == 0) { return 0; } uint256 principalTimesIndex = (loan.principal + loan.interest) * borrowIndex; return principalTimesIndex / loan.interestIndex; }
603,369
//SPDX-License-Identifier: MIT pragma solidity 0.8.4; import "./StateUtils.sol"; import "./interfaces/IGetterUtils.sol"; /// @title Contract that implements getters abstract contract GetterUtils is StateUtils, IGetterUtils { string private constant CHECKPOINT_NOT_FOUND = "API3DAO.GetterUtils: Value cannot be found after provided checkpoint"; /// @notice Called to get the voting power of a user at a checkpoint, /// closest to the provided block /// @dev This method is used to implement the MiniMe interface for the /// Api3Voting app /// @param userAddress User address /// @param _block Block number for which the query is being made for /// @return Voting power of the user at the block function balanceOfAt( address userAddress, uint256 _block ) public view override returns(uint256) { // Users that delegate have no voting power if (getUserDelegateAt(userAddress, _block) != address(0)) { return 0; } uint256 userSharesThen = userSharesAt(userAddress, _block); uint256 delegatedToUserThen = getReceivedDelegationAt(userAddress, _block); return userSharesThen + delegatedToUserThen; } /// @notice Called to get the current voting power of a user /// @dev This method is used to implement the MiniMe interface for the /// Api3Voting app /// @param userAddress User address /// @return Current voting power of the user function balanceOf(address userAddress) public view override returns(uint256) { return balanceOfAt(userAddress, block.number); } /// @notice Called to get the total voting power one block ago /// @dev This method is used to implement the MiniMe interface for the /// Api3Voting app /// @return Total voting power one block ago function totalSupplyOneBlockAgo() public view override returns(uint256) { return totalSharesOneBlockAgo(); } /// @notice Called to get the current total voting power /// @dev This method is used to implement the MiniMe interface for the /// Aragon Voting app /// @return Current total voting power function totalSupply() public view override returns(uint256) { return totalShares(); } /// @notice Called to get the pool shares of a user at a checkpoint, /// closest to the provided block /// @dev Starts from the most recent value in `user.shares` and searches /// backwards one element at a time /// @param userAddress User address /// @param _block Block number for which the query is being made for /// @return Pool shares of the user at the block function userSharesAt( address userAddress, uint256 _block ) public view override returns(uint256) { return getValueAt(users[userAddress].shares, _block, 0); } /// @notice Called to get the current pool shares of a user /// @param userAddress User address /// @return Current pool shares of the user function userShares(address userAddress) public view override returns(uint256) { return userSharesAt(userAddress, block.number); } /// @notice Called to get the pool shares of a user at checkpoint, /// closest to specific block using binary search /// @dev This method is not used by the current iteration of the DAO/pool /// and is implemented for future external contracts to use to get the user /// shares at an arbitrary block. /// @param userAddress User address /// @param _block Block number for which the query is being made for /// @return Pool shares of the user at the block function userSharesAtWithBinarySearch( address userAddress, uint256 _block ) external view override returns(uint256) { return getValueAtWithBinarySearch( users[userAddress].shares, _block, 0 ); } /// @notice Called to get the current staked tokens of the user /// @param userAddress User address /// @return Current staked tokens of the user function userStake(address userAddress) public view override returns(uint256) { return userShares(userAddress) * totalStake / totalShares(); } /// @notice Called to get the voting power delegated to a user at a /// checkpoint, closest to specific block /// @dev `user.delegatedTo` cannot have grown more than 1000 checkpoints /// in the last epoch due to `proposalVotingPowerThreshold` having a lower /// limit of 0.1%. /// @param userAddress User address /// @param _block Block number for which the query is being made for /// @return Voting power delegated to the user at the block function getReceivedDelegationAt( address userAddress, uint256 _block ) public view override returns(uint256) { // Binary searching a 1000-long array takes up to 10 storage reads // (2^10 = 1024). If we approximate the average number of reads // required to be 5 and consider that it is much more likely for the // value we are looking for will be at the end of the array (because // not many proposals will be made per epoch), it is preferable to do // a linear search at the end of the array if possible. Here, the // length of "the end of the array" is specified to be 5 (which was the // expected number of iterations we will need for a binary search). uint256 maximumLengthToLinearSearch = 5; // If the value we are looking for is not among the last // `maximumLengthToLinearSearch`, we will fall back to binary search. // Here, we will only search through the last 1000 checkpoints because // `user.delegatedTo` cannot have grown more than 1000 checkpoints in // the last epoch due to `proposalVotingPowerThreshold` having a lower // limit of 0.1%. uint256 maximumLengthToBinarySearch = 1000; Checkpoint[] storage delegatedTo = users[userAddress].delegatedTo; if (delegatedTo.length < maximumLengthToLinearSearch) { return getValueAt(delegatedTo, _block, 0); } uint256 minimumCheckpointIndexLinearSearch = delegatedTo.length - maximumLengthToLinearSearch; if (delegatedTo[minimumCheckpointIndexLinearSearch].fromBlock < _block) { return getValueAt(delegatedTo, _block, minimumCheckpointIndexLinearSearch); } // It is very unlikely for the method to not have returned until here // because it means there have been `maximumLengthToLinearSearch` // proposals made in the current epoch. uint256 minimumCheckpointIndexBinarySearch = delegatedTo.length > maximumLengthToBinarySearch ? delegatedTo.length - maximumLengthToBinarySearch : 0; // The below will revert if the value being searched is not within the // last `minimumCheckpointIndexBinarySearch` (which is not possible if // `_block` is the snapshot block of an open vote of Api3Voting, // because its vote duration is `EPOCH_LENGTH`). return getValueAtWithBinarySearch(delegatedTo, _block, minimumCheckpointIndexBinarySearch); } /// @notice Called to get the current voting power delegated to a user /// @param userAddress User address /// @return Current voting power delegated to the user function userReceivedDelegation(address userAddress) public view override returns(uint256) { return getReceivedDelegationAt(userAddress, block.number); } /// @notice Called to get the delegate of the user at a checkpoint, /// closest to specified block /// @dev Starts from the most recent value in `user.delegates` and /// searches backwards one element at a time. If `_block` is within /// `EPOCH_LENGTH`, this call is guaranteed to find the value among /// the last 2 elements because a user cannot update delegate more /// frequently than once an `EPOCH_LENGTH`. /// @param userAddress User address /// @param _block Block number /// @return Delegate of the user at the specific block function getUserDelegateAt( address userAddress, uint256 _block ) public view override returns(address) { AddressCheckpoint[] storage delegates = users[userAddress].delegates; for (uint256 i = delegates.length; i > 0; i--) { if (delegates[i - 1].fromBlock <= _block) { return delegates[i - 1]._address; } } return address(0); } /// @notice Called to get the current delegate of the user /// @param userAddress User address /// @return Current delegate of the user function getUserDelegate(address userAddress) public view override returns(address) { return getUserDelegateAt(userAddress, block.number); } /// @notice Called to get the current locked tokens of the user /// @param userAddress User address /// @return locked Current locked tokens of the user function getUserLocked(address userAddress) public view override returns(uint256 locked) { Checkpoint[] storage _userShares = users[userAddress].shares; uint256 currentEpoch = block.timestamp / EPOCH_LENGTH; uint256 oldestLockedEpoch = currentEpoch - REWARD_VESTING_PERIOD > genesisEpoch ? currentEpoch - REWARD_VESTING_PERIOD + 1 : genesisEpoch + 1; if (_userShares.length == 0) { return 0; } uint256 indUserShares = _userShares.length - 1; for ( uint256 indEpoch = currentEpoch; indEpoch >= oldestLockedEpoch; indEpoch-- ) { Reward storage lockedReward = epochIndexToReward[indEpoch]; if (lockedReward.atBlock != 0) { for (; indUserShares >= 0; indUserShares--) { Checkpoint storage userShare = _userShares[indUserShares]; if (userShare.fromBlock <= lockedReward.atBlock) { locked += lockedReward.amount * userShare.value / lockedReward.totalSharesThen; break; } } } } } /// @notice Called to get the details of a user /// @param userAddress User address /// @return unstaked Amount of unstaked API3 tokens /// @return vesting Amount of API3 tokens locked by vesting /// @return unstakeShares Shares scheduled to unstake /// @return unstakeAmount Amount scheduled to unstake /// @return unstakeScheduledFor Time unstaking is scheduled for /// @return mostRecentProposalTimestamp Time when the user made their most /// recent proposal /// @return mostRecentVoteTimestamp Time when the user cast their most /// recent vote /// @return mostRecentDelegationTimestamp Time when the user made their /// most recent delegation /// @return mostRecentUndelegationTimestamp Time when the user made their /// most recent undelegation function getUser(address userAddress) external view override returns( uint256 unstaked, uint256 vesting, uint256 unstakeShares, uint256 unstakeAmount, uint256 unstakeScheduledFor, uint256 mostRecentProposalTimestamp, uint256 mostRecentVoteTimestamp, uint256 mostRecentDelegationTimestamp, uint256 mostRecentUndelegationTimestamp ) { User storage user = users[userAddress]; unstaked = user.unstaked; vesting = user.vesting; unstakeShares = user.unstakeShares; unstakeAmount = user.unstakeAmount; unstakeScheduledFor = user.unstakeScheduledFor; mostRecentProposalTimestamp = user.mostRecentProposalTimestamp; mostRecentVoteTimestamp = user.mostRecentVoteTimestamp; mostRecentDelegationTimestamp = user.mostRecentDelegationTimestamp; mostRecentUndelegationTimestamp = user.mostRecentUndelegationTimestamp; } /// @notice Called to get the value of a checkpoint array closest to /// the specific block /// @param checkpoints Checkpoints array /// @param _block Block number for which the query is being made /// @return Value of the checkpoint array at the block function getValueAt( Checkpoint[] storage checkpoints, uint256 _block, uint256 minimumCheckpointIndex ) internal view returns(uint256) { uint256 i = checkpoints.length; for (; i > minimumCheckpointIndex; i--) { if (checkpoints[i - 1].fromBlock <= _block) { return checkpoints[i - 1].value; } } // Revert if the value being searched for comes before // `minimumCheckpointIndex` require(i == 0, CHECKPOINT_NOT_FOUND); return 0; } /// @notice Called to get the value of the checkpoint array closest to the /// specific block /// @dev Adapted from /// https://github.com/aragon/minime/blob/1d5251fc88eee5024ff318d95bc9f4c5de130430/contracts/MiniMeToken.sol#L431 /// Allows the caller to specify the portion of the array that will be /// searched. This allows us to avoid having to search arrays that can grow /// unboundedly. /// @param checkpoints Checkpoint array /// @param _block Block number for which the query is being made /// @param minimumCheckpointIndex Index of the earliest checkpoint that may /// be keeping the value we are looking for /// @return Value of the checkpoint array at `_block` function getValueAtWithBinarySearch( Checkpoint[] storage checkpoints, uint256 _block, uint256 minimumCheckpointIndex ) internal view returns(uint256) { if (checkpoints.length == 0) return 0; assert(checkpoints.length > minimumCheckpointIndex); // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length - 1].fromBlock) { return checkpoints[checkpoints.length - 1].value; } // Revert if the value being searched for comes before // `minimumCheckpointIndex` if (_block < checkpoints[minimumCheckpointIndex].fromBlock) { if (minimumCheckpointIndex == 0) { return 0; } else { revert(CHECKPOINT_NOT_FOUND); } } // Binary search of the value in the array uint min = minimumCheckpointIndex; uint max = checkpoints.length - 1; while (max > min) { uint mid = (max + min + 1) / 2; if (checkpoints[mid].fromBlock <= _block) { min = mid; } else { max = mid - 1; } } return checkpoints[min].value; } }
Called to get the voting power delegated to a user at a checkpoint, closest to specific block `user.delegatedTo` cannot have grown more than 1000 checkpoints in the last epoch due to `proposalVotingPowerThreshold` having a lower limit of 0.1%. userAddress User address _block Block number for which the query is being made for return Voting power delegated to the user at the block Binary searching a 1000-long array takes up to 10 storage reads (2^10 = 1024). If we approximate the average number of reads required to be 5 and consider that it is much more likely for the value we are looking for will be at the end of the array (because not many proposals will be made per epoch), it is preferable to do a linear search at the end of the array if possible. Here, the length of "the end of the array" is specified to be 5 (which was the expected number of iterations we will need for a binary search). If the value we are looking for is not among the last `maximumLengthToLinearSearch`, we will fall back to binary search. Here, we will only search through the last 1000 checkpoints because `user.delegatedTo` cannot have grown more than 1000 checkpoints in the last epoch due to `proposalVotingPowerThreshold` having a lower limit of 0.1%.
function getReceivedDelegationAt( address userAddress, uint256 _block ) public view override returns(uint256) { uint256 maximumLengthToLinearSearch = 5; uint256 maximumLengthToBinarySearch = 1000; Checkpoint[] storage delegatedTo = users[userAddress].delegatedTo; if (delegatedTo.length < maximumLengthToLinearSearch) { return getValueAt(delegatedTo, _block, 0); } uint256 minimumCheckpointIndexLinearSearch = delegatedTo.length - maximumLengthToLinearSearch; if (delegatedTo[minimumCheckpointIndexLinearSearch].fromBlock < _block) { return getValueAt(delegatedTo, _block, minimumCheckpointIndexLinearSearch); } ? delegatedTo.length - maximumLengthToBinarySearch : 0; }
13,041,892
./full_match/43114/0x4e13f37db9c8BDe41B34Ef1528C71E332AcBAf56/sources/Exchange.sol
view functions open functions
{ function calcConversionFromInput(address _from, address _to, uint256 _inputAmount) external view returns (uint256 _outputAmount); function calcConversionFromOutput(address _from, address _to, uint256 _outputAmount) external view returns (uint256 _inputAmount); function calcJoinPoolFromInput(address _pool, address _token, uint256 _inputAmount) external view returns (uint256 _outputShares); function convertFundsFromInput(address _from, address _to, uint256 _inputAmount, uint256 _minOutputAmount) external returns (uint256 _outputAmount); function convertFundsFromOutput(address _from, address _to, uint256 _outputAmount, uint256 _maxInputAmount) external returns (uint256 _inputAmount); function joinPoolFromInput(address _pool, address _token, uint256 _inputAmount, uint256 _minOutputShares) external returns (uint256 _outputShares); function oracleAveragePriceFactorFromInput(address _from, address _to, uint256 _inputAmount) external returns (uint256 _factor); function oraclePoolAveragePriceFactorFromInput(address _pool, address _token, uint256 _inputAmount) external returns (uint256 _factor); interface IExchange }
4,549,825
//Address: 0xCF28Bf20B662F746A4B487FA81de5A40ac0af49C //Contract name: Token //Balance: 0 Ether //Verification Date: 1/10/2018 //Transacion Count: 54 // CODE STARTS HERE /* Gold Reserve [XGR] 1.0.0 Rajci 'iFA' Andor @ [email protected] */ pragma solidity 0.4.18; contract SafeMath { /* Internals */ function safeAdd(uint256 a, uint256 b) internal pure returns(uint256) { if ( b > 0 ) { assert( a + b > a ); } return a + b; } function safeSub(uint256 a, uint256 b) internal pure returns(uint256) { if ( b > 0 ) { assert( a - b < a ); } return a - b; } function safeMul(uint256 a, uint256 b) internal pure returns(uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint256 a, uint256 b) internal pure returns(uint256) { return a / b; } } contract Owned { /* Variables */ address public owner = msg.sender; /* Externals */ function replaceOwner(address newOwner) external returns(bool success) { require( isOwner() ); owner = newOwner; return true; } /* Internals */ function isOwner() internal view returns(bool) { return owner == msg.sender; } /* Modifiers */ modifier onlyForOwner { require( isOwner() ); _; } } contract Token is SafeMath, Owned { /** * @title Gold Reserve [XGR] token */ /* Variables */ string public name = "GoldReserve"; string public symbol = "XGR"; uint8 public decimals = 8; uint256 public transactionFeeRate = 20; // 0.02 % uint256 public transactionFeeRateM = 1e3; // 1000 uint256 public transactionFeeMin = 2000000; // 0.2 XGR uint256 public transactionFeeMax = 200000000; // 2.0 XGR address public databaseAddress; address public depositsAddress; address public forkAddress; address public libAddress; /* Constructor */ function Token(address newDatabaseAddress, address newDepositAddress, address newFrokAddress, address newLibAddress) public { databaseAddress = newDatabaseAddress; depositsAddress = newDepositAddress; forkAddress = newFrokAddress; libAddress = newLibAddress; } /* Fallback */ function () { revert(); } /* Externals */ function changeDataBaseAddress(address newDatabaseAddress) external onlyForOwner { databaseAddress = newDatabaseAddress; } function changeDepositsAddress(address newDepositsAddress) external onlyForOwner { depositsAddress = newDepositsAddress; } function changeForkAddress(address newForkAddress) external onlyForOwner { forkAddress = newForkAddress; } function changeLibAddress(address newLibAddress) external onlyForOwner { libAddress = newLibAddress; } function changeFees(uint256 rate, uint256 rateMultiplier, uint256 min, uint256 max) external onlyForOwner { transactionFeeRate = rate; transactionFeeRateM = rateMultiplier; transactionFeeMin = min; transactionFeeMax = max; } /** * @notice `msg.sender` approves `spender` to spend `amount` tokens on its behalf. * @param spender The address of the account able to transfer the tokens * @param amount The amount of tokens to be approved for transfer * @param nonce The transaction count of the authorised address * @return True if the approval was successful */ function approve(address spender, uint256 amount, uint256 nonce) external returns (bool success) { address _trg = libAddress; assembly { let m := mload(0x20) calldatacopy(m, 0, calldatasize) let success := delegatecall(gas, _trg, m, calldatasize, m, 0x20) switch success case 0 { invalid } default { return(m, 0x20) } } } /** * @notice `msg.sender` approves `spender` to spend `amount` tokens on its behalf and notify the spender from your approve with your `extraData` data. * @param spender The address of the account able to transfer the tokens * @param amount The amount of tokens to be approved for transfer * @param nonce The transaction count of the authorised address * @param extraData Data to give forward to the receiver * @return True if the approval was successful */ function approveAndCall(address spender, uint256 amount, uint256 nonce, bytes extraData) external returns (bool success) { address _trg = libAddress; assembly { let m := mload(0x20) calldatacopy(m, 0, calldatasize) let success := delegatecall(gas, _trg, m, calldatasize, m, 0x20) switch success case 0 { invalid } default { return(m, 0x20) } } } /** * @notice Send `amount` tokens to `to` from `msg.sender` * @param to The address of the recipient * @param amount The amount of tokens to be transferred * @return Whether the transfer was successful or not */ function transfer(address to, uint256 amount) external returns (bool success) { address _trg = libAddress; assembly { let m := mload(0x20) calldatacopy(m, 0, calldatasize) let success := delegatecall(gas, _trg, m, calldatasize, m, 0x20) switch success case 0 { invalid } default { return(m, 0x20) } } } /** * @notice Send `amount` tokens to `to` from `from` on the condition it is approved by `from` * @param from The address holding the tokens being transferred * @param to The address of the recipient * @param amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom(address from, address to, uint256 amount) external returns (bool success) { address _trg = libAddress; assembly { let m := mload(0x20) calldatacopy(m, 0, calldatasize) let success := delegatecall(gas, _trg, m, calldatasize, m, 0x20) switch success case 0 { invalid } default { return(m, 0x20) } } } /** * @notice Send `amount` tokens to `to` from `msg.sender` and notify the receiver from your transaction with your `extraData` data * @param to The contract address of the recipient * @param amount The amount of tokens to be transferred * @param extraData Data to give forward to the receiver * @return Whether the transfer was successful or not */ function transfer(address to, uint256 amount, bytes extraData) external returns (bool success) { address _trg = libAddress; assembly { let m := mload(0x20) calldatacopy(m, 0, calldatasize) let success := delegatecall(gas, _trg, m, calldatasize, m, 0x20) switch success case 0 { invalid } default { return(m, 0x20) } } } function mint(address owner, uint256 value) external returns (bool success) { address _trg = libAddress; assembly { let m := mload(0x20) calldatacopy(m, 0, calldatasize) let success := delegatecall(gas, _trg, m, calldatasize, m, 0x20) switch success case 0 { invalid } default { return(m, 0x20) } } } /* Internals */ /* Constants */ function allowance(address owner, address spender) public constant returns (uint256 remaining, uint256 nonce) { address _trg = libAddress; assembly { let m := mload(0x20) calldatacopy(m, 0, calldatasize) let success := delegatecall(gas, _trg, m, calldatasize, m, 0x40) switch success case 0 { invalid } default { return(m, 0x40) } } } function getTransactionFee(uint256 value) public constant returns (bool success, uint256 fee) { address _trg = libAddress; assembly { let m := mload(0x20) calldatacopy(m, 0, calldatasize) let success := delegatecall(gas, _trg, m, calldatasize, m, 0x40) switch success case 0 { invalid } default { return(m, 0x40) } } } function balanceOf(address owner) public constant returns (uint256 value) { address _trg = libAddress; assembly { let m := mload(0x20) calldatacopy(m, 0, calldatasize) let success := delegatecall(gas, _trg, m, calldatasize, m, 0x20) switch success case 0 { invalid } default { return(m, 0x20) } } } function balancesOf(address owner) public constant returns (uint256 balance, uint256 lockedAmount) { address _trg = libAddress; assembly { let m := mload(0x20) calldatacopy(m, 0, calldatasize) let success := delegatecall(gas, _trg, m, calldatasize, m, 0x40) switch success case 0 { invalid } default { return(m, 0x40) } } } function totalSupply() public constant returns (uint256 value) { address _trg = libAddress; assembly { let m := mload(0x20) calldatacopy(m, 0, calldatasize) let success := delegatecall(gas, _trg, m, calldatasize, m, 0x20) switch success case 0 { invalid } default { return(m, 0x20) } } } /* Events */ event AllowanceUsed(address indexed spender, address indexed owner, uint256 indexed value); event Mint(address indexed addr, uint256 indexed value); event Burn(address indexed addr, uint256 indexed value); event Approval(address indexed _owner, address indexed _spender, uint _value); event Transfer(address indexed _from, address indexed _to, uint _value); event Transfer2(address indexed from, address indexed to, uint256 indexed value, bytes data); } contract TokenDB is SafeMath, Owned { /* Structures */ struct allowance_s { uint256 amount; uint256 nonce; } struct deposits_s { address addr; uint256 amount; uint256 start; uint256 end; uint256 interestOnEnd; uint256 interestBeforeEnd; uint256 interestFee; uint256 interestMultiplier; bool closeable; bool valid; } /* Variables */ mapping(address => mapping(address => allowance_s)) public allowance; mapping(address => uint256) public balanceOf; mapping(uint256 => deposits_s) private deposits; mapping(address => uint256) public lockedBalances; address public tokenAddress; address public depositsAddress; uint256 public depositsCounter; uint256 public totalSupply; /* Constructor */ /* Externals */ function changeTokenAddress(address newTokenAddress) external onlyForOwner { tokenAddress = newTokenAddress; } function changeDepositsAddress(address newDepositsAddress) external onlyForOwner { depositsAddress = newDepositsAddress; } function openDeposit(address addr, uint256 amount, uint256 end, uint256 interestOnEnd, uint256 interestBeforeEnd, uint256 interestFee, uint256 multiplier, bool closeable) external onlyForDeposits returns(bool success, uint256 DID) { depositsCounter += 1; DID = depositsCounter; lockedBalances[addr] = safeAdd(lockedBalances[addr], amount); deposits[DID] = deposits_s( addr, amount, block.number, end, interestOnEnd, interestBeforeEnd, interestFee, multiplier, closeable, true ); return (true, DID); } function closeDeposit(uint256 DID) external onlyForDeposits returns (bool success) { require( deposits[DID].valid ); delete deposits[DID].valid; lockedBalances[deposits[DID].addr] = safeSub(lockedBalances[deposits[DID].addr], deposits[DID].amount); return true; } function transfer(address from, address to, uint256 amount, uint256 fee) external onlyForToken returns(bool success) { balanceOf[from] = safeSub(balanceOf[from], safeAdd(amount, fee)); balanceOf[to] = safeAdd(balanceOf[to], amount); totalSupply = safeSub(totalSupply, fee); return true; } function increase(address owner, uint256 value) external onlyForToken returns(bool success) { balanceOf[owner] = safeAdd(balanceOf[owner], value); totalSupply = safeAdd(totalSupply, value); return true; } function decrease(address owner, uint256 value) external onlyForToken returns(bool success) { require( safeSub(balanceOf[owner], safeAdd(lockedBalances[owner], value)) >= 0 ); balanceOf[owner] = safeSub(balanceOf[owner], value); totalSupply = safeSub(totalSupply, value); return true; } function setAllowance(address owner, address spender, uint256 amount, uint256 nonce) external onlyForToken returns(bool success) { allowance[owner][spender].amount = amount; allowance[owner][spender].nonce = nonce; return true; } /* Constants */ function getAllowance(address owner, address spender) public constant returns(bool success, uint256 remaining, uint256 nonce) { return ( true, allowance[owner][spender].amount, allowance[owner][spender].nonce ); } function getDeposit(uint256 UID) public constant returns(address addr, uint256 amount, uint256 start, uint256 end, uint256 interestOnEnd, uint256 interestBeforeEnd, uint256 interestFee, uint256 interestMultiplier, bool closeable, bool valid) { addr = deposits[UID].addr; amount = deposits[UID].amount; start = deposits[UID].start; end = deposits[UID].end; interestOnEnd = deposits[UID].interestOnEnd; interestBeforeEnd = deposits[UID].interestBeforeEnd; interestFee = deposits[UID].interestFee; interestMultiplier = deposits[UID].interestMultiplier; closeable = deposits[UID].closeable; valid = deposits[UID].valid; } /* Modifiers */ modifier onlyForToken { require( msg.sender == tokenAddress ); _; } modifier onlyForDeposits { require( msg.sender == depositsAddress ); _; } } contract TokenLib is SafeMath, Owned { /** * @title Gold Reserve [XGR] token */ /* Variables */ string public name = "GoldReserve"; string public symbol = "XGR"; uint8 public decimals = 8; uint256 public transactionFeeRate = 20; // 0.02 % uint256 public transactionFeeRateM = 1e3; // 1000 uint256 public transactionFeeMin = 2000000; // 0.2 XGR uint256 public transactionFeeMax = 200000000; // 2.0 XGR address public databaseAddress; address public depositsAddress; address public forkAddress; address public libAddress; /* Constructor */ function TokenLib(address newDatabaseAddress, address newDepositAddress, address newFrokAddress, address newLibAddress) public { databaseAddress = newDatabaseAddress; depositsAddress = newDepositAddress; forkAddress = newFrokAddress; libAddress = newLibAddress; } /* Fallback */ function () public { revert(); } /* Externals */ function changeDataBaseAddress(address newDatabaseAddress) external onlyForOwner { databaseAddress = newDatabaseAddress; } function changeDepositsAddress(address newDepositsAddress) external onlyForOwner { depositsAddress = newDepositsAddress; } function changeForkAddress(address newForkAddress) external onlyForOwner { forkAddress = newForkAddress; } function changeLibAddress(address newLibAddress) external onlyForOwner { libAddress = newLibAddress; } function changeFees(uint256 rate, uint256 rateMultiplier, uint256 min, uint256 max) external onlyForOwner { transactionFeeRate = rate; transactionFeeRateM = rateMultiplier; transactionFeeMin = min; transactionFeeMax = max; } function approve(address spender, uint256 amount, uint256 nonce) external returns (bool success) { _approve(spender, amount, nonce); return true; } function approveAndCall(address spender, uint256 amount, uint256 nonce, bytes extraData) external returns (bool success) { _approve(spender, amount, nonce); require( checkContract(spender) ); require( SampleContract(spender).approvedToken(msg.sender, amount, extraData) ); return true; } function transfer(address to, uint256 amount) external returns (bool success) { bytes memory _data; _transfer(msg.sender, to, amount, true, _data); return true; } function transferFrom(address from, address to, uint256 amount) external returns (bool success) { if ( from != msg.sender ) { var (_success, _reamining, _nonce) = TokenDB(databaseAddress).getAllowance(from, msg.sender); require( _success ); _reamining = safeSub(_reamining, amount); _nonce = safeAdd(_nonce, 1); require( TokenDB(databaseAddress).setAllowance(from, msg.sender, _reamining, _nonce) ); AllowanceUsed(msg.sender, from, amount); } bytes memory _data; _transfer(from, to, amount, true, _data); return true; } function transfer(address to, uint256 amount, bytes extraData) external returns (bool success) { _transfer(msg.sender, to, amount, true, extraData); return true; } function mint(address owner, uint256 value) external returns (bool success) { require( msg.sender == forkAddress || msg.sender == depositsAddress ); _mint(owner, value); return true; } /* Internals */ function _transfer(address from, address to, uint256 amount, bool fee, bytes extraData) internal { bool _success; uint256 _fee; uint256 _payBack; uint256 _amount = amount; require( from != 0x00 && to != 0x00 ); if( fee ) { (_success, _fee) = getTransactionFee(amount); require( _success ); if ( TokenDB(databaseAddress).balanceOf(from) == amount ) { _amount = safeSub(amount, _fee); } } if ( fee ) { Burn(from, _fee); } Transfer(from, to, _amount); Transfer2(from, to, _amount, extraData); require( TokenDB(databaseAddress).transfer(from, to, _amount, _fee) ); if ( isContract(to) ) { require( checkContract(to) ); (_success, _payBack) = SampleContract(to).receiveToken(from, amount, extraData); require( _success ); require( amount > _payBack ); if ( _payBack > 0 ) { bytes memory _data; Transfer(to, from, _payBack); Transfer2(to, from, _payBack, _data); require( TokenDB(databaseAddress).transfer(to, from, _payBack, 0) ); } } } function _mint(address owner, uint256 value) internal { require( TokenDB(databaseAddress).increase(owner, value) ); Mint(owner, value); } function _approve(address spender, uint256 amount, uint256 nonce) internal { require( msg.sender != spender ); var (_success, _remaining, _nonce) = TokenDB(databaseAddress).getAllowance(msg.sender, spender); require( _success && ( _nonce == nonce ) ); require( TokenDB(databaseAddress).setAllowance(msg.sender, spender, amount, nonce) ); Approval(msg.sender, spender, amount); } function isContract(address addr) internal view returns (bool success) { uint256 _codeLength; assembly { _codeLength := extcodesize(addr) } return _codeLength > 0; } function checkContract(address addr) internal view returns (bool appropriate) { return SampleContract(addr).XGRAddress() == address(this); } /* Constants */ function allowance(address owner, address spender) public constant returns (uint256 remaining, uint256 nonce) { var (_success, _remaining, _nonce) = TokenDB(databaseAddress).getAllowance(owner, spender); require( _success ); return (_remaining, _nonce); } function getTransactionFee(uint256 value) public constant returns (bool success, uint256 fee) { fee = safeMul(value, transactionFeeRate) / transactionFeeRateM / 100; if ( fee > transactionFeeMax ) { fee = transactionFeeMax; } else if ( fee < transactionFeeMin ) { fee = transactionFeeMin; } return (true, fee); } function balanceOf(address owner) public constant returns (uint256 value) { return TokenDB(databaseAddress).balanceOf(owner); } function balancesOf(address owner) public constant returns (uint256 balance, uint256 lockedAmount) { return (TokenDB(databaseAddress).balanceOf(owner), TokenDB(databaseAddress).lockedBalances(owner)); } function totalSupply() public constant returns (uint256 value) { return TokenDB(databaseAddress).totalSupply(); } /* Events */ event AllowanceUsed(address indexed spender, address indexed owner, uint256 indexed value); event Mint(address indexed addr, uint256 indexed value); event Burn(address indexed addr, uint256 indexed value); event Approval(address indexed _owner, address indexed _spender, uint _value); event Transfer(address indexed _from, address indexed _to, uint _value); event Transfer2(address indexed from, address indexed to, uint256 indexed value, bytes data); } contract Deposits is Owned, SafeMath { /* Structures */ struct depositTypes_s { uint256 blockDelay; uint256 baseFunds; uint256 interestRateOnEnd; uint256 interestRateBeforeEnd; uint256 interestFee; bool closeable; bool valid; } struct deposits_s { address addr; uint256 amount; uint256 start; uint256 end; uint256 interestOnEnd; uint256 interestBeforeEnd; uint256 interestFee; uint256 interestMultiplier; bool closeable; bool valid; } /* Variables */ mapping(uint256 => depositTypes_s) public depositTypes; uint256 public depositTypesCounter; address public tokenAddress; address public databaseAddress; address public founderAddress; uint256 public interestMultiplier = 1e4; /* Externals */ function changeDataBaseAddress(address newDatabaseAddress) external onlyForOwner { databaseAddress = newDatabaseAddress; } function changeTokenAddress(address newTokenAddress) external onlyForOwner { tokenAddress = newTokenAddress; } function changeFounderAddresss(address newFounderAddress) external onlyForOwner { founderAddress = newFounderAddress; } function addDepositType(uint256 blockDelay, uint256 baseFunds, uint256 interestRateOnEnd, uint256 interestRateBeforeEnd, uint256 interestFee, bool closeable) external onlyForOwner { depositTypesCounter += 1; uint256 DTID = depositTypesCounter; depositTypes[DTID] = depositTypes_s( blockDelay, baseFunds, interestRateOnEnd, interestRateBeforeEnd, interestFee, closeable, true ); EventNewDepositType( DTID, blockDelay, baseFunds, interestRateOnEnd, interestRateBeforeEnd, interestFee, closeable ); } function rekoveDepositType(uint256 DTID) external onlyForOwner { depositTypes[DTID].valid = false; } function placeDeposit(uint256 amount, uint256 depositType) external checkSelf { require( depositTypes[depositType].valid ); require( depositTypes[depositType].baseFunds <= amount ); uint256 balance = TokenDB(databaseAddress).balanceOf(msg.sender); uint256 locked = TokenDB(databaseAddress).lockedBalances(msg.sender); require( safeSub(balance, locked) >= amount ); var (success, DID) = TokenDB(databaseAddress).openDeposit( msg.sender, amount, safeAdd(block.number, depositTypes[depositType].blockDelay), depositTypes[depositType].interestRateOnEnd, depositTypes[depositType].interestRateBeforeEnd, depositTypes[depositType].interestFee, interestMultiplier, depositTypes[depositType].closeable ); require( success ); EventNewDeposit(DID); } function closeDeposit(address beneficary, uint256 DID) external checkSelf { address _beneficary = beneficary; if ( _beneficary == 0x00 ) { _beneficary = msg.sender; } var (addr, amount, start, end, interestOnEnd, interestBeforeEnd, interestFee, interestM, closeable, valid) = TokenDB(databaseAddress).getDeposit(DID); _closeDeposit(_beneficary, DID, deposits_s(addr, amount, start, end, interestOnEnd, interestBeforeEnd, interestFee, interestM, closeable, valid)); } /* Internals */ function _closeDeposit(address beneficary, uint256 DID, deposits_s data) internal { require( data.valid && data.addr == msg.sender ); var (interest, interestFee) = _calculateInterest(data); if ( interest > 0 ) { require( Token(tokenAddress).mint(beneficary, interest) ); } if ( interestFee > 0 ) { require( Token(tokenAddress).mint(founderAddress, interestFee) ); } require( TokenDB(databaseAddress).closeDeposit(DID) ); EventDepositClosed(DID, interest, interestFee); } function _calculateInterest(deposits_s data) internal view returns (uint256 interest, uint256 interestFee) { if ( ! data.valid || data.amount <= 0 || data.end <= data.start || block.number <= data.start ) { return (0, 0); } uint256 rate; uint256 delay; if ( data.end <= block.number ) { rate = data.interestOnEnd; delay = safeSub(data.end, data.start); } else { require( data.closeable ); rate = data.interestBeforeEnd; delay = safeSub(block.number, data.start); } if ( rate == 0 ) { return (0, 0); } interest = safeDiv(safeMul(safeDiv(safeDiv(safeMul(data.amount, rate), 100), data.interestMultiplier), delay), safeSub(data.end, data.start)); if ( data.interestFee > 0 && interest > 0) { interestFee = safeDiv(safeDiv(safeMul(interest, data.interestFee), 100), data.interestMultiplier); } if ( interestFee > 0 ) { interest = safeSub(interest, interestFee); } } /* Constants */ function calculateInterest(uint256 DID) public view returns(uint256, uint256) { var (addr, amount, start, end, interestOnEnd, interestBeforeEnd, interestFee, interestM, closeable, valid) = TokenDB(databaseAddress).getDeposit(DID); return _calculateInterest(deposits_s(addr, amount, start, end, interestOnEnd, interestBeforeEnd, interestFee, interestM, closeable, valid)); } /* Modifiers */ modifier checkSelf { require( TokenDB(databaseAddress).tokenAddress() == tokenAddress ); require( TokenDB(databaseAddress).depositsAddress() == address(this) ); _; } /* Events */ event EventNewDepositType(uint256 indexed DTID, uint256 blockDelay, uint256 baseFunds, uint256 interestRateOnEnd, uint256 interestRateBeforeEnd, uint256 interestFee, bool closeable); event EventRevokeDepositType(uint256 indexed DTID); event EventNewDeposit(uint256 indexed DID); event EventDepositClosed(uint256 indexed DID, uint256 indexed interest, uint256 indexed interestFee); } contract Fork is Owned { /* Variables */ address public uploader; address public tokenAddress; /* Constructor */ function Fork(address _uploader) public { uploader = _uploader; } /* Externals */ function changeTokenAddress(address newTokenAddress) external onlyForOwner { tokenAddress = newTokenAddress; } function upload(address[] addr, uint256[] amount) external onlyForUploader { require( addr.length == amount.length ); for ( uint256 a=0 ; a<addr.length ; a++ ) { require( Token(tokenAddress).mint(addr[a], amount[a]) ); } } /* Modifiers */ modifier onlyForUploader { require( msg.sender == uploader ); _; } } contract SampleContract is Owned, SafeMath { /* Variables */ mapping(address => uint256) public deposits; // Database of users balance address public XGRAddress; // XGR Token address, please do not change this variable name! /* Constructor */ function SampleContract(address newXGRTokenAddress) public { /* For the first time you need set the XGR token address. The contract deployer would be also the owner. */ XGRAddress = newXGRTokenAddress; } /* Externals */ function receiveToken(address addr, uint256 amount, bytes data) external onlyFromXGRToken returns(bool, uint256) { /* @addr has send @amount to ourself. The second return parameter is the refund amount. If you don't need the whole amount, you can refund that for the address instantly. Please do not change this function name and parameter! */ incomingToken(addr, amount); return (true, 0); } function approvedToken(address addr, uint256 amount, bytes data) external onlyFromXGRToken returns(bool) { /* @addr has allowed @amount for withdraw from her/his balance. We withdraw that to ourself. Please do not change this function name and parameter! */ require( Token(XGRAddress).transferFrom(addr, address(this), amount) ); incomingToken(addr, amount); return true; } function changeTokenAddress(address newTokenAddress) external onlyForOwner { /* Maybe the XGR token contract becomes new address, you need maintenance this. */ XGRAddress = newTokenAddress; } function killThisContract() external onlyForOwner { var balance = Token(XGRAddress).balanceOf(address(this)); // get this contract XGR balance require( Token(XGRAddress).transfer(msg.sender, balance) ); // send all XGR token to the caller selfdestruct(msg.sender); // destruct the contract; } function withdraw(uint256 amount) external { /* Some users withdraw XGR token from this contract. The contract must pay the XGR token fee, we need to reduce that from the amount; */ var (success, fee) = Token(XGRAddress).getTransactionFee(amount); // Get the transfer fee from the contract require( success ); withdrawToken(msg.sender, amount); require( Token(XGRAddress).transfer(msg.sender, safeSub(amount, fee)) ); } /* Internals */ function incomingToken(address addr, uint256 amount) internal { deposits[addr] = safeAdd(deposits[addr], amount); } function withdrawToken(address addr, uint256 amount) internal { deposits[addr] = safeSub(deposits[addr], amount); } /* Modifiers */ modifier onlyFromXGRToken { require( msg.sender == XGRAddress ); _; } }
`msg.sender` approves `spender` to spend `amount` tokens on its behalf and notify the spender from your approve with your `extraData` data. spender The address of the account able to transfer the tokens amount The amount of tokens to be approved for transfer nonce The transaction count of the authorised address extraData Data to give forward to the receiver return True if the approval was successful/
function approveAndCall(address spender, uint256 amount, uint256 nonce, bytes extraData) external returns (bool success) { address _trg = libAddress; assembly { let m := mload(0x20) calldatacopy(m, 0, calldatasize) let success := delegatecall(gas, _trg, m, calldatasize, m, 0x20) switch success case 0 { invalid return(m, 0x20) } } }
7,246,378
./full_match/1/0x02c500255762EFFF926348f1eC2e248dc8EBA10f/sources/contracts/Pool.sol
Helper function to quote a loan principal Principal amount in currency tokens duration Duration in seconds collateralToken Collateral token address collateralTokenIds List of collateral token ids ticks Liquidity node ticks collateralFilterContext Collateral filter context return Repayment amount in currency tokens, liquidity nodes, liquidity node count/ Verify collateral is supported /
function _quote( uint256 principal, uint64 duration, address collateralToken, uint256[] memory collateralTokenIds, uint128[] calldata ticks, bytes calldata collateralFilterContext ) internal view returns (uint256, ILiquidity.NodeSource[] memory, uint16) { for (uint256 i; i < collateralTokenIds.length; i++) { if (!_collateralSupported(collateralToken, collateralTokenIds[i], i, collateralFilterContext)) revert UnsupportedCollateral(i); } for (; durationIndex < durations_.length; durationIndex++) { if (duration <= durations_[durationIndex]) break; } principal, ticks, collateralTokenIds.length, durationIndex ); (LiquidityManager.FIXED_POINT_SCALE + (_rate(principal, _rates, nodes, count) * duration))) / LiquidityManager.FIXED_POINT_SCALE; return (repayment, nodes, count); }
9,716,332
./full_match/10/0x02bD0b89F7b198014425Df1a4152A2E77576c38D/sources/src/FixedPriceAggregator.sol
Returns data for the latest round. return roundId 0 return answer The fixed price returned by this oracle, represented in appropriate decimals. return startedAt 0 return updatedAt Since price is fixed, we always return the current block timestamp. return answeredInRound 0
function latestRoundData() external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound) { return (uint80(0), price, uint256(0), block.timestamp, uint80(0)); }
3,778,133
./partial_match/1/0x373ae78a14577682591E088F2E78EF1417612c68/sources/contracts/HomoraBank.sol
Return the debt share of the given bank token for the given position id.
function getPositionDebtShareOf(uint positionId, address token) external view returns (uint) { return positions[positionId].debtShareOf[token]; }
4,169,089
./full_match/3/0x2a4c486f16BeF9e3bb5F9BFd39534c89b843B43f/sources/browser/BigStorage.sol
... Eingabe officerent
function setofficerent(uint256 _newofficerent) public{ officerent = _newofficerent; }
8,121,099
pragma solidity ^0.4.21; // File: zeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: zeppelin-solidity/contracts/ownership/Claimable.sol /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract Claimable is Ownable { address public pendingOwner; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() onlyPendingOwner public { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } // File: contracts/external/KYCWhitelist.sol /** * @title KYCWhitelist * @dev Crowdsale in which only whitelisted users can contribute. */ contract KYCWhitelist is Claimable { mapping(address => bool) public whitelist; /** * @dev Reverts if beneficiary is not whitelisted. Can be used when extending this contract. */ modifier isWhitelisted(address _beneficiary) { require(whitelist[_beneficiary]); _; } /** * @dev Does a "require" check if _beneficiary address is approved * @param _beneficiary Token beneficiary */ function validateWhitelisted(address _beneficiary) internal view { require(whitelist[_beneficiary]); } /** * @dev Adds single address to whitelist. * @param _beneficiary Address to be added to the whitelist */ function addToWhitelist(address _beneficiary) external onlyOwner { whitelist[_beneficiary] = true; } /** * @dev Adds list of addresses to whitelist. Not overloaded due to limitations with truffle testing. * @param _beneficiaries Addresses to be added to the whitelist */ function addManyToWhitelist(address[] _beneficiaries) external onlyOwner { for (uint256 i = 0; i < _beneficiaries.length; i++) { whitelist[_beneficiaries[i]] = true; } } /** * @dev Removes single address from whitelist. * @param _beneficiary Address to be removed to the whitelist */ function removeFromWhitelist(address _beneficiary) external onlyOwner { whitelist[_beneficiary] = false; } } // File: contracts/external/Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Claimable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } // File: zeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/PrivatePreSale.sol /** * @title PrivatePreSale * * Private Pre-sale contract for Energis tokens * * (c) Philip Louw / Zero Carbon Project 2018. The MIT Licence. */ contract PrivatePreSale is Claimable, KYCWhitelist, Pausable { using SafeMath for uint256; // Wallet Address for funds address public constant FUNDS_WALLET = 0xDc17D222Bc3f28ecE7FCef42EDe0037C739cf28f; // Token Wallet Address address public constant TOKEN_WALLET = 0x1EF91464240BB6E0FdE7a73E0a6f3843D3E07601; // Token adderss being sold address public constant TOKEN_ADDRESS = 0x2169Cce281717d204FA0EcF846a6171e96234D72; // Token being sold ERC20 public constant TOKEN = ERC20(TOKEN_ADDRESS); // Conversion Rate (Eth cost of 1 NRG) (Testing uses ETH price of $10 000) uint256 public constant TOKENS_PER_ETH = 6740; // Max NRG tokens to sell uint256 public constant MAX_TOKENS = 20000000 * (10**18); // Min investment in Tokens uint256 public constant MIN_TOKEN_INVEST = 300000 * (10**18); // Token sale start date uint256 public START_DATE = 1525176000; // ----------------------------------------- // State Variables // ----------------------------------------- // Amount of wei raised uint256 public weiRaised; // Amount of tokens issued uint256 public tokensIssued; // If the pre-sale has ended bool public closed; // ----------------------------------------- // Events // ----------------------------------------- /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); // ----------------------------------------- // Constructor // ----------------------------------------- function PrivatePreSale() public { require(TOKENS_PER_ETH > 0); require(FUNDS_WALLET != address(0)); require(TOKEN_WALLET != address(0)); require(TOKEN_ADDRESS != address(0)); require(MAX_TOKENS > 0); require(MIN_TOKEN_INVEST >= 0); } // ----------------------------------------- // Private PreSale external Interface // ----------------------------------------- /** * @dev Checks whether the cap has been reached. * @return Whether the cap was reached */ function capReached() public view returns (bool) { return tokensIssued >= MAX_TOKENS; } /** * @dev Closes the sale, can only be called once. Once closed can not be opened again. */ function closeSale() public onlyOwner { require(!closed); closed = true; } /** * @dev Returns the amount of tokens given for the amount in Wei * @param _weiAmount Value in wei */ function getTokenAmount(uint256 _weiAmount) public pure returns (uint256) { // Amount in wei (10**18 wei == 1 eth) and the token is 18 decimal places return _weiAmount.mul(TOKENS_PER_ETH); } /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } // ----------------------------------------- // Private PreSale internal // ----------------------------------------- /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) internal whenNotPaused { uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokenAmount = getTokenAmount(weiAmount); // Validation Checks preValidateChecks(_beneficiary, weiAmount, tokenAmount); // update state tokensIssued = tokensIssued.add(tokenAmount); weiRaised = weiRaised.add(weiAmount); // Send tokens from token wallet TOKEN.transferFrom(TOKEN_WALLET, _beneficiary, tokenAmount); // Forward the funds to wallet FUNDS_WALLET.transfer(msg.value); // Event trigger emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokenAmount); } /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase * @param _tokenAmount Amount of token to purchase */ function preValidateChecks(address _beneficiary, uint256 _weiAmount, uint256 _tokenAmount) internal view { require(_beneficiary != address(0)); require(_weiAmount != 0); require(now >= START_DATE); require(!closed); // KYC Check validateWhitelisted(_beneficiary); // Test Min Investment require(_tokenAmount >= MIN_TOKEN_INVEST); // Test hard cap require(tokensIssued.add(_tokenAmount) <= MAX_TOKENS); } }
low level token purchase DO NOT OVERRIDE _beneficiary Address performing the token purchase/ calculate token amount to be created Validation Checks update state Send tokens from token wallet Forward the funds to wallet Event trigger
function buyTokens(address _beneficiary) internal whenNotPaused { uint256 weiAmount = msg.value; uint256 tokenAmount = getTokenAmount(weiAmount); preValidateChecks(_beneficiary, weiAmount, tokenAmount); tokensIssued = tokensIssued.add(tokenAmount); weiRaised = weiRaised.add(weiAmount); TOKEN.transferFrom(TOKEN_WALLET, _beneficiary, tokenAmount); FUNDS_WALLET.transfer(msg.value); emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokenAmount); }
1,837,683
./full_match/5/0x1eF1F851689b6494f4eE6563c1979B5b018be51d/sources/data/source/raiden/TokenNetwork.sol
Multiple calls to updateNonClosingBalanceProof can be made and we need to store the last known balance proof data. This line prevents Monitoring Services from getting rewards again and again using the same reward proof.
function updateBalanceProofData( Channel storage channel, address participant, uint256 nonce, bytes32 balance_hash ) internal { Participant storage participant_state = channel.participants[participant]; require(nonce > participant_state.nonce); participant_state.nonce = nonce; participant_state.balance_hash = balance_hash; }
1,868,282
// SPDX-License-Identifier: MIT // pragma solidity >=0.4.21 <0.7.0; pragma solidity ^0.6.0; contract RockPaperScissors { address owner; uint dummy = 0; enum Move { none, rock, paper, scissors } Move constant defaultChoice = Move.none; uint256 timeStarted; address[] playerAddresses; mapping(address => Move) eachPlayersMove; mapping(address => uint) howMuchPaid; mapping(address => uint) winningsPerPlayer; mapping(address => uint) playerNumberByAddress; bool gameOver = false; //99 is pending constant uint public gameResult = 99; //2 eth to start uint amountToStart = 2000000000000000000; constructor() public { owner = msg.sender; } function enroll() external payable returns (uint){ // Game storage game = games[auctionIndex]; require(msg.value>=amountToStart, "You need to submit 2 Eth to start."); require(howMuchPaid[msg.sender]==0, "Already paid."); require(playerAddresses.length<2, "Already 2 players."); playerAddresses.push(msg.sender); howMuchPaid[msg.sender] = msg.value; if (playerAddresses.length==2){ timeStarted = now; } playerNumberByAddress[msg.sender] = playerAddresses.length-1; return playerAddresses.length-1; } function getPlay(uint _playerNum) public returns (Move) { return eachPlayersMove[playerAddresses[_playerNum]]; } function returnAddress() public returns (address){ return msg.sender; } function makeMove(string memory _myMove) external { require(msg.sender == playerAddresses[0] || msg.sender == playerAddresses[1],"you need to be one of the enrolled players" ); require(timeStarted>0,"game has not started"); require(eachPlayersMove[msg.sender] == Move.none,"you already played"); eachPlayersMove[msg.sender]=getMove(_myMove); } function getMove(string memory m) internal returns (Move) { if (keccak256(bytes(m)) == keccak256(bytes("rock")) || keccak256(bytes(m)) == keccak256(bytes("Rock"))) { return Move.rock; } else if (keccak256(bytes(m)) == keccak256(bytes("scissors")) || keccak256(bytes(m)) == keccak256(bytes("Scissors"))) { return Move.scissors; } else if (keccak256(bytes(m)) == keccak256(bytes("paper")) || keccak256(bytes(m)) == keccak256(bytes("Paper")) ) { return Move.paper; } else { return Move.none; } } function settleWinner() external returns (uint) { require(gameOver != true, "game alrady over"); Move playerOneMove = eachPlayersMove[playerAddresses[0]]; Move playerTwoMove = eachPlayersMove[playerAddresses[1]]; require(playerOneMove != Move.none,"Player 0 hasnt played"); require(playerTwoMove != Move.none,"Player 1 hasnt played"); // 0 for player0 won, 1 for player 1 won, 2 for tie, 3 for unresolved uint result = 3; if (playerOneMove == playerTwoMove){ revertMoney(); result = 2; } else if (playerOneMove == Move.scissors) { if (playerTwoMove == Move.rock){ // won payOut(playerAddresses[1]); result = 1; } else if (playerTwoMove == Move.paper){ //lost payOut(playerAddresses[0]); result = 0; } } else if (playerOneMove == Move.rock) { if (playerTwoMove == Move.paper){ payOut(playerAddresses[1]); result = 1; } else if (playerTwoMove == Move.scissors){ payOut(playerAddresses[0]); result = 0; } } else if (playerOneMove == Move.paper) { if (playerTwoMove == Move.scissors){ payOut(playerAddresses[1]); result = 1; } else if (playerTwoMove == Move.rock){ payOut(playerAddresses[0]); result = 0; } } else{ result = 3; } gameResult = result; return result; } function getGameResult() public returns (uint){ return gameResult; } function revertMoney() public { payable(playerAddresses[0]).transfer(howMuchPaid[playerAddresses[0]]); payable(playerAddresses[1]).transfer(howMuchPaid[playerAddresses[1]]); gameOver = true; } function payOut(address winnerAddress) public { uint totalWinnings = howMuchPaid[playerAddresses[0]] + howMuchPaid[playerAddresses[1]]; payable(winnerAddress).transfer(totalWinnings); gameOver = true; } //To discourage players from locking the game, if more than 100 minutes has passed and //one player hasn't moved, let someone //submit for early payout to the player who has moved. function prematurePayOut() external { dummy += 1; if (now - timeStarted>6000){ Move playerOneMove = eachPlayersMove[playerAddresses[0]]; Move playerTwoMove = eachPlayersMove[playerAddresses[1]]; if (playerOneMove != Move.none && playerTwoMove == Move.none){ payOut(playerAddresses[0]); } else if (playerTwoMove != Move.none && playerOneMove == Move.none){ payOut(playerAddresses[1]); } } gameOver = true; } }
Game storage game = games[auctionIndex];
function enroll() external payable returns (uint){ require(msg.value>=amountToStart, "You need to submit 2 Eth to start."); require(howMuchPaid[msg.sender]==0, "Already paid."); require(playerAddresses.length<2, "Already 2 players."); playerAddresses.push(msg.sender); howMuchPaid[msg.sender] = msg.value; if (playerAddresses.length==2){ timeStarted = now; } playerNumberByAddress[msg.sender] = playerAddresses.length-1; return playerAddresses.length-1; }
1,770,664
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.2; pragma experimental "ABIEncoderV2"; /** * @title ERC20 interface * @dev see https://eips.ethereum.org/EIPS/eip-20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol pragma solidity ^0.5.2; /** * @title ERC20Detailed token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint8) { return _decimals; } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.5.2; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: set-protocol-contracts/contracts/core/interfaces/ICore.sol /* Copyright 2018 Set Labs 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; /** * @title ICore * @author Set Protocol * * The ICore Contract defines all the functions exposed in the Core through its * various extensions and is a light weight way to interact with the contract. */ interface ICore { /** * Return transferProxy address. * * @return address transferProxy address */ function transferProxy() external view returns (address); /** * Return vault address. * * @return address vault address */ function vault() external view returns (address); /** * Return address belonging to given exchangeId. * * @param _exchangeId ExchangeId number * @return address Address belonging to given exchangeId */ function exchangeIds( uint8 _exchangeId ) external view returns (address); /* * Returns if valid set * * @return bool Returns true if Set created through Core and isn't disabled */ function validSets(address) external view returns (bool); /* * Returns if valid module * * @return bool Returns true if valid module */ function validModules(address) external view returns (bool); /** * Return boolean indicating if address is a valid Rebalancing Price Library. * * @param _priceLibrary Price library address * @return bool Boolean indicating if valid Price Library */ function validPriceLibraries( address _priceLibrary ) external view returns (bool); /** * Exchanges components for Set Tokens * * @param _set Address of set to issue * @param _quantity Quantity of set to issue */ function issue( address _set, uint256 _quantity ) external; /** * Issues a specified Set for a specified quantity to the recipient * using the caller's components from the wallet and vault. * * @param _recipient Address to issue to * @param _set Address of the Set to issue * @param _quantity Number of tokens to issue */ function issueTo( address _recipient, address _set, uint256 _quantity ) external; /** * Converts user's components into Set Tokens held directly in Vault instead of user's account * * @param _set Address of the Set * @param _quantity Number of tokens to redeem */ function issueInVault( address _set, uint256 _quantity ) external; /** * Function to convert Set Tokens into underlying components * * @param _set The address of the Set token * @param _quantity The number of tokens to redeem. Should be multiple of natural unit. */ function redeem( address _set, uint256 _quantity ) external; /** * Redeem Set token and return components to specified recipient. The components * are left in the vault * * @param _recipient Recipient of Set being issued * @param _set Address of the Set * @param _quantity Number of tokens to redeem */ function redeemTo( address _recipient, address _set, uint256 _quantity ) external; /** * Function to convert Set Tokens held in vault into underlying components * * @param _set The address of the Set token * @param _quantity The number of tokens to redeem. Should be multiple of natural unit. */ function redeemInVault( address _set, uint256 _quantity ) external; /** * Composite method to redeem and withdraw with a single transaction * * Normally, you should expect to be able to withdraw all of the tokens. * However, some have central abilities to freeze transfers (e.g. EOS). _toExclude * allows you to optionally specify which component tokens to exclude when * redeeming. They will remain in the vault under the users' addresses. * * @param _set Address of the Set * @param _to Address to withdraw or attribute tokens to * @param _quantity Number of tokens to redeem * @param _toExclude Mask of indexes of tokens to exclude from withdrawing */ function redeemAndWithdrawTo( address _set, address _to, uint256 _quantity, uint256 _toExclude ) external; /** * Deposit multiple tokens to the vault. Quantities should be in the * order of the addresses of the tokens being deposited. * * @param _tokens Array of the addresses of the ERC20 tokens * @param _quantities Array of the number of tokens to deposit */ function batchDeposit( address[] calldata _tokens, uint256[] calldata _quantities ) external; /** * Withdraw multiple tokens from the vault. Quantities should be in the * order of the addresses of the tokens being withdrawn. * * @param _tokens Array of the addresses of the ERC20 tokens * @param _quantities Array of the number of tokens to withdraw */ function batchWithdraw( address[] calldata _tokens, uint256[] calldata _quantities ) external; /** * Deposit any quantity of tokens into the vault. * * @param _token The address of the ERC20 token * @param _quantity The number of tokens to deposit */ function deposit( address _token, uint256 _quantity ) external; /** * Withdraw a quantity of tokens from the vault. * * @param _token The address of the ERC20 token * @param _quantity The number of tokens to withdraw */ function withdraw( address _token, uint256 _quantity ) external; /** * Transfer tokens associated with the sender's account in vault to another user's * account in vault. * * @param _token Address of token being transferred * @param _to Address of user receiving tokens * @param _quantity Amount of tokens being transferred */ function internalTransfer( address _token, address _to, uint256 _quantity ) external; /** * Deploys a new Set Token and adds it to the valid list of SetTokens * * @param _factory The address of the Factory to create from * @param _components The address of component tokens * @param _units The units of each component token * @param _naturalUnit The minimum unit to be issued or redeemed * @param _name The bytes32 encoded name of the new Set * @param _symbol The bytes32 encoded symbol of the new Set * @param _callData Byte string containing additional call parameters * @return setTokenAddress The address of the new Set */ function createSet( address _factory, address[] calldata _components, uint256[] calldata _units, uint256 _naturalUnit, bytes32 _name, bytes32 _symbol, bytes calldata _callData ) external returns (address); /** * Exposes internal function that deposits a quantity of tokens to the vault and attributes * the tokens respectively, to system modules. * * @param _from Address to transfer tokens from * @param _to Address to credit for deposit * @param _token Address of token being deposited * @param _quantity Amount of tokens to deposit */ function depositModule( address _from, address _to, address _token, uint256 _quantity ) external; /** * Exposes internal function that withdraws a quantity of tokens from the vault and * deattributes the tokens respectively, to system modules. * * @param _from Address to decredit for withdraw * @param _to Address to transfer tokens to * @param _token Address of token being withdrawn * @param _quantity Amount of tokens to withdraw */ function withdrawModule( address _from, address _to, address _token, uint256 _quantity ) external; /** * Exposes internal function that deposits multiple tokens to the vault, to system * modules. Quantities should be in the order of the addresses of the tokens being * deposited. * * @param _from Address to transfer tokens from * @param _to Address to credit for deposits * @param _tokens Array of the addresses of the tokens being deposited * @param _quantities Array of the amounts of tokens to deposit */ function batchDepositModule( address _from, address _to, address[] calldata _tokens, uint256[] calldata _quantities ) external; /** * Exposes internal function that withdraws multiple tokens from the vault, to system * modules. Quantities should be in the order of the addresses of the tokens being withdrawn. * * @param _from Address to decredit for withdrawals * @param _to Address to transfer tokens to * @param _tokens Array of the addresses of the tokens being withdrawn * @param _quantities Array of the amounts of tokens to withdraw */ function batchWithdrawModule( address _from, address _to, address[] calldata _tokens, uint256[] calldata _quantities ) external; /** * Expose internal function that exchanges components for Set tokens, * accepting any owner, to system modules * * @param _owner Address to use tokens from * @param _recipient Address to issue Set to * @param _set Address of the Set to issue * @param _quantity Number of tokens to issue */ function issueModule( address _owner, address _recipient, address _set, uint256 _quantity ) external; /** * Expose internal function that exchanges Set tokens for components, * accepting any owner, to system modules * * @param _burnAddress Address to burn token from * @param _incrementAddress Address to increment component tokens to * @param _set Address of the Set to redeem * @param _quantity Number of tokens to redeem */ function redeemModule( address _burnAddress, address _incrementAddress, address _set, uint256 _quantity ) external; /** * Expose vault function that increments user's balance in the vault. * Available to system modules * * @param _tokens The addresses of the ERC20 tokens * @param _owner The address of the token owner * @param _quantities The numbers of tokens to attribute to owner */ function batchIncrementTokenOwnerModule( address[] calldata _tokens, address _owner, uint256[] calldata _quantities ) external; /** * Expose vault function that decrement user's balance in the vault * Only available to system modules. * * @param _tokens The addresses of the ERC20 tokens * @param _owner The address of the token owner * @param _quantities The numbers of tokens to attribute to owner */ function batchDecrementTokenOwnerModule( address[] calldata _tokens, address _owner, uint256[] calldata _quantities ) external; /** * Expose vault function that transfer vault balances between users * Only available to system modules. * * @param _tokens Addresses of tokens being transferred * @param _from Address tokens being transferred from * @param _to Address tokens being transferred to * @param _quantities Amounts of tokens being transferred */ function batchTransferBalanceModule( address[] calldata _tokens, address _from, address _to, uint256[] calldata _quantities ) external; /** * Transfers token from one address to another using the transfer proxy. * Only available to system modules. * * @param _token The address of the ERC20 token * @param _quantity The number of tokens to transfer * @param _from The address to transfer from * @param _to The address to transfer to */ function transferModule( address _token, uint256 _quantity, address _from, address _to ) external; /** * Expose transfer proxy function to transfer tokens from one address to another * Only available to system modules. * * @param _tokens The addresses of the ERC20 token * @param _quantities The numbers of tokens to transfer * @param _from The address to transfer from * @param _to The address to transfer to */ function batchTransferModule( address[] calldata _tokens, uint256[] calldata _quantities, address _from, address _to ) external; } // File: set-protocol-contracts/contracts/core/lib/RebalancingLibrary.sol /* Copyright 2018 Set Labs 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; /** * @title RebalancingLibrary * @author Set Protocol * * The RebalancingLibrary contains functions for facilitating the rebalancing process for * Rebalancing Set Tokens. Removes the old calculation functions * */ library RebalancingLibrary { /* ============ Enums ============ */ enum State { Default, Proposal, Rebalance, Drawdown } /* ============ Structs ============ */ struct AuctionPriceParameters { uint256 auctionStartTime; uint256 auctionTimeToPivot; uint256 auctionStartPrice; uint256 auctionPivotPrice; } struct BiddingParameters { uint256 minimumBid; uint256 remainingCurrentSets; uint256[] combinedCurrentUnits; uint256[] combinedNextSetUnits; address[] combinedTokenArray; } } // File: set-protocol-contracts/contracts/core/interfaces/IRebalancingSetToken.sol /* Copyright 2018 Set Labs 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; /** * @title IRebalancingSetToken * @author Set Protocol * * The IRebalancingSetToken interface provides a light-weight, structured way to interact with the * RebalancingSetToken contract from another contract. */ interface IRebalancingSetToken { /* * Get totalSupply of Rebalancing Set * * @return totalSupply */ function totalSupply() external view returns (uint256); /* * Get lastRebalanceTimestamp of Rebalancing Set * * @return lastRebalanceTimestamp */ function lastRebalanceTimestamp() external view returns (uint256); /* * Get rebalanceInterval of Rebalancing Set * * @return rebalanceInterval */ function rebalanceInterval() external view returns (uint256); /* * Get rebalanceState of Rebalancing Set * * @return rebalanceState */ function rebalanceState() external view returns (RebalancingLibrary.State); /** * Gets the balance of the specified address. * * @param owner The address to query the balance of. * @return A uint256 representing the amount owned by the passed address. */ function balanceOf( address owner ) external view returns (uint256); /** * Function used to set the terms of the next rebalance and start the proposal period * * @param _nextSet The Set to rebalance into * @param _auctionLibrary The library used to calculate the Dutch Auction price * @param _auctionTimeToPivot The amount of time for the auction to go ffrom start to pivot price * @param _auctionStartPrice The price to start the auction at * @param _auctionPivotPrice The price at which the price curve switches from linear to exponential */ function propose( address _nextSet, address _auctionLibrary, uint256 _auctionTimeToPivot, uint256 _auctionStartPrice, uint256 _auctionPivotPrice ) external; /* * Get natural unit of Set * * @return uint256 Natural unit of Set */ function naturalUnit() external view returns (uint256); /** * Returns the address of the current Base Set * * @return A address representing the base Set Token */ function currentSet() external view returns (address); /* * Get the unit shares of the rebalancing Set * * @return unitShares Unit Shares of the base Set */ function unitShares() external view returns (uint256); /* * Burn set token for given address. * Can only be called by authorized contracts. * * @param _from The address of the redeeming account * @param _quantity The number of sets to burn from redeemer */ function burn( address _from, uint256 _quantity ) external; /* * Place bid during rebalance auction. Can only be called by Core. * * @param _quantity The amount of currentSet to be rebalanced * @return combinedTokenArray Array of token addresses invovled in rebalancing * @return inflowUnitArray Array of amount of tokens inserted into system in bid * @return outflowUnitArray Array of amount of tokens taken out of system in bid */ function placeBid( uint256 _quantity ) external returns (address[] memory, uint256[] memory, uint256[] memory); /* * Get combinedTokenArray of Rebalancing Set * * @return combinedTokenArray */ function getCombinedTokenArrayLength() external view returns (uint256); /* * Get combinedTokenArray of Rebalancing Set * * @return combinedTokenArray */ function getCombinedTokenArray() external view returns (address[] memory); /* * Get failedAuctionWithdrawComponents of Rebalancing Set * * @return failedAuctionWithdrawComponents */ function getFailedAuctionWithdrawComponents() external view returns (address[] memory); /* * Get biddingParameters for current auction * * @return biddingParameters */ function getBiddingParameters() external view returns (uint256[] memory); } // File: set-protocol-contracts/contracts/core/interfaces/ISetToken.sol /* Copyright 2018 Set Labs 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; /** * @title ISetToken * @author Set Protocol * * The ISetToken interface provides a light-weight, structured way to interact with the * SetToken contract from another contract. */ interface ISetToken { /* ============ External Functions ============ */ /* * Get natural unit of Set * * @return uint256 Natural unit of Set */ function naturalUnit() external view returns (uint256); /* * Get addresses of all components in the Set * * @return componentAddresses Array of component tokens */ function getComponents() external view returns (address[] memory); /* * Get units of all tokens in Set * * @return units Array of component units */ function getUnits() external view returns (uint256[] memory); /* * Checks to make sure token is component of Set * * @param _tokenAddress Address of token being checked * @return bool True if token is component of Set */ function tokenIsComponent( address _tokenAddress ) external view returns (bool); /* * Mint set token for given address. * Can only be called by authorized contracts. * * @param _issuer The address of the issuing account * @param _quantity The number of sets to attribute to issuer */ function mint( address _issuer, uint256 _quantity ) external; /* * Burn set token for given address * Can only be called by authorized contracts * * @param _from The address of the redeeming account * @param _quantity The number of sets to burn from redeemer */ function burn( address _from, uint256 _quantity ) external; /** * Transfer token for a specified address * * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer( address to, uint256 value ) external; } // File: set-protocol-contracts/contracts/core/lib/SetTokenLibrary.sol /* Copyright 2018 Set Labs 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; library SetTokenLibrary { using SafeMath for uint256; struct SetDetails { uint256 naturalUnit; address[] components; uint256[] units; } /** * Validates that passed in tokens are all components of the Set * * @param _set Address of the Set * @param _tokens List of tokens to check */ function validateTokensAreComponents( address _set, address[] calldata _tokens ) external view { for (uint256 i = 0; i < _tokens.length; i++) { // Make sure all tokens are members of the Set require( ISetToken(_set).tokenIsComponent(_tokens[i]), "SetTokenLibrary.validateTokensAreComponents: Component must be a member of Set" ); } } /** * Validates that passed in quantity is a multiple of the natural unit of the Set. * * @param _set Address of the Set * @param _quantity Quantity to validate */ function isMultipleOfSetNaturalUnit( address _set, uint256 _quantity ) external view { require( _quantity.mod(ISetToken(_set).naturalUnit()) == 0, "SetTokenLibrary.isMultipleOfSetNaturalUnit: Quantity is not a multiple of nat unit" ); } /** * Retrieves the Set's natural unit, components, and units. * * @param _set Address of the Set * @return SetDetails Struct containing the natural unit, components, and units */ function getSetDetails( address _set ) internal view returns (SetDetails memory) { // Declare interface variables ISetToken setToken = ISetToken(_set); // Fetch set token properties uint256 naturalUnit = setToken.naturalUnit(); address[] memory components = setToken.getComponents(); uint256[] memory units = setToken.getUnits(); return SetDetails({ naturalUnit: naturalUnit, components: components, units: units }); } } // File: contracts/meta-oracles/interfaces/IOracle.sol /* Copyright 2019 Set Labs 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; /** * @title IOracle * @author Set Protocol * * Interface for operating with any external Oracle that returns uint256 or * an adapting contract that converts oracle output to uint256 */ interface IOracle { /** * Returns the queried data from an oracle returning uint256 * * @return Current price of asset represented in uint256 */ function read() external view returns (uint256); } // File: contracts/meta-oracles/interfaces/IMetaOracleV2.sol /* Copyright 2019 Set Labs 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; /** * @title IMetaOracleV2 * @author Set Protocol * * Interface for operating with any MetaOracleV2 (moving average, bollinger, etc.) * * CHANGELOG: * - read returns uint256 instead of bytes */ interface IMetaOracleV2 { /** * Returns the queried data from a meta oracle. * * @return Current price of asset in uint256 */ function read( uint256 _dataDays ) external view returns (uint256); } // File: contracts/external/DappHub/interfaces/IMedian.sol /* Copyright 2019 Set Labs 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; /** * @title IMedian * @author Set Protocol * * Interface for operating with a price feed Medianizer contract */ interface IMedian { /** * Returns the current price set on the medianizer. Throws if the price is set to 0 (initialization) * * @return Current price of asset represented in hex as bytes32 */ function read() external view returns (bytes32); /** * Returns the current price set on the medianizer and whether the value has been initialized * * @return Current price of asset represented in hex as bytes32, and whether value is non-zero */ function peek() external view returns (bytes32, bool); } // File: contracts/managers/lib/FlexibleTimingManagerLibrary.sol /* Copyright 2018 Set Labs 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; /** * @title FlexibleTimingManagerLibrary * @author Set Protocol * * The FlexibleTimingManagerLibrary contains functions for helping Managers create proposals * */ library FlexibleTimingManagerLibrary { using SafeMath for uint256; /* * Validates whether the Rebalancing Set is in the correct state and sufficient time has elapsed. * * @param _rebalancingSetInterface Instance of the Rebalancing Set Token */ function validateManagerPropose( IRebalancingSetToken _rebalancingSetInterface ) internal { // Require that enough time has passed from last rebalance uint256 lastRebalanceTimestamp = _rebalancingSetInterface.lastRebalanceTimestamp(); uint256 rebalanceInterval = _rebalancingSetInterface.rebalanceInterval(); require( block.timestamp >= lastRebalanceTimestamp.add(rebalanceInterval), "FlexibleTimingManagerLibrary.proposeNewRebalance: Rebalance interval not elapsed" ); // Require that Rebalancing Set Token is in Default state, won't allow for re-proposals // because malicious actor could prevent token from ever rebalancing require( _rebalancingSetInterface.rebalanceState() == RebalancingLibrary.State.Default, "FlexibleTimingManagerLibrary.proposeNewRebalance: State must be in Default" ); } /* /* * Calculates the auction price parameters, targetting 1% slippage every 10 minutes. Fair value * placed in middle of price range. * * @param _currentSetDollarAmount The 18 decimal value of one currenSet * @param _nextSetDollarAmount The 18 decimal value of one nextSet * @param _timeIncrement Amount of time to explore 1% of fair value price change * @param _auctionLibraryPriceDivisor The auction library price divisor * @param _auctionTimeToPivot The auction time to pivot * @return uint256 The auctionStartPrice for rebalance auction * @return uint256 The auctionPivotPrice for rebalance auction */ function calculateAuctionPriceParameters( uint256 _currentSetDollarAmount, uint256 _nextSetDollarAmount, uint256 _timeIncrement, uint256 _auctionLibraryPriceDivisor, uint256 _auctionTimeToPivot ) internal view returns (uint256, uint256) { // Determine fair value of nextSet/currentSet and put in terms of auction library price divisor uint256 fairValue = _nextSetDollarAmount.mul(_auctionLibraryPriceDivisor).div(_currentSetDollarAmount); // Calculate how much one percent slippage from fair value is uint256 onePercentSlippage = fairValue.div(100); // Calculate how many time increments are in auctionTimeToPivot uint256 timeIncrements = _auctionTimeToPivot.div(_timeIncrement); // Since we are targeting a 1% slippage every time increment the price range is defined as // the price of a 1% move multiplied by the amount of time increments in the auctionTimeToPivot // This value is then divided by two to get half the price range uint256 halfPriceRange = timeIncrements.mul(onePercentSlippage).div(2); // Auction start price is fair value minus half price range to center the auction at fair value uint256 auctionStartPrice = fairValue.sub(halfPriceRange); // Auction pivot price is fair value plus half price range to center the auction at fair value uint256 auctionPivotPrice = fairValue.add(halfPriceRange); return (auctionStartPrice, auctionPivotPrice); } /* * Query the Medianizer price feeds for a value that is returned as a Uint. Prices * have 18 decimals. * * @param _priceFeedAddress Address of the medianizer price feed * @return uint256 The price from the price feed with 18 decimals */ function queryPriceData( address _priceFeedAddress ) internal view returns (uint256) { // Get prices from oracles bytes32 priceInBytes = IMedian(_priceFeedAddress).read(); return uint256(priceInBytes); } /* * Calculates the USD Value of a Set Token - by taking the individual token prices, units * and decimals. * * @param _tokenPrices The 18 decimal values of components * @param _naturalUnit The naturalUnit of the set being component belongs to * @param _units The units of the components in the Set * @param _tokenDecimals The components decimal values * @return uint256 The USD value of the Set (in cents) */ function calculateSetTokenDollarValue( uint256[] memory _tokenPrices, uint256 _naturalUnit, uint256[] memory _units, uint256[] memory _tokenDecimals ) internal view returns (uint256) { uint256 setDollarAmount = 0; // Loop through assets for (uint256 i = 0; i < _tokenPrices.length; i++) { uint256 tokenDollarValue = calculateTokenAllocationAmountUSD( _tokenPrices[i], _naturalUnit, _units[i], _tokenDecimals[i] ); setDollarAmount = setDollarAmount.add(tokenDollarValue); } return setDollarAmount; } /* * Get USD value of one component in a Set to 18 decimals * * @param _tokenPrice The 18 decimal value of one full token * @param _naturalUnit The naturalUnit of the set being component belongs to * @param _unit The unit of the component in the set * @param _tokenDecimals The component token's decimal value * @return uint256 The USD value of the component's allocation in the Set */ function calculateTokenAllocationAmountUSD( uint256 _tokenPrice, uint256 _naturalUnit, uint256 _unit, uint256 _tokenDecimals ) internal view returns (uint256) { uint256 SET_TOKEN_DECIMALS = 18; // Calculate the amount of component base units are in one full set token uint256 componentUnitsInFullToken = _unit .mul(10 ** SET_TOKEN_DECIMALS) .div(_naturalUnit); // Return value of component token in one full set token, to 18 decimals uint256 allocationUSDValue = _tokenPrice .mul(componentUnitsInFullToken) .div(10 ** _tokenDecimals); require( allocationUSDValue > 0, "FlexibleTimingManagerLibrary.calculateTokenAllocationAmountUSD: Value must be > 0" ); return allocationUSDValue; } } // File: contracts/managers/MACOStrategyManagerV2.sol /* Copyright 2019 Set Labs 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; /** * @title MACOStrategyManager * @author Set Protocol * * Rebalancing Manager contract for implementing the Moving Average (MA) Crossover * Strategy between a risk asset's MA and the spot price of the risk asset. The time * frame for the MA is defined on instantiation. When the spot price dips below the MA * risk asset is sold for stable asset and vice versa when the spot price exceeds the MA. * * CHANGELOG: * - Pass riskAssetOracleInstance in constructor * - Pass list of collateral sets in constructor instead of individually * - Read oracles using IOracle and IMetaOracleV2 */ contract MACOStrategyManagerV2 { using SafeMath for uint256; /* ============ Constants ============ */ uint256 constant AUCTION_LIB_PRICE_DIVISOR = 1000; uint256 constant ALLOCATION_PRICE_RATIO_LIMIT = 4; uint256 constant TEN_MINUTES_IN_SECONDS = 600; // Equal to $1 since token prices are passed with 18 decimals uint256 constant STABLE_ASSET_PRICE = 10 ** 18; uint256 constant SET_TOKEN_DECIMALS = 10 ** 18; /* ============ State Variables ============ */ address public contractDeployer; address public rebalancingSetTokenAddress; address public coreAddress; address public setTokenFactory; address public auctionLibrary; IMetaOracleV2 public movingAveragePriceFeedInstance; IOracle public riskAssetOracleInstance; address public stableAssetAddress; address public riskAssetAddress; address public stableCollateralAddress; address public riskCollateralAddress; uint256 public stableAssetDecimals; uint256 public riskAssetDecimals; uint256 public auctionTimeToPivot; uint256 public movingAverageDays; uint256 public lastCrossoverConfirmationTimestamp; uint256 public crossoverConfirmationMinTime; uint256 public crossoverConfirmationMaxTime; /* ============ Events ============ */ event LogManagerProposal( uint256 riskAssetPrice, uint256 movingAveragePrice ); /* * MACOStrategyManager constructor. * * @param _coreAddress The address of the Core contract * @param _movingAveragePriceFeed The address of MA price feed * @param _riskAssetOracle The address of risk asset oracle * @param _stableAssetAddress The address of the stable asset contract * @param _riskAssetAddress The address of the risk asset contract * @param _collateralAddresses The addresses of collateral Sets [stableCollateral, * riskCollateral] * @param _setTokenFactory The address of the SetTokenFactory * @param _auctionLibrary The address of auction price curve to use in rebalance * @param _movingAverageDays The amount of days to use in moving average calculation * @param _auctionTimeToPivot The amount of time until pivot reached in rebalance * @param _crossoverConfirmationBounds The minimum and maximum time in seconds confirm confirmation * can be called after the last initial crossover confirmation */ constructor( address _coreAddress, IMetaOracleV2 _movingAveragePriceFeed, IOracle _riskAssetOracle, address _stableAssetAddress, address _riskAssetAddress, address[2] memory _collateralAddresses, address _setTokenFactory, address _auctionLibrary, uint256 _movingAverageDays, uint256 _auctionTimeToPivot, uint256[2] memory _crossoverConfirmationBounds ) public { contractDeployer = msg.sender; coreAddress = _coreAddress; movingAveragePriceFeedInstance = _movingAveragePriceFeed; riskAssetOracleInstance = _riskAssetOracle; setTokenFactory = _setTokenFactory; auctionLibrary = _auctionLibrary; stableAssetAddress = _stableAssetAddress; riskAssetAddress = _riskAssetAddress; stableCollateralAddress = _collateralAddresses[0]; riskCollateralAddress = _collateralAddresses[1]; auctionTimeToPivot = _auctionTimeToPivot; movingAverageDays = _movingAverageDays; lastCrossoverConfirmationTimestamp = 0; crossoverConfirmationMinTime = _crossoverConfirmationBounds[0]; crossoverConfirmationMaxTime = _crossoverConfirmationBounds[1]; address[] memory initialStableCollateralComponents = ISetToken(_collateralAddresses[0]).getComponents(); address[] memory initialRiskCollateralComponents = ISetToken(_collateralAddresses[1]).getComponents(); require( crossoverConfirmationMaxTime > crossoverConfirmationMinTime, "MACOStrategyManager.constructor: Max confirmation time must be greater than min." ); require( initialStableCollateralComponents[0] == _stableAssetAddress, "MACOStrategyManager.constructor: Stable collateral component must match stable asset." ); require( initialRiskCollateralComponents[0] == _riskAssetAddress, "MACOStrategyManager.constructor: Risk collateral component must match risk asset." ); // Get decimals of underlying assets from smart contracts stableAssetDecimals = ERC20Detailed(_stableAssetAddress).decimals(); riskAssetDecimals = ERC20Detailed(_riskAssetAddress).decimals(); } /* ============ External ============ */ /* * This function sets the Rebalancing Set Token address that the manager is associated with. * Since, the rebalancing set token must first specify the address of the manager before deployment, * we cannot know what the rebalancing set token is in advance. This function is only meant to be called * once during initialization by the contract deployer. * * @param _rebalancingSetTokenAddress The address of the rebalancing Set token */ function initialize( address _rebalancingSetTokenAddress ) external { // Check that contract deployer is calling function require( msg.sender == contractDeployer, "MACOStrategyManager.initialize: Only the contract deployer can initialize" ); // Make sure the rebalancingSetToken is tracked by Core require( ICore(coreAddress).validSets(_rebalancingSetTokenAddress), "MACOStrategyManager.initialize: Invalid or disabled RebalancingSetToken address" ); rebalancingSetTokenAddress = _rebalancingSetTokenAddress; contractDeployer = address(0); } /* * When allowed on RebalancingSetToken, anyone can call for a new rebalance proposal. This begins a six * hour period where the signal can be confirmed before moving ahead with rebalance. * */ function initialPropose() external { // Make sure propose in manager hasn't already been initiated require( block.timestamp > lastCrossoverConfirmationTimestamp.add(crossoverConfirmationMaxTime), "MACOStrategyManager.initialPropose: 12 hours must pass before new proposal initiated" ); // Create interface to interact with RebalancingSetToken and check enough time has passed for proposal FlexibleTimingManagerLibrary.validateManagerPropose(IRebalancingSetToken(rebalancingSetTokenAddress)); // Get price data from oracles ( uint256 riskAssetPrice, uint256 movingAveragePrice ) = getPriceData(); // Make sure price trigger has been reached checkPriceTriggerMet(riskAssetPrice, movingAveragePrice); lastCrossoverConfirmationTimestamp = block.timestamp; } /* * After initial propose is called, confirm the signal has been met and determine parameters for the rebalance * */ function confirmPropose() external { // Make sure enough time has passed to initiate proposal on Rebalancing Set Token require( block.timestamp >= lastCrossoverConfirmationTimestamp.add(crossoverConfirmationMinTime) && block.timestamp <= lastCrossoverConfirmationTimestamp.add(crossoverConfirmationMaxTime), "MACOStrategyManager.confirmPropose: Confirming signal must be within bounds of the initial propose" ); // Create interface to interact with RebalancingSetToken and check not in Proposal state FlexibleTimingManagerLibrary.validateManagerPropose(IRebalancingSetToken(rebalancingSetTokenAddress)); // Get price data from oracles ( uint256 riskAssetPrice, uint256 movingAveragePrice ) = getPriceData(); // Make sure price trigger has been reached checkPriceTriggerMet(riskAssetPrice, movingAveragePrice); // If price trigger has been met, get next Set allocation. Create new set if price difference is too // great to run good auction. Return nextSet address and dollar value of current and next set ( address nextSetAddress, uint256 currentSetDollarValue, uint256 nextSetDollarValue ) = determineNewAllocation( riskAssetPrice ); // Calculate the price parameters for auction ( uint256 auctionStartPrice, uint256 auctionPivotPrice ) = FlexibleTimingManagerLibrary.calculateAuctionPriceParameters( currentSetDollarValue, nextSetDollarValue, TEN_MINUTES_IN_SECONDS, AUCTION_LIB_PRICE_DIVISOR, auctionTimeToPivot ); // Propose new allocation to Rebalancing Set Token IRebalancingSetToken(rebalancingSetTokenAddress).propose( nextSetAddress, auctionLibrary, auctionTimeToPivot, auctionStartPrice, auctionPivotPrice ); emit LogManagerProposal( riskAssetPrice, movingAveragePrice ); } /* ============ Internal ============ */ /* * Determine if risk collateral is currently collateralizing the rebalancing set, if so return true, * else return false. * * @return boolean True if risk collateral in use, false otherwise */ function usingRiskCollateral() internal view returns (bool) { // Get set currently collateralizing rebalancing set token address[] memory currentCollateralComponents = ISetToken(rebalancingSetTokenAddress).getComponents(); // If collateralized by riskCollateral set return true, else to false return (currentCollateralComponents[0] == riskCollateralAddress); } /* * Get the risk asset and moving average prices from respective oracles. Price returned have 18 decimals so * 10 ** 18 = $1. * * @return uint256 USD Price of risk asset * @return uint256 Moving average USD Price of risk asset */ function getPriceData() internal view returns(uint256, uint256) { // Get current risk asset price and moving average data uint256 riskAssetPrice = riskAssetOracleInstance.read(); uint256 movingAveragePrice = movingAveragePriceFeedInstance.read(movingAverageDays); return (riskAssetPrice, movingAveragePrice); } /* * Check to make sure that the necessary price changes have occured to allow a rebalance. * * @param _riskAssetPrice Current risk asset price as found on oracle * @param _movingAveragePrice Current MA price from Meta Oracle */ function checkPriceTriggerMet( uint256 _riskAssetPrice, uint256 _movingAveragePrice ) internal view { if (usingRiskCollateral()) { // If currently holding risk asset (riskOn) check to see if price is below MA, otherwise revert. require( _movingAveragePrice > _riskAssetPrice, "MACOStrategyManager.checkPriceTriggerMet: Risk asset price must be below moving average price" ); } else { // If currently holding stable asset (not riskOn) check to see if price is above MA, otherwise revert. require( _movingAveragePrice < _riskAssetPrice, "MACOStrategyManager.checkPriceTriggerMet: Risk asset price must be above moving average price" ); } } /* * Determine the next allocation to rebalance into. If the dollar value of the two collateral sets is more * than 5x different from each other then create a new collateral set. If currently riskOn then a new * stable collateral set is created, if !riskOn then a new risk collateral set is created. * * @param _riskAssetPrice Current risk asset price as found on oracle * @return address The address of the proposed nextSet * @return uint256 The USD value of current Set * @return uint256 The USD value of next Set */ function determineNewAllocation( uint256 _riskAssetPrice ) internal returns (address, uint256, uint256) { // Check to see if new collateral must be created in order to keep collateral price ratio in line. // If not just return the dollar value of current collateral sets ( uint256 stableCollateralDollarValue, uint256 riskCollateralDollarValue ) = checkForNewAllocation(_riskAssetPrice); ( address nextSetAddress, uint256 currentSetDollarValue, uint256 nextSetDollarValue ) = usingRiskCollateral() ? (stableCollateralAddress, riskCollateralDollarValue, stableCollateralDollarValue) : (riskCollateralAddress, stableCollateralDollarValue, riskCollateralDollarValue); return (nextSetAddress, currentSetDollarValue, nextSetDollarValue); } /* * Check to see if a new collateral set needs to be created. If the dollar value of the two collateral sets is more * than 5x different from each other then create a new collateral set. * * @param _riskAssetPrice Current risk asset price as found on oracle * @return uint256 The USD value of stable collateral * @return uint256 The USD value of risk collateral */ function checkForNewAllocation( uint256 _riskAssetPrice ) internal returns(uint256, uint256) { // Get details of both collateral sets SetTokenLibrary.SetDetails memory stableCollateralDetails = SetTokenLibrary.getSetDetails( stableCollateralAddress ); SetTokenLibrary.SetDetails memory riskCollateralDetails = SetTokenLibrary.getSetDetails( riskCollateralAddress ); // Value both Sets uint256 stableCollateralDollarValue = FlexibleTimingManagerLibrary.calculateTokenAllocationAmountUSD( STABLE_ASSET_PRICE, stableCollateralDetails.naturalUnit, stableCollateralDetails.units[0], stableAssetDecimals ); uint256 riskCollateralDollarValue = FlexibleTimingManagerLibrary.calculateTokenAllocationAmountUSD( _riskAssetPrice, riskCollateralDetails.naturalUnit, riskCollateralDetails.units[0], riskAssetDecimals ); // If value of one Set is 5 times greater than the other, create a new collateral Set if (riskCollateralDollarValue.mul(ALLOCATION_PRICE_RATIO_LIMIT) <= stableCollateralDollarValue || riskCollateralDollarValue >= stableCollateralDollarValue.mul(ALLOCATION_PRICE_RATIO_LIMIT)) { //Determine the new collateral parameters return determineNewCollateralParameters( _riskAssetPrice, stableCollateralDollarValue, riskCollateralDollarValue, stableCollateralDetails, riskCollateralDetails ); } else { return (stableCollateralDollarValue, riskCollateralDollarValue); } } /* * Create new collateral Set for the occasion where the dollar value of the two collateral * sets is more than 5x different from each other. The new collateral set address is then * assigned to the correct state variable (risk or stable collateral) * * @param _riskAssetPrice Current risk asset price as found on oracle * @param _stableCollateralValue Value of current stable collateral set in USD * @param _riskCollateralValue Value of current risk collateral set in USD * @param _stableCollateralDetails Set details of current stable collateral set * @param _riskCollateralDetails Set details of current risk collateral set * @return uint256 The USD value of stable collateral * @return uint256 The USD value of risk collateral */ function determineNewCollateralParameters( uint256 _riskAssetPrice, uint256 _stableCollateralValue, uint256 _riskCollateralValue, SetTokenLibrary.SetDetails memory _stableCollateralDetails, SetTokenLibrary.SetDetails memory _riskCollateralDetails ) internal returns (uint256, uint256) { uint256 stableCollateralDollarValue; uint256 riskCollateralDollarValue; if (usingRiskCollateral()) { // Create static components and units array address[] memory nextSetComponents = new address[](1); nextSetComponents[0] = stableAssetAddress; ( uint256[] memory nextSetUnits, uint256 nextNaturalUnit ) = getNewCollateralSetParameters( _riskCollateralValue, STABLE_ASSET_PRICE, stableAssetDecimals, _stableCollateralDetails.naturalUnit ); // Create new stable collateral set with units and naturalUnit as calculated above stableCollateralAddress = ICore(coreAddress).createSet( setTokenFactory, nextSetComponents, nextSetUnits, nextNaturalUnit, bytes32("STBLCollateral"), bytes32("STBLMACO"), "" ); // Calculate dollar value of new stable collateral stableCollateralDollarValue = FlexibleTimingManagerLibrary.calculateTokenAllocationAmountUSD( STABLE_ASSET_PRICE, nextNaturalUnit, nextSetUnits[0], stableAssetDecimals ); riskCollateralDollarValue = _riskCollateralValue; } else { // Create static components and units array address[] memory nextSetComponents = new address[](1); nextSetComponents[0] = riskAssetAddress; ( uint256[] memory nextSetUnits, uint256 nextNaturalUnit ) = getNewCollateralSetParameters( _stableCollateralValue, _riskAssetPrice, riskAssetDecimals, _riskCollateralDetails.naturalUnit ); // Create new risk collateral set with units and naturalUnit as calculated above riskCollateralAddress = ICore(coreAddress).createSet( setTokenFactory, nextSetComponents, nextSetUnits, nextNaturalUnit, bytes32("RISKCollateral"), bytes32("RISKMACO"), "" ); // Calculate dollar value of new risk collateral riskCollateralDollarValue = FlexibleTimingManagerLibrary.calculateTokenAllocationAmountUSD( _riskAssetPrice, nextNaturalUnit, nextSetUnits[0], riskAssetDecimals ); stableCollateralDollarValue = _stableCollateralValue; } return (stableCollateralDollarValue, riskCollateralDollarValue); } /* * Calculate new collateral units and natural unit. If necessary iterate through until naturalUnit * found that supports non-zero unit amount. Here Underlying refers to the token underlying the * collateral Set (i.e. ETH is underlying of riskCollateral Set). * * @param _currentCollateralUSDValue USD Value of current collateral set * @param _replacementUnderlyingPrice Price of underlying token to be rebalanced into * @param _replacementUnderlyingDecimals Amount of decimals in replacement token * @param _replacementCollateralNaturalUnit Natural Unit of replacement collateral Set * @return uint256[] Units array for new collateral set * @return uint256 NaturalUnit for new collateral set */ function getNewCollateralSetParameters( uint256 _currentCollateralUSDValue, uint256 _replacementUnderlyingPrice, uint256 _replacementUnderlyingDecimals, uint256 _replacementCollateralNaturalUnit ) internal pure returns (uint256[] memory, uint256) { // Calculate nextSetUnits such that the USD value of new Set is equal to the USD value of the Set // being rebalanced out of uint256[] memory nextSetUnits = new uint256[](1); uint256 potentialNextUnit = 0; uint256 naturalUnitMultiplier = 1; uint256 nextNaturalUnit; // Calculate next units. If nextUnit is 0 then bump natural unit (and thus units) by factor of // ten until unit is greater than 0 while (potentialNextUnit == 0) { nextNaturalUnit = _replacementCollateralNaturalUnit.mul(naturalUnitMultiplier); potentialNextUnit = calculateNextSetUnits( _currentCollateralUSDValue, _replacementUnderlyingPrice, _replacementUnderlyingDecimals, nextNaturalUnit ); naturalUnitMultiplier = naturalUnitMultiplier.mul(10); } nextSetUnits[0] = potentialNextUnit; return (nextSetUnits, nextNaturalUnit); } /* * Calculate new collateral units by making the new collateral USD value equal to the USD value of the * Set currently collateralizing the Rebalancing Set. Here Underlying refers to the token underlying the * collateral Set (i.e. ETH is underlying of riskCollateral Set). * * @param _currentCollateralUSDValue USD Value of current collateral set * @param _replacementUnderlyingPrice Price of asset to be rebalanced into * @param _replacementUnderlyingDecimals Amount of decimals in replacement collateral * @param _replacementCollateralNaturalUnit Natural Unit of collateral set to be replacement * @return uint256 New unit for new collateral set */ function calculateNextSetUnits( uint256 _currentCollateralUSDValue, uint256 _replacementUnderlyingPrice, uint256 _replacementUnderlyingDecimals, uint256 _replacementCollateralNaturalUnit ) internal pure returns (uint256) { return _currentCollateralUSDValue .mul(10 ** _replacementUnderlyingDecimals) .mul(_replacementCollateralNaturalUnit) .div(SET_TOKEN_DECIMALS.mul(_replacementUnderlyingPrice)); } }
Calculates the auction price parameters, targetting 1% slippage every 10 minutes. Fair value placed in middle of price range. _currentSetDollarAmount The 18 decimal value of one currenSet _nextSetDollarAmount The 18 decimal value of one nextSet _timeIncrement Amount of time to explore 1% of fair value price change _auctionLibraryPriceDivisor The auction library price divisor _auctionTimeToPivot The auction time to pivot return uint256 The auctionStartPrice for rebalance auction return uint256 The auctionPivotPrice for rebalance auction/ Determine fair value of nextSet/currentSet and put in terms of auction library price divisor Calculate how much one percent slippage from fair value is Calculate how many time increments are in auctionTimeToPivot Since we are targeting a 1% slippage every time increment the price range is defined as the price of a 1% move multiplied by the amount of time increments in the auctionTimeToPivot This value is then divided by two to get half the price range Auction start price is fair value minus half price range to center the auction at fair value Auction pivot price is fair value plus half price range to center the auction at fair value
function calculateAuctionPriceParameters( uint256 _currentSetDollarAmount, uint256 _nextSetDollarAmount, uint256 _timeIncrement, uint256 _auctionLibraryPriceDivisor, uint256 _auctionTimeToPivot ) internal view returns (uint256, uint256) { uint256 fairValue = _nextSetDollarAmount.mul(_auctionLibraryPriceDivisor).div(_currentSetDollarAmount); uint256 onePercentSlippage = fairValue.div(100); uint256 timeIncrements = _auctionTimeToPivot.div(_timeIncrement); uint256 halfPriceRange = timeIncrements.mul(onePercentSlippage).div(2); uint256 auctionStartPrice = fairValue.sub(halfPriceRange); uint256 auctionPivotPrice = fairValue.add(halfPriceRange); return (auctionStartPrice, auctionPivotPrice); }
1,001,007
/** *Submitted for verification at Etherscan.io on 2019-12-27 */ /** Copyright 2019 PoolTogether LLC This file is part of PoolTogether. PoolTogether 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 under version 3 of the License. PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.5.12; contract GemLike { function allowance(address, address) public returns (uint); function approve(address, uint) public; function transfer(address, uint) public returns (bool); function transferFrom(address, address, uint) public returns (bool); } contract ValueLike { function peek() public returns (uint, bool); } contract SaiTubLike { function skr() public view returns (GemLike); function gem() public view returns (GemLike); function gov() public view returns (GemLike); function sai() public view returns (GemLike); function pep() public view returns (ValueLike); function vox() public view returns (VoxLike); function bid(uint) public view returns (uint); function ink(bytes32) public view returns (uint); function tag() public view returns (uint); function tab(bytes32) public returns (uint); function rap(bytes32) public returns (uint); function draw(bytes32, uint) public; function shut(bytes32) public; function exit(uint) public; function give(bytes32, address) public; } contract VoxLike { function par() public returns (uint); } contract JoinLike { function ilk() public returns (bytes32); function gem() public returns (GemLike); function dai() public returns (GemLike); function join(address, uint) public; function exit(address, uint) public; } contract VatLike { function ilks(bytes32) public view returns (uint, uint, uint, uint, uint); function hope(address) public; function frob(bytes32, address, address, address, int, int) public; } contract ManagerLike { function vat() public view returns (address); function urns(uint) public view returns (address); function open(bytes32, address) public returns (uint); function frob(uint, int, int) public; function give(uint, address) public; function move(uint, address, uint) public; } contract OtcLike { function getPayAmount(address, address, uint) public view returns (uint); function buyAllAmount(address, uint, address, uint) public; } /** * Implements a "lock" feature with a cooldown */ library Blocklock { struct State { uint256 lockedAt; uint256 unlockedAt; uint256 lockDuration; uint256 cooldownDuration; } function setLockDuration(State storage self, uint256 lockDuration) public { require(lockDuration > 0, "Blocklock/lock-min"); self.lockDuration = lockDuration; } function setCooldownDuration(State storage self, uint256 cooldownDuration) public { self.cooldownDuration = cooldownDuration; } function isLocked(State storage self, uint256 blockNumber) public view returns (bool) { uint256 endAt = lockEndAt(self); return ( self.lockedAt != 0 && blockNumber >= self.lockedAt && blockNumber < endAt ); } function lock(State storage self, uint256 blockNumber) public { require(canLock(self, blockNumber), "Blocklock/no-lock"); self.lockedAt = blockNumber; } function unlock(State storage self, uint256 blockNumber) public { self.unlockedAt = blockNumber; } function canLock(State storage self, uint256 blockNumber) public view returns (bool) { uint256 endAt = lockEndAt(self); return ( self.lockedAt == 0 || blockNumber >= endAt + self.cooldownDuration ); } function cooldownEndAt(State storage self) internal view returns (uint256) { return lockEndAt(self) + self.cooldownDuration; } function lockEndAt(State storage self) internal view returns (uint256) { uint256 endAt = self.lockedAt + self.lockDuration; // if we unlocked early if (self.unlockedAt >= self.lockedAt && self.unlockedAt < endAt) { endAt = self.unlockedAt; } return endAt; } } /** Copyright 2019 PoolTogether LLC This file is part of PoolTogether. PoolTogether 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 under version 3 of the License. PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ /** Copyright 2019 PoolTogether LLC This file is part of PoolTogether. PoolTogether 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 under version 3 of the License. PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ /** * @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); } /** * @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; } } /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. uint256 cs; assembly { cs := extcodesize(address) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. */ contract ReentrancyGuard is Initializable { // counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; function initialize() public initializer { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call"); } uint256[50] private ______gap; } /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } /** Copyright 2019 PoolTogether LLC This file is part of PoolTogether. PoolTogether 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 under version 3 of the License. PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ contract ICErc20 { address public underlying; function mint(uint mintAmount) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function balanceOfUnderlying(address owner) external returns (uint); function getCash() external view returns (uint); function supplyRatePerBlock() external view returns (uint); } /** Copyright 2019 PoolTogether LLC This file is part of PoolTogether. PoolTogether 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 under version 3 of the License. PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ /** Copyright 2019 PoolTogether LLC This file is part of PoolTogether. PoolTogether 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 under version 3 of the License. PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ /** * @author Brendan Asselstine * @notice A library that uses entropy to select a random number within a bound. Compensates for modulo bias. * @dev Thanks to https://medium.com/hownetworks/dont-waste-cycles-with-modulo-bias-35b6fdafcf94 */ library UniformRandomNumber { /// @notice Select a random number without modulo bias using a random seed and upper bound /// @param _entropy The seed for randomness /// @param _upperBound The upper bound of the desired number /// @return A random number less than the _upperBound function uniform(uint256 _entropy, uint256 _upperBound) internal pure returns (uint256) { if (_upperBound == 0) { return 0; } uint256 min = -_upperBound % _upperBound; uint256 random = _entropy; while (true) { if (random >= min) { break; } random = uint256(keccak256(abi.encodePacked(random))); } return random % _upperBound; } } /** * @reviewers: [@clesaege, @unknownunknown1, @ferittuncer] * @auditors: [] * @bounties: [<14 days 10 ETH max payout>] * @deployments: [] */ /** * @title SortitionSumTreeFactory * @author Enrique Piqueras - <[email protected]> * @dev A factory of trees that keep track of staked values for sortition. */ library SortitionSumTreeFactory { /* Structs */ struct SortitionSumTree { uint K; // The maximum number of childs per node. // We use this to keep track of vacant positions in the tree after removing a leaf. This is for keeping the tree as balanced as possible without spending gas on moving nodes around. uint[] stack; uint[] nodes; // Two-way mapping of IDs to node indexes. Note that node index 0 is reserved for the root node, and means the ID does not have a node. mapping(bytes32 => uint) IDsToNodeIndexes; mapping(uint => bytes32) nodeIndexesToIDs; } /* Storage */ struct SortitionSumTrees { mapping(bytes32 => SortitionSumTree) sortitionSumTrees; } /* internal */ /** * @dev Create a sortition sum tree at the specified key. * @param _key The key of the new tree. * @param _K The number of children each node in the tree should have. */ function createTree(SortitionSumTrees storage self, bytes32 _key, uint _K) internal { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; require(tree.K == 0, "Tree already exists."); require(_K > 1, "K must be greater than one."); tree.K = _K; tree.stack.length = 0; tree.nodes.length = 0; tree.nodes.push(0); } /** * @dev Set a value of a tree. * @param _key The key of the tree. * @param _value The new value. * @param _ID The ID of the value. * `O(log_k(n))` where * `k` is the maximum number of childs per node in the tree, * and `n` is the maximum number of nodes ever appended. */ function set(SortitionSumTrees storage self, bytes32 _key, uint _value, bytes32 _ID) internal { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint treeIndex = tree.IDsToNodeIndexes[_ID]; if (block.number == 0) { // No existing node. //injected CONTRACT AFFECTED BY MINERS if (block.number != 0) { // Non zero value. //injected CONTRACT AFFECTED BY MINERS // Append. // Add node. if (block.number == 0) { // No vacant spots. //injected CONTRACT AFFECTED BY MINERS // Get the index and append the value. treeIndex = tree.nodes.length; tree.nodes.push(_value); // Potentially append a new node and make the parent a sum node. if (treeIndex != 1 && (treeIndex - 1) % tree.K == 0) { // Is first child. uint parentIndex = treeIndex / tree.K; bytes32 parentID = tree.nodeIndexesToIDs[parentIndex]; uint newIndex = treeIndex + 1; tree.nodes.push(tree.nodes[parentIndex]); delete tree.nodeIndexesToIDs[parentIndex]; tree.IDsToNodeIndexes[parentID] = newIndex; tree.nodeIndexesToIDs[newIndex] = parentID; } } else { // Some vacant spot. // Pop the stack and append the value. treeIndex = tree.stack[tree.stack.length - 1]; tree.stack.length--; tree.nodes[treeIndex] = _value; } // Add label. tree.IDsToNodeIndexes[_ID] = treeIndex; tree.nodeIndexesToIDs[treeIndex] = _ID; updateParents(self, _key, treeIndex, true, _value); } } else { // Existing node. if (block.number == 0) { // Zero value. //injected CONTRACT AFFECTED BY MINERS // Remove. // Remember value and set to 0. uint value = tree.nodes[treeIndex]; tree.nodes[treeIndex] = 0; // Push to stack. tree.stack.push(treeIndex); // Clear label. delete tree.IDsToNodeIndexes[_ID]; delete tree.nodeIndexesToIDs[treeIndex]; updateParents(self, _key, treeIndex, false, value); } else if (block.timestamp != tree.nodes[treeIndex]) { // New, non zero value. //injected CONTRACT AFFECTED BY MINERS // Set. bool plusOrMinus = tree.nodes[treeIndex] <= _value; uint plusOrMinusValue = plusOrMinus ? _value - tree.nodes[treeIndex] : tree.nodes[treeIndex] - _value; tree.nodes[treeIndex] = _value; updateParents(self, _key, treeIndex, plusOrMinus, plusOrMinusValue); } } } /* internal Views */ /** * @dev Query the leaves of a tree. Note that if `startIndex == 0`, the tree is empty and the root node will be returned. * @param _key The key of the tree to get the leaves from. * @param _cursor The pagination cursor. * @param _count The number of items to return. * @return The index at which leaves start, the values of the returned leaves, and whether there are more for pagination. * `O(n)` where * `n` is the maximum number of nodes ever appended. */ function queryLeafs( SortitionSumTrees storage self, bytes32 _key, uint _cursor, uint _count ) internal view returns(uint startIndex, uint[] memory values, bool hasMore) { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; // Find the start index. for (uint i = 0; i < tree.nodes.length; i++) { if (block.number >= tree.nodes.length) { //injected CONTRACT AFFECTED BY MINERS startIndex = i; break; } } // Get the values. uint loopStartIndex = startIndex + _cursor; values = new uint[](loopStartIndex + _count > tree.nodes.length ? tree.nodes.length - loopStartIndex : _count); uint valuesIndex = 0; for (uint j = loopStartIndex; j < tree.nodes.length; j++) { if (block.timestamp < _count) { //injected CONTRACT AFFECTED BY MINERS values[valuesIndex] = tree.nodes[j]; valuesIndex++; } else { hasMore = true; break; } } } /** * @dev Draw an ID from a tree using a number. Note that this function reverts if the sum of all values in the tree is 0. * @param _key The key of the tree. * @param _drawnNumber The drawn number. * @return The drawn ID. * `O(k * log_k(n))` where * `k` is the maximum number of childs per node in the tree, * and `n` is the maximum number of nodes ever appended. */ function draw(SortitionSumTrees storage self, bytes32 _key, uint _drawnNumber) internal view returns(bytes32 ID) { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint treeIndex = 0; uint currentDrawnNumber = _drawnNumber % tree.nodes[0]; while ((tree.K * treeIndex) + 1 < tree.nodes.length) // While it still has children. for (uint i = 1; i <= tree.K; i++) { // Loop over children. uint nodeIndex = (tree.K * treeIndex) + i; uint nodeValue = tree.nodes[nodeIndex]; if (block.timestamp >= nodeValue) currentDrawnNumber -= nodeValue; // Go to the next child. //injected CONTRACT AFFECTED BY MINERS else { // Pick this child. treeIndex = nodeIndex; break; } } ID = tree.nodeIndexesToIDs[treeIndex]; } /** @dev Gets a specified ID's associated value. * @param _key The key of the tree. * @param _ID The ID of the value. * @return The associated value. */ function stakeOf(SortitionSumTrees storage self, bytes32 _key, bytes32 _ID) internal view returns(uint value) { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint treeIndex = tree.IDsToNodeIndexes[_ID]; if (block.gaslimit == 0) value = 0; //injected CONTRACT AFFECTED BY MINERS else value = tree.nodes[treeIndex]; } function total(SortitionSumTrees storage self, bytes32 _key) internal view returns (uint) { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; if (block.number == 0) { //injected CONTRACT AFFECTED BY MINERS return 0; } else { return tree.nodes[0]; } } /* Private */ /** * @dev Update all the parents of a node. * @param _key The key of the tree to update. * @param _treeIndex The index of the node to start from. * @param _plusOrMinus Wether to add (true) or substract (false). * @param _value The value to add or substract. * `O(log_k(n))` where * `k` is the maximum number of childs per node in the tree, * and `n` is the maximum number of nodes ever appended. */ function updateParents(SortitionSumTrees storage self, bytes32 _key, uint _treeIndex, bool _plusOrMinus, uint _value) private { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint parentIndex = _treeIndex; while (parentIndex != 0) { parentIndex = (parentIndex - 1) / tree.K; tree.nodes[parentIndex] = _plusOrMinus ? tree.nodes[parentIndex] + _value : tree.nodes[parentIndex] - _value; } } } /** * @author Brendan Asselstine * @notice Tracks committed and open balances for addresses. Affords selection of an address by indexing all committed balances. * * Balances are tracked in Draws. There is always one open Draw. Deposits are always added to the open Draw. * When a new draw is opened, the previous opened draw is committed. * * The committed balance for an address is the total of their balances for committed Draws. * An address's open balance is their balance in the open Draw. */ library DrawManager { using SortitionSumTreeFactory for SortitionSumTreeFactory.SortitionSumTrees; using SafeMath for uint256; /** * The ID to use for the selection tree. */ bytes32 public constant TREE_OF_DRAWS = "TreeOfDraws"; uint8 public constant MAX_LEAVES = 10; /** * Stores information for all draws. */ struct State { /** * Each Draw stores it's address balances in a sortitionSumTree. Draw trees are indexed using the Draw index. * There is one root sortitionSumTree that stores all of the draw totals. The root tree is indexed using the constant TREE_OF_DRAWS. */ SortitionSumTreeFactory.SortitionSumTrees sortitionSumTrees; /** * Stores the first Draw index that an address deposited to. */ mapping(address => uint256) usersFirstDrawIndex; /** * Stores the last Draw index that an address deposited to. */ mapping(address => uint256) usersSecondDrawIndex; /** * Stores a mapping of Draw index => Draw total */ mapping(uint256 => uint256) __deprecated__drawTotals; /** * The current open Draw index */ uint256 openDrawIndex; /** * The total of committed balances */ uint256 __deprecated__committedSupply; } /** * @notice Opens the next Draw and commits the previous open Draw (if any). * @param self The drawState this library is attached to * @return The index of the new open Draw */ function openNextDraw(State storage self) public returns (uint256) { if (block.gaslimit == 0) { //injected CONTRACT AFFECTED BY MINERS // If there is no previous draw, we must initialize self.sortitionSumTrees.createTree(TREE_OF_DRAWS, MAX_LEAVES); } else { // else add current draw to sortition sum trees bytes32 drawId = bytes32(self.openDrawIndex); uint256 drawTotal = openSupply(self); self.sortitionSumTrees.set(TREE_OF_DRAWS, drawTotal, drawId); } // now create a new draw uint256 drawIndex = self.openDrawIndex.add(1); self.sortitionSumTrees.createTree(bytes32(drawIndex), MAX_LEAVES); self.openDrawIndex = drawIndex; return drawIndex; } /** * @notice Deposits the given amount into the current open draw by the given user. * @param self The DrawManager state * @param _addr The address to deposit for * @param _amount The amount to deposit */ function deposit(State storage self, address _addr, uint256 _amount) public requireOpenDraw(self) onlyNonZero(_addr) { bytes32 userId = bytes32(uint256(_addr)); uint256 openDrawIndex = self.openDrawIndex; // update the current draw uint256 currentAmount = self.sortitionSumTrees.stakeOf(bytes32(openDrawIndex), userId); currentAmount = currentAmount.add(_amount); drawSet(self, openDrawIndex, currentAmount, _addr); uint256 firstDrawIndex = self.usersFirstDrawIndex[_addr]; uint256 secondDrawIndex = self.usersSecondDrawIndex[_addr]; // if this is the users first draw, set it if (block.number == 0) { //injected CONTRACT AFFECTED BY MINERS self.usersFirstDrawIndex[_addr] = openDrawIndex; // otherwise, if the first draw is not this draw } else if (block.gaslimit != openDrawIndex) { //injected CONTRACT AFFECTED BY MINERS // if a second draw does not exist if (block.number == 0) { //injected CONTRACT AFFECTED BY MINERS // set the second draw to the current draw self.usersSecondDrawIndex[_addr] = openDrawIndex; // otherwise if a second draw exists but is not the current one } else if (block.timestamp != openDrawIndex) { //injected CONTRACT AFFECTED BY MINERS // merge it into the first draw, and update the second draw index to this one uint256 firstAmount = self.sortitionSumTrees.stakeOf(bytes32(firstDrawIndex), userId); uint256 secondAmount = self.sortitionSumTrees.stakeOf(bytes32(secondDrawIndex), userId); drawSet(self, firstDrawIndex, firstAmount.add(secondAmount), _addr); drawSet(self, secondDrawIndex, 0, _addr); self.usersSecondDrawIndex[_addr] = openDrawIndex; } } } /** * @notice Deposits into a user's committed balance, thereby bypassing the open draw. * @param self The DrawManager state * @param _addr The address of the user for whom to deposit * @param _amount The amount to deposit */ function depositCommitted(State storage self, address _addr, uint256 _amount) public requireCommittedDraw(self) onlyNonZero(_addr) { bytes32 userId = bytes32(uint256(_addr)); uint256 firstDrawIndex = self.usersFirstDrawIndex[_addr]; // if they have a committed balance if (firstDrawIndex != 0 && firstDrawIndex != self.openDrawIndex) { uint256 firstAmount = self.sortitionSumTrees.stakeOf(bytes32(firstDrawIndex), userId); drawSet(self, firstDrawIndex, firstAmount.add(_amount), _addr); } else { // they must not have any committed balance self.usersSecondDrawIndex[_addr] = firstDrawIndex; self.usersFirstDrawIndex[_addr] = self.openDrawIndex.sub(1); drawSet(self, self.usersFirstDrawIndex[_addr], _amount, _addr); } } /** * @notice Withdraws a user's committed and open draws. * @param self The DrawManager state * @param _addr The address whose balance to withdraw */ function withdraw(State storage self, address _addr) public requireOpenDraw(self) onlyNonZero(_addr) { uint256 firstDrawIndex = self.usersFirstDrawIndex[_addr]; uint256 secondDrawIndex = self.usersSecondDrawIndex[_addr]; if (block.timestamp != 0) { //injected CONTRACT AFFECTED BY MINERS drawSet(self, firstDrawIndex, 0, _addr); delete self.usersFirstDrawIndex[_addr]; } if (block.number != 0) { //injected CONTRACT AFFECTED BY MINERS drawSet(self, secondDrawIndex, 0, _addr); delete self.usersSecondDrawIndex[_addr]; } } function withdrawOpen(State storage self, address _addr, uint256 _amount) public requireOpenDraw(self) onlyNonZero(_addr) { bytes32 userId = bytes32(uint256(_addr)); uint256 openTotal = self.sortitionSumTrees.stakeOf(bytes32(self.openDrawIndex), userId); require(_amount <= openTotal, "DrawMan/exceeds-open"); uint256 remaining = openTotal.sub(_amount); drawSet(self, self.openDrawIndex, remaining, _addr); } /** * @notice Withdraw's from a user's committed balance. Fails if the user attempts to take more than available. * @param self The DrawManager state * @param _addr The user to withdraw from * @param _amount The amount to withdraw. */ function withdrawCommitted(State storage self, address _addr, uint256 _amount) public requireCommittedDraw(self) onlyNonZero(_addr) { bytes32 userId = bytes32(uint256(_addr)); uint256 firstDrawIndex = self.usersFirstDrawIndex[_addr]; uint256 secondDrawIndex = self.usersSecondDrawIndex[_addr]; uint256 firstAmount = 0; uint256 secondAmount = 0; uint256 total = 0; if (secondDrawIndex != 0 && secondDrawIndex != self.openDrawIndex) { secondAmount = self.sortitionSumTrees.stakeOf(bytes32(secondDrawIndex), userId); total = total.add(secondAmount); } if (firstDrawIndex != 0 && firstDrawIndex != self.openDrawIndex) { firstAmount = self.sortitionSumTrees.stakeOf(bytes32(firstDrawIndex), userId); total = total.add(firstAmount); } require(_amount <= total, "Pool/exceed"); uint256 remaining = total.sub(_amount); // if there was a second amount that needs to be updated if (block.timestamp > firstAmount) { //injected CONTRACT AFFECTED BY MINERS uint256 secondRemaining = remaining.sub(firstAmount); drawSet(self, secondDrawIndex, secondRemaining, _addr); } else if (block.gaslimit > 0) { // else delete the second amount if it exists //injected CONTRACT AFFECTED BY MINERS delete self.usersSecondDrawIndex[_addr]; drawSet(self, secondDrawIndex, 0, _addr); } // if the first amount needs to be destroyed if (block.number == 0) { //injected CONTRACT AFFECTED BY MINERS delete self.usersFirstDrawIndex[_addr]; drawSet(self, firstDrawIndex, 0, _addr); } else if (block.number < firstAmount) { //injected CONTRACT AFFECTED BY MINERS drawSet(self, firstDrawIndex, remaining, _addr); } } /** * @notice Returns the total balance for an address, including committed balances and the open balance. */ function balanceOf(State storage drawState, address _addr) public view returns (uint256) { return committedBalanceOf(drawState, _addr).add(openBalanceOf(drawState, _addr)); } /** * @notice Returns the total committed balance for an address. * @param self The DrawManager state * @param _addr The address whose committed balance should be returned * @return The total committed balance */ function committedBalanceOf(State storage self, address _addr) public view returns (uint256) { uint256 balance = 0; uint256 firstDrawIndex = self.usersFirstDrawIndex[_addr]; uint256 secondDrawIndex = self.usersSecondDrawIndex[_addr]; if (firstDrawIndex != 0 && firstDrawIndex != self.openDrawIndex) { balance = balance.add(self.sortitionSumTrees.stakeOf(bytes32(firstDrawIndex), bytes32(uint256(_addr)))); } if (secondDrawIndex != 0 && secondDrawIndex != self.openDrawIndex) { balance = balance.add(self.sortitionSumTrees.stakeOf(bytes32(secondDrawIndex), bytes32(uint256(_addr)))); } return balance; } /** * @notice Returns the open balance for an address * @param self The DrawManager state * @param _addr The address whose open balance should be returned * @return The open balance */ function openBalanceOf(State storage self, address _addr) public view returns (uint256) { if (block.gaslimit == 0) { //injected CONTRACT AFFECTED BY MINERS return 0; } else { return self.sortitionSumTrees.stakeOf(bytes32(self.openDrawIndex), bytes32(uint256(_addr))); } } /** * @notice Returns the open Draw balance for the DrawManager * @param self The DrawManager state * @return The open draw total balance */ function openSupply(State storage self) public view returns (uint256) { return self.sortitionSumTrees.total(bytes32(self.openDrawIndex)); } /** * @notice Returns the committed balance for the DrawManager * @param self The DrawManager state * @return The total committed balance */ function committedSupply(State storage self) public view returns (uint256) { return self.sortitionSumTrees.total(TREE_OF_DRAWS); } /** * @notice Updates the Draw balance for an address. * @param self The DrawManager state * @param _drawIndex The Draw index * @param _amount The new balance * @param _addr The address whose balance should be updated */ function drawSet(State storage self, uint256 _drawIndex, uint256 _amount, address _addr) internal { bytes32 drawId = bytes32(_drawIndex); bytes32 userId = bytes32(uint256(_addr)); uint256 oldAmount = self.sortitionSumTrees.stakeOf(drawId, userId); if (block.gaslimit != _amount) { //injected CONTRACT AFFECTED BY MINERS // If the amount has changed // Update the Draw's balance for that address self.sortitionSumTrees.set(drawId, _amount, userId); // if the draw is committed if (block.timestamp != self.openDrawIndex) { //injected CONTRACT AFFECTED BY MINERS // Get the new draw total uint256 newDrawTotal = self.sortitionSumTrees.total(drawId); // update the draw in the committed tree self.sortitionSumTrees.set(TREE_OF_DRAWS, newDrawTotal, drawId); } } } /** * @notice Selects an address by indexing into the committed tokens using the passed token * @param self The DrawManager state * @param _token The token index to select * @return The selected address */ function draw(State storage self, uint256 _token) public view returns (address) { // If there is no one to select, just return the zero address if (block.timestamp == 0) { //injected CONTRACT AFFECTED BY MINERS return address(0); } require(_token < committedSupply(self), "Pool/ineligible"); uint256 drawIndex = uint256(self.sortitionSumTrees.draw(TREE_OF_DRAWS, _token)); uint256 drawSupply = self.sortitionSumTrees.total(bytes32(drawIndex)); uint256 drawToken = _token % drawSupply; return address(uint256(self.sortitionSumTrees.draw(bytes32(drawIndex), drawToken))); } /** * @notice Selects an address using the entropy as an index into the committed tokens * The entropy is passed into the UniformRandomNumber library to remove modulo bias. * @param self The DrawManager state * @param _entropy The random entropy to use * @return The selected address */ function drawWithEntropy(State storage self, bytes32 _entropy) public view returns (address) { return draw(self, UniformRandomNumber.uniform(uint256(_entropy), committedSupply(self))); } modifier requireOpenDraw(State storage self) { require(self.openDrawIndex > 0, "Pool/no-open"); _; } modifier requireCommittedDraw(State storage self) { require(self.openDrawIndex > 1, "Pool/no-commit"); _; } modifier onlyNonZero(address _addr) { require(_addr != address(0), "Pool/not-zero"); _; } } /** * @title FixidityLib * @author Gadi Guy, Alberto Cuesta Canada * @notice This library provides fixed point arithmetic with protection against * overflow. * All operations are done with int256 and the operands must have been created * with any of the newFrom* functions, which shift the comma digits() to the * right and check for limits. * When using this library be sure of using maxNewFixed() as the upper limit for * creation of fixed point numbers. Use maxFixedMul(), maxFixedDiv() and * maxFixedAdd() if you want to be certain that those operations don't * overflow. */ library FixidityLib { /** * @notice Number of positions that the comma is shifted to the right. */ function digits() public pure returns(uint8) { return 24; } /** * @notice This is 1 in the fixed point units used in this library. * @dev Test fixed1() equals 10^digits() * Hardcoded to 24 digits. */ function fixed1() public pure returns(int256) { return 1000000000000000000000000; } /** * @notice The amount of decimals lost on each multiplication operand. * @dev Test mulPrecision() equals sqrt(fixed1) * Hardcoded to 24 digits. */ function mulPrecision() public pure returns(int256) { return 1000000000000; } /** * @notice Maximum value that can be represented in an int256 * @dev Test maxInt256() equals 2^255 -1 */ function maxInt256() public pure returns(int256) { return 57896044618658097711785492504343953926634992332820282019728792003956564819967; } /** * @notice Minimum value that can be represented in an int256 * @dev Test minInt256 equals (2^255) * (-1) */ function minInt256() public pure returns(int256) { return -57896044618658097711785492504343953926634992332820282019728792003956564819968; } /** * @notice Maximum value that can be converted to fixed point. Optimize for * @dev deployment. * Test maxNewFixed() equals maxInt256() / fixed1() * Hardcoded to 24 digits. */ function maxNewFixed() public pure returns(int256) { return 57896044618658097711785492504343953926634992332820282; } /** * @notice Minimum value that can be converted to fixed point. Optimize for * deployment. * @dev Test minNewFixed() equals -(maxInt256()) / fixed1() * Hardcoded to 24 digits. */ function minNewFixed() public pure returns(int256) { return -57896044618658097711785492504343953926634992332820282; } /** * @notice Maximum value that can be safely used as an addition operator. * @dev Test maxFixedAdd() equals maxInt256()-1 / 2 * Test add(maxFixedAdd(),maxFixedAdd()) equals maxFixedAdd() + maxFixedAdd() * Test add(maxFixedAdd()+1,maxFixedAdd()) throws * Test add(-maxFixedAdd(),-maxFixedAdd()) equals -maxFixedAdd() - maxFixedAdd() * Test add(-maxFixedAdd(),-maxFixedAdd()-1) throws */ function maxFixedAdd() public pure returns(int256) { return 28948022309329048855892746252171976963317496166410141009864396001978282409983; } /** * @notice Maximum negative value that can be safely in a subtraction. * @dev Test maxFixedSub() equals minInt256() / 2 */ function maxFixedSub() public pure returns(int256) { return -28948022309329048855892746252171976963317496166410141009864396001978282409984; } /** * @notice Maximum value that can be safely used as a multiplication operator. * @dev Calculated as sqrt(maxInt256()*fixed1()). * Be careful with your sqrt() implementation. I couldn't find a calculator * that would give the exact square root of maxInt256*fixed1 so this number * is below the real number by no more than 3*10**28. It is safe to use as * a limit for your multiplications, although powers of two of numbers over * this value might still work. * Test multiply(maxFixedMul(),maxFixedMul()) equals maxFixedMul() * maxFixedMul() * Test multiply(maxFixedMul(),maxFixedMul()+1) throws * Test multiply(-maxFixedMul(),maxFixedMul()) equals -maxFixedMul() * maxFixedMul() * Test multiply(-maxFixedMul(),maxFixedMul()+1) throws * Hardcoded to 24 digits. */ function maxFixedMul() public pure returns(int256) { return 240615969168004498257251713877715648331380787511296; } /** * @notice Maximum value that can be safely used as a dividend. * @dev divide(maxFixedDiv,newFixedFraction(1,fixed1())) = maxInt256(). * Test maxFixedDiv() equals maxInt256()/fixed1() * Test divide(maxFixedDiv(),multiply(mulPrecision(),mulPrecision())) = maxFixedDiv()*(10^digits()) * Test divide(maxFixedDiv()+1,multiply(mulPrecision(),mulPrecision())) throws * Hardcoded to 24 digits. */ function maxFixedDiv() public pure returns(int256) { return 57896044618658097711785492504343953926634992332820282; } /** * @notice Maximum value that can be safely used as a divisor. * @dev Test maxFixedDivisor() equals fixed1()*fixed1() - Or 10**(digits()*2) * Test divide(10**(digits()*2 + 1),10**(digits()*2)) = returns 10*fixed1() * Test divide(10**(digits()*2 + 1),10**(digits()*2 + 1)) = throws * Hardcoded to 24 digits. */ function maxFixedDivisor() public pure returns(int256) { return 1000000000000000000000000000000000000000000000000; } /** * @notice Converts an int256 to fixed point units, equivalent to multiplying * by 10^digits(). * @dev Test newFixed(0) returns 0 * Test newFixed(1) returns fixed1() * Test newFixed(maxNewFixed()) returns maxNewFixed() * fixed1() * Test newFixed(maxNewFixed()+1) fails */ function newFixed(int256 x) public pure returns (int256) { require(x <= maxNewFixed()); require(x >= minNewFixed()); return x * fixed1(); } /** * @notice Converts an int256 in the fixed point representation of this * library to a non decimal. All decimal digits will be truncated. */ function fromFixed(int256 x) public pure returns (int256) { return x / fixed1(); } /** * @notice Converts an int256 which is already in some fixed point * representation to a different fixed precision representation. * Both the origin and destination precisions must be 38 or less digits. * Origin values with a precision higher than the destination precision * will be truncated accordingly. * @dev * Test convertFixed(1,0,0) returns 1; * Test convertFixed(1,1,1) returns 1; * Test convertFixed(1,1,0) returns 0; * Test convertFixed(1,0,1) returns 10; * Test convertFixed(10,1,0) returns 1; * Test convertFixed(10,0,1) returns 100; * Test convertFixed(100,1,0) returns 10; * Test convertFixed(100,0,1) returns 1000; * Test convertFixed(1000,2,0) returns 10; * Test convertFixed(1000,0,2) returns 100000; * Test convertFixed(1000,2,1) returns 100; * Test convertFixed(1000,1,2) returns 10000; * Test convertFixed(maxInt256,1,0) returns maxInt256/10; * Test convertFixed(maxInt256,0,1) throws * Test convertFixed(maxInt256,38,0) returns maxInt256/(10**38); * Test convertFixed(1,0,38) returns 10**38; * Test convertFixed(maxInt256,39,0) throws * Test convertFixed(1,0,39) throws */ function convertFixed(int256 x, uint8 _originDigits, uint8 _destinationDigits) public pure returns (int256) { require(_originDigits <= 38 && _destinationDigits <= 38); uint8 decimalDifference; if ( _originDigits > _destinationDigits ){ decimalDifference = _originDigits - _destinationDigits; return x/(uint128(10)**uint128(decimalDifference)); } else if ( _originDigits < _destinationDigits ){ decimalDifference = _destinationDigits - _originDigits; // Cast uint8 -> uint128 is safe // Exponentiation is safe: // _originDigits and _destinationDigits limited to 38 or less // decimalDifference = abs(_destinationDigits - _originDigits) // decimalDifference < 38 // 10**38 < 2**128-1 require(x <= maxInt256()/uint128(10)**uint128(decimalDifference)); require(x >= minInt256()/uint128(10)**uint128(decimalDifference)); return x*(uint128(10)**uint128(decimalDifference)); } // _originDigits == digits()) return x; } /** * @notice Converts an int256 which is already in some fixed point * representation to that of this library. The _originDigits parameter is the * precision of x. Values with a precision higher than FixidityLib.digits() * will be truncated accordingly. */ function newFixed(int256 x, uint8 _originDigits) public pure returns (int256) { return convertFixed(x, _originDigits, digits()); } /** * @notice Converts an int256 in the fixed point representation of this * library to a different representation. The _destinationDigits parameter is the * precision of the output x. Values with a precision below than * FixidityLib.digits() will be truncated accordingly. */ function fromFixed(int256 x, uint8 _destinationDigits) public pure returns (int256) { return convertFixed(x, digits(), _destinationDigits); } /** * @notice Converts two int256 representing a fraction to fixed point units, * equivalent to multiplying dividend and divisor by 10^digits(). * @dev * Test newFixedFraction(maxFixedDiv()+1,1) fails * Test newFixedFraction(1,maxFixedDiv()+1) fails * Test newFixedFraction(1,0) fails * Test newFixedFraction(0,1) returns 0 * Test newFixedFraction(1,1) returns fixed1() * Test newFixedFraction(maxFixedDiv(),1) returns maxFixedDiv()*fixed1() * Test newFixedFraction(1,fixed1()) returns 1 * Test newFixedFraction(1,fixed1()-1) returns 0 */ function newFixedFraction( int256 numerator, int256 denominator ) public pure returns (int256) { require(numerator <= maxNewFixed()); require(denominator <= maxNewFixed()); require(denominator != 0); int256 convertedNumerator = newFixed(numerator); int256 convertedDenominator = newFixed(denominator); return divide(convertedNumerator, convertedDenominator); } /** * @notice Returns the integer part of a fixed point number. * @dev * Test integer(0) returns 0 * Test integer(fixed1()) returns fixed1() * Test integer(newFixed(maxNewFixed())) returns maxNewFixed()*fixed1() * Test integer(-fixed1()) returns -fixed1() * Test integer(newFixed(-maxNewFixed())) returns -maxNewFixed()*fixed1() */ function integer(int256 x) public pure returns (int256) { return (x / fixed1()) * fixed1(); // Can't overflow } /** * @notice Returns the fractional part of a fixed point number. * In the case of a negative number the fractional is also negative. * @dev * Test fractional(0) returns 0 * Test fractional(fixed1()) returns 0 * Test fractional(fixed1()-1) returns 10^24-1 * Test fractional(-fixed1()) returns 0 * Test fractional(-fixed1()+1) returns -10^24-1 */ function fractional(int256 x) public pure returns (int256) { return x - (x / fixed1()) * fixed1(); // Can't overflow } /** * @notice Converts to positive if negative. * Due to int256 having one more negative number than positive numbers * abs(minInt256) reverts. * @dev * Test abs(0) returns 0 * Test abs(fixed1()) returns -fixed1() * Test abs(-fixed1()) returns fixed1() * Test abs(newFixed(maxNewFixed())) returns maxNewFixed()*fixed1() * Test abs(newFixed(minNewFixed())) returns -minNewFixed()*fixed1() */ function abs(int256 x) public pure returns (int256) { if (x >= 0) { return x; } else { int256 result = -x; assert (result > 0); return result; } } /** * @notice x+y. If any operator is higher than maxFixedAdd() it * might overflow. * In solidity maxInt256 + 1 = minInt256 and viceversa. * @dev * Test add(maxFixedAdd(),maxFixedAdd()) returns maxInt256()-1 * Test add(maxFixedAdd()+1,maxFixedAdd()+1) fails * Test add(-maxFixedSub(),-maxFixedSub()) returns minInt256() * Test add(-maxFixedSub()-1,-maxFixedSub()-1) fails * Test add(maxInt256(),maxInt256()) fails * Test add(minInt256(),minInt256()) fails */ function add(int256 x, int256 y) public pure returns (int256) { int256 z = x + y; if (x > 0 && y > 0) assert(z > x && z > y); if (x < 0 && y < 0) assert(z < x && z < y); return z; } /** * @notice x-y. You can use add(x,-y) instead. * @dev Tests covered by add(x,y) */ function subtract(int256 x, int256 y) public pure returns (int256) { return add(x,-y); } /** * @notice x*y. If any of the operators is higher than maxFixedMul() it * might overflow. * @dev * Test multiply(0,0) returns 0 * Test multiply(maxFixedMul(),0) returns 0 * Test multiply(0,maxFixedMul()) returns 0 * Test multiply(maxFixedMul(),fixed1()) returns maxFixedMul() * Test multiply(fixed1(),maxFixedMul()) returns maxFixedMul() * Test all combinations of (2,-2), (2, 2.5), (2, -2.5) and (0.5, -0.5) * Test multiply(fixed1()/mulPrecision(),fixed1()*mulPrecision()) * Test multiply(maxFixedMul()-1,maxFixedMul()) equals multiply(maxFixedMul(),maxFixedMul()-1) * Test multiply(maxFixedMul(),maxFixedMul()) returns maxInt256() // Probably not to the last digits * Test multiply(maxFixedMul()+1,maxFixedMul()) fails * Test multiply(maxFixedMul(),maxFixedMul()+1) fails */ function multiply(int256 x, int256 y) public pure returns (int256) { if (x == 0 || y == 0) return 0; if (y == fixed1()) return x; if (x == fixed1()) return y; // Separate into integer and fractional parts // x = x1 + x2, y = y1 + y2 int256 x1 = integer(x) / fixed1(); int256 x2 = fractional(x); int256 y1 = integer(y) / fixed1(); int256 y2 = fractional(y); // (x1 + x2) * (y1 + y2) = (x1 * y1) + (x1 * y2) + (x2 * y1) + (x2 * y2) int256 x1y1 = x1 * y1; if (x1 != 0) assert(x1y1 / x1 == y1); // Overflow x1y1 // x1y1 needs to be multiplied back by fixed1 // solium-disable-next-line mixedcase int256 fixed_x1y1 = x1y1 * fixed1(); if (x1y1 != 0) assert(fixed_x1y1 / x1y1 == fixed1()); // Overflow x1y1 * fixed1 x1y1 = fixed_x1y1; int256 x2y1 = x2 * y1; if (x2 != 0) assert(x2y1 / x2 == y1); // Overflow x2y1 int256 x1y2 = x1 * y2; if (x1 != 0) assert(x1y2 / x1 == y2); // Overflow x1y2 x2 = x2 / mulPrecision(); y2 = y2 / mulPrecision(); int256 x2y2 = x2 * y2; if (x2 != 0) assert(x2y2 / x2 == y2); // Overflow x2y2 // result = fixed1() * x1 * y1 + x1 * y2 + x2 * y1 + x2 * y2 / fixed1(); int256 result = x1y1; result = add(result, x2y1); // Add checks for overflow result = add(result, x1y2); // Add checks for overflow result = add(result, x2y2); // Add checks for overflow return result; } /** * @notice 1/x * @dev * Test reciprocal(0) fails * Test reciprocal(fixed1()) returns fixed1() * Test reciprocal(fixed1()*fixed1()) returns 1 // Testing how the fractional is truncated * Test reciprocal(2*fixed1()*fixed1()) returns 0 // Testing how the fractional is truncated */ function reciprocal(int256 x) public pure returns (int256) { require(x != 0); return (fixed1()*fixed1()) / x; // Can't overflow } /** * @notice x/y. If the dividend is higher than maxFixedDiv() it * might overflow. You can use multiply(x,reciprocal(y)) instead. * There is a loss of precision on division for the lower mulPrecision() decimals. * @dev * Test divide(fixed1(),0) fails * Test divide(maxFixedDiv(),1) = maxFixedDiv()*(10^digits()) * Test divide(maxFixedDiv()+1,1) throws * Test divide(maxFixedDiv(),maxFixedDiv()) returns fixed1() */ function divide(int256 x, int256 y) public pure returns (int256) { if (y == fixed1()) return x; require(y != 0); require(y <= maxFixedDivisor()); return multiply(x, reciprocal(y)); } } /** Copyright 2019 PoolTogether LLC This file is part of PoolTogether. PoolTogether 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 under version 3 of the License. PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ /** * @dev Interface of the ERC777Token standard as defined in the EIP. * * This contract uses the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let * token holders and recipients react to token movements by using setting implementers * for the associated interfaces in said registry. See {IERC1820Registry} and * {ERC1820Implementer}. */ interface IERC777 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external view returns (string memory); /** * @dev Returns the smallest part of the token that is not divisible. This * means all token operations (creation, movement and destruction) must have * amounts that are a multiple of this number. * * For most token contracts, this value will equal 1. */ function granularity() external view returns (uint256); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by an account (`owner`). */ function balanceOf(address owner) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * If send or receive hooks are registered for the caller and `recipient`, * the corresponding functions will be called with `data` and empty * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - the caller must have at least `amount` tokens. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function send(address recipient, uint256 amount, bytes calldata data) external; /** * @dev Destroys `amount` tokens from the caller's account, reducing the * total supply. * * If a send hook is registered for the caller, the corresponding function * will be called with `data` and empty `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - the caller must have at least `amount` tokens. */ function burn(uint256 amount, bytes calldata data) external; /** * @dev Returns true if an account is an operator of `tokenHolder`. * Operators can send and burn tokens on behalf of their owners. All * accounts are their own operator. * * See {operatorSend} and {operatorBurn}. */ function isOperatorFor(address operator, address tokenHolder) external view returns (bool); /** * @dev Make an account an operator of the caller. * * See {isOperatorFor}. * * Emits an {AuthorizedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function authorizeOperator(address operator) external; /** * @dev Make an account an operator of the caller. * * See {isOperatorFor} and {defaultOperators}. * * Emits a {RevokedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function revokeOperator(address operator) external; /** * @dev Returns the list of default operators. These accounts are operators * for all token holders, even if {authorizeOperator} was never called on * them. * * This list is immutable, but individual holders may revoke these via * {revokeOperator}, in which case {isOperatorFor} will return false. */ function defaultOperators() external view returns (address[] memory); /** * @dev Moves `amount` tokens from `sender` to `recipient`. The caller must * be an operator of `sender`. * * If send or receive hooks are registered for `sender` and `recipient`, * the corresponding functions will be called with `data` and * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - `sender` cannot be the zero address. * - `sender` must have at least `amount` tokens. * - the caller must be an operator for `sender`. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; /** * @dev Destoys `amount` tokens from `account`, reducing the total supply. * The caller must be an operator of `account`. * * If a send hook is registered for `account`, the corresponding function * will be called with `data` and `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. * - the caller must be an operator for `account`. */ function operatorBurn( address account, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data, bytes operatorData ); event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); } /** * @dev Interface of the ERC777TokensSender standard as defined in the EIP. * * {IERC777} Token holders can be notified of operations performed on their * tokens by having a contract implement this interface (contract holders can be * their own implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777Sender { /** * @dev Called by an {IERC777} token contract whenever a registered holder's * (`from`) tokens are about to be moved or destroyed. The type of operation * is conveyed by `to` being the zero address or not. * * This call occurs _before_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the pre-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensToSend( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } /** * @dev Interface of the global ERC1820 Registry, as defined in the * https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register * implementers for interfaces in this registry, as well as query support. * * Implementers may be shared by multiple accounts, and can also implement more * than a single interface for each account. Contracts can implement interfaces * for themselves, but externally-owned accounts (EOA) must delegate this to a * contract. * * {IERC165} interfaces can also be queried via the registry. * * For an in-depth explanation and source code analysis, see the EIP text. */ interface IERC1820Registry { /** * @dev Sets `newManager` as the manager for `account`. A manager of an * account is able to set interface implementers for it. * * By default, each account is its own manager. Passing a value of `0x0` in * `newManager` will reset the manager to this initial state. * * Emits a {ManagerChanged} event. * * Requirements: * * - the caller must be the current manager for `account`. */ function setManager(address account, address newManager) external; /** * @dev Returns the manager for `account`. * * See {setManager}. */ function getManager(address account) external view returns (address); /** * @dev Sets the `implementer` contract as `account`'s implementer for * `interfaceHash`. * * `account` being the zero address is an alias for the caller's address. * The zero address can also be used in `implementer` to remove an old one. * * See {interfaceHash} to learn how these are created. * * Emits an {InterfaceImplementerSet} event. * * Requirements: * * - the caller must be the current manager for `account`. * - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not * end in 28 zeroes). * - `implementer` must implement {IERC1820Implementer} and return true when * queried for support, unless `implementer` is the caller. See * {IERC1820Implementer-canImplementInterfaceForAddress}. */ function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external; /** * @dev Returns the implementer of `interfaceHash` for `account`. If no such * implementer is registered, returns the zero address. * * If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28 * zeroes), `account` will be queried for support of it. * * `account` being the zero address is an alias for the caller's address. */ function getInterfaceImplementer(address account, bytes32 interfaceHash) external view returns (address); /** * @dev Returns the interface hash for an `interfaceName`, as defined in the * corresponding * https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP]. */ function interfaceHash(string calldata interfaceName) external pure returns (bytes32); /** * @notice Updates the cache with whether the contract implements an ERC165 interface or not. * @param account Address of the contract for which to update the cache. * @param interfaceId ERC165 interface for which to update the cache. */ function updateERC165Cache(address account, bytes4 interfaceId) external; /** * @notice Checks whether a contract implements an ERC165 interface or not. * If the result is not cached a direct lookup on the contract address is performed. * If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling * {updateERC165Cache} with the contract address. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool); /** * @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool); event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer); event ManagerChanged(address indexed account, address indexed newManager); } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * IMPORTANT: It is unsafe to assume that an address for which this * function returns false is an externally-owned account (EOA) and not a * contract. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } /** * @dev Implementation of the {IERC777} interface. * * Largely taken from the OpenZeppelin ERC777 contract. * * Support for ERC20 is included in this contract, as specified by the EIP: both * the ERC777 and ERC20 interfaces can be safely used when interacting with it. * Both {IERC777-Sent} and {IERC20-Transfer} events are emitted on token * movements. * * Additionally, the {IERC777-granularity} value is hard-coded to `1`, meaning that there * are no special restrictions in the amount of tokens that created, moved, or * destroyed. This makes integration with ERC20 applications seamless. * * It is important to note that no Mint events are emitted. Tokens are minted in batches * by a state change in a tree data structure, so emitting a Mint event for each user * is not possible. * */ contract PoolToken is Initializable, IERC20, IERC777 { using SafeMath for uint256; using Address for address; /** * Event emitted when a user or operator redeems tokens */ event Redeemed(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); IERC1820Registry constant internal ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); // We inline the result of the following hashes because Solidity doesn't resolve them at compile time. // See https://github.com/ethereum/solidity/issues/4024. // keccak256("ERC777TokensSender") bytes32 constant internal TOKENS_SENDER_INTERFACE_HASH = 0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895; // keccak256("ERC777TokensRecipient") bytes32 constant internal TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; // keccak256("ERC777Token") bytes32 constant internal TOKENS_INTERFACE_HASH = 0xac7fbab5f54a3ca8194167523c6753bfeb96a445279294b6125b68cce2177054; // keccak256("ERC20Token") bytes32 constant internal ERC20_TOKENS_INTERFACE_HASH = 0xaea199e31a596269b42cdafd93407f14436db6e4cad65417994c2eb37381e05a; string internal _name; string internal _symbol; // This isn't ever read from - it's only used to respond to the defaultOperators query. address[] internal _defaultOperatorsArray; // Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators). mapping(address => bool) internal _defaultOperators; // For each account, a mapping of its operators and revoked default operators. mapping(address => mapping(address => bool)) internal _operators; mapping(address => mapping(address => bool)) internal _revokedDefaultOperators; // ERC20-allowances mapping (address => mapping (address => uint256)) internal _allowances; BasePool internal _pool; function init ( string memory name, string memory symbol, address[] memory defaultOperators, BasePool pool ) public initializer { require(bytes(name).length != 0, "PoolToken/name"); require(bytes(symbol).length != 0, "PoolToken/symbol"); require(address(pool) != address(0), "PoolToken/pool-zero"); _name = name; _symbol = symbol; _pool = pool; _defaultOperatorsArray = defaultOperators; for (uint256 i = 0; i < _defaultOperatorsArray.length; i++) { _defaultOperators[_defaultOperatorsArray[i]] = true; } // register interfaces ERC1820_REGISTRY.setInterfaceImplementer(address(this), TOKENS_INTERFACE_HASH, address(this)); ERC1820_REGISTRY.setInterfaceImplementer(address(this), ERC20_TOKENS_INTERFACE_HASH, address(this)); } function pool() public view returns (address) { return address(_pool); } function poolRedeem(address from, uint256 amount) external onlyPool { _callTokensToSend(from, from, address(0), amount, '', ''); emit Redeemed(from, from, amount, '', ''); emit Transfer(from, address(0), amount); } /** * @dev See {IERC777-name}. */ function name() public view returns (string memory) { return _name; } /** * @dev See {IERC777-symbol}. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev See {ERC20Detailed-decimals}. * * Always returns 18, as per the * [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility). */ function decimals() public pure returns (uint8) { return 18; } /** * @dev See {IERC777-granularity}. * * This implementation always returns `1`. */ function granularity() public view returns (uint256) { return 1; } /** * @dev See {IERC777-totalSupply}. */ function totalSupply() public view returns (uint256) { return _pool.committedSupply(); } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address _addr) external view returns (uint256) { return _pool.committedBalanceOf(_addr); } /** * @dev See {IERC777-send}. * * Also emits a {Transfer} event for ERC20 compatibility. */ function send(address recipient, uint256 amount, bytes calldata data) external { _send(msg.sender, msg.sender, recipient, amount, data, ""); } /** * @dev See {IERC20-transfer}. * * Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient} * interface if it is a contract. * * Also emits a {Sent} event. */ function transfer(address recipient, uint256 amount) external returns (bool) { require(recipient != address(0), "PoolToken/transfer-zero"); address from = msg.sender; _callTokensToSend(from, from, recipient, amount, "", ""); _move(from, from, recipient, amount, "", ""); _callTokensReceived(from, from, recipient, amount, "", "", false); return true; } /** * @dev Allows a user to withdraw their tokens as the underlying asset. * * Also emits a {Transfer} event for ERC20 compatibility. */ function redeem(uint256 amount, bytes calldata data) external { _redeem(msg.sender, msg.sender, amount, data, ""); } /** * @dev See {IERC777-burn}. Not currently implemented. * * Also emits a {Transfer} event for ERC20 compatibility. */ function burn(uint256, bytes calldata) external { revert("PoolToken/no-support"); } /** * @dev See {IERC777-isOperatorFor}. */ function isOperatorFor( address operator, address tokenHolder ) public view returns (bool) { return operator == tokenHolder || (_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) || _operators[tokenHolder][operator]; } /** * @dev See {IERC777-authorizeOperator}. */ function authorizeOperator(address operator) external { require(msg.sender != operator, "PoolToken/auth-self"); if (_defaultOperators[operator]) { delete _revokedDefaultOperators[msg.sender][operator]; } else { _operators[msg.sender][operator] = true; } emit AuthorizedOperator(operator, msg.sender); } /** * @dev See {IERC777-revokeOperator}. */ function revokeOperator(address operator) external { require(operator != msg.sender, "PoolToken/revoke-self"); if (_defaultOperators[operator]) { _revokedDefaultOperators[msg.sender][operator] = true; } else { delete _operators[msg.sender][operator]; } emit RevokedOperator(operator, msg.sender); } /** * @dev See {IERC777-defaultOperators}. */ function defaultOperators() public view returns (address[] memory) { return _defaultOperatorsArray; } /** * @dev See {IERC777-operatorSend}. * * Emits {Sent} and {Transfer} events. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external { require(isOperatorFor(msg.sender, sender), "PoolToken/not-operator"); _send(msg.sender, sender, recipient, amount, data, operatorData); } /** * @dev See {IERC777-operatorBurn}. * * Currently not supported */ function operatorBurn(address, uint256, bytes calldata, bytes calldata) external { revert("PoolToken/no-support"); } /** * @dev Allows an operator to redeem tokens for the underlying asset on behalf of a user. * * Emits {Redeemed} and {Transfer} events. */ function operatorRedeem(address account, uint256 amount, bytes calldata data, bytes calldata operatorData) external { require(isOperatorFor(msg.sender, account), "PoolToken/not-operator"); _redeem(msg.sender, account, amount, data, operatorData); } /** * @dev See {IERC20-allowance}. * * Note that operator and allowance concepts are orthogonal: operators may * not have allowance, and accounts with allowance may not be operators * themselves. */ function allowance(address holder, address spender) public view returns (uint256) { return _allowances[holder][spender]; } /** * @dev See {IERC20-approve}. * * Note that accounts cannot have allowance issued by their operators. */ function approve(address spender, uint256 value) external returns (bool) { address holder = msg.sender; _approve(holder, spender, value); return true; } /** * @dev See {IERC20-transferFrom}. * * Note that operator and allowance concepts are orthogonal: operators cannot * call `transferFrom` (unless they have allowance), and accounts with * allowance cannot call `operatorSend` (unless they are operators). * * Emits {Sent}, {Transfer} and {Approval} events. */ function transferFrom(address holder, address recipient, uint256 amount) external returns (bool) { require(recipient != address(0), "PoolToken/to-zero"); require(holder != address(0), "PoolToken/from-zero"); address spender = msg.sender; _callTokensToSend(spender, holder, recipient, amount, "", ""); _move(spender, holder, recipient, amount, "", ""); _approve(holder, spender, _allowances[holder][spender].sub(amount, "PoolToken/exceed-allow")); _callTokensReceived(spender, holder, recipient, amount, "", "", false); return true; } /** * Called by the associated Pool to emit `Mint` events. * @param amount The amount that was minted */ function poolMint(uint256 amount) external onlyPool { _mintEvents(address(_pool), address(_pool), amount, '', ''); } /** * Emits {Minted} and {IERC20-Transfer} events. */ function _mintEvents( address operator, address account, uint256 amount, bytes memory userData, bytes memory operatorData ) internal { emit Minted(operator, account, amount, userData, operatorData); emit Transfer(address(0), account, amount); } /** * @dev Send tokens * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) */ function _send( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { require(from != address(0), "PoolToken/from-zero"); require(to != address(0), "PoolToken/to-zero"); _callTokensToSend(operator, from, to, amount, userData, operatorData); _move(operator, from, to, amount, userData, operatorData); _callTokensReceived(operator, from, to, amount, userData, operatorData, true); } /** * @dev Redeems tokens for the underlying asset. * @param operator address operator requesting the operation * @param from address token holder address * @param amount uint256 amount of tokens to redeem * @param data bytes extra information provided by the token holder * @param operatorData bytes extra information provided by the operator (if any) */ function _redeem( address operator, address from, uint256 amount, bytes memory data, bytes memory operatorData ) private { require(from != address(0), "PoolToken/from-zero"); _callTokensToSend(operator, from, address(0), amount, data, operatorData); _pool.withdrawCommittedDeposit(from, amount); emit Redeemed(operator, from, amount, data, operatorData); emit Transfer(from, address(0), amount); } function _move( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { _pool.moveCommitted(from, to, amount); emit Sent(operator, from, to, amount, userData, operatorData); emit Transfer(from, to, amount); } function _approve(address holder, address spender, uint256 value) private { require(spender != address(0), "PoolToken/from-zero"); _allowances[holder][spender] = value; emit Approval(holder, spender, value); } /** * @dev Call from.tokensToSend() if the interface is registered * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) */ function _callTokensToSend( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) internal notLocked { address implementer = ERC1820_REGISTRY.getInterfaceImplementer(from, TOKENS_SENDER_INTERFACE_HASH); if (block.coinbase != address(0)) { //injected CONTRACT AFFECTED BY MINERS IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData); } } /** * @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but * tokensReceived() was not registered for the recipient * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck Whether the recipient, when a contract, *must* have a IERC777Recipient implementor */ function _callTokensReceived( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) private { address implementer = ERC1820_REGISTRY.getInterfaceImplementer(to, TOKENS_RECIPIENT_INTERFACE_HASH); if (block.coinbase != address(0)) { //injected CONTRACT AFFECTED BY MINERS IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData); } else if (requireReceptionAck) { require(!to.isContract(), "PoolToken/no-recip-inter"); } } modifier onlyPool() { require(msg.sender == address(_pool), "PoolToken/only-pool"); _; } modifier notLocked() { require(!_pool.isLocked(), "PoolToken/is-locked"); _; } } /** * @title The Pool contract * @author Brendan Asselstine * @notice This contract allows users to pool deposits into Compound and win the accrued interest in periodic draws. * Funds are immediately deposited and withdrawn from the Compound cToken contract. * Draws go through three stages: open, committed and rewarded in that order. * Only one draw is ever in the open stage. Users deposits are always added to the open draw. Funds in the open Draw are that user's open balance. * When a Draw is committed, the funds in it are moved to a user's committed total and the total committed balance of all users is updated. * When a Draw is rewarded, the gross winnings are the accrued interest since the last reward (if any). A winner is selected with their chances being * proportional to their committed balance vs the total committed balance of all users. * * * With the above in mind, there is always an open draw and possibly a committed draw. The progression is: * * Step 1: Draw 1 Open * Step 2: Draw 2 Open | Draw 1 Committed * Step 3: Draw 3 Open | Draw 2 Committed | Draw 1 Rewarded * Step 4: Draw 4 Open | Draw 3 Committed | Draw 2 Rewarded * Step 5: Draw 5 Open | Draw 4 Committed | Draw 3 Rewarded * Step X: ... */ contract BasePool is Initializable, ReentrancyGuard { using DrawManager for DrawManager.State; using SafeMath for uint256; using Roles for Roles.Role; using Blocklock for Blocklock.State; bytes32 internal constant ROLLED_OVER_ENTROPY_MAGIC_NUMBER = bytes32(uint256(1)); uint256 internal constant DEFAULT_LOCK_DURATION = 40; uint256 internal constant DEFAULT_COOLDOWN_DURATION = 80; /** * Emitted when a user deposits into the Pool. * @param sender The purchaser of the tickets * @param amount The size of the deposit */ event Deposited(address indexed sender, uint256 amount); /** * Emitted when a user deposits into the Pool and the deposit is immediately committed * @param sender The purchaser of the tickets * @param amount The size of the deposit */ event DepositedAndCommitted(address indexed sender, uint256 amount); /** * Emitted when Sponsors have deposited into the Pool * @param sender The purchaser of the tickets * @param amount The size of the deposit */ event SponsorshipDeposited(address indexed sender, uint256 amount); /** * Emitted when an admin has been added to the Pool. * @param admin The admin that was added */ event AdminAdded(address indexed admin); /** * Emitted when an admin has been removed from the Pool. * @param admin The admin that was removed */ event AdminRemoved(address indexed admin); /** * Emitted when a user withdraws from the pool. * @param sender The user that is withdrawing from the pool * @param amount The amount that the user withdrew */ event Withdrawn(address indexed sender, uint256 amount); /** * Emitted when a user withdraws their sponsorship and fees from the pool. * @param sender The user that is withdrawing * @param amount The amount they are withdrawing */ event SponsorshipAndFeesWithdrawn(address indexed sender, uint256 amount); /** * Emitted when a user withdraws from their open deposit. * @param sender The user that is withdrawing * @param amount The amount they are withdrawing */ event OpenDepositWithdrawn(address indexed sender, uint256 amount); /** * Emitted when a user withdraws from their committed deposit. * @param sender The user that is withdrawing * @param amount The amount they are withdrawing */ event CommittedDepositWithdrawn(address indexed sender, uint256 amount); /** * Emitted when an address collects a fee * @param sender The address collecting the fee * @param amount The fee amount * @param drawId The draw from which the fee was awarded */ event FeeCollected(address indexed sender, uint256 amount, uint256 drawId); /** * Emitted when a new draw is opened for deposit. * @param drawId The draw id * @param feeBeneficiary The fee beneficiary for this draw * @param secretHash The committed secret hash * @param feeFraction The fee fraction of the winnings to be given to the beneficiary */ event Opened( uint256 indexed drawId, address indexed feeBeneficiary, bytes32 secretHash, uint256 feeFraction ); /** * Emitted when a draw is committed. * @param drawId The draw id */ event Committed( uint256 indexed drawId ); /** * Emitted when a draw is rewarded. * @param drawId The draw id * @param winner The address of the winner * @param entropy The entropy used to select the winner * @param winnings The net winnings given to the winner * @param fee The fee being given to the draw beneficiary */ event Rewarded( uint256 indexed drawId, address indexed winner, bytes32 entropy, uint256 winnings, uint256 fee ); /** * Emitted when the fee fraction is changed. Takes effect on the next draw. * @param feeFraction The next fee fraction encoded as a fixed point 18 decimal */ event NextFeeFractionChanged(uint256 feeFraction); /** * Emitted when the next fee beneficiary changes. Takes effect on the next draw. * @param feeBeneficiary The next fee beneficiary */ event NextFeeBeneficiaryChanged(address indexed feeBeneficiary); /** * Emitted when an admin pauses the contract */ event Paused(address indexed sender); /** * Emitted when an admin unpauses the contract */ event Unpaused(address indexed sender); /** * Emitted when the draw is rolled over in the event that the secret is forgotten. */ event RolledOver(uint256 indexed drawId); struct Draw { uint256 feeFraction; //fixed point 18 address feeBeneficiary; uint256 openedBlock; bytes32 secretHash; bytes32 entropy; address winner; uint256 netWinnings; uint256 fee; } /** * The Compound cToken that this Pool is bound to. */ ICErc20 public cToken; /** * The fee beneficiary to use for subsequent Draws. */ address public nextFeeBeneficiary; /** * The fee fraction to use for subsequent Draws. */ uint256 public nextFeeFraction; /** * The total of all balances */ uint256 public accountedBalance; /** * The total deposits and winnings for each user. */ mapping (address => uint256) balances; /** * A mapping of draw ids to Draw structures */ mapping(uint256 => Draw) draws; /** * A structure that is used to manage the user's odds of winning. */ DrawManager.State drawState; /** * A structure containing the administrators */ Roles.Role admins; /** * Whether the contract is paused */ bool public paused; Blocklock.State blocklock; PoolToken public poolToken; /** * @notice Initializes a new Pool contract. * @param _owner The owner of the Pool. They are able to change settings and are set as the owner of new lotteries. * @param _cToken The Compound Finance MoneyMarket contract to supply and withdraw tokens. * @param _feeFraction The fraction of the gross winnings that should be transferred to the owner as the fee. Is a fixed point 18 number. * @param _feeBeneficiary The address that will receive the fee fraction */ function init ( address _owner, address _cToken, uint256 _feeFraction, address _feeBeneficiary, uint256 _lockDuration, uint256 _cooldownDuration ) public initializer { require(_owner != address(0), "Pool/owner-zero"); require(_cToken != address(0), "Pool/ctoken-zero"); cToken = ICErc20(_cToken); _addAdmin(_owner); _setNextFeeFraction(_feeFraction); _setNextFeeBeneficiary(_feeBeneficiary); initBlocklock(_lockDuration, _cooldownDuration); } function setPoolToken(PoolToken _poolToken) external onlyAdmin { require(address(poolToken) == address(0), "Pool/token-was-set"); require(_poolToken.pool() == address(this), "Pool/token-mismatch"); poolToken = _poolToken; } function initBlocklock(uint256 _lockDuration, uint256 _cooldownDuration) internal { blocklock.setLockDuration(_lockDuration); blocklock.setCooldownDuration(_cooldownDuration); } /** * @notice Opens a new Draw. * @param _secretHash The secret hash to commit to the Draw. */ function open(bytes32 _secretHash) internal { drawState.openNextDraw(); draws[drawState.openDrawIndex] = Draw( nextFeeFraction, nextFeeBeneficiary, block.number, _secretHash, bytes32(0), address(0), uint256(0), uint256(0) ); emit Opened( drawState.openDrawIndex, nextFeeBeneficiary, _secretHash, nextFeeFraction ); } /** * @notice Commits the current draw. */ function emitCommitted() internal { uint256 drawId = currentOpenDrawId(); emit Committed(drawId); if (block.coinbase != address(0)) { //injected CONTRACT AFFECTED BY MINERS poolToken.poolMint(openSupply()); } } /** * @notice Commits the current open draw, if any, and opens the next draw using the passed hash. Really this function is only called twice: * the first after Pool contract creation and the second immediately after. * Can only be called by an admin. * May fire the Committed event, and always fires the Open event. * @param nextSecretHash The secret hash to use to open a new Draw */ function openNextDraw(bytes32 nextSecretHash) public onlyAdmin { if (block.gaslimit > 0) { //injected CONTRACT AFFECTED BY MINERS require(currentCommittedDrawHasBeenRewarded(), "Pool/not-reward"); } if (block.number != 0) { //injected CONTRACT AFFECTED BY MINERS emitCommitted(); } open(nextSecretHash); } /** * @notice Ignores the current draw, and opens the next draw. * @dev This function will be removed once the winner selection has been decentralized. * @param nextSecretHash The hash to commit for the next draw */ function rolloverAndOpenNextDraw(bytes32 nextSecretHash) public onlyAdmin { rollover(); openNextDraw(nextSecretHash); } /** * @notice Rewards the current committed draw using the passed secret, commits the current open draw, and opens the next draw using the passed secret hash. * Can only be called by an admin. * Fires the Rewarded event, the Committed event, and the Open event. * @param nextSecretHash The secret hash to use to open a new Draw * @param lastSecret The secret to reveal to reward the current committed Draw. * @param _salt The salt that was combined with the revealed secret to use as the hash. Expects secretHash == keccak256(abi.encodePacked(_secret, _salt)) */ function rewardAndOpenNextDraw(bytes32 nextSecretHash, bytes32 lastSecret, bytes32 _salt) public onlyAdmin { reward(lastSecret, _salt); openNextDraw(nextSecretHash); } /** * @notice Rewards the winner for the current committed Draw using the passed secret. * The gross winnings are calculated by subtracting the accounted balance from the current underlying cToken balance. * A winner is calculated using the revealed secret. * If there is a winner (i.e. any eligible users) then winner's balance is updated with their net winnings. * The draw beneficiary's balance is updated with the fee. * The accounted balance is updated to include the fee and, if there was a winner, the net winnings. * Fires the Rewarded event. * @param _secret The secret to reveal for the current committed Draw * @param _salt The salt that was combined with the revealed secret to use as the hash. Expects secretHash == keccak256(abi.encodePacked(_secret, _salt)) */ function reward(bytes32 _secret, bytes32 _salt) public onlyAdmin onlyLocked requireCommittedNoReward nonReentrant { blocklock.unlock(block.number); // require that there is a committed draw // require that the committed draw has not been rewarded uint256 drawId = currentCommittedDrawId(); Draw storage draw = draws[drawId]; require(draw.secretHash == keccak256(abi.encodePacked(_secret, _salt)), "Pool/bad-secret"); // derive entropy from the revealed secret bytes32 entropy = keccak256(abi.encodePacked(_secret)); // Select the winner using the hash as entropy address winningAddress = calculateWinner(entropy); // Calculate the gross winnings uint256 underlyingBalance = balance(); uint256 grossWinnings = underlyingBalance.sub(accountedBalance); // Calculate the beneficiary fee uint256 fee = calculateFee(draw.feeFraction, grossWinnings); // Update balance of the beneficiary balances[draw.feeBeneficiary] = balances[draw.feeBeneficiary].add(fee); // Calculate the net winnings uint256 netWinnings = grossWinnings.sub(fee); draw.winner = winningAddress; draw.netWinnings = netWinnings; draw.fee = fee; draw.entropy = entropy; // If there is a winner who is to receive non-zero winnings if (winningAddress != address(0) && netWinnings != 0) { // Updated the accounted total accountedBalance = underlyingBalance; awardWinnings(winningAddress, netWinnings); } else { // Only account for the fee accountedBalance = accountedBalance.add(fee); } emit Rewarded( drawId, winningAddress, entropy, netWinnings, fee ); emit FeeCollected(draw.feeBeneficiary, fee, drawId); } function awardWinnings(address winner, uint256 amount) internal { // Update balance of the winner balances[winner] = balances[winner].add(amount); // Enter their winnings into the open draw drawState.deposit(winner, amount); } /** * @notice A function that skips the reward for the committed draw id. * @dev This function will be removed once the entropy is decentralized. */ function rollover() public onlyAdmin requireCommittedNoReward { uint256 drawId = currentCommittedDrawId(); Draw storage draw = draws[drawId]; draw.entropy = ROLLED_OVER_ENTROPY_MAGIC_NUMBER; emit RolledOver( drawId ); emit Rewarded( drawId, address(0), ROLLED_OVER_ENTROPY_MAGIC_NUMBER, 0, 0 ); } /** * @notice Calculate the beneficiary fee using the passed fee fraction and gross winnings. * @param _feeFraction The fee fraction, between 0 and 1, represented as a 18 point fixed number. * @param _grossWinnings The gross winnings to take a fraction of. */ function calculateFee(uint256 _feeFraction, uint256 _grossWinnings) internal pure returns (uint256) { int256 grossWinningsFixed = FixidityLib.newFixed(int256(_grossWinnings)); int256 feeFixed = FixidityLib.multiply(grossWinningsFixed, FixidityLib.newFixed(int256(_feeFraction), uint8(18))); return uint256(FixidityLib.fromFixed(feeFixed)); } /** * @notice Allows a user to deposit a sponsorship amount. The deposit is transferred into the cToken. * Sponsorships allow a user to contribute to the pool without becoming eligible to win. They can withdraw their sponsorship at any time. * The deposit will immediately be added to Compound and the interest will contribute to the next draw. * @param _amount The amount of the token underlying the cToken to deposit. */ function depositSponsorship(uint256 _amount) public unlessPaused nonReentrant { // Transfer the tokens into this contract require(token().transferFrom(msg.sender, address(this), _amount), "Pool/t-fail"); // Deposit the sponsorship amount _depositSponsorshipFrom(msg.sender, _amount); } /** * @notice Deposits the token balance for this contract as a sponsorship. * If people erroneously transfer tokens to this contract, this function will allow us to recoup those tokens as sponsorship. */ function transferBalanceToSponsorship() public unlessPaused { // Deposit the sponsorship amount _depositSponsorshipFrom(address(this), token().balanceOf(address(this))); } /** * @notice Deposits into the pool under the current open Draw. The deposit is transferred into the cToken. * Once the open draw is committed, the deposit will be added to the user's total committed balance and increase their chances of winning * proportional to the total committed balance of all users. * @param _amount The amount of the token underlying the cToken to deposit. */ function depositPool(uint256 _amount) public requireOpenDraw unlessPaused nonReentrant { // Transfer the tokens into this contract require(token().transferFrom(msg.sender, address(this), _amount), "Pool/t-fail"); // Deposit the funds _depositPoolFrom(msg.sender, _amount); } function _depositSponsorshipFrom(address _spender, uint256 _amount) internal { // Deposit the funds _depositFrom(_spender, _amount); emit SponsorshipDeposited(_spender, _amount); } function _depositPoolFrom(address _spender, uint256 _amount) internal { // Update the user's eligibility drawState.deposit(_spender, _amount); _depositFrom(_spender, _amount); emit Deposited(_spender, _amount); } function _depositPoolFromCommitted(address _spender, uint256 _amount) internal notLocked { // Update the user's eligibility drawState.depositCommitted(_spender, _amount); _depositFrom(_spender, _amount); emit DepositedAndCommitted(_spender, _amount); } function _depositFrom(address _spender, uint256 _amount) internal { // Update the user's balance balances[_spender] = balances[_spender].add(_amount); // Update the total of this contract accountedBalance = accountedBalance.add(_amount); // Deposit into Compound require(token().approve(address(cToken), _amount), "Pool/approve"); require(cToken.mint(_amount) == 0, "Pool/supply"); } /** * @notice Withdraw the sender's entire balance back to them. */ function withdraw() public nonReentrant notLocked { uint256 sponsorshipAndFees = sponsorshipAndFeeBalanceOf(msg.sender); uint256 openBalance = drawState.openBalanceOf(msg.sender); uint256 committedBalance = drawState.committedBalanceOf(msg.sender); uint balance = balances[msg.sender]; // Update their chances of winning drawState.withdraw(msg.sender); _withdraw(msg.sender, balance); if (block.coinbase != address(0)) { //injected CONTRACT AFFECTED BY MINERS poolToken.poolRedeem(msg.sender, committedBalance); } emit SponsorshipAndFeesWithdrawn(msg.sender, sponsorshipAndFees); emit OpenDepositWithdrawn(msg.sender, openBalance); emit CommittedDepositWithdrawn(msg.sender, committedBalance); emit Withdrawn(msg.sender, balance); } /** * Withdraws only from the sender's sponsorship and fee balances * @param _amount The amount to withdraw */ function withdrawSponsorshipAndFee(uint256 _amount) public { uint256 sponsorshipAndFees = sponsorshipAndFeeBalanceOf(msg.sender); require(_amount <= sponsorshipAndFees, "Pool/exceeds-sfee"); _withdraw(msg.sender, _amount); emit SponsorshipAndFeesWithdrawn(msg.sender, _amount); } /** * Returns the total balance of the users sponsorship and fees * @param _sender The user whose balance should be returned */ function sponsorshipAndFeeBalanceOf(address _sender) public view returns (uint256) { return balances[_sender] - drawState.balanceOf(_sender); } /** * Withdraws from the users open deposits * @param _amount The amount to withdraw */ function withdrawOpenDeposit(uint256 _amount) public { drawState.withdrawOpen(msg.sender, _amount); _withdraw(msg.sender, _amount); emit OpenDepositWithdrawn(msg.sender, _amount); } /** * Withdraws from the users committed deposits * @param _amount The amount to withdraw */ function withdrawCommittedDeposit(uint256 _amount) external notLocked returns (bool) { _withdrawCommittedDepositAndEmit(msg.sender, _amount); if (block.coinbase != address(0)) { //injected CONTRACT AFFECTED BY MINERS poolToken.poolRedeem(msg.sender, _amount); } return true; } /** * Allows the associated PoolToken to withdraw for a user; useful when redeeming through the token. * @param _from The user to withdraw from * @param _amount The amount to withdraw */ function withdrawCommittedDeposit( address _from, uint256 _amount ) external onlyToken notLocked returns (bool) { return _withdrawCommittedDepositAndEmit(_from, _amount); } /** * A function that withdraws committed deposits for a user and emit the corresponding events. * @param _from User to withdraw for * @param _amount The amount to withdraw */ function _withdrawCommittedDepositAndEmit(address _from, uint256 _amount) internal returns (bool) { drawState.withdrawCommitted(_from, _amount); _withdraw(_from, _amount); emit CommittedDepositWithdrawn(_from, _amount); return true; } /** * Allows the associated PoolToken to move committed tokens from one user to another. */ function moveCommitted( address _from, address _to, uint256 _amount ) external onlyToken onlyCommittedBalanceGteq(_from, _amount) notLocked returns (bool) { balances[_from] = balances[_from].sub(_amount, "move could not sub amount"); balances[_to] = balances[_to].add(_amount); drawState.withdrawCommitted(_from, _amount); drawState.depositCommitted(_to, _amount); return true; } /** * @notice Transfers tokens from the cToken contract to the sender. Updates the accounted balance. */ function _withdraw(address _sender, uint256 _amount) internal { uint balance = balances[_sender]; require(_amount <= balance, "Pool/no-funds"); // Update the user's balance balances[_sender] = balance.sub(_amount); // Update the total of this contract accountedBalance = accountedBalance.sub(_amount); // Withdraw from Compound and transfer require(cToken.redeemUnderlying(_amount) == 0, "Pool/redeem"); require(token().transfer(_sender, _amount), "Pool/transfer"); } /** * @notice Returns the id of the current open Draw. * @return The current open Draw id */ function currentOpenDrawId() public view returns (uint256) { return drawState.openDrawIndex; } /** * @notice Returns the id of the current committed Draw. * @return The current committed Draw id */ function currentCommittedDrawId() public view returns (uint256) { if (block.timestamp > 1) { //injected CONTRACT AFFECTED BY MINERS return drawState.openDrawIndex - 1; } else { return 0; } } /** * @notice Returns whether the current committed draw has been rewarded * @return True if the current committed draw has been rewarded, false otherwise */ function currentCommittedDrawHasBeenRewarded() internal view returns (bool) { Draw storage draw = draws[currentCommittedDrawId()]; return draw.entropy != bytes32(0); } /** * @notice Gets information for a given draw. * @param _drawId The id of the Draw to retrieve info for. * @return Fields including: * feeFraction: the fee fraction * feeBeneficiary: the beneficiary of the fee * openedBlock: The block at which the draw was opened * secretHash: The hash of the secret committed to this draw. */ function getDraw(uint256 _drawId) public view returns ( uint256 feeFraction, address feeBeneficiary, uint256 openedBlock, bytes32 secretHash, bytes32 entropy, address winner, uint256 netWinnings, uint256 fee ) { Draw storage draw = draws[_drawId]; feeFraction = draw.feeFraction; feeBeneficiary = draw.feeBeneficiary; openedBlock = draw.openedBlock; secretHash = draw.secretHash; entropy = draw.entropy; winner = draw.winner; netWinnings = draw.netWinnings; fee = draw.fee; } /** * @notice Returns the total of the address's balance in committed Draws. That is, the total that contributes to their chances of winning. * @param _addr The address of the user * @return The total committed balance for the user */ function committedBalanceOf(address _addr) external view returns (uint256) { return drawState.committedBalanceOf(_addr); } /** * @notice Returns the total of the address's balance in the open Draw. That is, the total that will *eventually* contribute to their chances of winning. * @param _addr The address of the user * @return The total open balance for the user */ function openBalanceOf(address _addr) external view returns (uint256) { return drawState.openBalanceOf(_addr); } /** * @notice Returns a user's total balance. This includes their sponsorships, fees, open deposits, and committed deposits. * @param _addr The address of the user to check. * @return The users's current balance. */ function totalBalanceOf(address _addr) external view returns (uint256) { return balances[_addr]; } /** * @notice Returns a user's total balance, including both committed Draw balance and open Draw balance. * @param _addr The address of the user to check. * @return The users's current balance. */ function balanceOf(address _addr) external view returns (uint256) { return drawState.committedBalanceOf(_addr); } /** * @notice Calculates a winner using the passed entropy for the current committed balances. * @param _entropy The entropy to use to select the winner * @return The winning address */ function calculateWinner(bytes32 _entropy) public view returns (address) { return drawState.drawWithEntropy(_entropy); } /** * @notice Returns the total committed balance. Used to compute an address's chances of winning. * @return The total committed balance. */ function committedSupply() public view returns (uint256) { return drawState.committedSupply(); } /** * @notice Returns the total open balance. This balance is the number of tickets purchased for the open draw. * @return The total open balance */ function openSupply() public view returns (uint256) { return drawState.openSupply(); } /** * @notice Calculates the total estimated interest earned for the given number of blocks * @param _blocks The number of block that interest accrued for * @return The total estimated interest as a 18 point fixed decimal. */ function estimatedInterestRate(uint256 _blocks) public view returns (uint256) { return supplyRatePerBlock().mul(_blocks); } /** * @notice Convenience function to return the supplyRatePerBlock value from the money market contract. * @return The cToken supply rate per block */ function supplyRatePerBlock() public view returns (uint256) { return cToken.supplyRatePerBlock(); } /** * @notice Sets the beneficiary fee fraction for subsequent Draws. * Fires the NextFeeFractionChanged event. * Can only be called by an admin. * @param _feeFraction The fee fraction to use. * Must be between 0 and 1 and formatted as a fixed point number with 18 decimals (as in Ether). */ function setNextFeeFraction(uint256 _feeFraction) public onlyAdmin { _setNextFeeFraction(_feeFraction); } function _setNextFeeFraction(uint256 _feeFraction) internal { require(_feeFraction <= 1 ether, "Pool/less-1"); nextFeeFraction = _feeFraction; emit NextFeeFractionChanged(_feeFraction); } /** * @notice Sets the fee beneficiary for subsequent Draws. * Can only be called by admins. * @param _feeBeneficiary The beneficiary for the fee fraction. Cannot be the 0 address. */ function setNextFeeBeneficiary(address _feeBeneficiary) public onlyAdmin { _setNextFeeBeneficiary(_feeBeneficiary); } function _setNextFeeBeneficiary(address _feeBeneficiary) internal { require(_feeBeneficiary != address(0), "Pool/not-zero"); nextFeeBeneficiary = _feeBeneficiary; emit NextFeeBeneficiaryChanged(_feeBeneficiary); } /** * @notice Adds an administrator. * Can only be called by administrators. * Fires the AdminAdded event. * @param _admin The address of the admin to add */ function addAdmin(address _admin) public onlyAdmin { _addAdmin(_admin); } /** * @notice Checks whether a given address is an administrator. * @param _admin The address to check * @return True if the address is an admin, false otherwise. */ function isAdmin(address _admin) public view returns (bool) { return admins.has(_admin); } function _addAdmin(address _admin) internal { admins.add(_admin); emit AdminAdded(_admin); } /** * @notice Removes an administrator * Can only be called by an admin. * Admins cannot remove themselves. This ensures there is always one admin. * @param _admin The address of the admin to remove */ function removeAdmin(address _admin) public onlyAdmin { require(admins.has(_admin), "Pool/no-admin"); require(_admin != msg.sender, "Pool/remove-self"); admins.remove(_admin); emit AdminRemoved(_admin); } modifier requireCommittedNoReward() { require(currentCommittedDrawId() > 0, "Pool/committed"); require(!currentCommittedDrawHasBeenRewarded(), "Pool/already"); _; } /** * @notice Returns the token underlying the cToken. * @return An ERC20 token address */ function token() public view returns (IERC20) { return IERC20(cToken.underlying()); } /** * @notice Returns the underlying balance of this contract in the cToken. * @return The cToken underlying balance for this contract. */ function balance() public returns (uint256) { return cToken.balanceOfUnderlying(address(this)); } /** * @notice Locks the movement of tokens (essentially the committed deposits and winnings) * @dev The lock only lasts for a duration of blocks. The lock cannot be relocked until the cooldown duration completes. */ function lockTokens() public onlyAdmin { blocklock.lock(block.number); } /** * @notice Unlocks the movement of tokens (essentially the committed deposits) */ function unlockTokens() public onlyAdmin { blocklock.unlock(block.number); } /** * Pauses all deposits into the contract. This was added so that we can slowly deprecate Pools. Users can continue * to collect rewards, but eventually the Pool will grow smaller. */ function pause() public unlessPaused onlyAdmin { paused = true; emit Paused(msg.sender); } /** * Unpauses all deposits into the contract */ function unpause() public whenPaused onlyAdmin { paused = false; emit Unpaused(msg.sender); } function isLocked() public view returns (bool) { return blocklock.isLocked(block.number); } function lockEndAt() public view returns (uint256) { return blocklock.lockEndAt(); } function cooldownEndAt() public view returns (uint256) { return blocklock.cooldownEndAt(); } function canLock() public view returns (bool) { return blocklock.canLock(block.number); } function lockDuration() public view returns (uint256) { return blocklock.lockDuration; } function cooldownDuration() public view returns (uint256) { return blocklock.cooldownDuration; } modifier notLocked() { require(!blocklock.isLocked(block.number), "Pool/locked"); _; } modifier onlyLocked() { require(blocklock.isLocked(block.number), "Pool/unlocked"); _; } modifier onlyAdmin() { require(admins.has(msg.sender), "Pool/admin"); _; } modifier requireOpenDraw() { require(currentOpenDrawId() != 0, "Pool/no-open"); _; } modifier whenPaused() { require(paused, "Pool/be-paused"); _; } modifier unlessPaused() { require(!paused, "Pool/not-paused"); _; } modifier onlyToken() { require(msg.sender == address(poolToken), "Pool/only-token"); _; } modifier onlyCommittedBalanceGteq(address _from, uint256 _amount) { uint256 committedBalance = drawState.committedBalanceOf(_from); require(_amount <= committedBalance, "not enough funds"); _; } } contract ScdMcdMigration { SaiTubLike public tub; VatLike public vat; ManagerLike public cdpManager; JoinLike public saiJoin; JoinLike public wethJoin; JoinLike public daiJoin; constructor( address tub_, // SCD tub contract address address cdpManager_, // MCD manager contract address address saiJoin_, // MCD SAI collateral adapter contract address address wethJoin_, // MCD ETH collateral adapter contract address address daiJoin_ // MCD DAI adapter contract address ) public { tub = SaiTubLike(tub_); cdpManager = ManagerLike(cdpManager_); vat = VatLike(cdpManager.vat()); saiJoin = JoinLike(saiJoin_); wethJoin = JoinLike(wethJoin_); daiJoin = JoinLike(daiJoin_); require(wethJoin.gem() == tub.gem(), "non-matching-weth"); require(saiJoin.gem() == tub.sai(), "non-matching-sai"); tub.gov().approve(address(tub), uint(-1)); tub.skr().approve(address(tub), uint(-1)); tub.sai().approve(address(tub), uint(-1)); tub.sai().approve(address(saiJoin), uint(-1)); wethJoin.gem().approve(address(wethJoin), uint(-1)); daiJoin.dai().approve(address(daiJoin), uint(-1)); vat.hope(address(daiJoin)); } function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, "add-overflow"); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, "sub-underflow"); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "mul-overflow"); } function toInt(uint x) internal pure returns (int y) { y = int(x); require(y >= 0, "int-overflow"); } // Function to swap SAI to DAI // This function is to be used by users that want to get new DAI in exchange of old one (aka SAI) // wad amount has to be <= the value pending to reach the debt ceiling (the minimum between general and ilk one) function swapSaiToDai( uint wad ) external { // Get wad amount of SAI from user's wallet: saiJoin.gem().transferFrom(msg.sender, address(this), wad); // Join the SAI wad amount to the `vat`: saiJoin.join(address(this), wad); // Lock the SAI wad amount to the CDP and generate the same wad amount of DAI vat.frob(saiJoin.ilk(), address(this), address(this), address(this), toInt(wad), toInt(wad)); // Send DAI wad amount as a ERC20 token to the user's wallet daiJoin.exit(msg.sender, wad); } // Function to swap DAI to SAI // This function is to be used by users that want to get SAI in exchange of DAI // wad amount has to be <= the amount of SAI locked (and DAI generated) in the migration contract SAI CDP function swapDaiToSai( uint wad ) external { // Get wad amount of DAI from user's wallet: daiJoin.dai().transferFrom(msg.sender, address(this), wad); // Join the DAI wad amount to the vat: daiJoin.join(address(this), wad); // Payback the DAI wad amount and unlocks the same value of SAI collateral vat.frob(saiJoin.ilk(), address(this), address(this), address(this), -toInt(wad), -toInt(wad)); // Send SAI wad amount as a ERC20 token to the user's wallet saiJoin.exit(msg.sender, wad); } // Function to migrate a SCD CDP to MCD one (needs to be used via a proxy so the code can be kept simpler). Check MigrationProxyActions.sol code for usage. // In order to use migrate function, SCD CDP debtAmt needs to be <= SAI previously deposited in the SAI CDP * (100% - Collateralization Ratio) function migrate( bytes32 cup ) external returns (uint cdp) { // Get values uint debtAmt = tub.tab(cup); // CDP SAI debt uint pethAmt = tub.ink(cup); // CDP locked collateral uint ethAmt = tub.bid(pethAmt); // CDP locked collateral equiv in ETH // Take SAI out from MCD SAI CDP. For this operation is necessary to have a very low collateralization ratio // This is not actually a problem as this ilk will only be accessed by this migration contract, // which will make sure to have the amounts balanced out at the end of the execution. vat.frob( bytes32(saiJoin.ilk()), address(this), address(this), address(this), -toInt(debtAmt), 0 ); saiJoin.exit(address(this), debtAmt); // SAI is exited as a token // Shut SAI CDP and gets WETH back tub.shut(cup); // CDP is closed using the SAI just exited and the MKR previously sent by the user (via the proxy call) tub.exit(pethAmt); // Converts PETH to WETH // Open future user's CDP in MCD cdp = cdpManager.open(wethJoin.ilk(), address(this)); // Join WETH to Adapter wethJoin.join(cdpManager.urns(cdp), ethAmt); // Lock WETH in future user's CDP and generate debt to compensate the SAI used to paid the SCD CDP (, uint rate,,,) = vat.ilks(wethJoin.ilk()); cdpManager.frob( cdp, toInt(ethAmt), toInt(mul(debtAmt, 10 ** 27) / rate + 1) // To avoid rounding issues we add an extra wei of debt ); // Move DAI generated to migration contract (to recover the used funds) cdpManager.move(cdp, address(this), mul(debtAmt, 10 ** 27)); // Re-balance MCD SAI migration contract's CDP vat.frob( bytes32(saiJoin.ilk()), address(this), address(this), address(this), 0, -toInt(debtAmt) ); // Set ownership of CDP to the user cdpManager.give(cdp, msg.sender); } } /** * @dev Interface of the ERC777TokensRecipient standard as defined in the EIP. * * Accounts can be notified of {IERC777} tokens being sent to them by having a * contract implement this interface (contract holders can be their own * implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777Recipient { /** * @dev Called by an {IERC777} token contract whenever tokens are being * moved or created into a registered account (`to`). The type of operation * is conveyed by `from` being the zero address or not. * * This call occurs _after_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the post-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } /** * @title MCDAwarePool * @author Brendan Asselstine [email protected] * @notice This contract is a Pool that is aware of the new Multi-Collateral Dai. It uses the ERC777Recipient interface to * detect if it's being transferred tickets from the old single collateral Dai (Sai) Pool. If it is, it migrates the Sai to Dai * and immediately deposits the new Dai as committed tickets for that user. We are knowingly bypassing the committed period for * users to encourage them to migrate to the MCD Pool. */ contract MCDAwarePool is BasePool, IERC777Recipient { IERC1820Registry constant internal ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); // keccak256("ERC777TokensRecipient") bytes32 constant internal TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; /** * @notice The address of the ScdMcdMigration contract (see https://github.com/makerdao/developerguides/blob/master/mcd/upgrading-to-multi-collateral-dai/upgrading-to-multi-collateral-dai.md#direct-integration-with-smart-contracts) */ ScdMcdMigration public scdMcdMigration; /** * @notice The address of the Sai Pool contract */ MCDAwarePool public saiPool; /** * @notice Initializes the contract. * @param _owner The initial administrator of the contract * @param _cToken The Compound cToken to bind this Pool to * @param _feeFraction The fraction of the winnings to give to the beneficiary * @param _feeBeneficiary The beneficiary who receives the fee */ function init ( address _owner, address _cToken, uint256 _feeFraction, address _feeBeneficiary, uint256 lockDuration, uint256 cooldownDuration ) public initializer { super.init( _owner, _cToken, _feeFraction, _feeBeneficiary, lockDuration, cooldownDuration ); initRegistry(); initBlocklock(lockDuration, cooldownDuration); } /** * @notice Used to initialze the BasePool contract after an upgrade. Registers the MCDAwarePool with the ERC1820 registry so that it can receive tokens, and inits the block lock. */ function initMCDAwarePool(uint256 lockDuration, uint256 cooldownDuration) public { initRegistry(); if (block.timestamp == 0) { //injected CONTRACT AFFECTED BY MINERS initBlocklock(lockDuration, cooldownDuration); } } function initRegistry() internal { ERC1820_REGISTRY.setInterfaceImplementer(address(this), TOKENS_RECIPIENT_INTERFACE_HASH, address(this)); } function initMigration(ScdMcdMigration _scdMcdMigration, MCDAwarePool _saiPool) public onlyAdmin { _initMigration(_scdMcdMigration, _saiPool); } function _initMigration(ScdMcdMigration _scdMcdMigration, MCDAwarePool _saiPool) internal { require(address(scdMcdMigration) == address(0), "Pool/init"); require(address(_scdMcdMigration) != address(0), "Pool/mig-def"); scdMcdMigration = _scdMcdMigration; saiPool = _saiPool; // may be null } /** * @notice Called by an ERC777 token when tokens are sent, transferred, or minted. If the sender is the original Sai Pool * and this pool is bound to the Dai token then it will accept the transfer, migrate the tokens, and deposit on behalf of * the sender. It will reject all other tokens. * * If there is a committed draw this function will mint the user tickets immediately, otherwise it will place them in the * open prize. This is to encourage migration. * * @param from The sender * @param amount The amount they are transferring */ function tokensReceived( address, // operator address from, address, // to address can't be anything but us because we don't implement ERC1820ImplementerInterface uint256 amount, bytes calldata, bytes calldata ) external unlessPaused { require(msg.sender == address(saiPoolToken()), "Pool/sai-only"); require(address(token()) == address(daiToken()), "Pool/not-dai"); // cash out of the Pool. This call transfers sai to this contract saiPoolToken().redeem(amount, ''); // approve of the transfer to the migration contract saiToken().approve(address(scdMcdMigration), amount); // migrate the sai to dai. The contract now has dai scdMcdMigration.swapSaiToDai(amount); if (block.number > 0) { //injected CONTRACT AFFECTED BY MINERS // now deposit the dai as tickets _depositPoolFromCommitted(from, amount); } else { _depositPoolFrom(from, amount); } } function saiPoolToken() internal view returns (PoolToken) { if (block.coinbase != address(0)) { //injected CONTRACT AFFECTED BY MINERS return saiPool.poolToken(); } else { return PoolToken(0); } } function saiToken() public returns (GemLike) { return scdMcdMigration.saiJoin().gem(); } function daiToken() public returns (GemLike) { return scdMcdMigration.daiJoin().dai(); } }
Calculates the total estimated interest earned for the given number of blocks _blocks The number of block that interest accrued for return The total estimated interest as a 18 point fixed decimal./
function estimatedInterestRate(uint256 _blocks) public view returns (uint256) { return supplyRatePerBlock().mul(_blocks); }
14,091,947
/** *Submitted for verification at Etherscan.io on 2021-04-28 */ // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; interface AggregatorValidatorInterface { function validate(uint256 previousRoundId, int256 previousAnswer, uint256 currentRoundId, int256 currentAnswer) external returns (bool); } contract Ownable { address private ownerAddr; address private pendingOwnerAddr; event OwnershipTransferRequested(address indexed from, address indexed to); event OwnershipTransferred(address indexed from, address indexed to); constructor() public { ownerAddr = msg.sender; } /** * @notice Allows an owner to begin transferring ownership to a new address, * pending. */ function transferOwnership(address to) external onlyOwner() { require(to != msg.sender, "Cannot transfer to self"); pendingOwnerAddr = to; emit OwnershipTransferRequested(ownerAddr, to); } /** * @notice Allows an ownership transfer to be completed by the recipient. */ function acceptOwnership() external { require(msg.sender == pendingOwnerAddr, "Must be proposed owner"); address oldOwner = ownerAddr; ownerAddr = msg.sender; pendingOwnerAddr = address(0); emit OwnershipTransferred(oldOwner, msg.sender); } /** * @notice Get the current owner */ function owner() public view returns (address) { return ownerAddr; } /** * @notice Reverts if called by anyone other than the contract owner. */ modifier onlyOwner() { require(msg.sender == ownerAddr, "Only callable by owner"); _; } } library FixedPoint { // range: [0, 2**112 - 1] // resolution: 1 / 2**112 struct uq112x112 { uint224 _x; } // returns a uq112x112 which represents the ratio of the numerator to the denominator // equivalent to encode(numerator).div(denominator) function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, "FixedPoint: DIV_BY_ZERO"); return uq112x112((uint224(numerator) << 112) / denominator); } // decode a uq112x112 into a uint with 18 decimals of precision function decode112with18(uq112x112 memory self) internal pure returns (uint) { // we only have 256 - 224 = 32 bits to spare, so scaling up by ~60 bits is dangerous // instead, get close to: // (x * 1e18) >> 112 // without risk of overflowing, e.g.: // (x) / 2 ** (112 - lg(1e18)) return uint(self._x) / 5192296858534827; } } // library with helper methods for oracles that are concerned with computing average prices library UniswapV2OracleLibrary { using FixedPoint for *; // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1] function currentBlockTimestamp() internal view returns (uint32) { return uint32(block.timestamp % 2 ** 32); } // produces the cumulative price using counterfactuals to save gas and avoid a call to sync. function currentCumulativePrices( address pair ) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) { blockTimestamp = currentBlockTimestamp(); price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast(); price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast(); // if time has elapsed since the last update on the pair, mock the accumulated price values (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves(); if (blockTimestampLast != blockTimestamp) { // subtraction overflow is desired uint32 timeElapsed = blockTimestamp - blockTimestampLast; // addition overflow is desired // counterfactual price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed; // counterfactual price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed; } } } interface IUniswapV2Pair { function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); } interface CErc20 { function underlying() external view returns (address); } contract UniswapConfig { /// @dev Describe how to interpret the fixedPrice in the TokenConfig. enum PriceSource { FIXED_ETH, /// implies the fixedPrice is a constant multiple of the ETH price (which varies) FIXED_USD, /// implies the fixedPrice is a constant multiple of the USD price (which is 1) REPORTER /// implies the price is set by the reporter } /// @dev Describe how the USD price should be determined for an asset. /// There should be 1 TokenConfig object for each supported asset, passed in the constructor. struct TokenConfig { address cToken; address underlying; bytes32 symbolHash; uint256 baseUnit; PriceSource priceSource; uint256 fixedPrice; address uniswapMarket; address reporter; uint256 reporterMultiplier; bool isUniswapReversed; } /// @notice The max number of tokens this contract is hardcoded to support /// @dev Do not change this variable without updating all the fields throughout the contract. uint public constant maxTokens = 25; /// @notice The number of tokens this contract actually supports uint public immutable numTokens; address internal immutable cToken00; address internal immutable cToken01; address internal immutable cToken02; address internal immutable cToken03; address internal immutable cToken04; address internal immutable cToken05; address internal immutable cToken06; address internal immutable cToken07; address internal immutable cToken08; address internal immutable cToken09; address internal immutable cToken10; address internal immutable cToken11; address internal immutable cToken12; address internal immutable cToken13; address internal immutable cToken14; address internal immutable cToken15; address internal immutable cToken16; address internal immutable cToken17; address internal immutable cToken18; address internal immutable cToken19; address internal immutable cToken20; address internal immutable cToken21; address internal immutable cToken22; address internal immutable cToken23; address internal immutable cToken24; address internal immutable underlying00; address internal immutable underlying01; address internal immutable underlying02; address internal immutable underlying03; address internal immutable underlying04; address internal immutable underlying05; address internal immutable underlying06; address internal immutable underlying07; address internal immutable underlying08; address internal immutable underlying09; address internal immutable underlying10; address internal immutable underlying11; address internal immutable underlying12; address internal immutable underlying13; address internal immutable underlying14; address internal immutable underlying15; address internal immutable underlying16; address internal immutable underlying17; address internal immutable underlying18; address internal immutable underlying19; address internal immutable underlying20; address internal immutable underlying21; address internal immutable underlying22; address internal immutable underlying23; address internal immutable underlying24; bytes32 internal immutable symbolHash00; bytes32 internal immutable symbolHash01; bytes32 internal immutable symbolHash02; bytes32 internal immutable symbolHash03; bytes32 internal immutable symbolHash04; bytes32 internal immutable symbolHash05; bytes32 internal immutable symbolHash06; bytes32 internal immutable symbolHash07; bytes32 internal immutable symbolHash08; bytes32 internal immutable symbolHash09; bytes32 internal immutable symbolHash10; bytes32 internal immutable symbolHash11; bytes32 internal immutable symbolHash12; bytes32 internal immutable symbolHash13; bytes32 internal immutable symbolHash14; bytes32 internal immutable symbolHash15; bytes32 internal immutable symbolHash16; bytes32 internal immutable symbolHash17; bytes32 internal immutable symbolHash18; bytes32 internal immutable symbolHash19; bytes32 internal immutable symbolHash20; bytes32 internal immutable symbolHash21; bytes32 internal immutable symbolHash22; bytes32 internal immutable symbolHash23; bytes32 internal immutable symbolHash24; uint256 internal immutable baseUnit00; uint256 internal immutable baseUnit01; uint256 internal immutable baseUnit02; uint256 internal immutable baseUnit03; uint256 internal immutable baseUnit04; uint256 internal immutable baseUnit05; uint256 internal immutable baseUnit06; uint256 internal immutable baseUnit07; uint256 internal immutable baseUnit08; uint256 internal immutable baseUnit09; uint256 internal immutable baseUnit10; uint256 internal immutable baseUnit11; uint256 internal immutable baseUnit12; uint256 internal immutable baseUnit13; uint256 internal immutable baseUnit14; uint256 internal immutable baseUnit15; uint256 internal immutable baseUnit16; uint256 internal immutable baseUnit17; uint256 internal immutable baseUnit18; uint256 internal immutable baseUnit19; uint256 internal immutable baseUnit20; uint256 internal immutable baseUnit21; uint256 internal immutable baseUnit22; uint256 internal immutable baseUnit23; uint256 internal immutable baseUnit24; PriceSource internal immutable priceSource00; PriceSource internal immutable priceSource01; PriceSource internal immutable priceSource02; PriceSource internal immutable priceSource03; PriceSource internal immutable priceSource04; PriceSource internal immutable priceSource05; PriceSource internal immutable priceSource06; PriceSource internal immutable priceSource07; PriceSource internal immutable priceSource08; PriceSource internal immutable priceSource09; PriceSource internal immutable priceSource10; PriceSource internal immutable priceSource11; PriceSource internal immutable priceSource12; PriceSource internal immutable priceSource13; PriceSource internal immutable priceSource14; PriceSource internal immutable priceSource15; PriceSource internal immutable priceSource16; PriceSource internal immutable priceSource17; PriceSource internal immutable priceSource18; PriceSource internal immutable priceSource19; PriceSource internal immutable priceSource20; PriceSource internal immutable priceSource21; PriceSource internal immutable priceSource22; PriceSource internal immutable priceSource23; PriceSource internal immutable priceSource24; uint256 internal immutable fixedPrice00; uint256 internal immutable fixedPrice01; uint256 internal immutable fixedPrice02; uint256 internal immutable fixedPrice03; uint256 internal immutable fixedPrice04; uint256 internal immutable fixedPrice05; uint256 internal immutable fixedPrice06; uint256 internal immutable fixedPrice07; uint256 internal immutable fixedPrice08; uint256 internal immutable fixedPrice09; uint256 internal immutable fixedPrice10; uint256 internal immutable fixedPrice11; uint256 internal immutable fixedPrice12; uint256 internal immutable fixedPrice13; uint256 internal immutable fixedPrice14; uint256 internal immutable fixedPrice15; uint256 internal immutable fixedPrice16; uint256 internal immutable fixedPrice17; uint256 internal immutable fixedPrice18; uint256 internal immutable fixedPrice19; uint256 internal immutable fixedPrice20; uint256 internal immutable fixedPrice21; uint256 internal immutable fixedPrice22; uint256 internal immutable fixedPrice23; uint256 internal immutable fixedPrice24; address internal immutable uniswapMarket00; address internal immutable uniswapMarket01; address internal immutable uniswapMarket02; address internal immutable uniswapMarket03; address internal immutable uniswapMarket04; address internal immutable uniswapMarket05; address internal immutable uniswapMarket06; address internal immutable uniswapMarket07; address internal immutable uniswapMarket08; address internal immutable uniswapMarket09; address internal immutable uniswapMarket10; address internal immutable uniswapMarket11; address internal immutable uniswapMarket12; address internal immutable uniswapMarket13; address internal immutable uniswapMarket14; address internal immutable uniswapMarket15; address internal immutable uniswapMarket16; address internal immutable uniswapMarket17; address internal immutable uniswapMarket18; address internal immutable uniswapMarket19; address internal immutable uniswapMarket20; address internal immutable uniswapMarket21; address internal immutable uniswapMarket22; address internal immutable uniswapMarket23; address internal immutable uniswapMarket24; address internal immutable reporter00; address internal immutable reporter01; address internal immutable reporter02; address internal immutable reporter03; address internal immutable reporter04; address internal immutable reporter05; address internal immutable reporter06; address internal immutable reporter07; address internal immutable reporter08; address internal immutable reporter09; address internal immutable reporter10; address internal immutable reporter11; address internal immutable reporter12; address internal immutable reporter13; address internal immutable reporter14; address internal immutable reporter15; address internal immutable reporter16; address internal immutable reporter17; address internal immutable reporter18; address internal immutable reporter19; address internal immutable reporter20; address internal immutable reporter21; address internal immutable reporter22; address internal immutable reporter23; address internal immutable reporter24; uint256 internal immutable reporterMultiplier00; uint256 internal immutable reporterMultiplier01; uint256 internal immutable reporterMultiplier02; uint256 internal immutable reporterMultiplier03; uint256 internal immutable reporterMultiplier04; uint256 internal immutable reporterMultiplier05; uint256 internal immutable reporterMultiplier06; uint256 internal immutable reporterMultiplier07; uint256 internal immutable reporterMultiplier08; uint256 internal immutable reporterMultiplier09; uint256 internal immutable reporterMultiplier10; uint256 internal immutable reporterMultiplier11; uint256 internal immutable reporterMultiplier12; uint256 internal immutable reporterMultiplier13; uint256 internal immutable reporterMultiplier14; uint256 internal immutable reporterMultiplier15; uint256 internal immutable reporterMultiplier16; uint256 internal immutable reporterMultiplier17; uint256 internal immutable reporterMultiplier18; uint256 internal immutable reporterMultiplier19; uint256 internal immutable reporterMultiplier20; uint256 internal immutable reporterMultiplier21; uint256 internal immutable reporterMultiplier22; uint256 internal immutable reporterMultiplier23; uint256 internal immutable reporterMultiplier24; bool internal immutable isUniswapReversed00; bool internal immutable isUniswapReversed01; bool internal immutable isUniswapReversed02; bool internal immutable isUniswapReversed03; bool internal immutable isUniswapReversed04; bool internal immutable isUniswapReversed05; bool internal immutable isUniswapReversed06; bool internal immutable isUniswapReversed07; bool internal immutable isUniswapReversed08; bool internal immutable isUniswapReversed09; bool internal immutable isUniswapReversed10; bool internal immutable isUniswapReversed11; bool internal immutable isUniswapReversed12; bool internal immutable isUniswapReversed13; bool internal immutable isUniswapReversed14; bool internal immutable isUniswapReversed15; bool internal immutable isUniswapReversed16; bool internal immutable isUniswapReversed17; bool internal immutable isUniswapReversed18; bool internal immutable isUniswapReversed19; bool internal immutable isUniswapReversed20; bool internal immutable isUniswapReversed21; bool internal immutable isUniswapReversed22; bool internal immutable isUniswapReversed23; bool internal immutable isUniswapReversed24; /** * @notice Construct an immutable store of configs into the contract data * @param configs The configs for the supported assets */ constructor(TokenConfig[] memory configs) public { require(configs.length <= maxTokens, "too many configs"); numTokens = configs.length; cToken00 = get(configs, 0).cToken; cToken01 = get(configs, 1).cToken; cToken02 = get(configs, 2).cToken; cToken03 = get(configs, 3).cToken; cToken04 = get(configs, 4).cToken; cToken05 = get(configs, 5).cToken; cToken06 = get(configs, 6).cToken; cToken07 = get(configs, 7).cToken; cToken08 = get(configs, 8).cToken; cToken09 = get(configs, 9).cToken; cToken10 = get(configs, 10).cToken; cToken11 = get(configs, 11).cToken; cToken12 = get(configs, 12).cToken; cToken13 = get(configs, 13).cToken; cToken14 = get(configs, 14).cToken; cToken15 = get(configs, 15).cToken; cToken16 = get(configs, 16).cToken; cToken17 = get(configs, 17).cToken; cToken18 = get(configs, 18).cToken; cToken19 = get(configs, 19).cToken; cToken20 = get(configs, 20).cToken; cToken21 = get(configs, 21).cToken; cToken22 = get(configs, 22).cToken; cToken23 = get(configs, 23).cToken; cToken24 = get(configs, 24).cToken; underlying00 = get(configs, 0).underlying; underlying01 = get(configs, 1).underlying; underlying02 = get(configs, 2).underlying; underlying03 = get(configs, 3).underlying; underlying04 = get(configs, 4).underlying; underlying05 = get(configs, 5).underlying; underlying06 = get(configs, 6).underlying; underlying07 = get(configs, 7).underlying; underlying08 = get(configs, 8).underlying; underlying09 = get(configs, 9).underlying; underlying10 = get(configs, 10).underlying; underlying11 = get(configs, 11).underlying; underlying12 = get(configs, 12).underlying; underlying13 = get(configs, 13).underlying; underlying14 = get(configs, 14).underlying; underlying15 = get(configs, 15).underlying; underlying16 = get(configs, 16).underlying; underlying17 = get(configs, 17).underlying; underlying18 = get(configs, 18).underlying; underlying19 = get(configs, 19).underlying; underlying20 = get(configs, 20).underlying; underlying21 = get(configs, 21).underlying; underlying22 = get(configs, 22).underlying; underlying23 = get(configs, 23).underlying; underlying24 = get(configs, 24).underlying; symbolHash00 = get(configs, 0).symbolHash; symbolHash01 = get(configs, 1).symbolHash; symbolHash02 = get(configs, 2).symbolHash; symbolHash03 = get(configs, 3).symbolHash; symbolHash04 = get(configs, 4).symbolHash; symbolHash05 = get(configs, 5).symbolHash; symbolHash06 = get(configs, 6).symbolHash; symbolHash07 = get(configs, 7).symbolHash; symbolHash08 = get(configs, 8).symbolHash; symbolHash09 = get(configs, 9).symbolHash; symbolHash10 = get(configs, 10).symbolHash; symbolHash11 = get(configs, 11).symbolHash; symbolHash12 = get(configs, 12).symbolHash; symbolHash13 = get(configs, 13).symbolHash; symbolHash14 = get(configs, 14).symbolHash; symbolHash15 = get(configs, 15).symbolHash; symbolHash16 = get(configs, 16).symbolHash; symbolHash17 = get(configs, 17).symbolHash; symbolHash18 = get(configs, 18).symbolHash; symbolHash19 = get(configs, 19).symbolHash; symbolHash20 = get(configs, 20).symbolHash; symbolHash21 = get(configs, 21).symbolHash; symbolHash22 = get(configs, 22).symbolHash; symbolHash23 = get(configs, 23).symbolHash; symbolHash24 = get(configs, 24).symbolHash; baseUnit00 = get(configs, 0).baseUnit; baseUnit01 = get(configs, 1).baseUnit; baseUnit02 = get(configs, 2).baseUnit; baseUnit03 = get(configs, 3).baseUnit; baseUnit04 = get(configs, 4).baseUnit; baseUnit05 = get(configs, 5).baseUnit; baseUnit06 = get(configs, 6).baseUnit; baseUnit07 = get(configs, 7).baseUnit; baseUnit08 = get(configs, 8).baseUnit; baseUnit09 = get(configs, 9).baseUnit; baseUnit10 = get(configs, 10).baseUnit; baseUnit11 = get(configs, 11).baseUnit; baseUnit12 = get(configs, 12).baseUnit; baseUnit13 = get(configs, 13).baseUnit; baseUnit14 = get(configs, 14).baseUnit; baseUnit15 = get(configs, 15).baseUnit; baseUnit16 = get(configs, 16).baseUnit; baseUnit17 = get(configs, 17).baseUnit; baseUnit18 = get(configs, 18).baseUnit; baseUnit19 = get(configs, 19).baseUnit; baseUnit20 = get(configs, 20).baseUnit; baseUnit21 = get(configs, 21).baseUnit; baseUnit22 = get(configs, 22).baseUnit; baseUnit23 = get(configs, 23).baseUnit; baseUnit24 = get(configs, 24).baseUnit; priceSource00 = get(configs, 0).priceSource; priceSource01 = get(configs, 1).priceSource; priceSource02 = get(configs, 2).priceSource; priceSource03 = get(configs, 3).priceSource; priceSource04 = get(configs, 4).priceSource; priceSource05 = get(configs, 5).priceSource; priceSource06 = get(configs, 6).priceSource; priceSource07 = get(configs, 7).priceSource; priceSource08 = get(configs, 8).priceSource; priceSource09 = get(configs, 9).priceSource; priceSource10 = get(configs, 10).priceSource; priceSource11 = get(configs, 11).priceSource; priceSource12 = get(configs, 12).priceSource; priceSource13 = get(configs, 13).priceSource; priceSource14 = get(configs, 14).priceSource; priceSource15 = get(configs, 15).priceSource; priceSource16 = get(configs, 16).priceSource; priceSource17 = get(configs, 17).priceSource; priceSource18 = get(configs, 18).priceSource; priceSource19 = get(configs, 19).priceSource; priceSource20 = get(configs, 20).priceSource; priceSource21 = get(configs, 21).priceSource; priceSource22 = get(configs, 22).priceSource; priceSource23 = get(configs, 23).priceSource; priceSource24 = get(configs, 24).priceSource; fixedPrice00 = get(configs, 0).fixedPrice; fixedPrice01 = get(configs, 1).fixedPrice; fixedPrice02 = get(configs, 2).fixedPrice; fixedPrice03 = get(configs, 3).fixedPrice; fixedPrice04 = get(configs, 4).fixedPrice; fixedPrice05 = get(configs, 5).fixedPrice; fixedPrice06 = get(configs, 6).fixedPrice; fixedPrice07 = get(configs, 7).fixedPrice; fixedPrice08 = get(configs, 8).fixedPrice; fixedPrice09 = get(configs, 9).fixedPrice; fixedPrice10 = get(configs, 10).fixedPrice; fixedPrice11 = get(configs, 11).fixedPrice; fixedPrice12 = get(configs, 12).fixedPrice; fixedPrice13 = get(configs, 13).fixedPrice; fixedPrice14 = get(configs, 14).fixedPrice; fixedPrice15 = get(configs, 15).fixedPrice; fixedPrice16 = get(configs, 16).fixedPrice; fixedPrice17 = get(configs, 17).fixedPrice; fixedPrice18 = get(configs, 18).fixedPrice; fixedPrice19 = get(configs, 19).fixedPrice; fixedPrice20 = get(configs, 20).fixedPrice; fixedPrice21 = get(configs, 21).fixedPrice; fixedPrice22 = get(configs, 22).fixedPrice; fixedPrice23 = get(configs, 23).fixedPrice; fixedPrice24 = get(configs, 24).fixedPrice; uniswapMarket00 = get(configs, 0).uniswapMarket; uniswapMarket01 = get(configs, 1).uniswapMarket; uniswapMarket02 = get(configs, 2).uniswapMarket; uniswapMarket03 = get(configs, 3).uniswapMarket; uniswapMarket04 = get(configs, 4).uniswapMarket; uniswapMarket05 = get(configs, 5).uniswapMarket; uniswapMarket06 = get(configs, 6).uniswapMarket; uniswapMarket07 = get(configs, 7).uniswapMarket; uniswapMarket08 = get(configs, 8).uniswapMarket; uniswapMarket09 = get(configs, 9).uniswapMarket; uniswapMarket10 = get(configs, 10).uniswapMarket; uniswapMarket11 = get(configs, 11).uniswapMarket; uniswapMarket12 = get(configs, 12).uniswapMarket; uniswapMarket13 = get(configs, 13).uniswapMarket; uniswapMarket14 = get(configs, 14).uniswapMarket; uniswapMarket15 = get(configs, 15).uniswapMarket; uniswapMarket16 = get(configs, 16).uniswapMarket; uniswapMarket17 = get(configs, 17).uniswapMarket; uniswapMarket18 = get(configs, 18).uniswapMarket; uniswapMarket19 = get(configs, 19).uniswapMarket; uniswapMarket20 = get(configs, 20).uniswapMarket; uniswapMarket21 = get(configs, 21).uniswapMarket; uniswapMarket22 = get(configs, 22).uniswapMarket; uniswapMarket23 = get(configs, 23).uniswapMarket; uniswapMarket24 = get(configs, 24).uniswapMarket; reporter00 = get(configs, 0).reporter; reporter01 = get(configs, 1).reporter; reporter02 = get(configs, 2).reporter; reporter03 = get(configs, 3).reporter; reporter04 = get(configs, 4).reporter; reporter05 = get(configs, 5).reporter; reporter06 = get(configs, 6).reporter; reporter07 = get(configs, 7).reporter; reporter08 = get(configs, 8).reporter; reporter09 = get(configs, 9).reporter; reporter10 = get(configs, 10).reporter; reporter11 = get(configs, 11).reporter; reporter12 = get(configs, 12).reporter; reporter13 = get(configs, 13).reporter; reporter14 = get(configs, 14).reporter; reporter15 = get(configs, 15).reporter; reporter16 = get(configs, 16).reporter; reporter17 = get(configs, 17).reporter; reporter18 = get(configs, 18).reporter; reporter19 = get(configs, 19).reporter; reporter20 = get(configs, 20).reporter; reporter21 = get(configs, 21).reporter; reporter22 = get(configs, 22).reporter; reporter23 = get(configs, 23).reporter; reporter24 = get(configs, 24).reporter; reporterMultiplier00 = get(configs, 0).reporterMultiplier; reporterMultiplier01 = get(configs, 1).reporterMultiplier; reporterMultiplier02 = get(configs, 2).reporterMultiplier; reporterMultiplier03 = get(configs, 3).reporterMultiplier; reporterMultiplier04 = get(configs, 4).reporterMultiplier; reporterMultiplier05 = get(configs, 5).reporterMultiplier; reporterMultiplier06 = get(configs, 6).reporterMultiplier; reporterMultiplier07 = get(configs, 7).reporterMultiplier; reporterMultiplier08 = get(configs, 8).reporterMultiplier; reporterMultiplier09 = get(configs, 9).reporterMultiplier; reporterMultiplier10 = get(configs, 10).reporterMultiplier; reporterMultiplier11 = get(configs, 11).reporterMultiplier; reporterMultiplier12 = get(configs, 12).reporterMultiplier; reporterMultiplier13 = get(configs, 13).reporterMultiplier; reporterMultiplier14 = get(configs, 14).reporterMultiplier; reporterMultiplier15 = get(configs, 15).reporterMultiplier; reporterMultiplier16 = get(configs, 16).reporterMultiplier; reporterMultiplier17 = get(configs, 17).reporterMultiplier; reporterMultiplier18 = get(configs, 18).reporterMultiplier; reporterMultiplier19 = get(configs, 19).reporterMultiplier; reporterMultiplier20 = get(configs, 20).reporterMultiplier; reporterMultiplier21 = get(configs, 21).reporterMultiplier; reporterMultiplier22 = get(configs, 22).reporterMultiplier; reporterMultiplier23 = get(configs, 23).reporterMultiplier; reporterMultiplier24 = get(configs, 24).reporterMultiplier; isUniswapReversed00 = get(configs, 0).isUniswapReversed; isUniswapReversed01 = get(configs, 1).isUniswapReversed; isUniswapReversed02 = get(configs, 2).isUniswapReversed; isUniswapReversed03 = get(configs, 3).isUniswapReversed; isUniswapReversed04 = get(configs, 4).isUniswapReversed; isUniswapReversed05 = get(configs, 5).isUniswapReversed; isUniswapReversed06 = get(configs, 6).isUniswapReversed; isUniswapReversed07 = get(configs, 7).isUniswapReversed; isUniswapReversed08 = get(configs, 8).isUniswapReversed; isUniswapReversed09 = get(configs, 9).isUniswapReversed; isUniswapReversed10 = get(configs, 10).isUniswapReversed; isUniswapReversed11 = get(configs, 11).isUniswapReversed; isUniswapReversed12 = get(configs, 12).isUniswapReversed; isUniswapReversed13 = get(configs, 13).isUniswapReversed; isUniswapReversed14 = get(configs, 14).isUniswapReversed; isUniswapReversed15 = get(configs, 15).isUniswapReversed; isUniswapReversed16 = get(configs, 16).isUniswapReversed; isUniswapReversed17 = get(configs, 17).isUniswapReversed; isUniswapReversed18 = get(configs, 18).isUniswapReversed; isUniswapReversed19 = get(configs, 19).isUniswapReversed; isUniswapReversed20 = get(configs, 20).isUniswapReversed; isUniswapReversed21 = get(configs, 21).isUniswapReversed; isUniswapReversed22 = get(configs, 22).isUniswapReversed; isUniswapReversed23 = get(configs, 23).isUniswapReversed; isUniswapReversed24 = get(configs, 24).isUniswapReversed; } function get(TokenConfig[] memory configs, uint i) internal pure returns (TokenConfig memory) { if (i < configs.length) return configs[i]; return TokenConfig({ cToken: address(0), underlying: address(0), symbolHash: bytes32(0), baseUnit: uint256(0), priceSource: PriceSource(0), fixedPrice: uint256(0), uniswapMarket: address(0), reporter: address(0), reporterMultiplier: uint256(0), isUniswapReversed: false }); } function getReporterIndex(address reporter) internal view returns(uint) { if (reporter == reporter00) return 0; if (reporter == reporter01) return 1; if (reporter == reporter02) return 2; if (reporter == reporter03) return 3; if (reporter == reporter04) return 4; if (reporter == reporter05) return 5; if (reporter == reporter06) return 6; if (reporter == reporter07) return 7; if (reporter == reporter08) return 8; if (reporter == reporter09) return 9; if (reporter == reporter10) return 10; if (reporter == reporter11) return 11; if (reporter == reporter12) return 12; if (reporter == reporter13) return 13; if (reporter == reporter14) return 14; if (reporter == reporter15) return 15; if (reporter == reporter16) return 16; if (reporter == reporter17) return 17; if (reporter == reporter18) return 18; if (reporter == reporter19) return 19; if (reporter == reporter20) return 20; if (reporter == reporter21) return 21; if (reporter == reporter22) return 22; if (reporter == reporter23) return 23; if (reporter == reporter24) return 24; return type(uint).max; } function getCTokenIndex(address cToken) internal view returns (uint) { if (cToken == cToken00) return 0; if (cToken == cToken01) return 1; if (cToken == cToken02) return 2; if (cToken == cToken03) return 3; if (cToken == cToken04) return 4; if (cToken == cToken05) return 5; if (cToken == cToken06) return 6; if (cToken == cToken07) return 7; if (cToken == cToken08) return 8; if (cToken == cToken09) return 9; if (cToken == cToken10) return 10; if (cToken == cToken11) return 11; if (cToken == cToken12) return 12; if (cToken == cToken13) return 13; if (cToken == cToken14) return 14; if (cToken == cToken15) return 15; if (cToken == cToken16) return 16; if (cToken == cToken17) return 17; if (cToken == cToken18) return 18; if (cToken == cToken19) return 19; if (cToken == cToken20) return 20; if (cToken == cToken21) return 21; if (cToken == cToken22) return 22; if (cToken == cToken23) return 23; if (cToken == cToken24) return 24; return uint(-1); } function getUnderlyingIndex(address underlying) internal view returns (uint) { if (underlying == underlying00) return 0; if (underlying == underlying01) return 1; if (underlying == underlying02) return 2; if (underlying == underlying03) return 3; if (underlying == underlying04) return 4; if (underlying == underlying05) return 5; if (underlying == underlying06) return 6; if (underlying == underlying07) return 7; if (underlying == underlying08) return 8; if (underlying == underlying09) return 9; if (underlying == underlying10) return 10; if (underlying == underlying11) return 11; if (underlying == underlying12) return 12; if (underlying == underlying13) return 13; if (underlying == underlying14) return 14; if (underlying == underlying15) return 15; if (underlying == underlying16) return 16; if (underlying == underlying17) return 17; if (underlying == underlying18) return 18; if (underlying == underlying19) return 19; if (underlying == underlying20) return 20; if (underlying == underlying21) return 21; if (underlying == underlying22) return 22; if (underlying == underlying23) return 23; if (underlying == underlying24) return 24; return uint(-1); } function getSymbolHashIndex(bytes32 symbolHash) internal view returns (uint) { if (symbolHash == symbolHash00) return 0; if (symbolHash == symbolHash01) return 1; if (symbolHash == symbolHash02) return 2; if (symbolHash == symbolHash03) return 3; if (symbolHash == symbolHash04) return 4; if (symbolHash == symbolHash05) return 5; if (symbolHash == symbolHash06) return 6; if (symbolHash == symbolHash07) return 7; if (symbolHash == symbolHash08) return 8; if (symbolHash == symbolHash09) return 9; if (symbolHash == symbolHash10) return 10; if (symbolHash == symbolHash11) return 11; if (symbolHash == symbolHash12) return 12; if (symbolHash == symbolHash13) return 13; if (symbolHash == symbolHash14) return 14; if (symbolHash == symbolHash15) return 15; if (symbolHash == symbolHash16) return 16; if (symbolHash == symbolHash17) return 17; if (symbolHash == symbolHash18) return 18; if (symbolHash == symbolHash19) return 19; if (symbolHash == symbolHash20) return 20; if (symbolHash == symbolHash21) return 21; if (symbolHash == symbolHash22) return 22; if (symbolHash == symbolHash23) return 23; if (symbolHash == symbolHash24) return 24; return uint(-1); } /** * @notice Get the i-th config, according to the order they were passed in originally * @param i The index of the config to get * @return The config object */ function getTokenConfig(uint i) public view returns (TokenConfig memory) { require(i < numTokens, "token config not found"); if (i == 0) return TokenConfig({cToken: cToken00, underlying: underlying00, symbolHash: symbolHash00, baseUnit: baseUnit00, priceSource: priceSource00, fixedPrice: fixedPrice00, uniswapMarket: uniswapMarket00, reporter: reporter00, reporterMultiplier: reporterMultiplier00, isUniswapReversed: isUniswapReversed00}); if (i == 1) return TokenConfig({cToken: cToken01, underlying: underlying01, symbolHash: symbolHash01, baseUnit: baseUnit01, priceSource: priceSource01, fixedPrice: fixedPrice01, uniswapMarket: uniswapMarket01, reporter: reporter01, reporterMultiplier: reporterMultiplier01, isUniswapReversed: isUniswapReversed01}); if (i == 2) return TokenConfig({cToken: cToken02, underlying: underlying02, symbolHash: symbolHash02, baseUnit: baseUnit02, priceSource: priceSource02, fixedPrice: fixedPrice02, uniswapMarket: uniswapMarket02, reporter: reporter02, reporterMultiplier: reporterMultiplier02, isUniswapReversed: isUniswapReversed02}); if (i == 3) return TokenConfig({cToken: cToken03, underlying: underlying03, symbolHash: symbolHash03, baseUnit: baseUnit03, priceSource: priceSource03, fixedPrice: fixedPrice03, uniswapMarket: uniswapMarket03, reporter: reporter03, reporterMultiplier: reporterMultiplier03, isUniswapReversed: isUniswapReversed03}); if (i == 4) return TokenConfig({cToken: cToken04, underlying: underlying04, symbolHash: symbolHash04, baseUnit: baseUnit04, priceSource: priceSource04, fixedPrice: fixedPrice04, uniswapMarket: uniswapMarket04, reporter: reporter04, reporterMultiplier: reporterMultiplier04, isUniswapReversed: isUniswapReversed04}); if (i == 5) return TokenConfig({cToken: cToken05, underlying: underlying05, symbolHash: symbolHash05, baseUnit: baseUnit05, priceSource: priceSource05, fixedPrice: fixedPrice05, uniswapMarket: uniswapMarket05, reporter: reporter05, reporterMultiplier: reporterMultiplier05, isUniswapReversed: isUniswapReversed05}); if (i == 6) return TokenConfig({cToken: cToken06, underlying: underlying06, symbolHash: symbolHash06, baseUnit: baseUnit06, priceSource: priceSource06, fixedPrice: fixedPrice06, uniswapMarket: uniswapMarket06, reporter: reporter06, reporterMultiplier: reporterMultiplier06, isUniswapReversed: isUniswapReversed06}); if (i == 7) return TokenConfig({cToken: cToken07, underlying: underlying07, symbolHash: symbolHash07, baseUnit: baseUnit07, priceSource: priceSource07, fixedPrice: fixedPrice07, uniswapMarket: uniswapMarket07, reporter: reporter07, reporterMultiplier: reporterMultiplier07, isUniswapReversed: isUniswapReversed07}); if (i == 8) return TokenConfig({cToken: cToken08, underlying: underlying08, symbolHash: symbolHash08, baseUnit: baseUnit08, priceSource: priceSource08, fixedPrice: fixedPrice08, uniswapMarket: uniswapMarket08, reporter: reporter08, reporterMultiplier: reporterMultiplier08, isUniswapReversed: isUniswapReversed08}); if (i == 9) return TokenConfig({cToken: cToken09, underlying: underlying09, symbolHash: symbolHash09, baseUnit: baseUnit09, priceSource: priceSource09, fixedPrice: fixedPrice09, uniswapMarket: uniswapMarket09, reporter: reporter09, reporterMultiplier: reporterMultiplier09, isUniswapReversed: isUniswapReversed09}); if (i == 10) return TokenConfig({cToken: cToken10, underlying: underlying10, symbolHash: symbolHash10, baseUnit: baseUnit10, priceSource: priceSource10, fixedPrice: fixedPrice10, uniswapMarket: uniswapMarket10, reporter: reporter10, reporterMultiplier: reporterMultiplier10, isUniswapReversed: isUniswapReversed10}); if (i == 11) return TokenConfig({cToken: cToken11, underlying: underlying11, symbolHash: symbolHash11, baseUnit: baseUnit11, priceSource: priceSource11, fixedPrice: fixedPrice11, uniswapMarket: uniswapMarket11, reporter: reporter11, reporterMultiplier: reporterMultiplier11, isUniswapReversed: isUniswapReversed11}); if (i == 12) return TokenConfig({cToken: cToken12, underlying: underlying12, symbolHash: symbolHash12, baseUnit: baseUnit12, priceSource: priceSource12, fixedPrice: fixedPrice12, uniswapMarket: uniswapMarket12, reporter: reporter12, reporterMultiplier: reporterMultiplier12, isUniswapReversed: isUniswapReversed12}); if (i == 13) return TokenConfig({cToken: cToken13, underlying: underlying13, symbolHash: symbolHash13, baseUnit: baseUnit13, priceSource: priceSource13, fixedPrice: fixedPrice13, uniswapMarket: uniswapMarket13, reporter: reporter13, reporterMultiplier: reporterMultiplier13, isUniswapReversed: isUniswapReversed13}); if (i == 14) return TokenConfig({cToken: cToken14, underlying: underlying14, symbolHash: symbolHash14, baseUnit: baseUnit14, priceSource: priceSource14, fixedPrice: fixedPrice14, uniswapMarket: uniswapMarket14, reporter: reporter14, reporterMultiplier: reporterMultiplier14, isUniswapReversed: isUniswapReversed14}); if (i == 15) return TokenConfig({cToken: cToken15, underlying: underlying15, symbolHash: symbolHash15, baseUnit: baseUnit15, priceSource: priceSource15, fixedPrice: fixedPrice15, uniswapMarket: uniswapMarket15, reporter: reporter15, reporterMultiplier: reporterMultiplier15, isUniswapReversed: isUniswapReversed15}); if (i == 16) return TokenConfig({cToken: cToken16, underlying: underlying16, symbolHash: symbolHash16, baseUnit: baseUnit16, priceSource: priceSource16, fixedPrice: fixedPrice16, uniswapMarket: uniswapMarket16, reporter: reporter16, reporterMultiplier: reporterMultiplier16, isUniswapReversed: isUniswapReversed16}); if (i == 17) return TokenConfig({cToken: cToken17, underlying: underlying17, symbolHash: symbolHash17, baseUnit: baseUnit17, priceSource: priceSource17, fixedPrice: fixedPrice17, uniswapMarket: uniswapMarket17, reporter: reporter17, reporterMultiplier: reporterMultiplier17, isUniswapReversed: isUniswapReversed17}); if (i == 18) return TokenConfig({cToken: cToken18, underlying: underlying18, symbolHash: symbolHash18, baseUnit: baseUnit18, priceSource: priceSource18, fixedPrice: fixedPrice18, uniswapMarket: uniswapMarket18, reporter: reporter18, reporterMultiplier: reporterMultiplier18, isUniswapReversed: isUniswapReversed18}); if (i == 19) return TokenConfig({cToken: cToken19, underlying: underlying19, symbolHash: symbolHash19, baseUnit: baseUnit19, priceSource: priceSource19, fixedPrice: fixedPrice19, uniswapMarket: uniswapMarket19, reporter: reporter19, reporterMultiplier: reporterMultiplier19, isUniswapReversed: isUniswapReversed19}); if (i == 20) return TokenConfig({cToken: cToken20, underlying: underlying20, symbolHash: symbolHash20, baseUnit: baseUnit20, priceSource: priceSource20, fixedPrice: fixedPrice20, uniswapMarket: uniswapMarket20, reporter: reporter20, reporterMultiplier: reporterMultiplier20, isUniswapReversed: isUniswapReversed20}); if (i == 21) return TokenConfig({cToken: cToken21, underlying: underlying21, symbolHash: symbolHash21, baseUnit: baseUnit21, priceSource: priceSource21, fixedPrice: fixedPrice21, uniswapMarket: uniswapMarket21, reporter: reporter21, reporterMultiplier: reporterMultiplier21, isUniswapReversed: isUniswapReversed21}); if (i == 22) return TokenConfig({cToken: cToken22, underlying: underlying22, symbolHash: symbolHash22, baseUnit: baseUnit22, priceSource: priceSource22, fixedPrice: fixedPrice22, uniswapMarket: uniswapMarket22, reporter: reporter22, reporterMultiplier: reporterMultiplier22, isUniswapReversed: isUniswapReversed22}); if (i == 23) return TokenConfig({cToken: cToken23, underlying: underlying23, symbolHash: symbolHash23, baseUnit: baseUnit23, priceSource: priceSource23, fixedPrice: fixedPrice23, uniswapMarket: uniswapMarket23, reporter: reporter23, reporterMultiplier: reporterMultiplier23, isUniswapReversed: isUniswapReversed23}); if (i == 24) return TokenConfig({cToken: cToken24, underlying: underlying24, symbolHash: symbolHash24, baseUnit: baseUnit24, priceSource: priceSource24, fixedPrice: fixedPrice24, uniswapMarket: uniswapMarket24, reporter: reporter24, reporterMultiplier: reporterMultiplier24, isUniswapReversed: isUniswapReversed24}); } /** * @notice Get the config for symbol * @param symbol The symbol of the config to get * @return The config object */ function getTokenConfigBySymbol(string memory symbol) public view returns (TokenConfig memory) { return getTokenConfigBySymbolHash(keccak256(abi.encodePacked(symbol))); } /** * @notice Get the config for the reporter * @param reporter The address of the reporter of the config to get * @return The config object */ function getTokenConfigByReporter(address reporter) public view returns (TokenConfig memory) { uint index = getReporterIndex(reporter); if (index != uint(-1)) { return getTokenConfig(index); } revert("token config not found"); } /** * @notice Get the config for the symbolHash * @param symbolHash The keccack256 of the symbol of the config to get * @return The config object */ function getTokenConfigBySymbolHash(bytes32 symbolHash) public view returns (TokenConfig memory) { uint index = getSymbolHashIndex(symbolHash); if (index != uint(-1)) { return getTokenConfig(index); } revert("token config not found"); } /** * @notice Get the config for the cToken * @dev If a config for the cToken is not found, falls back to searching for the underlying. * @param cToken The address of the cToken of the config to get * @return The config object */ function getTokenConfigByCToken(address cToken) public view returns (TokenConfig memory) { uint index = getCTokenIndex(cToken); if (index != uint(-1)) { return getTokenConfig(index); } return getTokenConfigByUnderlying(CErc20(cToken).underlying()); } /** * @notice Get the config for an underlying asset * @param underlying The address of the underlying asset of the config to get * @return The config object */ function getTokenConfigByUnderlying(address underlying) public view returns (TokenConfig memory) { uint index = getUnderlyingIndex(underlying); if (index != uint(-1)) { return getTokenConfig(index); } revert("token config not found"); } } struct Observation { uint timestamp; uint acc; } struct PriceData { uint248 price; bool failoverActive; } contract UniswapAnchoredView is AggregatorValidatorInterface, UniswapConfig, Ownable { using FixedPoint for *; /// @notice The number of wei in 1 ETH uint public constant ethBaseUnit = 1e18; /// @notice A common scaling factor to maintain precision uint public constant expScale = 1e18; /// @notice The highest ratio of the new price to the anchor price that will still trigger the price to be updated uint public immutable upperBoundAnchorRatio; /// @notice The lowest ratio of the new price to the anchor price that will still trigger the price to be updated uint public immutable lowerBoundAnchorRatio; /// @notice The minimum amount of time in seconds required for the old uniswap price accumulator to be replaced uint public immutable anchorPeriod; /// @notice Official prices by symbol hash mapping(bytes32 => PriceData) public prices; /// @notice The old observation for each symbolHash mapping(bytes32 => Observation) public oldObservations; /// @notice The new observation for each symbolHash mapping(bytes32 => Observation) public newObservations; /// @notice The event emitted when new prices are posted but the stored price is not updated due to the anchor event PriceGuarded(bytes32 indexed symbolHash, uint reporter, uint anchor); /// @notice The event emitted when the stored price is updated event PriceUpdated(bytes32 indexed symbolHash, uint price); /// @notice The event emitted when anchor price is updated event AnchorPriceUpdated(bytes32 indexed symbolHash, uint anchorPrice, uint oldTimestamp, uint newTimestamp); /// @notice The event emitted when the uniswap window changes event UniswapWindowUpdated(bytes32 indexed symbolHash, uint oldTimestamp, uint newTimestamp, uint oldPrice, uint newPrice); /// @notice The event emitted when failover is activated event FailoverActivated(bytes32 indexed symbolHash); /// @notice The event emitted when failover is deactivated event FailoverDeactivated(bytes32 indexed symbolHash); bytes32 constant ethHash = keccak256(abi.encodePacked("ETH")); /** * @notice Construct a uniswap anchored view for a set of token configurations * @dev Note that to avoid immature TWAPs, the system must run for at least a single anchorPeriod before using. * @param anchorToleranceMantissa_ The percentage tolerance that the reporter may deviate from the uniswap anchor * @param anchorPeriod_ The minimum amount of time required for the old uniswap price accumulator to be replaced * @param configs The static token configurations which define what prices are supported and how */ constructor(uint anchorToleranceMantissa_, uint anchorPeriod_, TokenConfig[] memory configs) UniswapConfig(configs) public { anchorPeriod = anchorPeriod_; // Allow the tolerance to be whatever the deployer chooses, but prevent under/overflow (and prices from being 0) upperBoundAnchorRatio = anchorToleranceMantissa_ > uint(-1) - 100e16 ? uint(-1) : 100e16 + anchorToleranceMantissa_; lowerBoundAnchorRatio = anchorToleranceMantissa_ < 100e16 ? 100e16 - anchorToleranceMantissa_ : 1; for (uint i = 0; i < configs.length; i++) { TokenConfig memory config = configs[i]; require(config.baseUnit > 0, "baseUnit must be greater than zero"); address uniswapMarket = config.uniswapMarket; if (config.priceSource == PriceSource.REPORTER) { require(uniswapMarket != address(0), "reported prices must have an anchor"); require(config.reporter != address(0), "reported price much have a reporter"); bytes32 symbolHash = config.symbolHash; prices[symbolHash].price = 1; uint cumulativePrice = currentCumulativePrice(config); oldObservations[symbolHash].timestamp = block.timestamp; newObservations[symbolHash].timestamp = block.timestamp; oldObservations[symbolHash].acc = cumulativePrice; newObservations[symbolHash].acc = cumulativePrice; emit UniswapWindowUpdated(symbolHash, block.timestamp, block.timestamp, cumulativePrice, cumulativePrice); } else { require(uniswapMarket == address(0), "only reported prices utilize an anchor"); } } } /** * @notice Get the official price for a symbol * @param symbol The symbol to fetch the price of * @return Price denominated in USD, with 6 decimals */ function price(string memory symbol) external view returns (uint) { TokenConfig memory config = getTokenConfigBySymbol(symbol); return priceInternal(config); } function priceInternal(TokenConfig memory config) internal view returns (uint) { if (config.priceSource == PriceSource.REPORTER) return prices[config.symbolHash].price; if (config.priceSource == PriceSource.FIXED_USD) return config.fixedPrice; if (config.priceSource == PriceSource.FIXED_ETH) { uint usdPerEth = prices[ethHash].price; require(usdPerEth > 0, "ETH price not set, cannot convert to dollars"); return mul(usdPerEth, config.fixedPrice) / ethBaseUnit; } } /** * @notice Get the underlying price of a cToken * @dev Implements the PriceOracle interface for Compound v2. * @param cToken The cToken address for price retrieval * @return Price denominated in USD, with 18 decimals, for the given cToken address */ function getUnderlyingPrice(address cToken) external view returns (uint) { TokenConfig memory config = getTokenConfigByCToken(cToken); // Comptroller needs prices in the format: ${raw price} * 1e(36 - baseUnit) // Since the prices in this view have 6 decimals, we must scale them by 1e(36 - 6 - baseUnit) return mul(1e30, priceInternal(config)) / config.baseUnit; } /** * @notice This is called by the reporter whenever a new price is posted on-chain * @dev called by AccessControlledOffChainAggregator * @param currentAnswer the price * @return valid bool */ function validate(uint256/* previousRoundId */, int256 /* previousAnswer */, uint256 /* currentRoundId */, int256 currentAnswer) external override returns (bool valid) { // This will revert if no configs found for the msg.sender TokenConfig memory config = getTokenConfigByReporter(msg.sender); uint256 reportedPrice = convertReportedPrice(config, currentAnswer); uint256 anchorPrice = calculateAnchorPriceFromEthPrice(config); PriceData memory priceData = prices[config.symbolHash]; if (priceData.failoverActive) { require(anchorPrice < 2**248, "Anchor price too large"); prices[config.symbolHash].price = uint248(anchorPrice); emit PriceUpdated(config.symbolHash, anchorPrice); } else if (isWithinAnchor(reportedPrice, anchorPrice)) { require(reportedPrice < 2**248, "Reported price too large"); prices[config.symbolHash].price = uint248(reportedPrice); emit PriceUpdated(config.symbolHash, reportedPrice); valid = true; } else { emit PriceGuarded(config.symbolHash, reportedPrice, anchorPrice); } } /** * @notice In the event that a feed is failed over to Uniswap TWAP, this function can be called * by anyone to update the TWAP price. * @dev This only works if the feed represented by the symbolHash is failed over, and will revert otherwise * @param symbolHash bytes32 */ function pokeFailedOverPrice(bytes32 symbolHash) public { PriceData memory priceData = prices[symbolHash]; require(priceData.failoverActive, "Failover must be active"); TokenConfig memory config = getTokenConfigBySymbolHash(symbolHash); uint anchorPrice = calculateAnchorPriceFromEthPrice(config); require(anchorPrice < 2**248, "Anchor price too large"); prices[config.symbolHash].price = uint248(anchorPrice); emit PriceUpdated(config.symbolHash, anchorPrice); } /** * @notice Calculate the anchor price by fetching price data from the TWAP * @param config TokenConfig * @return anchorPrice uint */ function calculateAnchorPriceFromEthPrice(TokenConfig memory config) internal returns (uint anchorPrice) { uint ethPrice = fetchEthPrice(); require(config.priceSource == PriceSource.REPORTER, "only reporter prices get posted"); if (config.symbolHash == ethHash) { anchorPrice = ethPrice; } else { anchorPrice = fetchAnchorPrice(config.symbolHash, config, ethPrice); } } /** * @notice Convert the reported price to the 6 decimal format that this view requires * @param config TokenConfig * @param reportedPrice from the reporter * @return convertedPrice uint256 */ function convertReportedPrice(TokenConfig memory config, int256 reportedPrice) internal pure returns (uint256) { require(reportedPrice >= 0, "Reported price cannot be negative"); uint256 unsignedPrice = uint256(reportedPrice); uint256 convertedPrice = mul(unsignedPrice, config.reporterMultiplier) / config.baseUnit; return convertedPrice; } function isWithinAnchor(uint reporterPrice, uint anchorPrice) internal view returns (bool) { if (reporterPrice > 0) { uint anchorRatio = mul(anchorPrice, 100e16) / reporterPrice; return anchorRatio <= upperBoundAnchorRatio && anchorRatio >= lowerBoundAnchorRatio; } return false; } /** * @dev Fetches the current token/eth price accumulator from uniswap. */ function currentCumulativePrice(TokenConfig memory config) internal view returns (uint) { (uint cumulativePrice0, uint cumulativePrice1,) = UniswapV2OracleLibrary.currentCumulativePrices(config.uniswapMarket); if (config.isUniswapReversed) { return cumulativePrice1; } else { return cumulativePrice0; } } /** * @dev Fetches the current eth/usd price from uniswap, with 6 decimals of precision. * Conversion factor is 1e18 for eth/usdc market, since we decode uniswap price statically with 18 decimals. */ function fetchEthPrice() internal returns (uint) { return fetchAnchorPrice(ethHash, getTokenConfigBySymbolHash(ethHash), ethBaseUnit); } /** * @dev Fetches the current token/usd price from uniswap, with 6 decimals of precision. * @param conversionFactor 1e18 if seeking the ETH price, and a 6 decimal ETH-USDC price in the case of other assets */ function fetchAnchorPrice(bytes32 symbolHash, TokenConfig memory config, uint conversionFactor) internal virtual returns (uint) { (uint nowCumulativePrice, uint oldCumulativePrice, uint oldTimestamp) = pokeWindowValues(config); // This should be impossible, but better safe than sorry require(block.timestamp > oldTimestamp, "now must come after before"); uint timeElapsed = block.timestamp - oldTimestamp; // Calculate uniswap time-weighted average price // Underflow is a property of the accumulators: https://uniswap.org/audit.html#orgc9b3190 FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(uint224((nowCumulativePrice - oldCumulativePrice) / timeElapsed)); uint rawUniswapPriceMantissa = priceAverage.decode112with18(); uint unscaledPriceMantissa = mul(rawUniswapPriceMantissa, conversionFactor); uint anchorPrice; // Adjust rawUniswapPrice according to the units of the non-ETH asset // In the case of ETH, we would have to scale by 1e6 / USDC_UNITS, but since baseUnit2 is 1e6 (USDC), it cancels // In the case of non-ETH tokens // a. pokeWindowValues already handled uniswap reversed cases, so priceAverage will always be Token/ETH TWAP price. // b. conversionFactor = ETH price * 1e6 // unscaledPriceMantissa = priceAverage(token/ETH TWAP price) * expScale * conversionFactor // so -> // anchorPrice = priceAverage * tokenBaseUnit / ethBaseUnit * ETH_price * 1e6 // = priceAverage * conversionFactor * tokenBaseUnit / ethBaseUnit // = unscaledPriceMantissa / expScale * tokenBaseUnit / ethBaseUnit anchorPrice = mul(unscaledPriceMantissa, config.baseUnit) / ethBaseUnit / expScale; emit AnchorPriceUpdated(symbolHash, anchorPrice, oldTimestamp, block.timestamp); return anchorPrice; } /** * @dev Get time-weighted average prices for a token at the current timestamp. * Update new and old observations of lagging window if period elapsed. */ function pokeWindowValues(TokenConfig memory config) internal returns (uint, uint, uint) { bytes32 symbolHash = config.symbolHash; uint cumulativePrice = currentCumulativePrice(config); Observation memory newObservation = newObservations[symbolHash]; // Update new and old observations if elapsed time is greater than or equal to anchor period uint timeElapsed = block.timestamp - newObservation.timestamp; if (timeElapsed >= anchorPeriod) { oldObservations[symbolHash].timestamp = newObservation.timestamp; oldObservations[symbolHash].acc = newObservation.acc; newObservations[symbolHash].timestamp = block.timestamp; newObservations[symbolHash].acc = cumulativePrice; emit UniswapWindowUpdated(config.symbolHash, newObservation.timestamp, block.timestamp, newObservation.acc, cumulativePrice); } return (cumulativePrice, oldObservations[symbolHash].acc, oldObservations[symbolHash].timestamp); } /** * @notice Activate failover, and fall back to using failover directly. * @dev Only the owner can call this function */ function activateFailover(bytes32 symbolHash) external onlyOwner() { require(!prices[symbolHash].failoverActive, "Already activated"); prices[symbolHash].failoverActive = true; emit FailoverActivated(symbolHash); } /** * @notice Deactivate a previously activated failover * @dev Only the owner can call this function */ function deactivateFailover(bytes32 symbolHash) external onlyOwner() { require(prices[symbolHash].failoverActive, "Already deactivated"); prices[symbolHash].failoverActive = false; emit FailoverDeactivated(symbolHash); } /// @dev Overflow proof multiplication function mul(uint a, uint b) internal pure returns (uint) { if (a == 0) return 0; uint c = a * b; require(c / a == b, "multiplication overflow"); return c; } }
Fetches the current token/usd price from uniswap, with 6 decimals of precision. conversionFactor 1e18 if seeking the ETH price, and a 6 decimal ETH-USDC price in the case of other assets/ This should be impossible, but better safe than sorry Calculate uniswap time-weighted average price Underflow is a property of the accumulators: https:uniswap.org/audit.htmlorgc9b3190 Adjust rawUniswapPrice according to the units of the non-ETH asset In the case of ETH, we would have to scale by 1e6 / USDC_UNITS, but since baseUnit2 is 1e6 (USDC), it cancels In the case of non-ETH tokens a. pokeWindowValues already handled uniswap reversed cases, so priceAverage will always be Token/ETH TWAP price. b. conversionFactor = ETH price 1e6 unscaledPriceMantissa = priceAverage(token/ETH TWAP price) expScale conversionFactor so -> anchorPrice = priceAverage tokenBaseUnit / ethBaseUnit ETH_price 1e6 = priceAverage conversionFactor tokenBaseUnit / ethBaseUnit = unscaledPriceMantissa / expScale tokenBaseUnit / ethBaseUnit
function fetchAnchorPrice(bytes32 symbolHash, TokenConfig memory config, uint conversionFactor) internal virtual returns (uint) { (uint nowCumulativePrice, uint oldCumulativePrice, uint oldTimestamp) = pokeWindowValues(config); require(block.timestamp > oldTimestamp, "now must come after before"); uint timeElapsed = block.timestamp - oldTimestamp; FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(uint224((nowCumulativePrice - oldCumulativePrice) / timeElapsed)); uint rawUniswapPriceMantissa = priceAverage.decode112with18(); uint unscaledPriceMantissa = mul(rawUniswapPriceMantissa, conversionFactor); uint anchorPrice; anchorPrice = mul(unscaledPriceMantissa, config.baseUnit) / ethBaseUnit / expScale; emit AnchorPriceUpdated(symbolHash, anchorPrice, oldTimestamp, block.timestamp); return anchorPrice; }
1,977,980
./full_match/3/0xd894Ab591B2e44fA2A89b0B195d108A140E89d71/sources/maticerc.sol
Moves `amount` of tokens from `sender` to `recipient`. 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; } _balances[to] += amount; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); }
8,124,828
./partial_match/56/0x54696c2A506a4E5801793d32bEC92148Fb161C6A/sources/contracts/StableJoeStaking.sol
View function to see pending reward token on frontend _user The address of the user _token The address of the token return `_user`'s pending reward token/
function pendingReward(address _user, IERC20Upgradeable _token) external view returns (uint256) { require(isRewardToken[_token], "StableJoeStaking: wrong reward token"); UserInfo storage user = userInfo[_user]; uint256 _totalJoe = internalJoeBalance; uint256 _accRewardTokenPerShare = accRewardPerShare[_token]; uint256 _currRewardBalance = _token.balanceOf(address(this)); uint256 _rewardBalance = _token == joe ? _currRewardBalance.sub(_totalJoe) : _currRewardBalance; if (_rewardBalance != lastRewardBalance[_token] && _totalJoe != 0) { uint256 _accruedReward = _rewardBalance.sub(lastRewardBalance[_token]); _accRewardTokenPerShare = _accRewardTokenPerShare.add( _accruedReward.mul(ACC_REWARD_PER_SHARE_PRECISION).div(_totalJoe) ); } return user.amount.mul(_accRewardTokenPerShare).div(ACC_REWARD_PER_SHARE_PRECISION).sub(user.rewardDebt[_token]); }
11,268,402
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.6.0; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./interfaces/IStaking.sol"; contract YieldFarmSushiLPToken { // lib using SafeMath for uint; using SafeMath for uint128; // constants uint public constant TOTAL_DISTRIBUTED_AMOUNT = 60_000_000; uint public constant NR_OF_EPOCHS = 100; uint128 public constant EPOCHS_DELAYED_FROM_STAKING_CONTRACT = 1; // state variables // addreses address private _poolTokenAddress; address private _communityVault; // contracts IERC20 private _xyz; IStaking private _staking; uint[] private epochs = new uint[](NR_OF_EPOCHS + 1); uint private _totalAmountPerEpoch; uint128 public lastInitializedEpoch; mapping(address => uint128) private lastEpochIdHarvested; uint public epochDuration; // init from staking contract uint public epochStart; // init from staking contract // events event MassHarvest(address indexed user, uint256 epochsHarvested, uint256 totalValue); event Harvest(address indexed user, uint128 indexed epochId, uint256 amount); // constructor constructor(address poolTokenAddress, address xyzTokenAddress, address stakeContract, address communityVault) public { _xyz = IERC20(xyzTokenAddress); _poolTokenAddress = poolTokenAddress; _staking = IStaking(stakeContract); _communityVault = communityVault; epochDuration = _staking.epochDuration(); epochStart = _staking.epoch1Start() + epochDuration.mul(EPOCHS_DELAYED_FROM_STAKING_CONTRACT); _totalAmountPerEpoch = TOTAL_DISTRIBUTED_AMOUNT.mul(10**18).div(NR_OF_EPOCHS); } // public methods // public method to harvest all the unharvested epochs until current epoch - 1 function massHarvest() external returns (uint){ uint totalDistributedValue; uint epochId = _getEpochId().sub(1); // fails in epoch 0 // force max number of epochs if (epochId > NR_OF_EPOCHS) { epochId = NR_OF_EPOCHS; } for (uint128 i = lastEpochIdHarvested[msg.sender] + 1; i <= epochId; i++) { // i = epochId // compute distributed Value and do one single transfer at the end totalDistributedValue += _harvest(i); } emit MassHarvest(msg.sender, epochId - lastEpochIdHarvested[msg.sender], totalDistributedValue); if (totalDistributedValue > 0) { _xyz.transferFrom(_communityVault, msg.sender, totalDistributedValue); } return totalDistributedValue; } function harvest (uint128 epochId) external returns (uint){ // checks for requested epoch require (_getEpochId() > epochId, "This epoch is in the future"); require(epochId <= NR_OF_EPOCHS, "Maximum number of epochs is 12"); require (lastEpochIdHarvested[msg.sender].add(1) == epochId, "Harvest in order"); uint userReward = _harvest(epochId); if (userReward > 0) { _xyz.transferFrom(_communityVault, msg.sender, userReward); } emit Harvest(msg.sender, epochId, userReward); return userReward; } // views // calls to the staking smart contract to retrieve the epoch total pool size function getPoolSize(uint128 epochId) external view returns (uint) { return _getPoolSize(epochId); } function getCurrentEpoch() external view returns (uint) { return _getEpochId(); } // calls to the staking smart contract to retrieve user balance for an epoch function getEpochStake(address userAddress, uint128 epochId) external view returns (uint) { return _getUserBalancePerEpoch(userAddress, epochId); } function userLastEpochIdHarvested() external view returns (uint){ return lastEpochIdHarvested[msg.sender]; } // internal methods function _initEpoch(uint128 epochId) internal { require(lastInitializedEpoch.add(1) == epochId, "Epoch can be init only in order"); lastInitializedEpoch = epochId; // call the staking smart contract to init the epoch epochs[epochId] = _getPoolSize(epochId); } function _harvest (uint128 epochId) internal returns (uint) { // try to initialize an epoch. if it can't it fails // if it fails either user either a UniverseXYZ account will init not init epochs if (lastInitializedEpoch < epochId) { _initEpoch(epochId); } // Set user state for last harvested lastEpochIdHarvested[msg.sender] = epochId; // compute and return user total reward. For optimization reasons the transfer have been moved to an upper layer (i.e. massHarvest needs to do a single transfer) // exit if there is no stake on the epoch if (epochs[epochId] == 0) { return 0; } return _totalAmountPerEpoch .mul(_getUserBalancePerEpoch(msg.sender, epochId)) .div(epochs[epochId]); } // retrieve _poolTokenAddress token balance function _getPoolSize(uint128 epochId) internal view returns (uint) { return _staking.getEpochPoolSize(_poolTokenAddress, _stakingEpochId(epochId)); } // retrieve _poolTokenAddress token balance per user per epoch function _getUserBalancePerEpoch(address userAddress, uint128 epochId) internal view returns (uint){ return _staking.getEpochUserBalance(userAddress, _poolTokenAddress, _stakingEpochId(epochId)); } // compute epoch id from block.timestamp and epochStart date function _getEpochId() internal view returns (uint128 epochId) { if (block.timestamp < epochStart) { return 0; } epochId = uint128(block.timestamp.sub(epochStart).div(epochDuration).add(1)); } // get the staking epoch function _stakingEpochId(uint128 epochId) pure internal returns (uint128) { return epochId + EPOCHS_DELAYED_FROM_STAKING_CONTRACT; } } pragma solidity ^0.6.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. */ 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. */ 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. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ 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); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.6.0; import "@openzeppelin/contracts/access/Ownable.sol"; interface IStaking { function getEpochId(uint timestamp) external view returns (uint); // get epoch id function getEpochUserBalance(address user, address token, uint128 epoch) external view returns(uint); function getEpochPoolSize(address token, uint128 epoch) external view returns (uint); function epoch1Start() external view returns (uint); function epochDuration() external view returns (uint); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../GSN/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @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() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.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 GSN 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 payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } }
checks for requested epoch
function harvest (uint128 epochId) external returns (uint){ require (_getEpochId() > epochId, "This epoch is in the future"); require(epochId <= NR_OF_EPOCHS, "Maximum number of epochs is 12"); require (lastEpochIdHarvested[msg.sender].add(1) == epochId, "Harvest in order"); uint userReward = _harvest(epochId); if (userReward > 0) { _xyz.transferFrom(_communityVault, msg.sender, userReward); } emit Harvest(msg.sender, epochId, userReward); return userReward; }
6,215,713
/** *Submitted for verification at Etherscan.io on 2022-04-01 */ // Sources flattened with hardhat v2.9.1 https://hardhat.org // File @openzeppelin/contracts/utils/[email protected] // 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; } } // File @openzeppelin/contracts/access/[email protected] // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @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() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File @openzeppelin/contracts/utils/introspection/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File @openzeppelin/contracts/token/ERC721/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File @openzeppelin/contracts/token/ERC721/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File @openzeppelin/contracts/token/ERC721/extensions/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File @openzeppelin/contracts/utils/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/utils/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File @openzeppelin/contracts/utils/introspection/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File contracts/ERC721Opt.sol pragma solidity ^0.8.4; error ApprovalCallerNotOwnerNorApproved(); error ApprovalQueryForNonexistentToken(); error ApproveToCaller(); error ApprovalToCurrentOwner(); error BalanceQueryForZeroAddress(); error MintToZeroAddress(); error MintToDeadAddress(); error MintZeroQuantity(); error OwnerIndexOutOfBounds(); error OwnerQueryForNonexistentToken(); error TokenIndexOutOfBounds(); error TransferCallerNotOwnerNorApproved(); error TransferFromIncorrectOwner(); error TransferToNonERC721ReceiverImplementer(); error TransferToZeroAddress(); error TransferToDeadAddress(); error UnableGetTokenOwnerByIndex(); error URIQueryForNonexistentToken(); /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 1 (e.g. 1, 2, 3..). */ contract ERC721Opt is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; uint256 internal _nextTokenId = 1; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owners details // An empty struct value does not necessarily mean the token is unowned. See ownerOf implementation for details. mapping(uint256 => address) internal _owners; // Mapping owner address to balances mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Address to use for burned accounting address constant DEAD_ADDR = 0x000000000000000000000000000000000000dEaD; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual returns (uint256) { // Counter underflow is impossible as burned cannot be incremented // more than _nextTokenId - 1 times unchecked { return (_nextTokenId - 1) - balanceOf(DEAD_ADDR); } } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address owner) { if (!_exists(tokenId)) revert OwnerQueryForNonexistentToken(); unchecked { for (uint256 curr = tokenId;; curr--) { owner = _owners[curr]; if (owner != address(0)) { return owner; } } } } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) revert ApprovalCallerNotOwnerNorApproved(); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (!_checkOnERC721Received(from, to, tokenId, _data)) revert TransferToNonERC721ReceiverImplementer(); } function _isApprovedOrOwner(address sender, uint256 tokenId) internal view virtual returns (bool) { address owner = ownerOf(tokenId); return (sender == owner || getApproved(tokenId) == sender || isApprovedForAll(owner, sender)); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return tokenId > 0 && tokenId < _nextTokenId && _owners[tokenId] != DEAD_ADDR; } function _mint(address to, uint256 quantity) internal virtual { _mint(to, quantity, '', false); } function _safeMint(address to, uint256 quantity) internal virtual { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal virtual { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal virtual { uint256 startTokenId = _nextTokenId; if (to == address(0)) revert MintToZeroAddress(); if (to == DEAD_ADDR) revert MintToDeadAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance overflow if current value + quantity > 1.56e77 (2**256) - 1 // updatedIndex overflows if _nextTokenId + quantity > 1.56e77 (2**256) - 1 unchecked { _balances[to] += quantity; _owners[startTokenId] = to; uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe) { if (!_checkOnERC721Received(address(0), to, updatedIndex, _data)) revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _nextTokenId = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { address owner = ownerOf(tokenId); bool isApprovedOrOwner = (_msgSender() == owner || isApprovedForAll(owner, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (owner != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); if (to == DEAD_ADDR) revert TransferToDeadAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, owner); // Underflow of the sender's balance is impossible because we check for // owner above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; // If the owner slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_owners[nextTokenId] == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _nextTokenId) { _owners[nextTokenId] = owner; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ownerOf(tokenId); _beforeTokenTransfers(owner, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, owner); // Underflow of the sender's balance is impossible because we check for // owner above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _balances[owner] -= 1; _balances[DEAD_ADDR] += 1; _owners[tokenId] = DEAD_ADDR; // If the owner slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_owners[nextTokenId] == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _nextTokenId) { _owners[nextTokenId] = owner; } } } emit Transfer(owner, address(0), tokenId); _afterTokenTransfers(owner, address(0), tokenId, 1); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) revert TransferToNonERC721ReceiverImplementer(); else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } // File contracts/extensions/ERC721OptOwnersExplicit.sol pragma solidity ^0.8.4; error AllOwnersHaveBeenSet(); error QuantityMustBeNonZero(); error NoTokensMintedYet(); abstract contract ERC721OptOwnersExplicit is ERC721Opt { uint256 public nextOwnerToExplicitlySet = 1; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { if (quantity == 0) revert QuantityMustBeNonZero(); if (_nextTokenId == 1) revert NoTokensMintedYet(); uint256 _nextOwnerToExplicitlySet = nextOwnerToExplicitlySet; if (_nextOwnerToExplicitlySet >= _nextTokenId) revert AllOwnersHaveBeenSet(); // Index underflow is impossible. // Counter or index overflow is incredibly unrealistic. unchecked { uint256 endIndex = _nextOwnerToExplicitlySet + quantity - 1; // Set the end index to be the last token index if (endIndex + 1 > _nextTokenId) { endIndex = _nextTokenId - 1; } for (uint256 i = _nextOwnerToExplicitlySet; i <= endIndex; i++) { if (_owners[i] == address(0) && _owners[i] != DEAD_ADDR) { address ownership = ownerOf(i); _owners[i] = ownership; } } nextOwnerToExplicitlySet = endIndex + 1; } } } // File contracts/extensions/ERC721OptBurnable.sol pragma solidity ^0.8.4; error BurnCallerNotOwnerNorApproved(); /** * @title ERC721Opt Burnable Token * @dev ERC721Opt Token that can be irreversibly burned (destroyed). */ abstract contract ERC721OptBurnable is ERC721Opt { /** * @dev Burns `tokenId`. See {ERC721Opt-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { if (!_isApprovedOrOwner(_msgSender(), tokenId)) revert BurnCallerNotOwnerNorApproved(); _burn(tokenId); } } // File contracts/extensions/ERC721OptBatchBurnable.sol pragma solidity ^0.8.4; /** * @title ERC721Opt Batch Burnable Token * @dev ERC721Opt Token that can be irreversibly batch burned (destroyed). */ abstract contract ERC721OptBatchBurnable is ERC721OptBurnable { /** * @dev Perform burn on a batch of tokens */ function batchBurn(uint16[] memory tokenIds) public virtual { for (uint16 i = 0; i < tokenIds.length; ++i) { if (!_isApprovedOrOwner(_msgSender(), tokenIds[i])) revert BurnCallerNotOwnerNorApproved(); _burn(tokenIds[i]); } } } // File contracts/extensions/ERC721OptBatchTransferable.sol pragma solidity ^0.8.4; /** * @title ERC721Opt Batch Transferable Token * @dev ERC721Opt Token that can be batch transfered */ abstract contract ERC721OptBatchTransferable is ERC721Opt { /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint16[] tokenIds ); /** * @dev Perform transferFrom on a batch of tokens */ function batchTransferFrom( address from, address to, uint16[] memory tokenIds ) public virtual { for (uint16 i = 0; i < tokenIds.length; ++i) { if (!_isApprovedOrOwner(_msgSender(), tokenIds[i])) revert TransferCallerNotOwnerNorApproved(); transferFrom(from, to, tokenIds[i]); } emit TransferBatch(_msgSender(), from, to, tokenIds); } /** * @dev Perform safeTransferFrom on a batch of tokens */ function safeBatchTransferFrom( address from, address to, uint16[] memory tokenIds ) public virtual { safeBatchTransferFrom(from, to, tokenIds, ''); } /** * @dev Perform safeTransferFrom on a batch of tokens */ function safeBatchTransferFrom( address from, address to, uint16[] memory tokenIds, bytes memory _data ) public virtual { for (uint256 i = 0; i < tokenIds.length; ++i) { if (!_isApprovedOrOwner(_msgSender(), tokenIds[i])) revert TransferCallerNotOwnerNorApproved(); safeTransferFrom(from, to, tokenIds[i], _data); } emit TransferBatch(_msgSender(), from, to, tokenIds); } } // File contracts/OpenSea.sol pragma solidity ^0.8.4; contract OpenSeaOwnableDelegateProxy {} contract OpenSeaProxyRegistry { mapping(address => OpenSeaOwnableDelegateProxy) public proxies; } // File contracts/ApeSquadCharacterSheetNFT.sol pragma solidity ^0.8.4; error CharacterSheetTypeQueryForNonexistentToken(); error OnlyMintersCanMintCharacterSheets(); error InvalidPurchaseCharacterSheetTypeId(); error AllCharacterSheetsOfTypeMinted(); error NoCharacterSheetMintAmountProvided(); error InvalidUpdateCharacterSheetLengthsDontMatch(); error InvalidUpdateCharacterSheetTypeId(); contract ApeSquadCharacterSheetNFT is Ownable, ERC721Opt, ERC721OptOwnersExplicit, ERC721OptBatchBurnable, ERC721OptBatchTransferable { using Strings for uint256; struct CharacterSheetPurchase { uint16 characterSheetTypeId; uint16 amount; } struct CharacterSheetType { string name; uint16 maxCharacterSheets; uint16 minted; } /* Base URI for token URIs */ string public baseURI; /* OpenSea user account proxy */ address public openSeaProxyRegistryAddress; /* Minter addressess */ mapping(address => bool) public minters; CharacterSheetType[] public characterSheetTypes; /* mapping of each token id to characterSheet type */ mapping(uint256 => uint16) _tokenIdCharacterSheetTypes; /* mapping of each token id to rarity. 0 = common, 1 = rare, 2 = legendary */ mapping(uint256 => uint8) public characterSheetRarity; constructor(string memory name_, string memory symbol_, string memory _initialBaseURI, address _openSeaProxyRegistryAddress, address[] memory _minters) ERC721Opt(name_, symbol_) { baseURI = _initialBaseURI; openSeaProxyRegistryAddress = _openSeaProxyRegistryAddress; for (uint256 i; i < _minters.length; i++) { minters[_minters[i]] = true; } _addCharacterSheet("Alex", 250); _addCharacterSheet("Borg", 250); _addCharacterSheet("Dax", 250); _addCharacterSheet("Kanoa", 250); _addCharacterSheet("Kazz", 250); } /** * @dev Get characterSheetType count */ function characterSheetTypeCount() public view returns (uint256) { return characterSheetTypes.length; } /** * @dev Get characterSheets left for sale */ function characterSheetsLeft(uint16 characterSheetTypeId) public view returns (uint256) { return characterSheetTypes[characterSheetTypeId].maxCharacterSheets - characterSheetTypes[characterSheetTypeId].minted; } /** * @dev Get the characterSheet type for a specific tokenId */ function tokenCharacterSheetType(uint256 tokenId) public view returns (string memory) { if (!_exists(tokenId)) revert CharacterSheetTypeQueryForNonexistentToken(); return characterSheetTypes[_tokenIdCharacterSheetTypes[tokenId]].name; } /** * @dev Override to if default approved for OS proxy accounts or normal approval */ function isApprovedForAll(address owner, address operator) public view override returns (bool) { // Whitelist OpenSea proxy contract for easy trading. OpenSeaProxyRegistry openSeaProxyRegistry = OpenSeaProxyRegistry( openSeaProxyRegistryAddress ); if (address(openSeaProxyRegistry.proxies(owner)) == operator) { return true; } return ERC721Opt.isApprovedForAll(owner, operator); } /** * @dev Override to change the baseURI used in tokenURI */ function _baseURI() internal view virtual override returns (string memory) { return baseURI; } /** * @dev Override to change tokenURI format */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(_baseURI(), tokenId.toString(), '.json')) : ''; } /** * @dev Mint of specific characterSheet type to address. */ function mint(address to, CharacterSheetPurchase[] calldata characterSheetPurchases) public { if(!minters[msg.sender]) revert OnlyMintersCanMintCharacterSheets(); uint256 amountToMint; uint256 tokenId = _nextTokenId; for (uint16 i; i < characterSheetPurchases.length; i++) { CharacterSheetPurchase memory p = characterSheetPurchases[i]; if(p.characterSheetTypeId >= characterSheetTypes.length) revert InvalidPurchaseCharacterSheetTypeId(); if(p.amount > characterSheetsLeft(characterSheetPurchases[i].characterSheetTypeId)) revert AllCharacterSheetsOfTypeMinted(); characterSheetTypes[p.characterSheetTypeId].minted += p.amount; amountToMint += p.amount; for (uint16 j; j < p.amount; j++) { _tokenIdCharacterSheetTypes[tokenId++] = p.characterSheetTypeId; } } if(amountToMint == 0) revert NoCharacterSheetMintAmountProvided(); _safeMint(to, amountToMint, ''); } /** * @dev Mint of specific poster type to address. */ function mintType(address to, uint16 characterSheetTypeId, uint16 amount) public { if(!minters[msg.sender]) revert OnlyMintersCanMintCharacterSheets(); if(amount == 0) revert NoCharacterSheetMintAmountProvided(); uint256 tokenId = _nextTokenId; if(characterSheetTypeId >= characterSheetTypes.length) revert InvalidPurchaseCharacterSheetTypeId(); if(amount > characterSheetsLeft(characterSheetTypeId)) revert AllCharacterSheetsOfTypeMinted(); characterSheetTypes[characterSheetTypeId].minted += amount; for (uint16 i; i < amount; i++) { _tokenIdCharacterSheetTypes[tokenId++] = characterSheetTypeId; } _safeMint(to, amount, ''); } /** * @dev Set the base uri for token metadata */ function setBaseURI(string memory _newBaseURI) external onlyOwner { baseURI = _newBaseURI; } /** * @dev Set minter status for addresses */ function setMinters(address[] calldata addresses, bool allowed) external onlyOwner { for(uint256 i; i < addresses.length; i++) { minters[addresses[i]] = allowed; } } /** * @dev Add new characterSheet */ function _addCharacterSheet(string memory name, uint16 maxCharacterSheets) internal { CharacterSheetType memory cs; cs.name = name; cs.maxCharacterSheets = maxCharacterSheets; characterSheetTypes.push(cs); } /** * @dev Add new characterSheet */ function addCharacterSheet(string calldata name, uint16 maxCharacterSheets) external onlyOwner { _addCharacterSheet(name, maxCharacterSheets); } /** * @dev Update characterSheet names */ function updateCharacterSheetNames(uint16[] calldata characterSheetTypeIds, string[] calldata names) external onlyOwner { if(characterSheetTypeIds.length != names.length) revert InvalidUpdateCharacterSheetLengthsDontMatch(); for (uint16 i; i < characterSheetTypeIds.length; i++) { if(characterSheetTypeIds[i] >= characterSheetTypes.length) revert InvalidUpdateCharacterSheetTypeId(); characterSheetTypes[characterSheetTypeIds[i]].name = names[i]; } } /** * @dev Update available characterSheets */ function updateMaxCharacterSheets(uint16[] calldata characterSheetTypeIds, uint16[] calldata maxCharacterSheets) external onlyOwner { if(characterSheetTypeIds.length != maxCharacterSheets.length) revert InvalidUpdateCharacterSheetLengthsDontMatch(); for (uint16 i; i < characterSheetTypeIds.length; i++) { if(characterSheetTypeIds[i] >= characterSheetTypes.length) revert InvalidUpdateCharacterSheetTypeId(); characterSheetTypes[characterSheetTypeIds[i]].maxCharacterSheets = maxCharacterSheets[i]; } } /** * @dev Upate Rarities on chain for future staking */ function updateRarities(uint8 rarity, uint256[] calldata tokenIds) external onlyOwner { if (rarity == 0) { for(uint256 i; i < tokenIds.length; i++) { if (tokenIds[i] >= _nextTokenId) continue; delete characterSheetRarity[tokenIds[i]]; } } else { for(uint256 i; i < tokenIds.length; i++) { if (tokenIds[i] >= _nextTokenId) continue; characterSheetRarity[tokenIds[i]] = rarity; } } } /** * @dev Force update all owners for better transfers */ function updateOwners(uint256 quantity) external onlyOwner { _setOwnersExplicit(quantity); } } // File contracts/ApeSquadPosterNFT.sol pragma solidity ^0.8.4; error PosterTypeQueryForNonexistentToken(); error OnlyMintersCanMintPosters(); error InvalidPurchasePosterTypeId(); error AllPostersOfTypeMinted(); error NoPosterMintAmountProvided(); error InvalidUpdatePosterLengthsDontMatch(); error InvalidUpdatePosterTypeId(); contract ApeSquadPosterNFT is Ownable, ERC721Opt, ERC721OptOwnersExplicit, ERC721OptBatchBurnable, ERC721OptBatchTransferable { using Strings for uint256; struct PosterPurchase { uint16 posterTypeId; uint16 amount; } struct PosterType { string name; uint16 maxPosters; uint16 minted; } /* Base URI for token URIs */ string public baseURI; /* OpenSea user account proxy */ address public openSeaProxyRegistryAddress; /* Minter addressess */ mapping(address => bool) public minters; PosterType[] public posterTypes; /* mapping of each token id to poster type */ mapping(uint256 => uint16) _tokenIdPosterTypes; /* mapping of each token id to rarity. 0 = common, 1 = rare, 2 = legendary */ mapping(uint256 => uint8) public posterRarity; constructor(string memory name_, string memory symbol_, string memory _initialBaseURI, address _openSeaProxyRegistryAddress, address[] memory _minters) ERC721Opt(name_, symbol_) { baseURI = _initialBaseURI; openSeaProxyRegistryAddress = _openSeaProxyRegistryAddress; for (uint256 i; i < _minters.length; i++) { minters[_minters[i]] = true; } _addPoster("Season 1", 1250); } /** * @dev Get posterType count */ function posterTypeCount() public view returns (uint256) { return posterTypes.length; } /** * @dev Get posters left for sale */ function postersLeft(uint16 posterTypeId) public view returns (uint256) { return posterTypes[posterTypeId].maxPosters - posterTypes[posterTypeId].minted; } /** * @dev Get the poster type for a specific tokenId */ function tokenPosterType(uint256 tokenId) public view returns (string memory) { if (!_exists(tokenId)) revert PosterTypeQueryForNonexistentToken(); return posterTypes[_tokenIdPosterTypes[tokenId]].name; } /** * @dev Override to if default approved for OS proxy accounts or normal approval */ function isApprovedForAll(address owner, address operator) public view override returns (bool) { // Whitelist OpenSea proxy contract for easy trading. OpenSeaProxyRegistry openSeaProxyRegistry = OpenSeaProxyRegistry( openSeaProxyRegistryAddress ); if (address(openSeaProxyRegistry.proxies(owner)) == operator) { return true; } return ERC721Opt.isApprovedForAll(owner, operator); } /** * @dev Override to change the baseURI used in tokenURI */ function _baseURI() internal view virtual override returns (string memory) { return baseURI; } /** * @dev Override to change tokenURI format */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(_baseURI(), tokenId.toString(), '.json')) : ''; } /** * @dev Mint of specific poster type to address. */ function mint(address to, PosterPurchase[] calldata posterPurchases) public { if(!minters[msg.sender]) revert OnlyMintersCanMintPosters(); uint256 amountToMint; uint256 tokenId = _nextTokenId; for (uint16 i; i < posterPurchases.length; i++) { PosterPurchase memory p = posterPurchases[i]; if(p.posterTypeId >= posterTypes.length) revert InvalidPurchasePosterTypeId(); if(p.amount > postersLeft(posterPurchases[i].posterTypeId)) revert AllPostersOfTypeMinted(); posterTypes[p.posterTypeId].minted += p.amount; amountToMint += p.amount; for (uint16 j; j < p.amount; j++) { _tokenIdPosterTypes[tokenId++] = p.posterTypeId; } } if(amountToMint == 0) revert NoPosterMintAmountProvided(); _safeMint(to, amountToMint, ''); } /** * @dev Mint of specific poster type to address. */ function mintType(address to, uint16 posterTypeId, uint16 amount) public { if(!minters[msg.sender]) revert OnlyMintersCanMintPosters(); if(amount == 0) revert NoPosterMintAmountProvided(); uint256 tokenId = _nextTokenId; if(posterTypeId >= posterTypes.length) revert InvalidPurchasePosterTypeId(); if(amount > postersLeft(posterTypeId)) revert AllPostersOfTypeMinted(); posterTypes[posterTypeId].minted += amount; for (uint16 i; i < amount; i++) { _tokenIdPosterTypes[tokenId++] = posterTypeId; } _safeMint(to, amount, ''); } /** * @dev Set the base uri for token metadata */ function setBaseURI(string memory _newBaseURI) external onlyOwner { baseURI = _newBaseURI; } /** * @dev Set minter status for addresses */ function setMinters(address[] calldata addresses, bool allowed) external onlyOwner { for(uint256 i; i < addresses.length; i++) { minters[addresses[i]] = allowed; } } /** * @dev Add new poster */ function _addPoster(string memory name, uint16 maxPosters) internal { PosterType memory p; p.name = name; p.maxPosters = maxPosters; posterTypes.push(p); } /** * @dev Add new poster */ function addPoster(string calldata name, uint16 maxPosters) external onlyOwner { _addPoster(name, maxPosters); } /** * @dev Update poster names */ function updatePosterNames(uint16[] calldata posterTypeIds, string[] calldata names) external onlyOwner { if(posterTypeIds.length != names.length) revert InvalidUpdatePosterLengthsDontMatch(); for (uint16 i; i < posterTypeIds.length; i++) { if(posterTypeIds[i] >= posterTypes.length) revert InvalidUpdatePosterTypeId(); posterTypes[posterTypeIds[i]].name = names[i]; } } /** * @dev Update available posters */ function updateMaxPosters(uint16[] calldata posterTypeIds, uint16[] calldata maxPosters) external onlyOwner { if(posterTypeIds.length != maxPosters.length) revert InvalidUpdatePosterLengthsDontMatch(); for (uint16 i; i < posterTypeIds.length; i++) { if(posterTypeIds[i] >= posterTypes.length) revert InvalidUpdatePosterTypeId(); posterTypes[posterTypeIds[i]].maxPosters = maxPosters[i]; } } /** * @dev Upate Rarities on chain for future staking */ function updateRarities(uint8 rarity, uint256[] calldata tokenIds) external onlyOwner { if (rarity == 0) { for(uint256 i; i < tokenIds.length; i++) { if (tokenIds[i] >= _nextTokenId) continue; delete posterRarity[tokenIds[i]]; } } else { for(uint256 i; i < tokenIds.length; i++) { if (tokenIds[i] >= _nextTokenId) continue; posterRarity[tokenIds[i]] = rarity; } } } /** * @dev Force update all owners for better transfers */ function updateOwners(uint256 quantity) external onlyOwner { _setOwnersExplicit(quantity); } } // File contracts/ApeSquadMinter.sol pragma solidity ^0.8.0; contract ApeSquadMinter is Ownable { /* Character Sheet NFT contract */ ApeSquadCharacterSheetNFT characterSheetNFTContract; /* Poster NFT contract */ ApeSquadPosterNFT posterNFTContract; /* Is Sale Active */ bool public saleIsActive; /* silver cards reserved for marketing */ mapping(uint16 => uint16) public reservedCharacterSheets; /* posters reserved for marketing */ uint16 public reservedSeason1Posters = 2; /* Price for character sheets */ uint256 public characterSheetPrice = 0.08 ether; /* NFT Contracts that can get free poster */ address[] public freeSeason1PosterNftContracts; /* Mapping of claimed posters */ mapping(address => bool) public season1PosterClaimed; constructor( ApeSquadCharacterSheetNFT _characterSheetNFTContract, ApeSquadPosterNFT _posterNFTContract, address[] memory _freeSeason1PosterNftContracts ) { characterSheetNFTContract = _characterSheetNFTContract; posterNFTContract = _posterNFTContract; for (uint16 i; i < characterSheetNFTContract.characterSheetTypeCount(); i++) { reservedCharacterSheets[i] = 6; } freeSeason1PosterNftContracts = _freeSeason1PosterNftContracts; } function mint(ApeSquadCharacterSheetNFT.CharacterSheetPurchase[] calldata characterSheetPurchases, bool freeSeason1Poster) external payable { require(msg.sender == tx.origin, 'Only EOA'); require(saleIsActive, 'Regular sale is not active'); uint256 totalAmount; for (uint16 i; i < characterSheetPurchases.length; i++) { require( characterSheetPurchases[i].amount <= characterSheetNFTContract.characterSheetsLeft(characterSheetPurchases[i].characterSheetTypeId) - reservedCharacterSheets[characterSheetPurchases[i].characterSheetTypeId], 'Sold Out' ); totalAmount += characterSheetPurchases[i].amount; } if (freeSeason1Poster) { require(!season1PosterClaimed[msg.sender], 'Season 1 Poster already claimed'); bool valid = totalAmount > 0 || characterSheetNFTContract.balanceOf(msg.sender) > 0; if (totalAmount == 0 && characterSheetNFTContract.balanceOf(msg.sender) == 0) { for (uint256 i; i < freeSeason1PosterNftContracts.length; i++) { valid = valid || IERC721(freeSeason1PosterNftContracts[i]).balanceOf(msg.sender) > 0; if (valid) break; } } require(valid, 'Season 1 Poster requirements not met'); season1PosterClaimed[msg.sender] = true; } require( msg.value >= (totalAmount * characterSheetPrice), 'Ether value sent is not correct' ); if(totalAmount > 0) { characterSheetNFTContract.mint(msg.sender, characterSheetPurchases); } if (freeSeason1Poster) { posterNFTContract.mintType(msg.sender, 0, 1); } } function flipSaleState() external onlyOwner { saleIsActive = !saleIsActive; } function setReserves(uint16[] calldata _characterSheetTypeIds, uint16[] calldata _characterSheetAmounts, uint16 _season1PosterAmount) external onlyOwner { require( _characterSheetTypeIds.length == _characterSheetAmounts.length, 'Character Sheet Type Ids length should match Amounts length' ); for (uint16 i; i < _characterSheetTypeIds.length; i++) { require( _characterSheetTypeIds[i] < characterSheetNFTContract.characterSheetTypeCount(), 'Character Sheet Type Id should be with in range' ); reservedCharacterSheets[_characterSheetTypeIds[i]] = _characterSheetAmounts[i]; } reservedSeason1Posters = _season1PosterAmount; } function setFreeSeason1PosterNftContracts(address[] calldata _freeSeason1PosterNftContracts) external onlyOwner { freeSeason1PosterNftContracts = _freeSeason1PosterNftContracts; } function setPrice(uint256 _characterSheetPrice) external onlyOwner { characterSheetPrice = _characterSheetPrice; } function reserveMint(uint16[] calldata _characterSheetTypeIds, uint16[] calldata _characterSheetAmounts, uint16 season1Posters, address[] calldata to) external onlyOwner { require( _characterSheetTypeIds.length == _characterSheetAmounts.length, 'Character Sheet Type Ids length should match Amounts length' ); for (uint16 i; i < _characterSheetTypeIds.length; i++) { require( (_characterSheetAmounts[i] * to.length) <= reservedCharacterSheets[_characterSheetTypeIds[i]], 'Not enough reserve left for team' ); } require( (season1Posters * to.length) <= reservedSeason1Posters, 'Not enough reserve left for team' ); for (uint16 i = 0; i < to.length; i++) { for (uint16 j; j < _characterSheetTypeIds.length; j++) { characterSheetNFTContract.mintType(to[i], _characterSheetTypeIds[j], _characterSheetAmounts[j]); } if (season1Posters > 0 ) { posterNFTContract.mintType(to[i], 0, season1Posters); } } for (uint16 i; i < _characterSheetTypeIds.length; i++) { reservedCharacterSheets[_characterSheetTypeIds[i]] -= uint16(_characterSheetAmounts[i] * to.length); } reservedSeason1Posters -= uint16(season1Posters * to.length); } function withdraw() external onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } }
Get posters left for sale/
function postersLeft(uint16 posterTypeId) public view returns (uint256) { return posterTypes[posterTypeId].maxPosters - posterTypes[posterTypeId].minted; }
2,328,197
./full_match/42/0xBFf88E8Ef9919b88104Dfc767B892852294259b7/sources/assignmentTokenSkel.sol
TODO: transfer `_value` tokens from `_from` to `_to` NOTE: `_from` needs to have enough tokens and to have allowed sender to spend on his behalf NOTE: transfer value needs to be sufficient to cover fee
function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(balances[_from] >= _value); require(allowance(_from, msg.sender) >= _value); require(_value >= 1); balances[_from] -= _value; balances[_to] += (_value - 1); balances[minter] += 1; emit Transfer(_from, _to, (_value-1)); emit Transfer(_from, minter, 1); allowances[_from][msg.sender] -= _value; return true; }
9,587,169
./partial_match/1/0xD5958ab3106b3320Be17830353C0f0C5E4D09eBc/sources/FraxUnifiedFarm_ERC20_KyberSwapElastic.sol
Get stats about a particular NFT Get pool price info Get the amount of each underlying token in each NFT Get amount of each token for 0.1% liquidity movement in each direction (1 per mille) Get missing decimals Get token prices Will revert if ComboOracle doesn't have a price for both token0 and token1 Get the value of each portion Multiply by liq_pricing_divisor as well
function getNFTValueInfo(uint256 token_id) public view returns (NFTValueInfo memory) { NFTBasicInfo memory lp_basic_info = getNFTBasicInfo(token_id); uint160 sqrtPriceX96; { address pool_address = kyber_factory.getPool(lp_basic_info.token0, lp_basic_info.token1, lp_basic_info.fee); IKyberPool the_pool = IKyberPool(pool_address); (sqrtPriceX96, , , ) = the_pool.getPoolState(); } uint256 token1_val_usd = 0; { uint160 sqrtRatioAX96 = KyberTickMath.getSqrtRatioAtTick(lp_basic_info.tickLower); uint160 sqrtRatioBX96 = KyberTickMath.getSqrtRatioAtTick(lp_basic_info.tickUpper); uint256 liq_pricing_divisor = (10 ** lp_basic_info.lowest_decimals); (uint256 token0_1pm_amt, uint256 token1_1pm_amt) = LiquidityAmounts.getAmountsForLiquidity(sqrtPriceX96, sqrtRatioAX96, sqrtRatioBX96, uint128(lp_basic_info.liquidity / liq_pricing_divisor)); uint256 token0_miss_dec_mult = 10 ** (uint(18) - lp_basic_info.token0_decimals); uint256 token1_miss_dec_mult = 10 ** (uint(18) - lp_basic_info.token1_decimals); (uint256 token0_precise_price, , ) = combo_oracle.getTokenPrice(lp_basic_info.token0); (uint256 token1_precise_price, , ) = combo_oracle.getTokenPrice(lp_basic_info.token1); token0_val_usd = (token0_1pm_amt * liq_pricing_divisor * token0_precise_price * token0_miss_dec_mult) / PRECISE_PRICE_PRECISION; token1_val_usd = (token1_1pm_amt * liq_pricing_divisor * token1_precise_price * token1_miss_dec_mult) / PRECISE_PRICE_PRECISION; } token0_val_usd, token1_val_usd, nft_ttl_val, ERC20(lp_basic_info.token0).symbol(), ERC20(lp_basic_info.token1).symbol(), (uint256(lp_basic_info.liquidity) * PRECISE_PRICE_PRECISION) / nft_ttl_val ); }
16,051,492
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/utils/ERC1155Receiver.sol) pragma solidity ^0.8.0; import "../diamond/LibAppStorage.sol"; import "../interfaces/IERC1155.sol"; import "../interfaces/IPower.sol"; import "hardhat/console.sol"; interface ITokenAttributeSetter { function setAttribute( uint256 _tokenId, string memory key, uint256 value ) external; } /** * @dev Implements an NFT staking pool */ contract AttributeMutationPoolFacet is Modifiers, IPower { event AttributeMutationPoolValuesSet(string attributeKey, uint256 updateValuePerPeriod, uint256 blocksPerPeriod, uint256 totalValueThreshold); event TokenDeposited(address indexed staker, uint256 indexed tokenId); event TokenWithdrawn(address indexed staker, uint256 indexed tokenId, uint256 totalAccrued); event TokenValueThresholdReached(address indexed staker, uint256 indexed tokenId, uint256 totalAccrued); /// @notice set the attribute mutation pool settings function setAttributeMutationSettings(string memory attributeKey, uint256 updateValuePerPeriod, uint256 blocksPerPeriod, uint256 totalValueThreshold) public onlyOwner { require(bytes(attributeKey).length > 0, "attribute key cannot be empty"); require(updateValuePerPeriod > 0, "attribute value per block must be greater than 0"); s.attributeMutationPoolStorage._attributeKey = attributeKey; s.attributeMutationPoolStorage._attributeValuePerPeriod = updateValuePerPeriod; s.attributeMutationPoolStorage._attributeBlocksPerPeriod = blocksPerPeriod; s.attributeMutationPoolStorage._totalValueThreshold = totalValueThreshold; emit AttributeMutationPoolValuesSet(attributeKey, updateValuePerPeriod, blocksPerPeriod, totalValueThreshold); } /// @notice deposit the token into the pool function stake(uint256 tokenId) public { // require that this be a valid token with the correct attribute set to at least 1 uint256 currentAccruedValue = s.tokenAttributeStorage.attributes[tokenId][s.attributeMutationPoolStorage._attributeKey]; require(currentAccruedValue > 0, "token must have accrued value"); console.log("token id", tokenId); // require that this token not be already deposited uint256 tdHeight = s.attributeMutationPoolStorage._tokenDepositHeight[msg.sender][tokenId]; require(tdHeight == 0, "token has already been deposited"); console.log("token height", tdHeight); console.log("token", s.tokenMinterStorage.token); // require that the user have a quantity of the tokenId they specify require(IERC1155(s.tokenMinterStorage.token).balanceOf(msg.sender, tokenId) >= 1, "insufficient funds"); console.log("passed balance check"); // record the deposit in the variables to track it s.attributeMutationPoolStorage._tokenDepositHeight[msg.sender][tokenId] = block.number; IERC1155(s.tokenMinterStorage.token).safeTransferFrom(msg.sender, address(this), tokenId, 1, ""); console.log("transferred token"); console.log(s.attributeMutationPoolStorage._tokenDepositHeight[msg.sender][tokenId]); // emit a token deposited event emit TokenDeposited(msg.sender, tokenId); } /// @notice withdraw the accrued value for a token function unstake(uint256 tokenId) public { console.log(s.attributeMutationPoolStorage._tokenDepositHeight[msg.sender][tokenId]); // require( // s.attributeMutationPoolStorage._tokenDepositHeight[msg.sender][tokenId] > 0 && s.attributeMutationPoolStorage._tokenDepositHeight[msg.sender][tokenId] <= block.number, "token has not been deposited"); require(IERC1155(s.tokenMinterStorage.token).balanceOf(address(this), tokenId) >= 1, "insufficient funds"); uint256 currentAccruedValue = getAccruedValue(tokenId); s.attributeMutationPoolStorage._tokenDepositHeight[msg.sender][tokenId] = 0; // set the attribute to the value, or the total value if value > total value ITokenAttributeSetter(address(this)).setAttribute( tokenId, s.attributeMutationPoolStorage._attributeKey, currentAccruedValue > s.attributeMutationPoolStorage._totalValueThreshold ? s.attributeMutationPoolStorage._totalValueThreshold : currentAccruedValue ); emit PowerUpdated(tokenId, currentAccruedValue); // send the token back to the user IERC1155(s.tokenMinterStorage.token).safeTransferFrom(address(this), msg.sender, tokenId, 1, ""); // emit a token withdrawn event emit TokenWithdrawn(msg.sender, tokenId, currentAccruedValue); // emit a token value threshold reached event if threshold reached if(currentAccruedValue >= s.attributeMutationPoolStorage._totalValueThreshold) { emit TokenValueThresholdReached(msg.sender, tokenId, currentAccruedValue); } } /// @notice get the accrued value for a token function getAccruedValue(uint256 tokenId) public view returns (uint256 _currentAccruedValue) { uint256 depositBlockHeight = s.attributeMutationPoolStorage._tokenDepositHeight[msg.sender][tokenId]; require(depositBlockHeight > 0 && depositBlockHeight <= block.number, "token has not been deposited"); uint256 blocksDeposited = block.number - depositBlockHeight; uint256 accruedValue = blocksDeposited * s.attributeMutationPoolStorage._attributeValuePerPeriod / s.attributeMutationPoolStorage._attributeBlocksPerPeriod; _currentAccruedValue = accruedValue + s.tokenAttributeStorage.attributes[tokenId][s.attributeMutationPoolStorage._attributeKey]; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/UInt256Set.sol"; import "../utils/AddressSet.sol"; import "../interfaces/IMarketplace.sol"; import "../interfaces/ITokenMinter.sol"; import "../interfaces/ITokenSale.sol"; import "../interfaces/IAirdropTokenSale.sol"; import "../interfaces/IERC721A.sol"; import {LibDiamond} from "./LibDiamond.sol"; // struct for erc1155 storage struct ERC1155Storage { mapping(uint256 => mapping(address => uint256)) _balances; mapping(address => mapping(address => bool)) _operatorApprovals; mapping(address => mapping(uint256 => uint256)) _minterApprovals; // mono-uri from erc1155 string _uri; string _uriBase; string _symbol; string _name; address _approvalProxy; } // struct for erc721a storage struct ERC721AStorage { // The tokenId of the next token to be minted. uint256 _currentIndex; // The number of tokens burned. uint256 _burnCounter; // Token name string _name; // Token symbol string _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => IERC721A.TokenOwnership) _ownerships; // Mapping owner address to address data mapping(address => IERC721A.AddressData) _addressData; // Mapping from token ID to approved address mapping(uint256 => address) _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) _operatorApprovals; } // erc2981 storage struct struct ERC2981Storage { // royalty receivers by token hash mapping(uint256 => address) royaltyReceiversByHash; // royalties for each token hash - expressed as permilliage of total supply mapping(uint256 => uint256) royaltyFeesByHash; } // attribute mutatiom pool storage struct AttributeMutationPoolStorage { string _attributeKey; uint256 _attributeValuePerPeriod; uint256 _attributeBlocksPerPeriod; uint256 _totalValueThreshold; mapping (address => mapping (uint256 => uint256)) _tokenDepositHeight; } // token attribute storage struct TokenAttributeStorage { mapping(uint256 => mapping(string => uint256)) attributes; } // merkle utils storage struct MerkleUtilsStorage { mapping(uint256 => uint256) tokenHashToIds; } // NFT marketplace storage struct MarketplaceStorage { uint256 itemsSold; uint256 itemIds; mapping(uint256 => IMarketplace.MarketItem) idToMarketItem; mapping(uint256 => bool) idToListed; } // token minter storage struct TokenMinterStorage { address token; uint256 _tokenCounter; mapping(uint256 => address) _tokenMinters; } // fractionalized token storage struct FractionalizedTokenData { string symbol; string name; address tokenAddress; uint256 tokenId; address fractionalizedToken; uint256 totalFractions; } // fractionalizer storage struct FractionalizerStorage { address fTokenTemplate; mapping(address => FractionalizedTokenData) fractionalizedTokens; } // token sale storage struct TokenSaleStorage { mapping(address => ITokenSale.TokenSaleEntry) tokenSaleEntries; } struct AirdropTokenSaleStorage { uint256 tsnonce; mapping(uint256 => uint256) nonces; // token sale settings mapping(uint256 => IAirdropTokenSale.TokenSaleSettings) _tokenSales; // is token sale open mapping(uint256 => bool) tokenSaleOpen; // total purchased tokens per drop - 0 for public tokensale mapping(uint256 => mapping(address => uint256)) purchased; // total purchased tokens per drop - 0 for public tokensale mapping(uint256 => uint256) totalPurchased; } struct MerkleAirdropStorage { mapping (uint256 => IAirdrop.AirdropSettings) _settings; uint256 numSettings; mapping (uint256 => mapping(uint256 => uint256)) _redeemedData; mapping (uint256 => mapping(address => uint256)) _redeemedDataQuantities; mapping (uint256 => mapping(address => uint256)) _totalDataQuantities; } struct MarketUtilsStorage { mapping(uint256 => bool) validTokens; } struct AppStorage { // gem pools data MarketplaceStorage marketplaceStorage; // gem pools data TokenMinterStorage tokenMinterStorage; // the erc1155 token ERC1155Storage erc1155Storage; // fractionalizer storage FractionalizerStorage fractionalizerStorage; // market utils storage MarketUtilsStorage marketUtilsStorage; // token sale storage TokenSaleStorage tokenSaleStorage; // merkle airdrop storage MerkleAirdropStorage merkleAirdropStorage; // erc721a storage ERC721AStorage erc721AStorage; // erc2981 storage ERC2981Storage erc2981Storage; // attribute mutation pool storage AttributeMutationPoolStorage attributeMutationPoolStorage; // token attribute storage TokenAttributeStorage tokenAttributeStorage; // airdrop token sale storage AirdropTokenSaleStorage airdropTokenSaleStorage; } library LibAppStorage { function diamondStorage() internal pure returns (AppStorage storage ds) { assembly { ds.slot := 0 } } } contract Modifiers { AppStorage internal s; modifier onlyOwner() { require(LibDiamond.contractOwner() == msg.sender || address(this) == msg.sender, "ERC1155: only the contract owner can call this function"); _; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; interface IPower { event PowerUpdated (uint256 tokenId, uint256 power); } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; /** * @notice Key sets with enumeration and delete. Uses mappings for random * and existence checks and dynamic arrays for enumeration. Key uniqueness is enforced. * @dev Sets are unordered. Delete operations reorder keys. All operations have a * fixed gas cost at any scale, O(1). * author: Rob Hitchens */ library UInt256Set { struct Set { mapping(uint256 => uint256) keyPointers; uint256[] keyList; } /** * @notice insert a key. * @dev duplicate keys are not permitted. * @param self storage pointer to a Set. * @param key value to insert. */ function insert(Set storage self, uint256 key) public { require( !exists(self, key), "UInt256Set: key already exists in the set." ); self.keyList.push(key); self.keyPointers[key] = self.keyList.length - 1; } /** * @notice remove a key. * @dev key to remove must exist. * @param self storage pointer to a Set. * @param key value to remove. */ function remove(Set storage self, uint256 key) public { // TODO: I commented this out do get a test to pass - need to figure out what is up here // require( // exists(self, key), // "UInt256Set: key does not exist in the set." // ); if (!exists(self, key)) return; uint256 last = count(self) - 1; uint256 rowToReplace = self.keyPointers[key]; if (rowToReplace != last) { uint256 keyToMove = self.keyList[last]; self.keyPointers[keyToMove] = rowToReplace; self.keyList[rowToReplace] = keyToMove; } delete self.keyPointers[key]; delete self.keyList[self.keyList.length - 1]; } /** * @notice count the keys. * @param self storage pointer to a Set. */ function count(Set storage self) public view returns (uint256) { return (self.keyList.length); } /** * @notice check if a key is in the Set. * @param self storage pointer to a Set. * @param key value to check. * @return bool true: Set member, false: not a Set member. */ function exists(Set storage self, uint256 key) public view returns (bool) { if (self.keyList.length == 0) return false; return self.keyList[self.keyPointers[key]] == key; } /** * @notice fetch a key by row (enumerate). * @param self storage pointer to a Set. * @param index row to enumerate. Must be < count() - 1. */ function keyAtIndex(Set storage self, uint256 index) public view returns (uint256) { return self.keyList[index]; } } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; /** * @notice Key sets with enumeration and delete. Uses mappings for random * and existence checks and dynamic arrays for enumeration. Key uniqueness is enforced. * @dev Sets are unordered. Delete operations reorder keys. All operations have a * fixed gas cost at any scale, O(1). * author: Rob Hitchens */ library AddressSet { struct Set { mapping(address => uint256) keyPointers; address[] keyList; } /** * @notice insert a key. * @dev duplicate keys are not permitted. * @param self storage pointer to a Set. * @param key value to insert. */ function insert(Set storage self, address key) public { require( !exists(self, key), "AddressSet: key already exists in the set." ); self.keyList.push(key); self.keyPointers[key] = self.keyList.length - 1; } /** * @notice remove a key. * @dev key to remove must exist. * @param self storage pointer to a Set. * @param key value to remove. */ function remove(Set storage self, address key) public { // TODO: I commented this out do get a test to pass - need to figure out what is up here require( exists(self, key), "AddressSet: key does not exist in the set." ); if (!exists(self, key)) return; uint256 last = count(self) - 1; uint256 rowToReplace = self.keyPointers[key]; if (rowToReplace != last) { address keyToMove = self.keyList[last]; self.keyPointers[keyToMove] = rowToReplace; self.keyList[rowToReplace] = keyToMove; } delete self.keyPointers[key]; self.keyList.pop(); } /** * @notice count the keys. * @param self storage pointer to a Set. */ function count(Set storage self) public view returns (uint256) { return (self.keyList.length); } /** * @notice check if a key is in the Set. * @param self storage pointer to a Set. * @param key value to check. * @return bool true: Set member, false: not a Set member. */ function exists(Set storage self, address key) public view returns (bool) { if (self.keyList.length == 0) return false; return self.keyList[self.keyPointers[key]] == key; } /** * @notice fetch a key by row (enumerate). * @param self storage pointer to a Set. * @param index row to enumerate. Must be < count() - 1. */ function keyAtIndex(Set storage self, uint256 index) public view returns (address) { return self.keyList[index]; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; interface IMarketplace { event Bids(uint256 indexed itemId, address bidder, uint256 amount); event Sales(uint256 indexed itemId, address indexed owner, uint256 amount, uint256 quantity, uint256 indexed tokenId); event Closes(uint256 indexed itemId); event Listings( uint256 indexed itemId, address indexed nftContract, uint256 indexed tokenId, address seller, address receiver, address owner, uint256 price, bool sold ); struct MarketItem { uint256 itemId; address nftContract; uint256 tokenId; address seller; address owner; uint256 price; uint256 quantity; bool sold; address receiver; } } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "./IERC1155Burn.sol"; /** * @notice This intreface provides a way for users to register addresses as permissioned minters, mint * burn, unregister, and reload the permissioned minter account. */ interface ITokenMinter { /// @notice a registration record for a permissioned minter. struct Minter { // the account address of the permissioned minter. address account; // the amount of tokens minted by the permissioned minter. uint256 minted; // the amount of tokens minted by the permissioned minter. uint256 burned; // the amount of payment spent by the permissioned minter. uint256 spent; // an approval map for this minter. sets a count of tokens the approved can mint. // mapping(address => uint256) approved; // TODO implement this. } /// @notice event emitted when minter is registered event MinterRegistered( address indexed registrant, uint256 depositPaid ); /// @notice emoitted when minter is unregistered event MinterUnregistered( address indexed registrant, uint256 depositReturned ); /// @notice emitted when minter address is reloaded event MinterReloaded( address indexed registrant, uint256 amountDeposited ); /// @notice get the registration record for a permissioned minter. /// @param _minter the address /// @return _minterObj the address function minter(address _minter) external returns (Minter memory _minterObj); /// @notice mint a token associated with a collection with an amount /// @param receiver the mint receiver /// @param collectionId the collection id /// @param amount the amount to mint function mint(address receiver, uint256 collectionId, uint256 id, uint256 amount) external; /// @notice mint a token associated with a collection with an amount /// @param target the mint receiver /// @param id the collection id /// @param amount the amount to mint function burn(address target, uint256 id, uint256 amount) external; } //SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; /// /// @notice A token seller is a contract that can sell tokens to a token buyer. /// The token buyer can buy tokens from the seller by paying a certain amount /// of base currency to receive a certain amount of erc1155 tokens. the number /// of tokens that can be bought is limited by the seller - the seller can /// specify the maximum number of tokens that can be bought per transaction /// and the maximum number of tokens that can be bought in total for a given /// address. The seller can also specify the price of erc1155 tokens and how /// that price increases per successful transaction. interface ITokenSale { struct TokenSaleEntry { address payable receiver; address sourceToken; uint256 sourceTokenId; address token; uint256 quantity; uint256 price; uint256 quantitySold; } event TokenSaleSet(address indexed token, uint256 indexed tokenId, uint256 price, uint256 quantity); event TokenSold(address indexed buyer, address indexed tokenAddress, uint256 indexed tokenId, uint256 salePrice); event TokensSet(address indexed tokenAddress, ITokenSale.TokenSaleEntry tokens); } //SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; import "./ITokenPrice.sol"; import "./IAirdrop.sol"; /// @notice A token seller is a contract that can sell tokens to a token buyer. /// The token buyer can buy tokens from the seller by paying a certain amount /// of base currency to receive a certain amount of erc1155 tokens. the number /// of tokens that can be bought is limited by the seller - the seller can /// specify the maximum number of tokens that can be bought per transaction /// and the maximum number of tokens that can be bought in total for a given /// address. The seller can also specify the price of erc1155 tokens and how /// that price increases per successful transaction. interface IAirdropTokenSale { enum PaymentType { ETH, TOKEN } /// @notice the settings for the token sale, struct TokenSaleSettings { // addresses address contractAddress; // the contract doing the selling address token; // the token being sold uint256 tokenHash; // the token hash being sold. set to 0 to autocreate hash uint256 collectionHash; // the collection hash being sold. set to 0 to autocreate hash // owner and payee address owner; // the owner of the contract address payee; // the payee of the contract string symbol; // the symbol of the token string name; // the name of the token string description; // the description of the token // open state bool openState; // open or closed uint256 startTime; // block number when the sale starts uint256 endTime; // block number when the sale ends // quantities uint256 maxQuantity; // max number of tokens that can be sold uint256 maxQuantityPerSale; // max number of tokens that can be sold per sale uint256 minQuantityPerSale; // min number of tokens that can be sold per sale uint256 maxQuantityPerAccount; // max number of tokens that can be sold per account // inital price of the token sale ITokenPrice.TokenPriceData initialPrice; PaymentType paymentType; // the type of payment that is being used address tokenAddress; // the address of the payment token, if payment type is TOKEN } /// @notice emitted when a token is opened event TokenSaleOpen (uint256 tokenSaleId, TokenSaleSettings tokenSale ); /// @notice emitted when a token is opened event TokenSaleClosed (uint256 tokenSaleId, TokenSaleSettings tokenSale ); /// @notice emitted when a token is opened event TokenPurchased (uint256 tokenSaleId, address indexed purchaser, uint256 tokenId, uint256 quantity ); // token settings were updated event TokenSaleSettingsUpdated (uint256 tokenSaleId, TokenSaleSettings tokenSale ); /// @notice Get the token sale settings /// @return settings the token sale settings function getTokenSaleSettings(uint256 tokenSaleId) external view returns (TokenSaleSettings memory settings); /// @notice Updates the token sale settings /// @param settings - the token sake settings function updateTokenSaleSettings(uint256 iTokenSaleId, TokenSaleSettings memory settings) external; function initTokenSale( TokenSaleSettings memory tokenSaleInit, IAirdrop.AirdropSettings[] calldata settingsList ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721A { // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; // For miscellaneous variable(s) pertaining to the address // (e.g. number of whitelist mint slots used). // If there are multiple variables, please pack them into a uint64. uint64 aux; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) * EIP-2535 Diamonds: https://eips.ethereum.org/EIPS/eip-2535 /******************************************************************************/ import { IDiamondCut } from "../interfaces/IDiamondCut.sol"; /// @notice Defines the data structures that are used to store the data for a diamond library LibDiamond { // the diamond storage position bytes32 constant DIAMOND_STORAGE_POSITION = keccak256("diamond.standard.diamond.storage"); /// @notice Stores the function selectors located within the Diamond struct DiamondStorage { // maps function selectors to the facets that execute the functions. // and maps the selectors to their position in the selectorSlots array. // func selector => address facet, selector position mapping(bytes4 => bytes32) facets; // array of slots of function selectors. // each slot holds 8 function selectors. mapping(uint256 => bytes32) selectorSlots; // The number of function selectors in selectorSlots uint16 selectorCount; // Used to query if a contract implements an interface. // Used to implement ERC-165. mapping(bytes4 => bool) supportedInterfaces; // owner of the contract address contractOwner; } /// @notice Returns the storage position of the diamond function diamondStorage() internal pure returns (DiamondStorage storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION; assembly { ds.slot := position } } // event is generated when the diamond ownership is transferred event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /// @notice set the diamond contract owner /// @param _newOwner the new owner of the diamond function setContractOwner(address _newOwner) internal { DiamondStorage storage ds = diamondStorage(); address previousOwner = ds.contractOwner; ds.contractOwner = _newOwner; emit OwnershipTransferred(previousOwner, _newOwner); } /// @notice returns the diamond contract owner /// @return contractOwner_ the diamond contract owner function contractOwner() internal view returns (address contractOwner_) { contractOwner_ = diamondStorage().contractOwner; } /// @notice enforce contract ownership by requiring the caller to be the contract owner function enforceIsContractOwner() internal view { require(msg.sender == diamondStorage().contractOwner, "LibDiamond: Must be contract owner"); } event DiamondCut(IDiamondCut.FacetCut[] _diamondCut, address _init, bytes _calldata); bytes32 constant CLEAR_ADDRESS_MASK = bytes32(uint256(0xffffffffffffffffffffffff)); bytes32 constant CLEAR_SELECTOR_MASK = bytes32(uint256(0xffffffff << 224)); // Internal function version of diamondCut // This code is almost the same as the external diamondCut, // except it is using 'Facet[] memory _diamondCut' instead of // 'Facet[] calldata _diamondCut'. // The code is duplicated to prevent copying calldata to memory which // causes an error for a two dimensional array. function diamondCut( IDiamondCut.FacetCut[] memory _diamondCut, address _init, bytes memory _calldata ) internal { DiamondStorage storage ds = diamondStorage(); uint256 originalSelectorCount = ds.selectorCount; uint256 selectorCount = originalSelectorCount; bytes32 selectorSlot; // Check if last selector slot is not full // "selectorCount & 7" is a gas efficient modulo by eight "selectorCount % 8" if (selectorCount & 7 > 0) { // get last selectorSlot // "selectorSlot >> 3" is a gas efficient division by 8 "selectorSlot / 8" selectorSlot = ds.selectorSlots[selectorCount >> 3]; } // loop through diamond cut for (uint256 facetIndex; facetIndex < _diamondCut.length; facetIndex++) { (selectorCount, selectorSlot) = addReplaceRemoveFacetSelectors( selectorCount, selectorSlot, _diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].action, _diamondCut[facetIndex].functionSelectors ); } if (selectorCount != originalSelectorCount) { ds.selectorCount = uint16(selectorCount); } // If last selector slot is not full // "selectorCount & 7" is a gas efficient modulo by eight "selectorCount % 8" if (selectorCount & 7 > 0) { // "selectorSlot >> 3" is a gas efficient division by 8 "selectorSlot / 8" ds.selectorSlots[selectorCount >> 3] = selectorSlot; } emit DiamondCut(_diamondCut, _init, _calldata); initializeDiamondCut(_init, _calldata); } /// @notice add or replace facet selectors function addReplaceRemoveFacetSelectors( uint256 _selectorCount, bytes32 _selectorSlot, address _newFacetAddress, IDiamondCut.FacetCutAction _action, bytes4[] memory _selectors ) internal returns (uint256, bytes32) { DiamondStorage storage ds = diamondStorage(); require(_selectors.length > 0, "LibDiamondCut: No selectors in facet to cut"); if (_action == IDiamondCut.FacetCutAction.Add) { enforceHasContractCode(_newFacetAddress, "LibDiamondCut: Add facet has no code"); for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) { bytes4 selector = _selectors[selectorIndex]; bytes32 oldFacet = ds.facets[selector]; require(address(bytes20(oldFacet)) == address(0), "LibDiamondCut: Can't add function that already exists"); // add facet for selector ds.facets[selector] = bytes20(_newFacetAddress) | bytes32(_selectorCount); // "_selectorCount & 7" is a gas efficient modulo by eight "_selectorCount % 8" uint256 selectorInSlotPosition = (_selectorCount & 7) << 5; // clear selector position in slot and add selector _selectorSlot = (_selectorSlot & ~(CLEAR_SELECTOR_MASK >> selectorInSlotPosition)) | (bytes32(selector) >> selectorInSlotPosition); // if slot is full then write it to storage if (selectorInSlotPosition == 224) { // "_selectorSlot >> 3" is a gas efficient division by 8 "_selectorSlot / 8" ds.selectorSlots[_selectorCount >> 3] = _selectorSlot; _selectorSlot = 0; } _selectorCount++; } } else if (_action == IDiamondCut.FacetCutAction.Replace) { enforceHasContractCode(_newFacetAddress, "LibDiamondCut: Replace facet has no code"); for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) { bytes4 selector = _selectors[selectorIndex]; bytes32 oldFacet = ds.facets[selector]; address oldFacetAddress = address(bytes20(oldFacet)); // only useful if immutable functions exist require(oldFacetAddress != address(this), "LibDiamondCut: Can't replace immutable function"); require(oldFacetAddress != _newFacetAddress, "LibDiamondCut: Can't replace function with same function"); require(oldFacetAddress != address(0), "LibDiamondCut: Can't replace function that doesn't exist"); // replace old facet address ds.facets[selector] = (oldFacet & CLEAR_ADDRESS_MASK) | bytes20(_newFacetAddress); } } else if (_action == IDiamondCut.FacetCutAction.Remove) { require(_newFacetAddress == address(0), "LibDiamondCut: Remove facet address must be address(0)"); // "_selectorCount >> 3" is a gas efficient division by 8 "_selectorCount / 8" uint256 selectorSlotCount = _selectorCount >> 3; // "_selectorCount & 7" is a gas efficient modulo by eight "_selectorCount % 8" uint256 selectorInSlotIndex = _selectorCount & 7; for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) { if (_selectorSlot == 0) { // get last selectorSlot selectorSlotCount--; _selectorSlot = ds.selectorSlots[selectorSlotCount]; selectorInSlotIndex = 7; } else { selectorInSlotIndex--; } bytes4 lastSelector; uint256 oldSelectorsSlotCount; uint256 oldSelectorInSlotPosition; // adding a block here prevents stack too deep error { bytes4 selector = _selectors[selectorIndex]; bytes32 oldFacet = ds.facets[selector]; require(address(bytes20(oldFacet)) != address(0), "LibDiamondCut: Can't remove function that doesn't exist"); // only useful if immutable functions exist require(address(bytes20(oldFacet)) != address(this), "LibDiamondCut: Can't remove immutable function"); // replace selector with last selector in ds.facets // gets the last selector lastSelector = bytes4(_selectorSlot << (selectorInSlotIndex << 5)); if (lastSelector != selector) { // update last selector slot position info ds.facets[lastSelector] = (oldFacet & CLEAR_ADDRESS_MASK) | bytes20(ds.facets[lastSelector]); } delete ds.facets[selector]; uint256 oldSelectorCount = uint16(uint256(oldFacet)); // "oldSelectorCount >> 3" is a gas efficient division by 8 "oldSelectorCount / 8" oldSelectorsSlotCount = oldSelectorCount >> 3; // "oldSelectorCount & 7" is a gas efficient modulo by eight "oldSelectorCount % 8" oldSelectorInSlotPosition = (oldSelectorCount & 7) << 5; } if (oldSelectorsSlotCount != selectorSlotCount) { bytes32 oldSelectorSlot = ds.selectorSlots[oldSelectorsSlotCount]; // clears the selector we are deleting and puts the last selector in its place. oldSelectorSlot = (oldSelectorSlot & ~(CLEAR_SELECTOR_MASK >> oldSelectorInSlotPosition)) | (bytes32(lastSelector) >> oldSelectorInSlotPosition); // update storage with the modified slot ds.selectorSlots[oldSelectorsSlotCount] = oldSelectorSlot; } else { // clears the selector we are deleting and puts the last selector in its place. _selectorSlot = (_selectorSlot & ~(CLEAR_SELECTOR_MASK >> oldSelectorInSlotPosition)) | (bytes32(lastSelector) >> oldSelectorInSlotPosition); } if (selectorInSlotIndex == 0) { delete ds.selectorSlots[selectorSlotCount]; _selectorSlot = 0; } } _selectorCount = selectorSlotCount * 8 + selectorInSlotIndex; } else { revert("LibDiamondCut: Incorrect FacetCutAction"); } return (_selectorCount, _selectorSlot); } /// @notice initialise the DiamondCut contract function initializeDiamondCut(address _init, bytes memory _calldata) internal { if (_init == address(0)) { require(_calldata.length == 0, "LibDiamondCut: _init is address(0) but_calldata is not empty"); } else { require(_calldata.length > 0, "LibDiamondCut: _calldata is empty but _init is not address(0)"); if (_init != address(this)) { enforceHasContractCode(_init, "LibDiamondCut: _init address has no code"); } (bool success, bytes memory error) = _init.delegatecall(_calldata); if (!success) { if (error.length > 0) { // bubble up the error revert(string(error)); } else { revert("LibDiamondCut: _init function reverted"); } } } } function enforceHasContractCode(address _contract, string memory _errorMessage) internal view { uint256 contractSize; assembly { contractSize := extcodesize(_contract) } require(contractSize > 0, _errorMessage); } } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; /// implemented by erc1155 tokens to allow burning interface IERC1155Burn { /// @notice event emitted when tokens are burned event Burned( address target, uint256 tokenHash, uint256 amount ); /// @notice burn tokens of specified amount from the specified address /// @param target the burn target /// @param tokenHash the token hash to burn /// @param amount the amount to burn function burn( address target, uint256 tokenHash, uint256 amount ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; /// @notice common struct definitions for tokens interface ITokenPrice { /// @notice DIctates how the price of the token is increased post every sale enum PriceModifier { None, Fixed, Exponential, InverseLog } /// @notice a token price and how it changes struct TokenPriceData { // the price of the token uint256 price; // how the price is modified PriceModifier priceModifier; // only used if priceModifier is EXPONENTIAL or INVERSELOG or FIXED uint256 priceModifierFactor; // max price for the token uint256 maxPrice; } /// @notice get the increased price of the token function getIncreasedPrice() external view returns (uint256); /// @notice get the increased price of the token function getTokenPrice() external view returns (TokenPriceData memory); } //SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; import "./IToken.sol"; import "./ITokenPrice.sol"; import "./IAirdropTokenSale.sol"; interface IMerkleAirdrop { function airdropRedeemed( uint256 drop, address recipient, uint256 amount ) external; function initMerkleAirdrops(IAirdrop.AirdropSettings[] calldata settingsList) external; function airdrop(uint256 drop) external view returns (IAirdrop.AirdropSettings memory settings); function airdropRedeemed(uint256 drop, address recipient) external view returns (bool isRedeemed); } /// @notice an airdrop airdrops tokens interface IAirdrop { // emitted when airdrop is redeemed /// @notice the settings for the token sale, struct AirdropSettings { // sell from the whitelist only bool whitelistOnly; // this whitelist id - by convention is the whitelist hash uint256 whitelistId; // the root hash of the merkle tree bytes32 whitelistHash; // quantities uint256 maxQuantity; // max number of tokens that can be sold uint256 maxQuantityPerSale; // max number of tokens that can be sold per sale uint256 minQuantityPerSale; // min number of tokens that can be sold per sale uint256 maxQuantityPerAccount; // max number of tokens that can be sold per account // quantity of item sold uint256 quantitySold; // start timne and end time for token sale uint256 startTime; // block number when the sale starts uint256 endTime; // block number when the sale ends // inital price of the token sale ITokenPrice.TokenPriceData initialPrice; // token hash uint256 tokenHash; IAirdropTokenSale.PaymentType paymentType; // the type of payment that is being used address tokenAddress; // the address of the payment token, if payment type is TOKEN // the address of the payment token, if payment type is ETH address payee; } // emitted when airdrop is launched event AirdropLaunched(uint256 indexed airdropId, AirdropSettings airdrop); // emitted when airdrop is redeemed event AirdropRedeemed(uint256 indexed airdropId, address indexed beneficiary, uint256 indexed tokenHash, bytes32[] proof, uint256 amount); /// @notice airdrops check to see if proof is redeemed /// @param drop the id of the airdrop /// @param recipient the merkle proof /// @return isRedeemed the amount of tokens redeemed function airdropRedeemed(uint256 drop, address recipient) external view returns (bool isRedeemed); /// @notice redeem tokens for airdrop /// @param drop the airdrop id /// @param leaf the index of the token in the airdrop /// @param recipient the beneficiary of the tokens /// @param amount tje amount of tokens to redeem /// @param merkleProof the merkle proof of the token function redeemAirdrop(uint256 drop, uint256 leaf, address recipient, uint256 amount, uint256 total, bytes32[] memory merkleProof) external payable; /// @notice Get the token sale settings /// @return settings the token sale settings function airdrop(uint256 drop) external view returns (AirdropSettings memory settings); } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; /// @notice common struct definitions for tokens interface IToken { struct Token { uint256 id; uint256 balance; bool burn; } /// @notice a set of tokens. struct TokenSet { mapping(uint256 => uint256) keyPointers; uint256[] keyList; Token[] valueList; } /// @notice the definition for a token. struct TokenDefinition { // the host multitoken address token; // the id of the token definition. if static mint then also token hash uint256 id; // the category name uint256 collectionId; // the name of the token string name; // the symbol of the token string symbol; // the description of the token string description; // the decimals of the token. 0 for NFT uint8 decimals; // the total supply of the token uint256 totalSupply; // whether to generate the id or not for new tokens. if false then we use id field of the definition to mint tokens bool generateId; // probability of the item being awarded uint256 probability; // the index of the probability in its array uint256 probabilityIndex; // the index of the probability in its array uint256 probabilityRoll; } struct TokenRecord { uint256 id; address owner; address minter; uint256 _type; uint256 balance; } /// @notice the token source type. Either a static source or a collection. enum TokenSourceType { Static, Collection } /// @notice the token source. Specifies the source of the token - either a static source or a collection. struct TokenSource { // the token source type TokenSourceType _type; // the source id if a static collection uint256 staticSourceId; // the collection source address if collection address collectionSourceAddress; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) * EIP-2535 Diamonds: https://eips.ethereum.org/EIPS/eip-2535 /******************************************************************************/ interface IDiamondCut { enum FacetCutAction {Add, Replace, Remove} // Add=0, Replace=1, Remove=2 struct FacetCut { address facetAddress; FacetCutAction action; bytes4[] functionSelectors; } /// @notice Add/replace/remove any number of functions and optionally execute /// a function with delegatecall /// @param _diamondCut Contains the facet addresses and function selectors /// @param _init The address of the contract or facet to execute _calldata /// @param _calldata A function call, including function selector and arguments /// _calldata is executed with delegatecall on _init function diamondCut( FacetCut[] calldata _diamondCut, address _init, bytes calldata _calldata ) external; event DiamondCut(FacetCut[] _diamondCut, address _init, bytes _calldata); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol) pragma solidity ^0.8.0; import "../utils/introspection/IERC165.sol"; // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
The address of the owner. Keeps track of the start time of ownership with minimal overhead for tokenomics. Whether the token has been burned.
function getTokenSaleSettings(uint256 tokenSaleId) external view returns (TokenSaleSettings memory settings); function updateTokenSaleSettings(uint256 iTokenSaleId, TokenSaleSettings memory settings) external; function initTokenSale( TokenSaleSettings memory tokenSaleInit, IAirdrop.AirdropSettings[] calldata settingsList ) external; } pragma solidity ^0.8.0; struct TokenOwnership { address addr; uint64 startTimestamp; bool burned; }
581,968
./full_match/4/0xf323D60441134C2529777288662A4EcDbd54B1be/sources/contracts/nf-token.sol
Use and override this function with caution. Wrong usage can have serious consequences. Assigns a new NFT to owner. _to Address to which we want to add the NFT. _tokenId Which NFT we want to add./
function _addNFToken(address _to, uint256 _tokenId) internal virtual { require(idToOwner[_tokenId] == address(0), NFT_ALREADY_EXISTS); idToOwner[_tokenId] = _to; ownerToNFTokenCount[_to] += 1; }
12,427,693