Unnamed: 0
int64
0
7.36k
comments
stringlengths
3
35.2k
code_string
stringlengths
1
527k
code
stringlengths
1
527k
__index_level_0__
int64
0
88.6k
322
// Get the (soon to be) popped strategy.
Strategy poppedStrategy = withdrawalStack[withdrawalStack.length - 1];
Strategy poppedStrategy = withdrawalStack[withdrawalStack.length - 1];
40,340
4
// Owned Basic contract to define an owner. Julien Niset - <julien@argent.xyz> /
contract Owned { // The owner address public owner; event OwnerChanged(address indexed _newOwner); /** * @dev Throws if the sender is not the owner. */ modifier onlyOwner { require(msg.sender == owner, "O: Must be owner"); _; } constructor() public { owner = msg.sender; } /** * @dev Lets the owner transfer ownership of the contract to a new owner. * @param _newOwner The new owner. */ function changeOwner(address _newOwner) external onlyOwner { require(_newOwner != address(0), "O: _newOwner must not be 0"); owner = _newOwner; emit OwnerChanged(_newOwner); } }
contract Owned { // The owner address public owner; event OwnerChanged(address indexed _newOwner); /** * @dev Throws if the sender is not the owner. */ modifier onlyOwner { require(msg.sender == owner, "O: Must be owner"); _; } constructor() public { owner = msg.sender; } /** * @dev Lets the owner transfer ownership of the contract to a new owner. * @param _newOwner The new owner. */ function changeOwner(address _newOwner) external onlyOwner { require(_newOwner != address(0), "O: _newOwner must not be 0"); owner = _newOwner; emit OwnerChanged(_newOwner); } }
4,911
159
// Переходим ко второй стадии Если повторно вызвать финализатор, то еще раз токены не создадутся, условие внутри
mintTokensForSecondStage(); isFirstStageFinalized = true;
mintTokensForSecondStage(); isFirstStageFinalized = true;
36,241
26
// Returns the downcasted uint72 from uint256, reverting onoverflow (when the input is greater than largest uint72). Counterpart to Solidity's `uint72` operator. Requirements: - input must fit into 72 bits /
function toUint72(uint256 value) internal pure returns (uint72) { if (value > type(uint72).max) { revert SafeCastOverflowedUintDowncast(72, value); } return uint72(value); }
function toUint72(uint256 value) internal pure returns (uint72) { if (value > type(uint72).max) { revert SafeCastOverflowedUintDowncast(72, value); } return uint72(value); }
37,574
5
// Each of the variables below is saved in the mapping apiUintVars for each api requeste.g. requestDetails[_requestId].apiUintVars[keccak256("totalTip")]These are the variables saved in this mapping: uint keccak256("granularity"); multiplier for miners uint keccak256("requestQPosition"); index in requestQ uint keccak256("totalTip");bonus portion of payout
mapping(uint => uint) minedBlockNum;//[apiId][minedTimestamp]=>block.number mapping(uint => uint) finalValues;//This the time series of finalValues stored by the contract where uint UNIX timestamp is mapped to value mapping(uint => bool) inDispute;//checks if API id is in dispute or finalized. mapping(uint => address[5]) minersByValue; mapping(uint => uint[5])valuesByTimestamp;
mapping(uint => uint) minedBlockNum;//[apiId][minedTimestamp]=>block.number mapping(uint => uint) finalValues;//This the time series of finalValues stored by the contract where uint UNIX timestamp is mapped to value mapping(uint => bool) inDispute;//checks if API id is in dispute or finalized. mapping(uint => address[5]) minersByValue; mapping(uint => uint[5])valuesByTimestamp;
20,383
5
// Struct for depositing and withdrawing from the BAKC (Pair) pool
struct PairNftWithAmount { uint256 mainTokenId; uint256 bakcTokenId; uint256 amount; }
struct PairNftWithAmount { uint256 mainTokenId; uint256 bakcTokenId; uint256 amount; }
11,483
155
// this function is called by the treasury, and informs sEXO of changes to debt. note that addresses with debt balances cannot transfer collateralized sEXO until the debt has been repaid.
function changeDebt( uint256 amount, address debtor, bool add
function changeDebt( uint256 amount, address debtor, bool add
24,112
0
// IAsset Supertype. Any token that interacts with our system must be wrapped in an asset,whether it is used as RToken backing or not. Any token that can report a price in the UoAis eligible to be an asset. /
interface IAsset { /// @return {UoA/tok} Our best guess at the market price of 1 whole token in the UoA function price() external view returns (uint192); /// @return {tok} The balance of the ERC20 in whole tokens function bal(address account) external view returns (uint192); /// @return The ERC20 contract of the token with decimals() available function erc20() external view returns (IERC20Metadata); /// @return If the asset is an instance of ICollateral or not function isCollateral() external view returns (bool); /// @return {UoA} function maxTradeVolume() external view returns (uint192); // ==== Rewards ==== /// Get the message needed to call in order to claim rewards for holding this asset. /// Returns zero values if there is no reward function to call. /// @return _to The address to send the call to /// @return _calldata The calldata to send function getClaimCalldata() external view returns (address _to, bytes memory _calldata); /// The ERC20 token address that this Asset's rewards are paid in. /// If there are no rewards, will return a zero value. function rewardERC20() external view returns (IERC20 reward); }
interface IAsset { /// @return {UoA/tok} Our best guess at the market price of 1 whole token in the UoA function price() external view returns (uint192); /// @return {tok} The balance of the ERC20 in whole tokens function bal(address account) external view returns (uint192); /// @return The ERC20 contract of the token with decimals() available function erc20() external view returns (IERC20Metadata); /// @return If the asset is an instance of ICollateral or not function isCollateral() external view returns (bool); /// @return {UoA} function maxTradeVolume() external view returns (uint192); // ==== Rewards ==== /// Get the message needed to call in order to claim rewards for holding this asset. /// Returns zero values if there is no reward function to call. /// @return _to The address to send the call to /// @return _calldata The calldata to send function getClaimCalldata() external view returns (address _to, bytes memory _calldata); /// The ERC20 token address that this Asset's rewards are paid in. /// If there are no rewards, will return a zero value. function rewardERC20() external view returns (IERC20 reward); }
51,442
40
// Returns the current nonce for `owner`. This value must beincluded whenever a signature is generated for {permit}. Every successful call to {permit} increases ``owner``'s nonce by one. Thisprevents a signature from being used multiple times. /
function nonces(address owner) external view returns (uint256);
function nonces(address owner) external view returns (uint256);
551
4
// Mapping from token ID => the max number of NFTs of the token ID a wallet can claim.
mapping(uint256 => uint256) maxWalletClaimCount;
mapping(uint256 => uint256) maxWalletClaimCount;
14,793
95
// Only allowed to be executed after endPhase
require(!icoOnSale);
require(!icoOnSale);
24,579
29
// Full ticket id; Jackpot
ids[0] = (_numbers[0] << 30) + (_numbers[1] << 24) + (_numbers[2] << 18) + (_numbers[3] << 12) + (_numbers[4] << 6) + _numbers[5];
ids[0] = (_numbers[0] << 30) + (_numbers[1] << 24) + (_numbers[2] << 18) + (_numbers[3] << 12) + (_numbers[4] << 6) + _numbers[5];
49,143
24
// Emits a {TxWindowChanged} event indicating the updated txWindow.Requirements: - the caller must have the ``OWNER_ROLE``. /
function setTxWindow(uint256 _newTxWindow) public onlyRole(OWNER_ROLE) returns (bool) { txWindow = _newTxWindow; emit TxWindowChanged(_newTxWindow); return true; }
function setTxWindow(uint256 _newTxWindow) public onlyRole(OWNER_ROLE) returns (bool) { txWindow = _newTxWindow; emit TxWindowChanged(_newTxWindow); return true; }
10,664
6
// Mint/burn can be only called by minter contract
modifier onlyMinter { require( msg.sender == minter, "Only minter can call this function." ); _; }
modifier onlyMinter { require( msg.sender == minter, "Only minter can call this function." ); _; }
44,212
5
// Check if an account is blacklist admin member
function isBlacklistAdmin(address account) public view returns (bool) { return _blacklistAdmins.has(account); }
function isBlacklistAdmin(address account) public view returns (bool) { return _blacklistAdmins.has(account); }
49,906
3
// Mochi waits until the stability fees hit 1% and then starts calculating debt after that./E.g. If the stability fees are 10% for a year/Mochi will wait 36.5 days (the time period required for the pre-minted 1%)
mapping(uint256 => Detail) public override details; mapping(uint256 => uint256) public lastDeposit;
mapping(uint256 => Detail) public override details; mapping(uint256 => uint256) public lastDeposit;
47,407
1
// // Minting Rewards ///
{ uint256 reward = getPrice(index) * 400; reward = (reward * (MAX_MINTABLE - index)); reward = reward / 1000 / MAX_MINTABLE; return reward; }
{ uint256 reward = getPrice(index) * 400; reward = (reward * (MAX_MINTABLE - index)); reward = reward / 1000 / MAX_MINTABLE; return reward; }
10,335
156
// ========== ADDRESS RESOLVER CONFIGURATION ========== /
{} /* ========== VIEWS ========== */ function dtrade() internal view returns (IdTrade) { return IdTrade( requireAndGetAddress(CONTRACT_DTRADE, "Missing dTrade address") ); }
{} /* ========== VIEWS ========== */ function dtrade() internal view returns (IdTrade) { return IdTrade( requireAndGetAddress(CONTRACT_DTRADE, "Missing dTrade address") ); }
9,641
45
// Get the options contract's address based on the passed parameters optionTerms is the terms of the option contract /
function getOptionsAddress(
function getOptionsAddress(
19,470
9
// Event emitted when transfer KSM from relay chain to parachain called
event TransferToParachain ( bytes32 from, address to, uint256 amount );
event TransferToParachain ( bytes32 from, address to, uint256 amount );
45,271
7
// end of inline reentrancy guard
function outboundTransfer( address _l1Token, address _to, uint256 _amount, uint256 _maxGas, uint256 _gasPriceBid, bytes calldata _data
function outboundTransfer( address _l1Token, address _to, uint256 _amount, uint256 _maxGas, uint256 _gasPriceBid, bytes calldata _data
33,006
24
// Set token uri prefix for tokens with no extension /
function _setTokenURIPrefix(string calldata prefix) internal { _extensionURIPrefix[address(this)] = prefix; }
function _setTokenURIPrefix(string calldata prefix) internal { _extensionURIPrefix[address(this)] = prefix; }
19,122
27
// Destroys `amount` tokens tokens from `msg.sender`, reducing the total supply. Requirements - `msg.sender` must have at least `amount` tokens./
function burn(uint256 amount) external override returns (bool) { _burn(_msgSender(), amount); return true; }
function burn(uint256 amount) external override returns (bool) { _burn(_msgSender(), amount); return true; }
2,226
185
// This implements an optional extension of {ERC721} defined in the EIP that adds Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
2,332
241
// Calculates initial values for Merkle Tree Insert leaves into the current merkle treeNote: this function INTENTIONALLY causes side effects to save on gas._leafHashes and _count should never be reused. _leafHashes - array of leaf hashes to be added to the merkle tree /
function insertLeaves(uint256[] memory _leafHashes) internal { /* Loop through leafHashes at each level, if the leaf is on the left (index is even) then hash with zeros value and update subtree on this level, if the leaf is on the right (index is odd) then hash with subtree value. After calculating each hash push to relevent spot on leafHashes array. For gas efficiency we reuse the same array and use the count variable to loop to the right index each time. Example of updating a tree of depth 4 with elements 13, 14, and 15 [1,7,15] {1} 1 | [3,7,15] {1} 2-------------------3 | | [6,7,15] {2} 4---------5 6---------7 / \ / \ / \ / \ [13,14,15] {3} 08 09 10 11 12 13 14 15 [] = leafHashes array {} = count variable */ // Get initial count uint256 count = _leafHashes.length; // Create new tree if current one can't contain new leaves // We insert all new commitment into a new tree to ensure they can be spent in the same transaction if ((nextLeafIndex + count) >= (2 ** TREE_DEPTH)) { newTree(); } // Current index is the index at each level to insert the hash uint256 levelInsertionIndex = nextLeafIndex; // Update nextLeafIndex nextLeafIndex += count; // Variables for starting point at next tree level uint256 nextLevelHashIndex; uint256 nextLevelStartIndex; // Loop through each level of the merkle tree and update for (uint256 level = 0; level < TREE_DEPTH; level++) { // Calculate the index to start at for the next level // >> is equivilent to / 2 rounded down nextLevelStartIndex = levelInsertionIndex >> 1; uint256 insertionElement = 0; // If we're on the right, hash and increment to get on the left if (levelInsertionIndex % 2 == 1) { // Calculate index to insert hash into leafHashes[] // >> is equivilent to / 2 rounded down nextLevelHashIndex = (levelInsertionIndex >> 1) - nextLevelStartIndex; // Calculate the hash for the next level _leafHashes[nextLevelHashIndex] = hashLeftRight(filledSubTrees[level], _leafHashes[insertionElement]); // Increment insertionElement += 1; levelInsertionIndex += 1; } // We'll always be on the left side now for (insertionElement; insertionElement < count; insertionElement += 2) { uint256 right; // Calculate right value if (insertionElement < count - 1) { right = _leafHashes[insertionElement + 1]; } else { right = zeros[level]; } // If we've created a new subtree at this level, update if (insertionElement == count - 1 || insertionElement == count - 2) { filledSubTrees[level] = _leafHashes[insertionElement]; } // Calculate index to insert hash into leafHashes[] // >> is equivilent to / 2 rounded down nextLevelHashIndex = (levelInsertionIndex >> 1) - nextLevelStartIndex; // Calculate the hash for the next level _leafHashes[nextLevelHashIndex] = hashLeftRight(_leafHashes[insertionElement], right); // Increment level insertion index levelInsertionIndex += 2; } // Get starting levelInsertionIndex value for next level levelInsertionIndex = nextLevelStartIndex; // Get count of elements for next level count = nextLevelHashIndex + 1; } // Update the Merkle tree root merkleRoot = _leafHashes[0]; rootHistory[treeNumber][merkleRoot] = true; }
function insertLeaves(uint256[] memory _leafHashes) internal { /* Loop through leafHashes at each level, if the leaf is on the left (index is even) then hash with zeros value and update subtree on this level, if the leaf is on the right (index is odd) then hash with subtree value. After calculating each hash push to relevent spot on leafHashes array. For gas efficiency we reuse the same array and use the count variable to loop to the right index each time. Example of updating a tree of depth 4 with elements 13, 14, and 15 [1,7,15] {1} 1 | [3,7,15] {1} 2-------------------3 | | [6,7,15] {2} 4---------5 6---------7 / \ / \ / \ / \ [13,14,15] {3} 08 09 10 11 12 13 14 15 [] = leafHashes array {} = count variable */ // Get initial count uint256 count = _leafHashes.length; // Create new tree if current one can't contain new leaves // We insert all new commitment into a new tree to ensure they can be spent in the same transaction if ((nextLeafIndex + count) >= (2 ** TREE_DEPTH)) { newTree(); } // Current index is the index at each level to insert the hash uint256 levelInsertionIndex = nextLeafIndex; // Update nextLeafIndex nextLeafIndex += count; // Variables for starting point at next tree level uint256 nextLevelHashIndex; uint256 nextLevelStartIndex; // Loop through each level of the merkle tree and update for (uint256 level = 0; level < TREE_DEPTH; level++) { // Calculate the index to start at for the next level // >> is equivilent to / 2 rounded down nextLevelStartIndex = levelInsertionIndex >> 1; uint256 insertionElement = 0; // If we're on the right, hash and increment to get on the left if (levelInsertionIndex % 2 == 1) { // Calculate index to insert hash into leafHashes[] // >> is equivilent to / 2 rounded down nextLevelHashIndex = (levelInsertionIndex >> 1) - nextLevelStartIndex; // Calculate the hash for the next level _leafHashes[nextLevelHashIndex] = hashLeftRight(filledSubTrees[level], _leafHashes[insertionElement]); // Increment insertionElement += 1; levelInsertionIndex += 1; } // We'll always be on the left side now for (insertionElement; insertionElement < count; insertionElement += 2) { uint256 right; // Calculate right value if (insertionElement < count - 1) { right = _leafHashes[insertionElement + 1]; } else { right = zeros[level]; } // If we've created a new subtree at this level, update if (insertionElement == count - 1 || insertionElement == count - 2) { filledSubTrees[level] = _leafHashes[insertionElement]; } // Calculate index to insert hash into leafHashes[] // >> is equivilent to / 2 rounded down nextLevelHashIndex = (levelInsertionIndex >> 1) - nextLevelStartIndex; // Calculate the hash for the next level _leafHashes[nextLevelHashIndex] = hashLeftRight(_leafHashes[insertionElement], right); // Increment level insertion index levelInsertionIndex += 2; } // Get starting levelInsertionIndex value for next level levelInsertionIndex = nextLevelStartIndex; // Get count of elements for next level count = nextLevelHashIndex + 1; } // Update the Merkle tree root merkleRoot = _leafHashes[0]; rootHistory[treeNumber][merkleRoot] = true; }
21,303
48
// start time of this tier should be greater than previous tier
require(_startTimes[i] > _endTimes[i-1]); phases.push(PhaseInfo({ cummulativeHardCap:_cummulativeHardCaps[i], startTime:_startTimes[i], endTime:_endTimes[i], bonusPercentages:_bonusPercentages[i], weiRaised:0 }));
require(_startTimes[i] > _endTimes[i-1]); phases.push(PhaseInfo({ cummulativeHardCap:_cummulativeHardCaps[i], startTime:_startTimes[i], endTime:_endTimes[i], bonusPercentages:_bonusPercentages[i], weiRaised:0 }));
40,354
328
// Freeze `_id` role_id ID of the role to be frozen/
function freeze(bytes32 _id) external onlyConfigGovernor { _freeze(_id); }
function freeze(bytes32 _id) external onlyConfigGovernor { _freeze(_id); }
19,554
27
// if a place for a dragon is found
if (_coolness > leaderboard[i].coolness && !_isIndex) { _index = i; _isIndex = true; }
if (_coolness > leaderboard[i].coolness && !_isIndex) { _index = i; _isIndex = true; }
15,908
68
// fixed window oracle that recomputes the average price for the entire period once every period note that the price average is only guaranteed to be over at least 1 period, but may be over a longer period
contract OracleTWAP { using SafeMath for uint; using FixedPoint for *; IUniswapV2Pair immutable pairRamWeth; IUniswapV2Pair immutable pairUsdtWeth; address public immutable token0; address public immutable token1; address private immutable token0USDT; address private immutable token1USDT; address public wethToken; address public usdtToken; uint256 public tokenPrice; uint256 public wethUSDTPrice; uint public price0CumulativeLast; uint public price1CumulativeLast; uint32 public blockTimestampLast; FixedPoint.uq112x112 public price0Average; FixedPoint.uq112x112 public price1Average; uint public price0CumulativeLastForUSDT; uint public price1CumulativeLastForUSDT; uint32 public blockTimestampLastForUSDT; FixedPoint.uq112x112 public price0AverageForUSDT; FixedPoint.uq112x112 public price1AverageForUSDT; constructor(address factory, address mainToken, address _wethToken, address _usdtToken) public { IUniswapV2Pair _pairRamWeth = IUniswapV2Pair(UniswapV2Library.pairFor(factory, mainToken, _wethToken)); IUniswapV2Pair _pairUsdtWeth = IUniswapV2Pair(UniswapV2Library.pairFor(factory, _usdtToken, _wethToken)); pairRamWeth = _pairRamWeth; pairUsdtWeth = _pairUsdtWeth; wethToken = _wethToken; usdtToken = _usdtToken; token0 = _pairRamWeth.token0(); token1 = _pairRamWeth.token1(); price0CumulativeLast = _pairRamWeth.price0CumulativeLast(); // fetch the current accumulated price value (1 / 0) price1CumulativeLast = _pairRamWeth.price1CumulativeLast(); // fetch the current accumulated price value (0 / 1) uint112 reserve0; uint112 reserve1; (reserve0, reserve1, blockTimestampLast) = _pairRamWeth.getReserves(); require(reserve0 != 0 && reserve1 != 0, 'OraclePrice: NO_RESERVES'); // ensure that there's liquidity in the pair token0USDT = _pairUsdtWeth.token0(); token1USDT = _pairUsdtWeth.token1(); price0CumulativeLastForUSDT = _pairUsdtWeth.price0CumulativeLast(); // fetch the current accumulated price value (1 / 0) price1CumulativeLastForUSDT = _pairUsdtWeth.price1CumulativeLast(); // fetch the current accumulated price value (0 / 1) uint112 reserve0USDT; uint112 reserve1USDT; (reserve0USDT, reserve1USDT, blockTimestampLastForUSDT) = _pairUsdtWeth.getReserves(); require(reserve0USDT != 0 && reserve1USDT != 0, 'OraclePrice: NO_RESERVES USDT'); // ensure that there's liquidity in the pair } function update() internal { (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(address(pairRamWeth)); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired // overflow is desired, casting never truncates // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed price0Average = FixedPoint.uq112x112(uint224((price0Cumulative - price0CumulativeLast) / timeElapsed)); price1Average = FixedPoint.uq112x112(uint224((price1Cumulative - price1CumulativeLast) / timeElapsed)); price0CumulativeLast = price0Cumulative; price1CumulativeLast = price1Cumulative; blockTimestampLast = blockTimestamp; } function updateUsdtWeth() internal { (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(address(pairUsdtWeth)); uint32 timeElapsed = blockTimestamp - blockTimestampLastForUSDT; // overflow is desired // overflow is desired, casting never truncates // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed price0AverageForUSDT = FixedPoint.uq112x112(uint224((price0Cumulative - price0CumulativeLastForUSDT) / timeElapsed)); price1AverageForUSDT = FixedPoint.uq112x112(uint224((price1Cumulative - price1CumulativeLastForUSDT) / timeElapsed)); price0CumulativeLastForUSDT = price0Cumulative; price1CumulativeLastForUSDT = price1Cumulative; blockTimestampLastForUSDT = blockTimestamp; } function getData() external returns (uint256, bool) { update(); updateUsdtWeth(); uint price = 10**18; if (token0 != wethToken) { price = price1Average.mul(10**18).decode144(); wethUSDTPrice = price0AverageForUSDT.mul(10**18).decode144(); wethUSDTPrice = wethUSDTPrice.mul(10**12).add(999999999999); price = (wethUSDTPrice.mul(10**18)).div(price.mul(10**9).add(999999999)); } else { require(token1 != wethToken, 'OraclePrice: INVALID_TOKEN'); price = price0Average.mul(10**18).decode144(); wethUSDTPrice = price1AverageForUSDT.mul(10**18).decode144(); wethUSDTPrice = wethUSDTPrice.mul(10**12).add(999999999999); price = (wethUSDTPrice.mul(10**18)).div(price.mul(10**9).add(999999999)); } tokenPrice = price; return (price, true); } // note this will always return 0 before update has been called successfully for the first time. function consult(address token, uint amountIn) external view returns (uint amountOut) { if (token == token0) { amountOut = price0Average.mul(amountIn).decode144(); } else { require(token == token1, 'OraclePrice: INVALID_TOKEN'); amountOut = price1Average.mul(amountIn).decode144(); } } }
contract OracleTWAP { using SafeMath for uint; using FixedPoint for *; IUniswapV2Pair immutable pairRamWeth; IUniswapV2Pair immutable pairUsdtWeth; address public immutable token0; address public immutable token1; address private immutable token0USDT; address private immutable token1USDT; address public wethToken; address public usdtToken; uint256 public tokenPrice; uint256 public wethUSDTPrice; uint public price0CumulativeLast; uint public price1CumulativeLast; uint32 public blockTimestampLast; FixedPoint.uq112x112 public price0Average; FixedPoint.uq112x112 public price1Average; uint public price0CumulativeLastForUSDT; uint public price1CumulativeLastForUSDT; uint32 public blockTimestampLastForUSDT; FixedPoint.uq112x112 public price0AverageForUSDT; FixedPoint.uq112x112 public price1AverageForUSDT; constructor(address factory, address mainToken, address _wethToken, address _usdtToken) public { IUniswapV2Pair _pairRamWeth = IUniswapV2Pair(UniswapV2Library.pairFor(factory, mainToken, _wethToken)); IUniswapV2Pair _pairUsdtWeth = IUniswapV2Pair(UniswapV2Library.pairFor(factory, _usdtToken, _wethToken)); pairRamWeth = _pairRamWeth; pairUsdtWeth = _pairUsdtWeth; wethToken = _wethToken; usdtToken = _usdtToken; token0 = _pairRamWeth.token0(); token1 = _pairRamWeth.token1(); price0CumulativeLast = _pairRamWeth.price0CumulativeLast(); // fetch the current accumulated price value (1 / 0) price1CumulativeLast = _pairRamWeth.price1CumulativeLast(); // fetch the current accumulated price value (0 / 1) uint112 reserve0; uint112 reserve1; (reserve0, reserve1, blockTimestampLast) = _pairRamWeth.getReserves(); require(reserve0 != 0 && reserve1 != 0, 'OraclePrice: NO_RESERVES'); // ensure that there's liquidity in the pair token0USDT = _pairUsdtWeth.token0(); token1USDT = _pairUsdtWeth.token1(); price0CumulativeLastForUSDT = _pairUsdtWeth.price0CumulativeLast(); // fetch the current accumulated price value (1 / 0) price1CumulativeLastForUSDT = _pairUsdtWeth.price1CumulativeLast(); // fetch the current accumulated price value (0 / 1) uint112 reserve0USDT; uint112 reserve1USDT; (reserve0USDT, reserve1USDT, blockTimestampLastForUSDT) = _pairUsdtWeth.getReserves(); require(reserve0USDT != 0 && reserve1USDT != 0, 'OraclePrice: NO_RESERVES USDT'); // ensure that there's liquidity in the pair } function update() internal { (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(address(pairRamWeth)); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired // overflow is desired, casting never truncates // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed price0Average = FixedPoint.uq112x112(uint224((price0Cumulative - price0CumulativeLast) / timeElapsed)); price1Average = FixedPoint.uq112x112(uint224((price1Cumulative - price1CumulativeLast) / timeElapsed)); price0CumulativeLast = price0Cumulative; price1CumulativeLast = price1Cumulative; blockTimestampLast = blockTimestamp; } function updateUsdtWeth() internal { (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(address(pairUsdtWeth)); uint32 timeElapsed = blockTimestamp - blockTimestampLastForUSDT; // overflow is desired // overflow is desired, casting never truncates // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed price0AverageForUSDT = FixedPoint.uq112x112(uint224((price0Cumulative - price0CumulativeLastForUSDT) / timeElapsed)); price1AverageForUSDT = FixedPoint.uq112x112(uint224((price1Cumulative - price1CumulativeLastForUSDT) / timeElapsed)); price0CumulativeLastForUSDT = price0Cumulative; price1CumulativeLastForUSDT = price1Cumulative; blockTimestampLastForUSDT = blockTimestamp; } function getData() external returns (uint256, bool) { update(); updateUsdtWeth(); uint price = 10**18; if (token0 != wethToken) { price = price1Average.mul(10**18).decode144(); wethUSDTPrice = price0AverageForUSDT.mul(10**18).decode144(); wethUSDTPrice = wethUSDTPrice.mul(10**12).add(999999999999); price = (wethUSDTPrice.mul(10**18)).div(price.mul(10**9).add(999999999)); } else { require(token1 != wethToken, 'OraclePrice: INVALID_TOKEN'); price = price0Average.mul(10**18).decode144(); wethUSDTPrice = price1AverageForUSDT.mul(10**18).decode144(); wethUSDTPrice = wethUSDTPrice.mul(10**12).add(999999999999); price = (wethUSDTPrice.mul(10**18)).div(price.mul(10**9).add(999999999)); } tokenPrice = price; return (price, true); } // note this will always return 0 before update has been called successfully for the first time. function consult(address token, uint amountIn) external view returns (uint amountOut) { if (token == token0) { amountOut = price0Average.mul(amountIn).decode144(); } else { require(token == token1, 'OraclePrice: INVALID_TOKEN'); amountOut = price1Average.mul(amountIn).decode144(); } } }
37,856
172
// withdraw ether to nami multisignature wallet, only escrow can call/_amount value ether in wei to withdraw
function withdrawEther(uint _amount) public onlyEscrow
function withdrawEther(uint _amount) public onlyEscrow
12,483
169
// Given a utxo position and a unique ID, returns an exit priority. _exitId Unique exit identifier. _utxoPos Position of the exit in the blockchain.return An exit priority.Anatomy of returned value, most significant bits first42 bits - timestamp (exitable_at); unix timestamp fits into 32 bits54 bits - blknum10^9 + txindex; to represent all utxo for 10 years we need only 54 bits8 bits - oindex; set to zero for in-flight tx1 bit - in-flight flag151 bit - tx hash /
function getStandardExitPriority(uint192 _exitId, uint256 _utxoPos) public view returns (uint256)
function getStandardExitPriority(uint192 _exitId, uint256 _utxoPos) public view returns (uint256)
26,777
3
// events when votes are casted
event VoteCasted(string indexed _choice);
event VoteCasted(string indexed _choice);
42,522
37
// Checks whether primary sale recipient can be set in the given execution context.
function _canSetPrimarySaleRecipient() internal view override returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, msg.sender); }
function _canSetPrimarySaleRecipient() internal view override returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, msg.sender); }
15,732
33
// Processes the message coming from the bridge DEPOSIT/RECOVERFUNDS messages are the only messages that can be sent to the portfolio sub for the momentEven when the contract is paused, this method is allowed for the messages thatare in flight to complete properly.CAUTION: if Paused for upgrade, wait to make sure no messages are in flight, then upgrade. _traderAddress of the trader _symbolSymbol of the token _quantityAmount of the token _transactionTransaction type /
function processXFerPayload( address _trader, bytes32 _symbol, uint256 _quantity, Tx _transaction
function processXFerPayload( address _trader, bytes32 _symbol, uint256 _quantity, Tx _transaction
34,326
18
// The platform provider payment address for all primary sales revenues/ (packed)
address payable public platformProviderPrimarySalesAddress;
address payable public platformProviderPrimarySalesAddress;
33,077
8
// Transfers control of the contract to a newOwner. _newOwner The address to transfer ownership to. /
function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; }
function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; }
8,414
33
// Storage for Governor Delegate For future upgrades, do not change GovernorStorage. Create a newcontract which implements GovernorStorage and following the naming conventionGovernor DelegateStorageVX. /
contract GovernorStorage { /// @notice Administrator for this contract address public admin; /// @notice Pending administrator for this contract address public pendingAdmin; /// @notice Active brains of Governor address public implementation; /// @notice The delay before voting on a proposal may take place, once proposed, in blocks uint256 public votingDelay; /// @notice The duration of voting on a proposal, in blocks uint256 public votingPeriod; /// @notice The number of votes required in order for a voter to become a proposer uint256 public proposalThreshold; /// @notice Initial proposal id set at become uint256 public initialProposalId; /// @notice The total number of proposals uint256 public proposalCount; /// @notice The address of the DETF Protocol Timelock ITokenTimelock public timelock; /// @notice The address of the DETF token IDetf public detf; /// @notice The official record of all proposals ever proposed mapping(uint256 => Proposal) public proposals; /// @notice The latest proposal for each proposer mapping(address => uint256) public latestProposalIds; struct Proposal { /// @notice Unique id for looking up a proposal uint256 id; /// @notice Creator of the proposal address proposer; /// @notice The timestamp that the proposal will be available for execution, set once the vote succeeds uint256 eta; /// @notice the ordered list of target addresses for calls to be made address[] targets; /// @notice The ordered list of values (i.e. msg.value) to be passed to the calls to be made uint256[] values; /// @notice The ordered list of function signatures to be called string[] signatures; /// @notice The ordered list of calldata to be passed to each call bytes[] calldatas; /// @notice The block at which voting begins: holders must delegate their votes prior to this block uint256 startBlock; /// @notice The block at which voting ends: votes must be cast prior to this block uint256 endBlock; /// @notice Current number of votes in favor of this proposal uint256 forVotes; /// @notice Current number of votes in opposition to this proposal uint256 againstVotes; /// @notice Current number of votes for abstaining for this proposal uint256 abstainVotes; /// @notice Flag marking whether the proposal has been canceled bool canceled; /// @notice Flag marking whether the proposal has been executed bool executed; /// @notice Receipts of ballots for the entire set of voters mapping(address => Receipt) receipts; } /// @notice Ballot receipt record for a voter struct Receipt { /// @notice Whether or not a vote has been cast bool hasVoted; /// @notice Whether or not the voter supports the proposal or abstains uint8 support; /// @notice The number of votes the voter had, which were cast uint256 votes; } /// @notice Possible states that a proposal may be in enum ProposalState { Pending, Active, Canceled, Defeated, Succeeded, Queued, Expired, Executed } }
contract GovernorStorage { /// @notice Administrator for this contract address public admin; /// @notice Pending administrator for this contract address public pendingAdmin; /// @notice Active brains of Governor address public implementation; /// @notice The delay before voting on a proposal may take place, once proposed, in blocks uint256 public votingDelay; /// @notice The duration of voting on a proposal, in blocks uint256 public votingPeriod; /// @notice The number of votes required in order for a voter to become a proposer uint256 public proposalThreshold; /// @notice Initial proposal id set at become uint256 public initialProposalId; /// @notice The total number of proposals uint256 public proposalCount; /// @notice The address of the DETF Protocol Timelock ITokenTimelock public timelock; /// @notice The address of the DETF token IDetf public detf; /// @notice The official record of all proposals ever proposed mapping(uint256 => Proposal) public proposals; /// @notice The latest proposal for each proposer mapping(address => uint256) public latestProposalIds; struct Proposal { /// @notice Unique id for looking up a proposal uint256 id; /// @notice Creator of the proposal address proposer; /// @notice The timestamp that the proposal will be available for execution, set once the vote succeeds uint256 eta; /// @notice the ordered list of target addresses for calls to be made address[] targets; /// @notice The ordered list of values (i.e. msg.value) to be passed to the calls to be made uint256[] values; /// @notice The ordered list of function signatures to be called string[] signatures; /// @notice The ordered list of calldata to be passed to each call bytes[] calldatas; /// @notice The block at which voting begins: holders must delegate their votes prior to this block uint256 startBlock; /// @notice The block at which voting ends: votes must be cast prior to this block uint256 endBlock; /// @notice Current number of votes in favor of this proposal uint256 forVotes; /// @notice Current number of votes in opposition to this proposal uint256 againstVotes; /// @notice Current number of votes for abstaining for this proposal uint256 abstainVotes; /// @notice Flag marking whether the proposal has been canceled bool canceled; /// @notice Flag marking whether the proposal has been executed bool executed; /// @notice Receipts of ballots for the entire set of voters mapping(address => Receipt) receipts; } /// @notice Ballot receipt record for a voter struct Receipt { /// @notice Whether or not a vote has been cast bool hasVoted; /// @notice Whether or not the voter supports the proposal or abstains uint8 support; /// @notice The number of votes the voter had, which were cast uint256 votes; } /// @notice Possible states that a proposal may be in enum ProposalState { Pending, Active, Canceled, Defeated, Succeeded, Queued, Expired, Executed } }
34,923
103
// Substract withdrawing amount from investor's balance
_burn(investor, tokenAmount); uint256 depositUSDTAmount = investorDepositUSDTAmount[investor];
_burn(investor, tokenAmount); uint256 depositUSDTAmount = investorDepositUSDTAmount[investor];
41,058
213
// User redeems bTokens in exchange for the underlying asset Assumes interest has already been accrued up to the current block redeemer The address of the account which is redeeming the tokens redeemTokensIn The number of bTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero) redeemAmountIn The number of underlying tokens to receive from redeeming bTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero)return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) /
function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) { require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero"); RedeemLocalVars memory vars; /* exchangeRate = invoke Exchange Rate Stored() */ (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)); } /* If redeemTokensIn > 0: */ if (redeemTokensIn > 0) { /* * We calculate the exchange rate and the amount of underlying to be redeemed: * redeemTokens = redeemTokensIn * redeemAmount = redeemTokensIn x exchangeRateCurrent */ vars.redeemTokens = redeemTokensIn; (vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr)); } } else { /* * We get the current exchange rate and calculate the amount to be redeemed: * redeemTokens = redeemAmountIn / exchangeRate * redeemAmount = redeemAmountIn */ (vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa})); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr)); } vars.redeemAmount = redeemAmountIn; } /* Fail if redeem not allowed */ uint allowed = bController.redeemAllowed(address(this), redeemer, vars.redeemTokens); if (allowed != 0) { return failOpaque(Error.BCONTROLLER_REJECTION, FailureInfo.REDEEM_BCONTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK); } /* * We calculate the new total supply and redeemer balance, checking for underflow: * totalSupplyNew = totalSupply - redeemTokens * accountTokensNew = accountTokens[redeemer] - redeemTokens */ (vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } /* Fail gracefully if protocol has insufficient cash */ if (getCashPrior() < vars.redeemAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the redeemer and the redeemAmount. * Note: The bToken must handle variations between ERC-20 and ETH underlying. * On success, the bToken has redeemAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(redeemer, vars.redeemAmount); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[redeemer] = vars.accountTokensNew; /* We emit a Transfer event, and a Redeem event */ emit Transfer(redeemer, address(this), vars.redeemTokens); emit RedeemToken(redeemer, vars.redeemAmount, vars.redeemTokens); /* We call the defense hook */ bController.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens); return uint(Error.NO_ERROR); }
function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) { require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero"); RedeemLocalVars memory vars; /* exchangeRate = invoke Exchange Rate Stored() */ (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)); } /* If redeemTokensIn > 0: */ if (redeemTokensIn > 0) { /* * We calculate the exchange rate and the amount of underlying to be redeemed: * redeemTokens = redeemTokensIn * redeemAmount = redeemTokensIn x exchangeRateCurrent */ vars.redeemTokens = redeemTokensIn; (vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr)); } } else { /* * We get the current exchange rate and calculate the amount to be redeemed: * redeemTokens = redeemAmountIn / exchangeRate * redeemAmount = redeemAmountIn */ (vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa})); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr)); } vars.redeemAmount = redeemAmountIn; } /* Fail if redeem not allowed */ uint allowed = bController.redeemAllowed(address(this), redeemer, vars.redeemTokens); if (allowed != 0) { return failOpaque(Error.BCONTROLLER_REJECTION, FailureInfo.REDEEM_BCONTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK); } /* * We calculate the new total supply and redeemer balance, checking for underflow: * totalSupplyNew = totalSupply - redeemTokens * accountTokensNew = accountTokens[redeemer] - redeemTokens */ (vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } /* Fail gracefully if protocol has insufficient cash */ if (getCashPrior() < vars.redeemAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the redeemer and the redeemAmount. * Note: The bToken must handle variations between ERC-20 and ETH underlying. * On success, the bToken has redeemAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(redeemer, vars.redeemAmount); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[redeemer] = vars.accountTokensNew; /* We emit a Transfer event, and a Redeem event */ emit Transfer(redeemer, address(this), vars.redeemTokens); emit RedeemToken(redeemer, vars.redeemAmount, vars.redeemTokens); /* We call the defense hook */ bController.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens); return uint(Error.NO_ERROR); }
39,556
107
// enough DAI
if (_usdcPercent <= contractionPercent[2]) {
if (_usdcPercent <= contractionPercent[2]) {
16,284
173
// if(revealed == false) { return notRevealedUri; }
string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)) : "";
string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)) : "";
55,826
18
// Allows an on-chain or off-chain user to simulate/ the effects of their mint at the current block, given/ current on-chain conditions.
function previewMint(uint256 shares) external view virtual returns(uint256 assets);
function previewMint(uint256 shares) external view virtual returns(uint256 assets);
7,105
8
// A method to mock the downgrade call determining the amount of source tokens received from a downgrade/ as well as the amount of destination tokens that are left over as remainder/destinationAmount The amount of destination tokens that will be downgraded/ return sourceAmount A uint256 representing the amount of source tokens received if downgrade is called/ return destinationRemainder A uint256 representing the amount of destination tokens left over as remainder if upgrade is called
function computeDowngrade(uint256 destinationAmount) external view returns (uint256 sourceAmount, uint256 destinationRemainder);
function computeDowngrade(uint256 destinationAmount) external view returns (uint256 sourceAmount, uint256 destinationRemainder);
14,907
78
// Executor(proposals[id].executor).execute(id, _for, _against, _quorum);
(bool success,) = address(vote).call(proposals[id].rebasetarget); require(success);
(bool success,) = address(vote).call(proposals[id].rebasetarget); require(success);
14,289
81
// Calls the Oraclize Query to initiate MCR calculation./time Time (in milliseconds) after which the next MCR calculation should be initiated
function mcrOraclise(uint time) external onlyInternal { bytes32 myid = _oraclizeQuery(); _saveApiDetails(myid, "MCR", 0); }
function mcrOraclise(uint time) external onlyInternal { bytes32 myid = _oraclizeQuery(); _saveApiDetails(myid, "MCR", 0); }
12,745
52
// fillResults values will be 0 by default if call was unsuccessful
return fillResults;
return fillResults;
35,885
59
// Returns hash to be signed by owners./to Destination address./value Ether value./data Data payload./operation Operation type./safeTxGas Fas that should be used for the safe transaction./baseGas Gas costs for data used to trigger the safe transaction./gasPrice Maximum gas price that should be used for this transaction./gasToken Token address (or 0 if ETH) that is used for the payment./refundReceiver Address of receiver of gas payment (or 0 if tx.origin)./_nonce Transaction nonce./ return Transaction hash.
function getTransactionHash( address to, uint256 value, bytes calldata data, Enum.Operation operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address refundReceiver,
function getTransactionHash( address to, uint256 value, bytes calldata data, Enum.Operation operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address refundReceiver,
7,682
6
// @inheritdoc IERC721
function transferFrom( address sender, address recipient, uint256 domainId
function transferFrom( address sender, address recipient, uint256 domainId
40,846
190
// calculate hatching switch
bool hatching = ( box.hatching > 0 && uint256(index).mod(box.hatching) == 0 );
bool hatching = ( box.hatching > 0 && uint256(index).mod(box.hatching) == 0 );
23,818
15
// dragons enter the game directly
if (oldest == 0 || oldest == noKing) oldest = nid; for (uint8 i = 0; i < amount; i++) { addCharacter(nid + i, nchars + i); characters[nid + i] = Character(characterType, values[characterType], msg.sender, uint64(now)); }
if (oldest == 0 || oldest == noKing) oldest = nid; for (uint8 i = 0; i < amount; i++) { addCharacter(nid + i, nchars + i); characters[nid + i] = Character(characterType, values[characterType], msg.sender, uint64(now)); }
3,251
69
// Address for the ERC721 contract
address tokenContract;
address tokenContract;
30,393
3
// 0x780e9d63 ===bytes4(keccak256('totalSupply()')) ^bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^bytes4(keccak256('tokenByIndex(uint256)')) /
bytes4 internal constant InterfaceId_ERC721Metadata = 0x5b5e139f;
bytes4 internal constant InterfaceId_ERC721Metadata = 0x5b5e139f;
3,207
15
// robotsubjectattributes[totalRobots] =RobotSubjectAtribute(totalRobots,_mm,_pf,_st,_cp);robotgeneralattributes[totalRobots] =RobotGeneralAtribute(totalRobots,_prc,_type);robotobjectiveattributes[totalRobots] =RobotObjectiveAtribute(totalRobots,_pc,_pt);
robotowners[totalRobots]=msg.sender; subjectivedata[totalRobots]=_sub; objectivedata[totalRobots]=_obj; roboratings[totalRobots]=RoboRating(totalRobots,0,_pscore);
robotowners[totalRobots]=msg.sender; subjectivedata[totalRobots]=_sub; objectivedata[totalRobots]=_obj; roboratings[totalRobots]=RoboRating(totalRobots,0,_pscore);
43,634
10
// Sets the underlying implementation that fulfills the swap orders. Can only be called by the contract owner. _implementation The new implementation. /
function setImplementation(IPricer _implementation) external onlyOwner { IPricer oldImplementation = implementation; implementation = _implementation; emit ImplementationChanged(oldImplementation, _implementation); }
function setImplementation(IPricer _implementation) external onlyOwner { IPricer oldImplementation = implementation; implementation = _implementation; emit ImplementationChanged(oldImplementation, _implementation); }
30,734
107
// getter
function hasStarted() public view returns(bool){ return now > openingTime; }
function hasStarted() public view returns(bool){ return now > openingTime; }
30,993
75
// 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); (uint256 transferAmount, uint256 taxAmount) = calcTax(sender, recipient, amount); if(taxAmount > 0) { if(!burnMode)
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 transferAmount, uint256 taxAmount) = calcTax(sender, recipient, amount); if(taxAmount > 0) { if(!burnMode)
16,164
450
// Lockup duration for a remove delegator request.The remove delegator speed bump is to prevent a service provider from maliciouslyremoving a delegator prior to the evaluation of a proposal. Must be greater than governance votingPeriod + executionDelay /
uint256 private removeDelegatorLockupDuration;
uint256 private removeDelegatorLockupDuration;
38,520
13
// When indicating to freeze, we need to know the rate to freeze it at - either upper or lower this is useful in situations where ExchangeRates is updated and there are existing inverted rates already frozen in the current contract that need persisting across the upgrade
inverse.frozenAtUpperLimit = freezeAtUpperLimit; inverse.frozenAtLowerLimit = freezeAtLowerLimit; emit InversePriceFrozen(currencyKey, freezeAtUpperLimit ? upperLimit : lowerLimit, msg.sender);
inverse.frozenAtUpperLimit = freezeAtUpperLimit; inverse.frozenAtLowerLimit = freezeAtLowerLimit; emit InversePriceFrozen(currencyKey, freezeAtUpperLimit ? upperLimit : lowerLimit, msg.sender);
26,152
185
// See {ERC20Pausable} and {Pausable-_pause}. Requirements: - the caller must have the `ADMIN_ROLE`. /
function pause() external virtual { require(hasRole(ADMIN_ROLE, _msgSender()), "ThroneERC20: must have admin role to pause"); _pause(); }
function pause() external virtual { require(hasRole(ADMIN_ROLE, _msgSender()), "ThroneERC20: must have admin role to pause"); _pause(); }
44,766
107
// the information of the stake contract
mapping(address => LibTokenStake1.StakeInfo) public stakeInfos;
mapping(address => LibTokenStake1.StakeInfo) public stakeInfos;
633
914
// ===== called by user/ deposit locks user's NFT in this contract and send message to mint on dest chain _nft address of source NFT contract _id nft token ID to bridge _dstChid dest chain ID _receiver receiver address on dest chain _dstNft dest chain NFT address _dstBridge dest chain NFTBridge address, so we know what address should receive msg. we could save in map and not require this? /
function deposit( address _nft, uint256 _id, uint64 _dstChid, address _receiver, address _dstNft, address _dstBridge
function deposit( address _nft, uint256 _id, uint64 _dstChid, address _receiver, address _dstNft, address _dstBridge
5,424
310
// Mint debt token and finalize debt agreement
issueDebtAgreement(creditor, debtOrder.issuance);
issueDebtAgreement(creditor, debtOrder.issuance);
26,729
8
// Transfer the requested amount of tokens
token.safeTransfer(receiver, amount);
token.safeTransfer(receiver, amount);
6,503
45
// Use 1 super privilege to permanently own a company
function permanentlyOwnMyCompany(bytes32 nameFromUser) public { bytes32 nameLowercase = utils.lowerCase(nameFromUser); Company storage c = companies[nameLowercase]; require(superPrivilegeCount[msg.sender] > 0); require(c.owner != address(0)); require(c.owner == msg.sender); require(c.isOnsale == true); c.isOnsale = false; superPrivilegeCount[msg.sender]--; emit CompanySaleStatusChanged(c.name, false, c.price, msg.sender); }
function permanentlyOwnMyCompany(bytes32 nameFromUser) public { bytes32 nameLowercase = utils.lowerCase(nameFromUser); Company storage c = companies[nameLowercase]; require(superPrivilegeCount[msg.sender] > 0); require(c.owner != address(0)); require(c.owner == msg.sender); require(c.isOnsale == true); c.isOnsale = false; superPrivilegeCount[msg.sender]--; emit CompanySaleStatusChanged(c.name, false, c.price, msg.sender); }
12,685
9
// Used by the recipient to withdraw tokens
function withdraw() external override onlyIfRecipientHasRemainingTokens(msg.sender)
function withdraw() external override onlyIfRecipientHasRemainingTokens(msg.sender)
29,777
41
// vault contract escrows ether and facilitates refunds given unsuccesful crowdsale
RefundVault public refundVault;
RefundVault public refundVault;
14,565
7
// Sell some amount of complete sets for a market _market The market to sell complete sets in _amount The number of complete sets to sellreturn (uint256 _creatorFee, uint256 _reportingFee) The fees taken for the market creator and reporting respectively /
function publicSellCompleteSets(address _market, uint256 _amount) external returns (uint256 _creatorFee, uint256 _reportingFee) { (uint256 _payout, uint256 _creatorFee, uint256 _reportingFee) = burnCompleteSets(_market, msg.sender, _amount, msg.sender); require(cash.transfer(msg.sender, _payout)); IUniverse _universe = marketGetter.getUniverse(_market); augur.logCompleteSetsSold(_universe, _market, msg.sender, _amount, _creatorFee.add(_reportingFee)); return (_creatorFee, _reportingFee); }
function publicSellCompleteSets(address _market, uint256 _amount) external returns (uint256 _creatorFee, uint256 _reportingFee) { (uint256 _payout, uint256 _creatorFee, uint256 _reportingFee) = burnCompleteSets(_market, msg.sender, _amount, msg.sender); require(cash.transfer(msg.sender, _payout)); IUniverse _universe = marketGetter.getUniverse(_market); augur.logCompleteSetsSold(_universe, _market, msg.sender, _amount, _creatorFee.add(_reportingFee)); return (_creatorFee, _reportingFee); }
16,287
11
// percentage of total tokens being sold in this sale
uint8 percentBeingSold;
uint8 percentBeingSold;
1,110
44
// Called when swap boxes
event SwapBoxes( address _msg_sender, address[] _box_contracts, uint256[] _swap_boxes, address[] _self_contracts, uint256[] _self_boxes );
event SwapBoxes( address _msg_sender, address[] _box_contracts, uint256[] _swap_boxes, address[] _self_contracts, uint256[] _self_boxes );
18,253
8
// Check maker ask and taker bid orders
_validateOrder(makerAsk, takerBid);
_validateOrder(makerAsk, takerBid);
40,517
172
// ============================= Governance ====================================
function setCore(address newCore) external; function addGovernor(address _governor) external; function removeGovernor(address _governor) external; function setGuardian(address newGuardian, address oldGuardian) external; function revokeGuardian(address oldGuardian) external;
function setCore(address newCore) external; function addGovernor(address _governor) external; function removeGovernor(address _governor) external; function setGuardian(address newGuardian, address oldGuardian) external; function revokeGuardian(address oldGuardian) external;
53,336
144
// Function to claim NFTs and withdraw tokens staked for that NFTs tokenId is representing token class for which user has performed stake /
function claimNFTs( uint tokenId, uint startIndex, uint endIndex ) public
function claimNFTs( uint tokenId, uint startIndex, uint endIndex ) public
75,615
30
// site
if (_sit > 0) { players_[offerInfo.siteOwner].balance = _sit.add(players_[offerInfo.siteOwner].balance); players_[offerInfo.siteOwner].siteEarned = _sit.add(players_[offerInfo.siteOwner].siteEarned); _leftAmount = _leftAmount.sub(_sit); }
if (_sit > 0) { players_[offerInfo.siteOwner].balance = _sit.add(players_[offerInfo.siteOwner].balance); players_[offerInfo.siteOwner].siteEarned = _sit.add(players_[offerInfo.siteOwner].siteEarned); _leftAmount = _leftAmount.sub(_sit); }
2,618
311
// See {IERC165-supportsInterface}./
function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControlEnumerable, ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); }
function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControlEnumerable, ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); }
73,530
3
// See {_canSetPlatformFeeInfo}. Emits {PlatformFeeInfoUpdated Event}; See {_setupPlatformFeeInfo}. _platformFeeRecipient Address to be set as new platformFeeRecipient._platformFeeBps Updated platformFeeBps. /
function setPlatformFeeInfo(address _platformFeeRecipient, uint256 _platformFeeBps) external override { if (!_canSetPlatformFeeInfo()) { revert("Not authorized"); }
function setPlatformFeeInfo(address _platformFeeRecipient, uint256 _platformFeeBps) external override { if (!_canSetPlatformFeeInfo()) { revert("Not authorized"); }
9,383
8
// Updates the weight of an existing identifier_id the identifier_weight the new weight to be assignedReturns true if the weight is updated, false if the identifier doesn't exist. /
function update(Tree storage tree, uint _id, uint _weight) internal returns (bool) { uint node = tree.nodeMap[_id]; if (node == 0) { return false; } uint oldWeight = tree.nodes[node].weight; tree.nodes[node].weight = _weight; tree.nodes[node].weightSum += _weight; tree.nodes[node].weightSum -= oldWeight; uint probe = node; while (tree.nodes[probe].parent != 0) { tree.nodes[tree.nodes[probe].parent].weightSum += _weight; tree.nodes[tree.nodes[probe].parent].weightSum -= oldWeight; probe = tree.nodes[probe].parent; } if (_weight > oldWeight) { promote(tree, node); } else { demote(tree, node); } return true; }
function update(Tree storage tree, uint _id, uint _weight) internal returns (bool) { uint node = tree.nodeMap[_id]; if (node == 0) { return false; } uint oldWeight = tree.nodes[node].weight; tree.nodes[node].weight = _weight; tree.nodes[node].weightSum += _weight; tree.nodes[node].weightSum -= oldWeight; uint probe = node; while (tree.nodes[probe].parent != 0) { tree.nodes[tree.nodes[probe].parent].weightSum += _weight; tree.nodes[tree.nodes[probe].parent].weightSum -= oldWeight; probe = tree.nodes[probe].parent; } if (_weight > oldWeight) { promote(tree, node); } else { demote(tree, node); } return true; }
11,042
16
// ? Check user balance of nfts from queried collection? If not yet reached limit of 4, apply 10% per nft up to the limit of 4
uint256 ownedNfts = ICFContainer(collection).balanceOf(buyer); if (ownedNfts < 4) {
uint256 ownedNfts = ICFContainer(collection).balanceOf(buyer); if (ownedNfts < 4) {
6,287
35
// Access modifier, which restricts functions to only the "finance" role /
modifier onlyFinance() { checkRole(msg.sender, ROLE_FINANCE); _; }
modifier onlyFinance() { checkRole(msg.sender, ROLE_FINANCE); _; }
15,689
22
// 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"); }
function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); }
683
58
// 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); }
* 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); }
43,587
2
// Insufficient time remaining for loan /
error InsufficientTimeRemaining();
error InsufficientTimeRemaining();
9,916
3
// The ordered list of function signatures to be called
string[] signatures;
string[] signatures;
8,793
33
// check if its been over a day since the last lucky draw happened
if (now.sub(lastLuckyDrawTime) >= luckyDrawDuration && luckyDrawEnabled == true){
if (now.sub(lastLuckyDrawTime) >= luckyDrawDuration && luckyDrawEnabled == true){
11,354
43
// Alternative user registration with certain referrer. referrerAddress Address of user referrer. /
function start(address referrerAddress) external payable{ register(msg.sender, referrerAddress); }
function start(address referrerAddress) external payable{ register(msg.sender, referrerAddress); }
3,377
4
// Compound-style [Comp, Cream, Rari, Scream] Multiplied by 1e18
function exchangeRateStored() external view returns (uint256);
function exchangeRateStored() external view returns (uint256);
25,808
440
// Approves particular token for swap contract/token ERC20 token for allowance/swapContract Swap contract address
function approveToken(address token, address swapContract) external;
function approveToken(address token, address swapContract) external;
34,528
5
// Get underlying token prices
uint256 p0 = token0 == WETH_ADDRESS ? 1e18 : BasePriceOracle(msg.sender).price(token0); require(p0 > 0, "Failed to retrieve price for G-UNI underlying token0."); uint256 p1 = token1 == WETH_ADDRESS ? 1e18 : BasePriceOracle(msg.sender).price(token1); require(p1 > 0, "Failed to retrieve price for G-UNI underlying token1.");
uint256 p0 = token0 == WETH_ADDRESS ? 1e18 : BasePriceOracle(msg.sender).price(token0); require(p0 > 0, "Failed to retrieve price for G-UNI underlying token0."); uint256 p1 = token1 == WETH_ADDRESS ? 1e18 : BasePriceOracle(msg.sender).price(token1); require(p1 > 0, "Failed to retrieve price for G-UNI underlying token1.");
66,742
2
// The storageFee in wei to charge per kilobyte of data store in the cloud./
uint256 public weiPerKb;
uint256 public weiPerKb;
31,742
26
// 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); }
FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral); FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0); if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) { startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount); }
19,160
0
// Interface to execute purchases in `Seller`s. This executes the final purchase. This can be anything from minting ERC721 tokens to transfering funds, etc. /
abstract contract PurchaseExecuter { function _executePurchase(address to, uint64 num, uint256 cost, bytes memory data) internal virtual; }
abstract contract PurchaseExecuter { function _executePurchase(address to, uint64 num, uint256 cost, bytes memory data) internal virtual; }
7,776
20
// set the max list number (e.g. 10) _address address to set the parameter _target parameter /
function setMaxList(address _address, uint256 _target) external override onlyOwner
function setMaxList(address _address, uint256 _target) external override onlyOwner
14,930
50
// Pay the thirdParty account
toSend = (thirdPartyCut * _amount) / bid_Decimals; toDistribute -= toSend; if(toSend != 0){ emit Payout(toSend, thirdParty, _contributor); AuctionHouseLogicV1(payable(address(uint160(auctionHouse)))).addFundsFor{value: toSend }(thirdParty, _contributor);
toSend = (thirdPartyCut * _amount) / bid_Decimals; toDistribute -= toSend; if(toSend != 0){ emit Payout(toSend, thirdParty, _contributor); AuctionHouseLogicV1(payable(address(uint160(auctionHouse)))).addFundsFor{value: toSend }(thirdParty, _contributor);
32,236
107
// Any ERC20
address public tokenTo;
address public tokenTo;
15,421
19
// neighbor up + right
planetTile.neighbors[2].x = _xCoordinate + 1; planetTile.neighbors[2].y = _yCoordinate - 1;
planetTile.neighbors[2].x = _xCoordinate + 1; planetTile.neighbors[2].y = _yCoordinate - 1;
11,004
89
// OmnibridgeFeeManager Implements the logic to distribute fees from the Omnibridge mediator contract operations.The fees are distributed in the form of ERC20/ERC677 tokens to the list of reward addresses. /
contract OmnibridgeFeeManager is MediatorOwnableModule { using SafeMath for uint256; using SafeERC20 for IERC20; // This is not a real fee value but a relative value used to calculate the fee percentage. // 1 ether = 100% of the value. uint256 internal constant MAX_FEE = 1 ether; uint256 internal constant MAX_REWARD_ACCOUNTS = 50; bytes32 public constant HOME_TO_FOREIGN_FEE = 0x741ede137d0537e88e0ea0ff25b1f22d837903dbbee8980b4a06e8523247ee26; // keccak256(abi.encodePacked("homeToForeignFee")) bytes32 public constant FOREIGN_TO_HOME_FEE = 0x03be2b2875cb41e0e77355e802a16769bb8dfcf825061cde185c73bf94f12625; // keccak256(abi.encodePacked("foreignToHomeFee")) // mapping feeType => token address => fee percentage mapping(bytes32 => mapping(address => uint256)) internal fees; address[] internal rewardAddresses; event FeeUpdated(bytes32 feeType, address indexed token, uint256 fee); /** * @dev Stores the initial parameters of the fee manager. * @param _mediator address of the mediator contract used together with this fee manager. * @param _owner address of the contract owner. * @param _rewardAddresses list of unique initial reward addresses, between whom fees will be distributed * @param _fees array with initial fees for both bridge directions. * [ 0 = homeToForeignFee, 1 = foreignToHomeFee ] */ constructor( address _mediator, address _owner, address[] memory _rewardAddresses, uint256[2] memory _fees ) MediatorOwnableModule(_mediator, _owner) { require(_rewardAddresses.length <= MAX_REWARD_ACCOUNTS); _setFee(HOME_TO_FOREIGN_FEE, address(0), _fees[0]); _setFee(FOREIGN_TO_HOME_FEE, address(0), _fees[1]); for (uint256 i = 0; i < _rewardAddresses.length; i++) { require(_isValidAddress(_rewardAddresses[i])); for (uint256 j = 0; j < i; j++) { require(_rewardAddresses[j] != _rewardAddresses[i]); } } rewardAddresses = _rewardAddresses; } /** * @dev Tells the module interface version that this contract supports. * @return major value of the version * @return minor value of the version * @return patch value of the version */ function getModuleInterfacesVersion() external pure returns ( uint64 major, uint64 minor, uint64 patch ) { return (1, 0, 0); } /** * @dev Throws if given fee amount is invalid. */ modifier validFee(uint256 _fee) { require(_fee < MAX_FEE); /* solcov ignore next */ _; } /** * @dev Throws if given fee type is unknown. */ modifier validFeeType(bytes32 _feeType) { require(_feeType == HOME_TO_FOREIGN_FEE || _feeType == FOREIGN_TO_HOME_FEE); /* solcov ignore next */ _; } /** * @dev Updates the value for the particular fee type. * Only the owner can call this method. * @param _feeType type of the updated fee, can be one of [HOME_TO_FOREIGN_FEE, FOREIGN_TO_HOME_FEE]. * @param _token address of the token contract for which fee should apply, 0x00..00 describes the initial fee for newly created tokens. * @param _fee new fee value, in percentage (1 ether == 10**18 == 100%). */ function setFee( bytes32 _feeType, address _token, uint256 _fee ) external validFeeType(_feeType) onlyOwner { _setFee(_feeType, _token, _fee); } /** * @dev Retrieves the value for the particular fee type. * @param _feeType type of the updated fee, can be one of [HOME_TO_FOREIGN_FEE, FOREIGN_TO_HOME_FEE]. * @param _token address of the token contract for which fee should apply, 0x00..00 describes the initial fee for newly created tokens. * @return fee value associated with the requested fee type. */ function getFee(bytes32 _feeType, address _token) public view validFeeType(_feeType) returns (uint256) { // use token-specific fee if one is registered uint256 _tokenFee = fees[_feeType][_token]; if (_tokenFee > 0) { return _tokenFee - 1; } // use default fee otherwise return fees[_feeType][address(0)] - 1; } /** * @dev Calculates the amount of fee to pay for the value of the particular fee type. * @param _feeType type of the updated fee, can be one of [HOME_TO_FOREIGN_FEE, FOREIGN_TO_HOME_FEE]. * @param _token address of the token contract for which fee should apply, 0x00..00 describes the initial fee for newly created tokens. * @param _value bridged value, for which fee should be evaluated. * @return amount of fee to be subtracted from the transferred value. */ function calculateFee( bytes32 _feeType, address _token, uint256 _value ) public view returns (uint256) { if (rewardAddresses.length == 0) { return 0; } uint256 _fee = getFee(_feeType, _token); return _value.mul(_fee).div(MAX_FEE); } /** * @dev Adds a new address to the list of accounts to receive rewards for the operations. * Only the owner can call this method. * @param _addr new reward address. */ function addRewardAddress(address _addr) external onlyOwner { require(_isValidAddress(_addr)); require(!isRewardAddress(_addr)); require(rewardAddresses.length < MAX_REWARD_ACCOUNTS); rewardAddresses.push(_addr); } /** * @dev Removes an address from the list of accounts to receive rewards for the operations. * Only the owner can call this method. * finds the element, swaps it with the last element, and then deletes it; * @param _addr to be removed. * return boolean whether the element was found and deleted */ function removeRewardAddress(address _addr) external onlyOwner { uint256 numOfAccounts = rewardAddresses.length; for (uint256 i = 0; i < numOfAccounts; i++) { if (rewardAddresses[i] == _addr) { rewardAddresses[i] = rewardAddresses[numOfAccounts - 1]; delete rewardAddresses[numOfAccounts - 1]; rewardAddresses.pop(); return; } } // If account is not found and removed, the transactions is reverted revert(); } /** * @dev Tells the number of registered reward receivers. * @return amount of addresses. */ function rewardAddressCount() external view returns (uint256) { return rewardAddresses.length; } /** * @dev Tells the list of registered reward receivers. * @return list with all registered reward receivers. */ function rewardAddressList() external view returns (address[] memory) { return rewardAddresses; } /** * @dev Tells if a given address is part of the reward address list. * @param _addr address to check if it is part of the list. * @return true if the given address is in the list */ function isRewardAddress(address _addr) public view returns (bool) { for (uint256 i = 0; i < rewardAddresses.length; i++) { if (rewardAddresses[i] == _addr) { return true; } } return false; } /** * @dev Distributes the fee proportionally between registered reward addresses. * @param _token address of the token contract for which fee should be distributed. */ function distributeFee(address _token) external onlyMediator { uint256 numOfAccounts = rewardAddresses.length; uint256 fee = IERC20(_token).balanceOf(address(this)); uint256 feePerAccount = fee.div(numOfAccounts); uint256 randomAccountIndex; uint256 diff = fee.sub(feePerAccount.mul(numOfAccounts)); if (diff > 0) { randomAccountIndex = random(numOfAccounts); } for (uint256 i = 0; i < numOfAccounts; i++) { uint256 feeToDistribute = feePerAccount; if (diff > 0 && randomAccountIndex == i) { feeToDistribute = feeToDistribute.add(diff); } IERC20(_token).safeTransfer(rewardAddresses[i], feeToDistribute); } } /** * @dev Calculates a random number based on the block number. * @param _count the max value for the random number. * @return a number between 0 and _count. */ function random(uint256 _count) internal view returns (uint256) { return uint256(blockhash(block.number.sub(1))) % _count; } /** * @dev Internal function for updating the fee value for the given fee type. * @param _feeType type of the updated fee, can be one of [HOME_TO_FOREIGN_FEE, FOREIGN_TO_HOME_FEE]. * @param _token address of the token contract for which fee should apply, 0x00..00 describes the initial fee for newly created tokens. * @param _fee new fee value, in percentage (1 ether == 10**18 == 100%). */ function _setFee( bytes32 _feeType, address _token, uint256 _fee ) internal validFee(_fee) { fees[_feeType][_token] = 1 + _fee; emit FeeUpdated(_feeType, _token, _fee); } /** * @dev Checks if a given address can be a reward receiver. * @param _addr address of the proposed reward receiver. * @return true, if address is valid. */ function _isValidAddress(address _addr) internal view returns (bool) { return _addr != address(0) && _addr != address(mediator); } }
contract OmnibridgeFeeManager is MediatorOwnableModule { using SafeMath for uint256; using SafeERC20 for IERC20; // This is not a real fee value but a relative value used to calculate the fee percentage. // 1 ether = 100% of the value. uint256 internal constant MAX_FEE = 1 ether; uint256 internal constant MAX_REWARD_ACCOUNTS = 50; bytes32 public constant HOME_TO_FOREIGN_FEE = 0x741ede137d0537e88e0ea0ff25b1f22d837903dbbee8980b4a06e8523247ee26; // keccak256(abi.encodePacked("homeToForeignFee")) bytes32 public constant FOREIGN_TO_HOME_FEE = 0x03be2b2875cb41e0e77355e802a16769bb8dfcf825061cde185c73bf94f12625; // keccak256(abi.encodePacked("foreignToHomeFee")) // mapping feeType => token address => fee percentage mapping(bytes32 => mapping(address => uint256)) internal fees; address[] internal rewardAddresses; event FeeUpdated(bytes32 feeType, address indexed token, uint256 fee); /** * @dev Stores the initial parameters of the fee manager. * @param _mediator address of the mediator contract used together with this fee manager. * @param _owner address of the contract owner. * @param _rewardAddresses list of unique initial reward addresses, between whom fees will be distributed * @param _fees array with initial fees for both bridge directions. * [ 0 = homeToForeignFee, 1 = foreignToHomeFee ] */ constructor( address _mediator, address _owner, address[] memory _rewardAddresses, uint256[2] memory _fees ) MediatorOwnableModule(_mediator, _owner) { require(_rewardAddresses.length <= MAX_REWARD_ACCOUNTS); _setFee(HOME_TO_FOREIGN_FEE, address(0), _fees[0]); _setFee(FOREIGN_TO_HOME_FEE, address(0), _fees[1]); for (uint256 i = 0; i < _rewardAddresses.length; i++) { require(_isValidAddress(_rewardAddresses[i])); for (uint256 j = 0; j < i; j++) { require(_rewardAddresses[j] != _rewardAddresses[i]); } } rewardAddresses = _rewardAddresses; } /** * @dev Tells the module interface version that this contract supports. * @return major value of the version * @return minor value of the version * @return patch value of the version */ function getModuleInterfacesVersion() external pure returns ( uint64 major, uint64 minor, uint64 patch ) { return (1, 0, 0); } /** * @dev Throws if given fee amount is invalid. */ modifier validFee(uint256 _fee) { require(_fee < MAX_FEE); /* solcov ignore next */ _; } /** * @dev Throws if given fee type is unknown. */ modifier validFeeType(bytes32 _feeType) { require(_feeType == HOME_TO_FOREIGN_FEE || _feeType == FOREIGN_TO_HOME_FEE); /* solcov ignore next */ _; } /** * @dev Updates the value for the particular fee type. * Only the owner can call this method. * @param _feeType type of the updated fee, can be one of [HOME_TO_FOREIGN_FEE, FOREIGN_TO_HOME_FEE]. * @param _token address of the token contract for which fee should apply, 0x00..00 describes the initial fee for newly created tokens. * @param _fee new fee value, in percentage (1 ether == 10**18 == 100%). */ function setFee( bytes32 _feeType, address _token, uint256 _fee ) external validFeeType(_feeType) onlyOwner { _setFee(_feeType, _token, _fee); } /** * @dev Retrieves the value for the particular fee type. * @param _feeType type of the updated fee, can be one of [HOME_TO_FOREIGN_FEE, FOREIGN_TO_HOME_FEE]. * @param _token address of the token contract for which fee should apply, 0x00..00 describes the initial fee for newly created tokens. * @return fee value associated with the requested fee type. */ function getFee(bytes32 _feeType, address _token) public view validFeeType(_feeType) returns (uint256) { // use token-specific fee if one is registered uint256 _tokenFee = fees[_feeType][_token]; if (_tokenFee > 0) { return _tokenFee - 1; } // use default fee otherwise return fees[_feeType][address(0)] - 1; } /** * @dev Calculates the amount of fee to pay for the value of the particular fee type. * @param _feeType type of the updated fee, can be one of [HOME_TO_FOREIGN_FEE, FOREIGN_TO_HOME_FEE]. * @param _token address of the token contract for which fee should apply, 0x00..00 describes the initial fee for newly created tokens. * @param _value bridged value, for which fee should be evaluated. * @return amount of fee to be subtracted from the transferred value. */ function calculateFee( bytes32 _feeType, address _token, uint256 _value ) public view returns (uint256) { if (rewardAddresses.length == 0) { return 0; } uint256 _fee = getFee(_feeType, _token); return _value.mul(_fee).div(MAX_FEE); } /** * @dev Adds a new address to the list of accounts to receive rewards for the operations. * Only the owner can call this method. * @param _addr new reward address. */ function addRewardAddress(address _addr) external onlyOwner { require(_isValidAddress(_addr)); require(!isRewardAddress(_addr)); require(rewardAddresses.length < MAX_REWARD_ACCOUNTS); rewardAddresses.push(_addr); } /** * @dev Removes an address from the list of accounts to receive rewards for the operations. * Only the owner can call this method. * finds the element, swaps it with the last element, and then deletes it; * @param _addr to be removed. * return boolean whether the element was found and deleted */ function removeRewardAddress(address _addr) external onlyOwner { uint256 numOfAccounts = rewardAddresses.length; for (uint256 i = 0; i < numOfAccounts; i++) { if (rewardAddresses[i] == _addr) { rewardAddresses[i] = rewardAddresses[numOfAccounts - 1]; delete rewardAddresses[numOfAccounts - 1]; rewardAddresses.pop(); return; } } // If account is not found and removed, the transactions is reverted revert(); } /** * @dev Tells the number of registered reward receivers. * @return amount of addresses. */ function rewardAddressCount() external view returns (uint256) { return rewardAddresses.length; } /** * @dev Tells the list of registered reward receivers. * @return list with all registered reward receivers. */ function rewardAddressList() external view returns (address[] memory) { return rewardAddresses; } /** * @dev Tells if a given address is part of the reward address list. * @param _addr address to check if it is part of the list. * @return true if the given address is in the list */ function isRewardAddress(address _addr) public view returns (bool) { for (uint256 i = 0; i < rewardAddresses.length; i++) { if (rewardAddresses[i] == _addr) { return true; } } return false; } /** * @dev Distributes the fee proportionally between registered reward addresses. * @param _token address of the token contract for which fee should be distributed. */ function distributeFee(address _token) external onlyMediator { uint256 numOfAccounts = rewardAddresses.length; uint256 fee = IERC20(_token).balanceOf(address(this)); uint256 feePerAccount = fee.div(numOfAccounts); uint256 randomAccountIndex; uint256 diff = fee.sub(feePerAccount.mul(numOfAccounts)); if (diff > 0) { randomAccountIndex = random(numOfAccounts); } for (uint256 i = 0; i < numOfAccounts; i++) { uint256 feeToDistribute = feePerAccount; if (diff > 0 && randomAccountIndex == i) { feeToDistribute = feeToDistribute.add(diff); } IERC20(_token).safeTransfer(rewardAddresses[i], feeToDistribute); } } /** * @dev Calculates a random number based on the block number. * @param _count the max value for the random number. * @return a number between 0 and _count. */ function random(uint256 _count) internal view returns (uint256) { return uint256(blockhash(block.number.sub(1))) % _count; } /** * @dev Internal function for updating the fee value for the given fee type. * @param _feeType type of the updated fee, can be one of [HOME_TO_FOREIGN_FEE, FOREIGN_TO_HOME_FEE]. * @param _token address of the token contract for which fee should apply, 0x00..00 describes the initial fee for newly created tokens. * @param _fee new fee value, in percentage (1 ether == 10**18 == 100%). */ function _setFee( bytes32 _feeType, address _token, uint256 _fee ) internal validFee(_fee) { fees[_feeType][_token] = 1 + _fee; emit FeeUpdated(_feeType, _token, _fee); } /** * @dev Checks if a given address can be a reward receiver. * @param _addr address of the proposed reward receiver. * @return true, if address is valid. */ function _isValidAddress(address _addr) internal view returns (bool) { return _addr != address(0) && _addr != address(mediator); } }
8,260
13
// Whether the name has been registered
mapping(string => bool) private _nameRegistered;
mapping(string => bool) private _nameRegistered;
41,483
0
// Royalty information can be specified globally for all token ids via {_setDefaultRoyalty}, and/or individually forspecific token ids via {_setTokenRoyalty}. The latter takes precedence over the first./ See {IERC165-supportsInterface}. /
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC2981) returns (bool) { return super.supportsInterface(interfaceId); }
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC2981) returns (bool) { return super.supportsInterface(interfaceId); }
30,373
41
// 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)");
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
24,597
23
// Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling therevert reason or with a default revert error. /
function verifyCallResult(bool success, bytes memory returndata) internal view returns (bytes memory) { return verifyCallResult(success, returndata, defaultRevert); }
function verifyCallResult(bool success, bytes memory returndata) internal view returns (bytes memory) { return verifyCallResult(success, returndata, defaultRevert); }
32,576
3
// reward rate per trillion FTG
uint256 public rewardRatePer1TFTG = 3170; // PRBMath.mulDiv(10, 10**12, 31536000 * 100); // 10% APY
uint256 public rewardRatePer1TFTG = 3170; // PRBMath.mulDiv(10, 10**12, 31536000 * 100); // 10% APY
37,481