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
15
// Transfers LP to caller
address _lp = ISinglePlus(_single).token(); uint256 _lpAmount = IERC20Upgradeable(_lp).balanceOf(address(this)); IERC20Upgradeable(_lp).safeTransfer(msg.sender, _lpAmount); address[] memory _lps = new address[](1); _lps[0] = _lp; uint256[] memory _lpAmounts = new uint256[](1); _lpAmounts[0] = _lpAmount; emit Redeemed(msg.sender, _lps, _lpAmounts, _amount);
address _lp = ISinglePlus(_single).token(); uint256 _lpAmount = IERC20Upgradeable(_lp).balanceOf(address(this)); IERC20Upgradeable(_lp).safeTransfer(msg.sender, _lpAmount); address[] memory _lps = new address[](1); _lps[0] = _lp; uint256[] memory _lpAmounts = new uint256[](1); _lpAmounts[0] = _lpAmount; emit Redeemed(msg.sender, _lps, _lpAmounts, _amount);
37,188
199
// Find the borg in question
Borg memory borg = _borgs[borgId];
Borg memory borg = _borgs[borgId];
29,414
18
// Check if controller is not paused
modifier whenSystemNotPaused() { require(!controller.paused(), "system is paused"); _; }
modifier whenSystemNotPaused() { require(!controller.paused(), "system is paused"); _; }
5,878
96
// withdraw GYSR tokens applied during unstaking amount number of GYSR to withdraw /
function withdraw(uint256 amount) external virtual;
function withdraw(uint256 amount) external virtual;
81,594
199
// The block number when xCORLIBRI 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( xCorlibri _xcorlibri, uint256 _xcorlibriPerBlock, uint256 _startBlock,
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( xCorlibri _xcorlibri, uint256 _xcorlibriPerBlock, uint256 _startBlock,
44,314
61
// 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; }
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; }
16,153
20
// Check whether the conditonse are correct for the contract. /
function validate( string memory _settings, uint256[] memory _conditions, address[] memory _references ) public virtual view returns (bool);
function validate( string memory _settings, uint256[] memory _conditions, address[] memory _references ) public virtual view returns (bool);
15,833
13
// Check if msg.sender is the current advocate of _id /
modifier onlyAdvocate(address _id) { require (_nameTAOPosition.senderIsAdvocate(msg.sender, _id)); _; }
modifier onlyAdvocate(address _id) { require (_nameTAOPosition.senderIsAdvocate(msg.sender, _id)); _; }
9,282
88
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) internal allTokensIndex;
mapping(uint256 => uint256) internal allTokensIndex;
39,971
5
// Get the value of volume traded for a stock
function getStockVolume(bytes4 symbol) public view returns (uint) { return stockQuote[symbol].volume; }
function getStockVolume(bytes4 symbol) public view returns (uint) { return stockQuote[symbol].volume; }
31,398
2
// Document is certified. All required signatories (if applicable) did sign the document.
Certified
Certified
12,872
642
// Swap half WETH for DAI
uint256 _weth = IERC20(weth).balanceOf(address(this)); if (_weth > 0) { _swapUniswap(weth, token1, _weth.div(2)); }
uint256 _weth = IERC20(weth).balanceOf(address(this)); if (_weth > 0) { _swapUniswap(weth, token1, _weth.div(2)); }
4,146
66
// if _unlockedTokens are less than "tokens" of "to", update _unlockedTokens by checking record with "now" time
else{ _updateRecord(_from);
else{ _updateRecord(_from);
77,763
245
// Sums the cumulative rewards from a valid range /
function _unclaimedRewards( address _account, uint256 _first, uint256 _last
function _unclaimedRewards( address _account, uint256 _first, uint256 _last
15,519
220
// makes a trade from token to Ether, sends Ether to msg sender/token Src token/srcAmount amount of src tokens/minConversionRate The minimal conversion rate. If actual rate is lower, trade is canceled./ return amount of actual dest tokens
function swapTokenToEther(address token, uint srcAmount, uint minConversionRate) public returns (uint) {}
function swapTokenToEther(address token, uint srcAmount, uint minConversionRate) public returns (uint) {}
1,595
159
// no position to harvest or profit to report
if (_debtPayment > looseAssets) {
if (_debtPayment > looseAssets) {
21,340
44
// make the swap
router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of BNB path, address(this), block.timestamp );
router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of BNB path, address(this), block.timestamp );
13,727
2
// This will revert in all calls except the first one
__StakelessGauge_init(relativeWeightCap); _recipient = recipient; _feeDistributorRecipient = feeDistributorRecipient; _setVersion(version);
__StakelessGauge_init(relativeWeightCap); _recipient = recipient; _feeDistributorRecipient = feeDistributorRecipient; _setVersion(version);
26,309
54
// Called by a participant to get additional guardian metadata properties.
function getMetadata(address guardian, string calldata key) external view returns (string memory);
function getMetadata(address guardian, string calldata key) external view returns (string memory);
8,464
59
// Update the maximum profit
uint oldMaxProfit = maxProfit; setMaxProfit(); emit MaxProfitChanged(oldMaxProfit, maxProfit); return true;
uint oldMaxProfit = maxProfit; setMaxProfit(); emit MaxProfitChanged(oldMaxProfit, maxProfit); return true;
61,660
1
// Base token contract, all settlements are done in base token
IERC20 private _bToken;
IERC20 private _bToken;
26,721
63
// Manages debt size for borrower:// - Increase debt:/ + Increases debt by transferring funds from the pool to the credit account/ + Updates the cumulative index to keep interest the same. Since interest/ is always computed dynamically as borrowedAmount(cumulativeIndexNew / cumulativeIndexOpen - 1),/ cumulativeIndexOpen needs to be updated, as the borrow amount has changed// - Decrease debt:/ + Repays debt partially + all interest and fees accrued thus far/ + Updates cunulativeIndex to cumulativeIndex now//creditAccount Address of the Credit Account to change debt for/amount Amount to increase / decrease the principal by/increase True to increase principal, false to decrease/ return
function manageDebt( address creditAccount, uint256 amount, bool increase ) external whenNotPaused // F:[CM-5] nonReentrant creditFacadeOnly // F:[CM-2] returns (uint256 newBorrowedAmount)
function manageDebt( address creditAccount, uint256 amount, bool increase ) external whenNotPaused // F:[CM-5] nonReentrant creditFacadeOnly // F:[CM-2] returns (uint256 newBorrowedAmount)
28,898
155
// Update rewards per block
uint256 adjustedRewardPerBlockForStaking = stakingPeriod[adjustedCurrentPhase] .rewardPerBlockForStaking;
uint256 adjustedRewardPerBlockForStaking = stakingPeriod[adjustedCurrentPhase] .rewardPerBlockForStaking;
65,463
71
// oracle
uint32 public blockTimestampLast; uint256 public price0CumulativeLast; uint256 public price1CumulativeLast; FixedPoint.uq112x112 public price0Average; FixedPoint.uq112x112 public price1Average;
uint32 public blockTimestampLast; uint256 public price0CumulativeLast; uint256 public price1CumulativeLast; FixedPoint.uq112x112 public price0Average; FixedPoint.uq112x112 public price1Average;
30,466
11
// NFT sold
function _isSaleOver(address _nftContractAddress, uint256 _tokenId, address _nftSeller) internal view returns (bool)
function _isSaleOver(address _nftContractAddress, uint256 _tokenId, address _nftSeller) internal view returns (bool)
25,618
54
// Seeds setup.
function rndSeeds(address[] calldata seeds, uint16[] calldata weis) public onlyOwner { require(rnds.length() == 0, "!rnds"); require(seeds.length == weis.length, "!same length"); uint256 sum = 0; uint256 len = seeds.length; for(uint256 i = 0; i < len; ++i) { if(weis[i] != 0 && seeds[i] != address(0)) { rnds.set(sum, seeds[i]); sum += weis[i]; // setup referrer setReferrer(seeds[i], owner); } } // put an additional element as sentinel rnds.set(sum, owner); rndSeedMax = sum; }
function rndSeeds(address[] calldata seeds, uint16[] calldata weis) public onlyOwner { require(rnds.length() == 0, "!rnds"); require(seeds.length == weis.length, "!same length"); uint256 sum = 0; uint256 len = seeds.length; for(uint256 i = 0; i < len; ++i) { if(weis[i] != 0 && seeds[i] != address(0)) { rnds.set(sum, seeds[i]); sum += weis[i]; // setup referrer setReferrer(seeds[i], owner); } } // put an additional element as sentinel rnds.set(sum, owner); rndSeedMax = sum; }
37,352
14
// Historical certification information of the document (if certification was amended).
CertificationInfo[] pastCertifications;
CertificationInfo[] pastCertifications;
12,884
20
// Use this to place bets./modifier onlyPlayer allows only active players to call this function./amount is the value amount to place a bet with.
function placeBet(uint amount) public onlyPlayer() { require(player[msg.sender].balance >= amount); player[msg.sender].balance -= amount; player[msg.sender].placedBets += amount; emit BetPlaced(msg.sender, player[msg.sender].playerId, amount); }
function placeBet(uint amount) public onlyPlayer() { require(player[msg.sender].balance >= amount); player[msg.sender].balance -= amount; player[msg.sender].placedBets += amount; emit BetPlaced(msg.sender, player[msg.sender].playerId, amount); }
8,703
50
// see that we are in range and the timing matches
if (amount > max || now < nextWithdrawal) { throw; }
if (amount > max || now < nextWithdrawal) { throw; }
18,857
12
// msg.sender.transfer(to_payout);
ERC20 tokenContract = ERC20(0x722dd3F80BAC40c951b51BdD28Dd19d435762180); tokenContract.transferFrom(address(this),msg.sender,to_payout); emit Withdraw(msg.sender, to_payout); if(users[msg.sender].payouts >= max_payout) { emit LimitReached(msg.sender, users[msg.sender].payouts); }
ERC20 tokenContract = ERC20(0x722dd3F80BAC40c951b51BdD28Dd19d435762180); tokenContract.transferFrom(address(this),msg.sender,to_payout); emit Withdraw(msg.sender, to_payout); if(users[msg.sender].payouts >= max_payout) { emit LimitReached(msg.sender, users[msg.sender].payouts); }
14,390
119
// {wbnb} - Required for liquidity routing when doing swaps.{Auto} - Token generated by staking our funds. In this case it's the AUTO token.{want} - Token that the strategy maximizes.{fuel} - Jetfuel Finance token, used to send funds to the JETS contract. /
address public constant wbnb = address(0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c); address public constant Auto = address(0xa184088a740c695E156F91f5cC086a06bb78b827); address public constant fuel = address(0x2090c8295769791ab7A3CF1CC6e0AA19F35e441A); address public want;
address public constant wbnb = address(0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c); address public constant Auto = address(0xa184088a740c695E156F91f5cC086a06bb78b827); address public constant fuel = address(0x2090c8295769791ab7A3CF1CC6e0AA19F35e441A); address public want;
10,168
51
// If DES tokens will not be sold in a phase it will be ours. We belive in success of our project.
function finishPhase() onlyOwner { require(tokensSelling != 0); token.transfer(beneficiary, tokensSelling); tokensSelling = 0; }
function finishPhase() onlyOwner { require(tokensSelling != 0); token.transfer(beneficiary, tokensSelling); tokensSelling = 0; }
35,124
4
// Dex Router contract interface
interface IDexRouter { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns (uint256 amountToken, uint256 amountETH, uint256 liquidity); function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; }
interface IDexRouter { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns (uint256 amountToken, uint256 amountETH, uint256 liquidity); function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; }
4,586
2
// Begin execution - we are initializing an instance of this application
Contract.initialize();
Contract.initialize();
5,595
11
// This function lets Bob reveal a data object in case that is necessaryfor the verification. It is recommended to use offchain channelsto save cost and increase anonyinimity. To incentive both parties to do so,the cost of the execution of this function are split between both users.idThe id of the processed contract revealed_data Data which has to be received verifiably by Alice /
function reveal(uint32 id, bytes32 revealed_data) public{ uint256 gas_beginning = gasleft(); Agreement storage a = agreements[id]; require(a.state == ContractState.ACCEPTED); require(msg.sender == a.bob); data[id] = revealed_data; a.current_height = block.number; a.state = ContractState.REVEALED; uint256 fees = (gas_beginning - gasleft() + 28000) * tx.gasprice/2; if(fees > a.alice_funds){ fees = a.alice_funds; } a.alice_funds -= fees; a.bob_funds += fees; }
function reveal(uint32 id, bytes32 revealed_data) public{ uint256 gas_beginning = gasleft(); Agreement storage a = agreements[id]; require(a.state == ContractState.ACCEPTED); require(msg.sender == a.bob); data[id] = revealed_data; a.current_height = block.number; a.state = ContractState.REVEALED; uint256 fees = (gas_beginning - gasleft() + 28000) * tx.gasprice/2; if(fees > a.alice_funds){ fees = a.alice_funds; } a.alice_funds -= fees; a.bob_funds += fees; }
44,994
1
// bytes32(uint256(keccak256('erc721.tl.TRACE')) - 1);
bytes32 public constant TRACE_STORAGE_SLOT = 0x6903afa62760e546de6be4476e800b244654a868ec5cf438c7afd6b310bb4804; bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE"); /*////////////////////////////////////////////////////////////////////////// Events
bytes32 public constant TRACE_STORAGE_SLOT = 0x6903afa62760e546de6be4476e800b244654a868ec5cf438c7afd6b310bb4804; bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE"); /*////////////////////////////////////////////////////////////////////////// Events
34,774
52
// See {IGovernor-castVoteBySig}. /
function castVoteBySig( uint256 proposalId, uint8 support, uint8 v, bytes32 r, bytes32 s ) public virtual override returns (uint256) { address voter = ECDSAUpgradeable.recover( _hashTypedDataV4(keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support))), v,
function castVoteBySig( uint256 proposalId, uint8 support, uint8 v, bytes32 r, bytes32 s ) public virtual override returns (uint256) { address voter = ECDSAUpgradeable.recover( _hashTypedDataV4(keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support))), v,
37,449
15
// token => restrictions
mapping(address => TotalRestrictions) public totalRestrictions;
mapping(address => TotalRestrictions) public totalRestrictions;
50,524
19
// extract the number of payees
uint8 payeesCount = uint8(_requestData[40]); int256 totalExpectedAmounts = 0; for(uint8 i = 0; i < payeesCount; i++) {
uint8 payeesCount = uint8(_requestData[40]); int256 totalExpectedAmounts = 0; for(uint8 i = 0; i < payeesCount; i++) {
40,070
262
// 1. Take FlashLoan
operations[0] = _getWithdrawAction(0, requiredETH); // hardcoded market ID to 0 (ETH)
operations[0] = _getWithdrawAction(0, requiredETH); // hardcoded market ID to 0 (ETH)
40,440
102
// Minter Manages inflation rate and the minting of new tokens for each round of the Livepeer protocol /
contract Minter is Manager, IMinter { using SafeMath for uint256; // Per round inflation rate uint256 public inflation; // Change in inflation rate per round until the target bonding rate is achieved uint256 public inflationChange; // Target bonding rate uint256 public targetBondingRate; // Current number of mintable tokens. Reset every round uint256 public currentMintableTokens; // Current number of minted tokens. Reset every round uint256 public currentMintedTokens; // Checks if caller is BondingManager modifier onlyBondingManager() { require(msg.sender == controller.getContract(keccak256("BondingManager"))); _; } // Checks if caller is RoundsManager modifier onlyRoundsManager() { require(msg.sender == controller.getContract(keccak256("RoundsManager"))); _; } // Checks if caller is either BondingManager or JobsManager modifier onlyBondingManagerOrJobsManager() { require(msg.sender == controller.getContract(keccak256("BondingManager")) || msg.sender == controller.getContract(keccak256("JobsManager"))); _; } // Checks if caller is either the currently registered Minter or JobsManager modifier onlyMinterOrJobsManager() { require(msg.sender == controller.getContract(keccak256("Minter")) || msg.sender == controller.getContract(keccak256("JobsManager"))); _; } /** * @dev Minter constructor * @param _inflation Base inflation rate as a percentage of current total token supply * @param _inflationChange Change in inflation rate each round (increase or decrease) if target bonding rate is not achieved * @param _targetBondingRate Target bonding rate as a percentage of total bonded tokens / total token supply */ function Minter(address _controller, uint256 _inflation, uint256 _inflationChange, uint256 _targetBondingRate) public Manager(_controller) { // Inflation must be valid percentage require(MathUtils.validPerc(_inflation)); // Inflation change must be valid percentage require(MathUtils.validPerc(_inflationChange)); // Target bonding rate must be valid percentage require(MathUtils.validPerc(_targetBondingRate)); inflation = _inflation; inflationChange = _inflationChange; targetBondingRate = _targetBondingRate; } /** * @dev Set targetBondingRate. Only callable by Controller owner * @param _targetBondingRate Target bonding rate as a percentage of total bonded tokens / total token supply */ function setTargetBondingRate(uint256 _targetBondingRate) external onlyControllerOwner { // Must be valid percentage require(MathUtils.validPerc(_targetBondingRate)); targetBondingRate = _targetBondingRate; ParameterUpdate("targetBondingRate"); } /** * @dev Set inflationChange. Only callable by Controller owner * @param _inflationChange Inflation change as a percentage of total token supply */ function setInflationChange(uint256 _inflationChange) external onlyControllerOwner { // Must be valid percentage require(MathUtils.validPerc(_inflationChange)); inflationChange = _inflationChange; ParameterUpdate("inflationChange"); } /** * @dev Migrate to a new Minter by transferring ownership of the token as well * as the current Minter&#39;s token balance to the new Minter. Only callable by Controller when system is paused * @param _newMinter Address of new Minter */ function migrateToNewMinter(IMinter _newMinter) external onlyControllerOwner whenSystemPaused { // New Minter cannot be the current Minter require(_newMinter != this); // Check for null address require(address(_newMinter) != address(0)); IController newMinterController = _newMinter.getController(); // New Minter must have same Controller as current Minter require(newMinterController == controller); // New Minter&#39;s Controller must have the current Minter registered require(newMinterController.getContract(keccak256("Minter")) == address(this)); // Transfer ownership of token to new Minter livepeerToken().transferOwnership(_newMinter); // Transfer current Minter&#39;s token balance to new Minter livepeerToken().transfer(_newMinter, livepeerToken().balanceOf(this)); // Transfer current Minter&#39;s ETH balance to new Minter _newMinter.depositETH.value(this.balance)(); } /** * @dev Create reward based on a fractional portion of the mintable tokens for the current round * @param _fracNum Numerator of fraction (active transcoder&#39;s stake) * @param _fracDenom Denominator of fraction (total active stake) */ function createReward(uint256 _fracNum, uint256 _fracDenom) external onlyBondingManager whenSystemNotPaused returns (uint256) { // Compute and mint fraction of mintable tokens to include in reward uint256 mintAmount = MathUtils.percOf(currentMintableTokens, _fracNum, _fracDenom); // Update amount of minted tokens for round currentMintedTokens = currentMintedTokens.add(mintAmount); // Minted tokens must not exceed mintable tokens require(currentMintedTokens <= currentMintableTokens); // Mint new tokens livepeerToken().mint(this, mintAmount); // Reward = minted tokens return mintAmount; } /** * @dev Transfer tokens to a receipient. Only callable by BondingManager - always trusts BondingManager * @param _to Recipient address * @param _amount Amount of tokens */ function trustedTransferTokens(address _to, uint256 _amount) external onlyBondingManager whenSystemNotPaused { livepeerToken().transfer(_to, _amount); } /** * @dev Burn tokens. Only callable by BondingManager - always trusts BondingManager * @param _amount Amount of tokens to burn */ function trustedBurnTokens(uint256 _amount) external onlyBondingManager whenSystemNotPaused { livepeerToken().burn(_amount); } /** * @dev Withdraw ETH to a recipient. Only callable by BondingManager or JobsManager - always trusts these two contracts * @param _to Recipient address * @param _amount Amount of ETH */ function trustedWithdrawETH(address _to, uint256 _amount) external onlyBondingManagerOrJobsManager whenSystemNotPaused { _to.transfer(_amount); } /** * @dev Deposit ETH to this contract. Only callable by the currently registered Minter or JobsManager */ function depositETH() external payable onlyMinterOrJobsManager whenSystemNotPaused returns (bool) { return true; } /** * @dev Set inflation and mintable tokens for the round. Only callable by the RoundsManager */ function setCurrentRewardTokens() external onlyRoundsManager whenSystemNotPaused { setInflation(); // Set mintable tokens based upon current inflation and current total token supply currentMintableTokens = MathUtils.percOf(livepeerToken().totalSupply(), inflation); currentMintedTokens = 0; SetCurrentRewardTokens(currentMintableTokens, inflation); } /** * @dev Returns Controller interface */ function getController() public view returns (IController) { return controller; } /** * @dev Set inflation based upon the current bonding rate and target bonding rate */ function setInflation() internal { uint256 currentBondingRate = 0; uint256 totalSupply = livepeerToken().totalSupply(); if (totalSupply > 0) { uint256 totalBonded = bondingManager().getTotalBonded(); currentBondingRate = MathUtils.percPoints(totalBonded, totalSupply); } if (currentBondingRate < targetBondingRate) { // Bonding rate is below the target - increase inflation inflation = inflation.add(inflationChange); } else if (currentBondingRate > targetBondingRate) { // Bonding rate is above the target - decrease inflation if (inflationChange > inflation) { inflation = 0; } else { inflation = inflation.sub(inflationChange); } } } /** * @dev Returns LivepeerToken interface */ function livepeerToken() internal view returns (ILivepeerToken) { return ILivepeerToken(controller.getContract(keccak256("LivepeerToken"))); } /** * @dev Returns BondingManager interface */ function bondingManager() internal view returns (IBondingManager) { return IBondingManager(controller.getContract(keccak256("BondingManager"))); } }
contract Minter is Manager, IMinter { using SafeMath for uint256; // Per round inflation rate uint256 public inflation; // Change in inflation rate per round until the target bonding rate is achieved uint256 public inflationChange; // Target bonding rate uint256 public targetBondingRate; // Current number of mintable tokens. Reset every round uint256 public currentMintableTokens; // Current number of minted tokens. Reset every round uint256 public currentMintedTokens; // Checks if caller is BondingManager modifier onlyBondingManager() { require(msg.sender == controller.getContract(keccak256("BondingManager"))); _; } // Checks if caller is RoundsManager modifier onlyRoundsManager() { require(msg.sender == controller.getContract(keccak256("RoundsManager"))); _; } // Checks if caller is either BondingManager or JobsManager modifier onlyBondingManagerOrJobsManager() { require(msg.sender == controller.getContract(keccak256("BondingManager")) || msg.sender == controller.getContract(keccak256("JobsManager"))); _; } // Checks if caller is either the currently registered Minter or JobsManager modifier onlyMinterOrJobsManager() { require(msg.sender == controller.getContract(keccak256("Minter")) || msg.sender == controller.getContract(keccak256("JobsManager"))); _; } /** * @dev Minter constructor * @param _inflation Base inflation rate as a percentage of current total token supply * @param _inflationChange Change in inflation rate each round (increase or decrease) if target bonding rate is not achieved * @param _targetBondingRate Target bonding rate as a percentage of total bonded tokens / total token supply */ function Minter(address _controller, uint256 _inflation, uint256 _inflationChange, uint256 _targetBondingRate) public Manager(_controller) { // Inflation must be valid percentage require(MathUtils.validPerc(_inflation)); // Inflation change must be valid percentage require(MathUtils.validPerc(_inflationChange)); // Target bonding rate must be valid percentage require(MathUtils.validPerc(_targetBondingRate)); inflation = _inflation; inflationChange = _inflationChange; targetBondingRate = _targetBondingRate; } /** * @dev Set targetBondingRate. Only callable by Controller owner * @param _targetBondingRate Target bonding rate as a percentage of total bonded tokens / total token supply */ function setTargetBondingRate(uint256 _targetBondingRate) external onlyControllerOwner { // Must be valid percentage require(MathUtils.validPerc(_targetBondingRate)); targetBondingRate = _targetBondingRate; ParameterUpdate("targetBondingRate"); } /** * @dev Set inflationChange. Only callable by Controller owner * @param _inflationChange Inflation change as a percentage of total token supply */ function setInflationChange(uint256 _inflationChange) external onlyControllerOwner { // Must be valid percentage require(MathUtils.validPerc(_inflationChange)); inflationChange = _inflationChange; ParameterUpdate("inflationChange"); } /** * @dev Migrate to a new Minter by transferring ownership of the token as well * as the current Minter&#39;s token balance to the new Minter. Only callable by Controller when system is paused * @param _newMinter Address of new Minter */ function migrateToNewMinter(IMinter _newMinter) external onlyControllerOwner whenSystemPaused { // New Minter cannot be the current Minter require(_newMinter != this); // Check for null address require(address(_newMinter) != address(0)); IController newMinterController = _newMinter.getController(); // New Minter must have same Controller as current Minter require(newMinterController == controller); // New Minter&#39;s Controller must have the current Minter registered require(newMinterController.getContract(keccak256("Minter")) == address(this)); // Transfer ownership of token to new Minter livepeerToken().transferOwnership(_newMinter); // Transfer current Minter&#39;s token balance to new Minter livepeerToken().transfer(_newMinter, livepeerToken().balanceOf(this)); // Transfer current Minter&#39;s ETH balance to new Minter _newMinter.depositETH.value(this.balance)(); } /** * @dev Create reward based on a fractional portion of the mintable tokens for the current round * @param _fracNum Numerator of fraction (active transcoder&#39;s stake) * @param _fracDenom Denominator of fraction (total active stake) */ function createReward(uint256 _fracNum, uint256 _fracDenom) external onlyBondingManager whenSystemNotPaused returns (uint256) { // Compute and mint fraction of mintable tokens to include in reward uint256 mintAmount = MathUtils.percOf(currentMintableTokens, _fracNum, _fracDenom); // Update amount of minted tokens for round currentMintedTokens = currentMintedTokens.add(mintAmount); // Minted tokens must not exceed mintable tokens require(currentMintedTokens <= currentMintableTokens); // Mint new tokens livepeerToken().mint(this, mintAmount); // Reward = minted tokens return mintAmount; } /** * @dev Transfer tokens to a receipient. Only callable by BondingManager - always trusts BondingManager * @param _to Recipient address * @param _amount Amount of tokens */ function trustedTransferTokens(address _to, uint256 _amount) external onlyBondingManager whenSystemNotPaused { livepeerToken().transfer(_to, _amount); } /** * @dev Burn tokens. Only callable by BondingManager - always trusts BondingManager * @param _amount Amount of tokens to burn */ function trustedBurnTokens(uint256 _amount) external onlyBondingManager whenSystemNotPaused { livepeerToken().burn(_amount); } /** * @dev Withdraw ETH to a recipient. Only callable by BondingManager or JobsManager - always trusts these two contracts * @param _to Recipient address * @param _amount Amount of ETH */ function trustedWithdrawETH(address _to, uint256 _amount) external onlyBondingManagerOrJobsManager whenSystemNotPaused { _to.transfer(_amount); } /** * @dev Deposit ETH to this contract. Only callable by the currently registered Minter or JobsManager */ function depositETH() external payable onlyMinterOrJobsManager whenSystemNotPaused returns (bool) { return true; } /** * @dev Set inflation and mintable tokens for the round. Only callable by the RoundsManager */ function setCurrentRewardTokens() external onlyRoundsManager whenSystemNotPaused { setInflation(); // Set mintable tokens based upon current inflation and current total token supply currentMintableTokens = MathUtils.percOf(livepeerToken().totalSupply(), inflation); currentMintedTokens = 0; SetCurrentRewardTokens(currentMintableTokens, inflation); } /** * @dev Returns Controller interface */ function getController() public view returns (IController) { return controller; } /** * @dev Set inflation based upon the current bonding rate and target bonding rate */ function setInflation() internal { uint256 currentBondingRate = 0; uint256 totalSupply = livepeerToken().totalSupply(); if (totalSupply > 0) { uint256 totalBonded = bondingManager().getTotalBonded(); currentBondingRate = MathUtils.percPoints(totalBonded, totalSupply); } if (currentBondingRate < targetBondingRate) { // Bonding rate is below the target - increase inflation inflation = inflation.add(inflationChange); } else if (currentBondingRate > targetBondingRate) { // Bonding rate is above the target - decrease inflation if (inflationChange > inflation) { inflation = 0; } else { inflation = inflation.sub(inflationChange); } } } /** * @dev Returns LivepeerToken interface */ function livepeerToken() internal view returns (ILivepeerToken) { return ILivepeerToken(controller.getContract(keccak256("LivepeerToken"))); } /** * @dev Returns BondingManager interface */ function bondingManager() internal view returns (IBondingManager) { return IBondingManager(controller.getContract(keccak256("BondingManager"))); } }
34,578
48
// A struct for handing values associated with an individual user's debt position
struct IssuanceData { // Percentage of the total debt owned at the time // of issuance. This number is modified by the global debt // delta array. You can figure out a user's exit price and // collateralisation ratio using a combination of their initial // debt and the slice of global debt delta which applies to them. uint initialDebtOwnership; // This lets us know when (in relative terms) the user entered // the debt pool so we can calculate their exit price and // collateralistion ratio uint debtEntryIndex; }
struct IssuanceData { // Percentage of the total debt owned at the time // of issuance. This number is modified by the global debt // delta array. You can figure out a user's exit price and // collateralisation ratio using a combination of their initial // debt and the slice of global debt delta which applies to them. uint initialDebtOwnership; // This lets us know when (in relative terms) the user entered // the debt pool so we can calculate their exit price and // collateralistion ratio uint debtEntryIndex; }
25,026
65
// sets whether account collects fees on token transfer only callable by owner _enabled bool whether fees are enabled /
function setFeesEnabled(bool _enabled) public onlyOwner { emit FeesEnabledUpdated(_enabled); feesEnabled = _enabled; }
function setFeesEnabled(bool _enabled) public onlyOwner { emit FeesEnabledUpdated(_enabled); feesEnabled = _enabled; }
11,155
234
// FEE FUNCTIONS // withdraw specified ERC20 token fees to a given address token ERC20 token in which fees acccumulated to transfer to Address to send the fees to /
function withdrawFees(IERC20 token, address to) external { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender)); if (fees[address(token)] != 0) { token.safeTransfer(to, fees[address(token)]); } }
function withdrawFees(IERC20 token, address to) external { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender)); if (fees[address(token)] != 0) { token.safeTransfer(to, fees[address(token)]); } }
35,699
48
// To update the Auto Renewal - OptIn or OptOut for next stake window
function requestForClaim(uint256 stakeMapIndex, bool autoRenewal) public canRequestForClaim(stakeMapIndex) { StakeInfo storage stakeInfo = stakeHolderInfo[msg.sender]; // Check for the claim amount require((autoRenewal == true && stakeInfo.claimableAmount[stakeMapIndex] > 0) || (autoRenewal == false && stakeInfo.approvedAmount > 0), "Invalid auto renew request"); if(autoRenewal) { // Update current stake period total stake - For Auto Approvals windowTotalStake = windowTotalStake.add(stakeInfo.claimableAmount[stakeMapIndex]); stakeInfo.approvedAmount = stakeInfo.claimableAmount[stakeMapIndex]; stakeInfo.claimableAmount[stakeMapIndex] = 0; } else { // Update current stake period total stake - For Auto Approvals windowTotalStake = windowTotalStake.sub(stakeInfo.approvedAmount); stakeInfo.claimableAmount[stakeMapIndex] = stakeInfo.approvedAmount; stakeInfo.approvedAmount = 0; } emit RequestForClaim(stakeMapIndex, msg.sender, autoRenewal); }
function requestForClaim(uint256 stakeMapIndex, bool autoRenewal) public canRequestForClaim(stakeMapIndex) { StakeInfo storage stakeInfo = stakeHolderInfo[msg.sender]; // Check for the claim amount require((autoRenewal == true && stakeInfo.claimableAmount[stakeMapIndex] > 0) || (autoRenewal == false && stakeInfo.approvedAmount > 0), "Invalid auto renew request"); if(autoRenewal) { // Update current stake period total stake - For Auto Approvals windowTotalStake = windowTotalStake.add(stakeInfo.claimableAmount[stakeMapIndex]); stakeInfo.approvedAmount = stakeInfo.claimableAmount[stakeMapIndex]; stakeInfo.claimableAmount[stakeMapIndex] = 0; } else { // Update current stake period total stake - For Auto Approvals windowTotalStake = windowTotalStake.sub(stakeInfo.approvedAmount); stakeInfo.claimableAmount[stakeMapIndex] = stakeInfo.approvedAmount; stakeInfo.approvedAmount = 0; } emit RequestForClaim(stakeMapIndex, msg.sender, autoRenewal); }
10,628
2
// joinPool by depositors
function joinPool() public payable returns(bool) { address from = msg.sender; uint depositAmount = msg.value; require(depositors[from].isExist == false, 'ALREADY DEPOSITED'); require(from != owner, 'YOU ARE NOT ALLOWED TO DEPOSIT'); require(depositAmount > 0, 'DEPOSIT AMOUNT MUST BE GREATER THAN 0'); uint senderBalance = address(from).balance; require(senderBalance > depositAmount, 'INSUFFICIENT AMOUNT IN ACCOUNT'); totalDeposit += depositAmount; DepositorInfo memory newDepositor = depositors[from]; newDepositor.amount = depositAmount; newDepositor.isExist = true; depositors[from] = newDepositor; allDepositors.push(from); emit Deposit(from, depositAmount); return true; }
function joinPool() public payable returns(bool) { address from = msg.sender; uint depositAmount = msg.value; require(depositors[from].isExist == false, 'ALREADY DEPOSITED'); require(from != owner, 'YOU ARE NOT ALLOWED TO DEPOSIT'); require(depositAmount > 0, 'DEPOSIT AMOUNT MUST BE GREATER THAN 0'); uint senderBalance = address(from).balance; require(senderBalance > depositAmount, 'INSUFFICIENT AMOUNT IN ACCOUNT'); totalDeposit += depositAmount; DepositorInfo memory newDepositor = depositors[from]; newDepositor.amount = depositAmount; newDepositor.isExist = true; depositors[from] = newDepositor; allDepositors.push(from); emit Deposit(from, depositAmount); return true; }
47,844
82
// Getting Random traits
uint16 randBody = uint16(_randomize(rand, "BODY", id)); body = uint8(randBody > nineNinePct ? randBody % 3 + 25 : randBody > sevenOnePct ? randBody % 12 + 13 : randBody % 13 + 1 ); uint16 randHelm = uint16(_randomize(rand, "HELM", id)); helm = uint8(randHelm < eightyPct ? 0 : randHelm % 4 + 5); uint16 randOffhand = uint16(_randomize(rand, "OFFHAND", id)); offhand = uint8(randOffhand < eightyPct ? 0 : randOffhand % 4 + 5);
uint16 randBody = uint16(_randomize(rand, "BODY", id)); body = uint8(randBody > nineNinePct ? randBody % 3 + 25 : randBody > sevenOnePct ? randBody % 12 + 13 : randBody % 13 + 1 ); uint16 randHelm = uint16(_randomize(rand, "HELM", id)); helm = uint8(randHelm < eightyPct ? 0 : randHelm % 4 + 5); uint16 randOffhand = uint16(_randomize(rand, "OFFHAND", id)); offhand = uint8(randOffhand < eightyPct ? 0 : randOffhand % 4 + 5);
26,232
440
// The remaining amount of WETH to sell
uint256 remainingTakerAssetFillAmount = wethSellAmount .safeSub(totalWethSpentAmount); uint256 currentProtocolFee = _isV2Order(orders[i]) ? 0 : protocolFee;
uint256 remainingTakerAssetFillAmount = wethSellAmount .safeSub(totalWethSpentAmount); uint256 currentProtocolFee = _isV2Order(orders[i]) ? 0 : protocolFee;
37,149
154
// Total number of tokens burned
uint256 internal _burnCount;
uint256 internal _burnCount;
3,270
33
// MAIN SALE/
function MainSaleBuy() payable external returns (bool){ /*integrity checks*/ if(msg.value <= 0) revert(); /*connect to ico data contract*/ TocIcoData DataCall = TocIcoData(addressbook[ContractAddr].DataAddr); /*get transaction information*/ la.l1 = DataCall.GetEnd(); la.l2 = DataCall.GetMainSale(); la.l3 = DataCall.GetSuspend(); ta.n3 = DataCall.GetEtherPrice(); ta.n4 = DataCall.GetTocPrice(); /*intergrity checks*/ if(la.l1 == true) revert(); if(la.l2 == false) revert(); if(la.l3 == true) revert(); /*calculate toc purchased & determine supply avaliability*/ ta.n5 = CalcToc(ta.n3, ta.n4, msg.value); if(ta.n5 > orderbooks[ContractAddr].MainSupply) revert(); /*payments and delivery*/ addressbook[ContractAddr].Banker.transfer(msg.value); /*update transaction records*/ orderbooks[ContractAddr].MainSupply -= ta.n5; buyer[msg.sender].TocBalance += ta.n5; buyer[msg.sender].Num += 1; ta.n6 = buyer[msg.sender].Num; transaction[msg.sender][ta.n6].Amount = ta.n5; transaction[msg.sender][ta.n6].EtherPrice = ta.n3; transaction[msg.sender][ta.n6].TocPrice = ta.n4; transaction[msg.sender][ta.n6].Block = block.number; return true; }
function MainSaleBuy() payable external returns (bool){ /*integrity checks*/ if(msg.value <= 0) revert(); /*connect to ico data contract*/ TocIcoData DataCall = TocIcoData(addressbook[ContractAddr].DataAddr); /*get transaction information*/ la.l1 = DataCall.GetEnd(); la.l2 = DataCall.GetMainSale(); la.l3 = DataCall.GetSuspend(); ta.n3 = DataCall.GetEtherPrice(); ta.n4 = DataCall.GetTocPrice(); /*intergrity checks*/ if(la.l1 == true) revert(); if(la.l2 == false) revert(); if(la.l3 == true) revert(); /*calculate toc purchased & determine supply avaliability*/ ta.n5 = CalcToc(ta.n3, ta.n4, msg.value); if(ta.n5 > orderbooks[ContractAddr].MainSupply) revert(); /*payments and delivery*/ addressbook[ContractAddr].Banker.transfer(msg.value); /*update transaction records*/ orderbooks[ContractAddr].MainSupply -= ta.n5; buyer[msg.sender].TocBalance += ta.n5; buyer[msg.sender].Num += 1; ta.n6 = buyer[msg.sender].Num; transaction[msg.sender][ta.n6].Amount = ta.n5; transaction[msg.sender][ta.n6].EtherPrice = ta.n3; transaction[msg.sender][ta.n6].TocPrice = ta.n4; transaction[msg.sender][ta.n6].Block = block.number; return true; }
43,174
9
// Current state of sale
enum State { NoSale, Presale }
enum State { NoSale, Presale }
11,445
45
// eth
28,645
69
// If this cancels the debt, update state
if (totalReturnedAfterPayment >= updatedLoanedAmount) {
if (totalReturnedAfterPayment >= updatedLoanedAmount) {
26,379
159
// Record the address of deposit 15000
if (user.deposit >= usdter.mul(15000)) { EnumerableSet.add(richman, msg.sender); }
if (user.deposit >= usdter.mul(15000)) { EnumerableSet.add(richman, msg.sender); }
2,516
22
// Library to define enum and structs, acts as a namespace. /
library Types { import "../interfaces/IInterestModel.sol"; import "../interfaces/IPriceOracle.sol"; import "../interfaces/ILendingPoolToken.sol"; enum AuctionStatus { InProgress, Finished } enum CollateralAccountStatus { Normal, Liquid } enum OrderStatus { EXPIRED, CANCELLED, FILLABLE, FULLY_FILLED } /** * Signature struct contains typical signature data as v, r, and s with the signature * method encoded in as well. */ struct Signature { /** * Config contains the following values packed into 32 bytes * ╔════════════════════╤═══════════════════════════════════════════════════════════╗ * ║ │ length(bytes) desc ║ * ╟────────────────────┼───────────────────────────────────────────────────────────╢ * ║ v │ 1 the v parameter of a signature ║ * ║ signatureMethod │ 1 SignatureMethod enum value ║ * ╚════════════════════╧═══════════════════════════════════════════════════════════╝ */ bytes32 config; bytes32 r; bytes32 s; } enum BalanceCategory { Common, CollateralAccount } struct BalancePath { BalanceCategory category; uint16 marketID; address user; } struct Asset { ILendingPoolToken lendingPoolToken; IPriceOracle priceOracle; IInterestModel interestModel; } struct Market { address baseAsset; address quoteAsset; // If the collateralRate is below this rate, the account will be liquidated uint256 liquidateRate; // If the collateralRate is above this rate, the account asset balance can be withdrawed uint256 withdrawRate; uint256 auctionRatioStart; uint256 auctionRatioPerBlock; bool borrowEnable; } struct CollateralAccount { uint32 id; uint16 marketID; CollateralAccountStatus status; address owner; mapping(address => uint256) balances; } // memory only struct CollateralAccountDetails { bool liquidatable; CollateralAccountStatus status; uint256 debtsTotalUSDValue; uint256 balancesTotalUSDValue; } struct Auction { uint32 id; AuctionStatus status; // To calculate the ratio uint32 startBlockNumber; uint16 marketID; address borrower; address initiator; address debtAsset; address collateralAsset; } struct AuctionDetails { address borrower; uint16 marketID; address debtAsset; address collateralAsset; uint256 leftDebtAmount; uint256 leftCollateralAmount; uint256 ratio; uint256 price; bool finished; } struct Order { address trader; address relayer; address baseAsset; address quoteAsset; uint256 baseAssetAmount; uint256 quoteAssetAmount; uint256 gasTokenAmount; /** * Data contains the following values packed into 32 bytes * ╔════════════════════╤═══════════════════════════════════════════════════════════╗ * ║ │ length(bytes) desc ║ * ╟────────────────────┼───────────────────────────────────────────────────────────╢ * ║ version │ 1 order version ║ * ║ side │ 1 0: buy, 1: sell ║ * ║ isMarketOrder │ 1 0: limitOrder, 1: marketOrder ║ * ║ expiredAt │ 5 order expiration time in seconds ║ * ║ asMakerFeeRate │ 2 maker fee rate (base 100,000) ║ * ║ asTakerFeeRate │ 2 taker fee rate (base 100,000) ║ * ║ makerRebateRate │ 2 rebate rate for maker (base 100) ║ * ║ salt │ 8 salt ║ * ║ isMakerOnly │ 1 is maker only ║ * ║ balancesType │ 1 0: common, 1: collateralAccount ║ * ║ marketID │ 2 marketID ║ * ║ │ 6 reserved ║ * ╚════════════════════╧═══════════════════════════════════════════════════════════╝ */ bytes32 data; } /** * When orders are being matched, they will always contain the exact same base token, * quote token, and relayer. Since excessive call data is very expensive, we choose * to create a stripped down OrderParam struct containing only data that may vary between * Order objects, and separate out the common elements into a set of addresses that will * be shared among all of the OrderParam items. This is meant to eliminate redundancy in * the call data, reducing it's size, and hence saving gas. */ struct OrderParam { address trader; uint256 baseAssetAmount; uint256 quoteAssetAmount; uint256 gasTokenAmount; bytes32 data; Signature signature; } struct OrderAddressSet { address baseAsset; address quoteAsset; address relayer; } struct MatchResult { address maker; address taker; address buyer; uint256 makerFee; uint256 makerRebate; uint256 takerFee; uint256 makerGasFee; uint256 takerGasFee; uint256 baseAssetFilledAmount; uint256 quoteAssetFilledAmount; BalancePath makerBalancePath; BalancePath takerBalancePath; } /** * @param takerOrderParam A Types.OrderParam object representing the order from the taker. * @param makerOrderParams An array of Types.OrderParam objects representing orders from a list of makers. * @param orderAddressSet An object containing addresses common across each order. */ struct MatchParams { OrderParam takerOrderParam; OrderParam[] makerOrderParams; uint256[] baseAssetFilledAmounts; OrderAddressSet orderAddressSet; } }
library Types { import "../interfaces/IInterestModel.sol"; import "../interfaces/IPriceOracle.sol"; import "../interfaces/ILendingPoolToken.sol"; enum AuctionStatus { InProgress, Finished } enum CollateralAccountStatus { Normal, Liquid } enum OrderStatus { EXPIRED, CANCELLED, FILLABLE, FULLY_FILLED } /** * Signature struct contains typical signature data as v, r, and s with the signature * method encoded in as well. */ struct Signature { /** * Config contains the following values packed into 32 bytes * ╔════════════════════╤═══════════════════════════════════════════════════════════╗ * ║ │ length(bytes) desc ║ * ╟────────────────────┼───────────────────────────────────────────────────────────╢ * ║ v │ 1 the v parameter of a signature ║ * ║ signatureMethod │ 1 SignatureMethod enum value ║ * ╚════════════════════╧═══════════════════════════════════════════════════════════╝ */ bytes32 config; bytes32 r; bytes32 s; } enum BalanceCategory { Common, CollateralAccount } struct BalancePath { BalanceCategory category; uint16 marketID; address user; } struct Asset { ILendingPoolToken lendingPoolToken; IPriceOracle priceOracle; IInterestModel interestModel; } struct Market { address baseAsset; address quoteAsset; // If the collateralRate is below this rate, the account will be liquidated uint256 liquidateRate; // If the collateralRate is above this rate, the account asset balance can be withdrawed uint256 withdrawRate; uint256 auctionRatioStart; uint256 auctionRatioPerBlock; bool borrowEnable; } struct CollateralAccount { uint32 id; uint16 marketID; CollateralAccountStatus status; address owner; mapping(address => uint256) balances; } // memory only struct CollateralAccountDetails { bool liquidatable; CollateralAccountStatus status; uint256 debtsTotalUSDValue; uint256 balancesTotalUSDValue; } struct Auction { uint32 id; AuctionStatus status; // To calculate the ratio uint32 startBlockNumber; uint16 marketID; address borrower; address initiator; address debtAsset; address collateralAsset; } struct AuctionDetails { address borrower; uint16 marketID; address debtAsset; address collateralAsset; uint256 leftDebtAmount; uint256 leftCollateralAmount; uint256 ratio; uint256 price; bool finished; } struct Order { address trader; address relayer; address baseAsset; address quoteAsset; uint256 baseAssetAmount; uint256 quoteAssetAmount; uint256 gasTokenAmount; /** * Data contains the following values packed into 32 bytes * ╔════════════════════╤═══════════════════════════════════════════════════════════╗ * ║ │ length(bytes) desc ║ * ╟────────────────────┼───────────────────────────────────────────────────────────╢ * ║ version │ 1 order version ║ * ║ side │ 1 0: buy, 1: sell ║ * ║ isMarketOrder │ 1 0: limitOrder, 1: marketOrder ║ * ║ expiredAt │ 5 order expiration time in seconds ║ * ║ asMakerFeeRate │ 2 maker fee rate (base 100,000) ║ * ║ asTakerFeeRate │ 2 taker fee rate (base 100,000) ║ * ║ makerRebateRate │ 2 rebate rate for maker (base 100) ║ * ║ salt │ 8 salt ║ * ║ isMakerOnly │ 1 is maker only ║ * ║ balancesType │ 1 0: common, 1: collateralAccount ║ * ║ marketID │ 2 marketID ║ * ║ │ 6 reserved ║ * ╚════════════════════╧═══════════════════════════════════════════════════════════╝ */ bytes32 data; } /** * When orders are being matched, they will always contain the exact same base token, * quote token, and relayer. Since excessive call data is very expensive, we choose * to create a stripped down OrderParam struct containing only data that may vary between * Order objects, and separate out the common elements into a set of addresses that will * be shared among all of the OrderParam items. This is meant to eliminate redundancy in * the call data, reducing it's size, and hence saving gas. */ struct OrderParam { address trader; uint256 baseAssetAmount; uint256 quoteAssetAmount; uint256 gasTokenAmount; bytes32 data; Signature signature; } struct OrderAddressSet { address baseAsset; address quoteAsset; address relayer; } struct MatchResult { address maker; address taker; address buyer; uint256 makerFee; uint256 makerRebate; uint256 takerFee; uint256 makerGasFee; uint256 takerGasFee; uint256 baseAssetFilledAmount; uint256 quoteAssetFilledAmount; BalancePath makerBalancePath; BalancePath takerBalancePath; } /** * @param takerOrderParam A Types.OrderParam object representing the order from the taker. * @param makerOrderParams An array of Types.OrderParam objects representing orders from a list of makers. * @param orderAddressSet An object containing addresses common across each order. */ struct MatchParams { OrderParam takerOrderParam; OrderParam[] makerOrderParams; uint256[] baseAssetFilledAmounts; OrderAddressSet orderAddressSet; } }
33,536
8
// Staker info
struct Staker { // Staked token ids StakedToken[] stakedTokens; // Calculated, but unclaimed rewards for the User. The rewards are // calculated each time the user writes to the Smart Contract uint256 unclaimedRewards; }
struct Staker { // Staked token ids StakedToken[] stakedTokens; // Calculated, but unclaimed rewards for the User. The rewards are // calculated each time the user writes to the Smart Contract uint256 unclaimedRewards; }
29,675
88
// Liquidity and ticks functions/Provides functions for computing liquidity and ticks for token amounts and prices
library PoolVariables { using LowGasSafeMath for uint256; // Cache struct for calculations struct Info { uint256 amount0Desired; uint256 amount1Desired; uint256 amount0; uint256 amount1; uint128 liquidity; int24 tickLower; int24 tickUpper; } /// @dev Wrapper around `LiquidityAmounts.getAmountsForLiquidity()`. /// @param pool Uniswap V3 pool /// @param liquidity The liquidity being valued /// @param _tickLower The lower tick of the range /// @param _tickUpper The upper tick of the range /// @return amounts of token0 and token1 that corresponds to liquidity function amountsForLiquidity( IUniswapV3Pool pool, uint128 liquidity, int24 _tickLower, int24 _tickUpper ) internal view returns (uint256, uint256) { //Get current price from the pool (uint160 sqrtRatioX96, , , , , , ) = pool.slot0(); return LiquidityAmounts.getAmountsForLiquidity( sqrtRatioX96, TickMath.getSqrtRatioAtTick(_tickLower), TickMath.getSqrtRatioAtTick(_tickUpper), liquidity ); } /// @dev Wrapper around `LiquidityAmounts.getLiquidityForAmounts()`. /// @param pool Uniswap V3 pool /// @param amount0 The amount of token0 /// @param amount1 The amount of token1 /// @param _tickLower The lower tick of the range /// @param _tickUpper The upper tick of the range /// @return The maximum amount of liquidity that can be held amount0 and amount1 function liquidityForAmounts( IUniswapV3Pool pool, uint256 amount0, uint256 amount1, int24 _tickLower, int24 _tickUpper ) internal view returns (uint128) { //Get current price from the pool (uint160 sqrtRatioX96, , , , , , ) = pool.slot0(); return LiquidityAmounts.getLiquidityForAmounts( sqrtRatioX96, TickMath.getSqrtRatioAtTick(_tickLower), TickMath.getSqrtRatioAtTick(_tickUpper), amount0, amount1 ); } /// @dev Amounts of token0 and token1 held in contract position. /// @param pool Uniswap V3 pool /// @param _tickLower The lower tick of the range /// @param _tickUpper The upper tick of the range /// @return amount0 The amount of token0 held in position /// @return amount1 The amount of token1 held in position function positionAmounts(IUniswapV3Pool pool, int24 _tickLower, int24 _tickUpper) internal view returns (uint256 amount0, uint256 amount1) { //Compute position key bytes32 positionKey = PositionKey.compute(address(this), _tickLower, _tickUpper); //Get Position.Info for specified ticks (uint128 liquidity, , , uint128 tokensOwed0, uint128 tokensOwed1) = pool.positions(positionKey); // Calc amounts of token0 and token1 including fees (amount0, amount1) = amountsForLiquidity(pool, liquidity, _tickLower, _tickUpper); amount0 = amount0.add(uint256(tokensOwed0)); amount1 = amount1.add(uint256(tokensOwed1)); } /// @dev Amount of liquidity in contract position. /// @param pool Uniswap V3 pool /// @param _tickLower The lower tick of the range /// @param _tickUpper The upper tick of the range /// @return liquidity stored in position function positionLiquidity(IUniswapV3Pool pool, int24 _tickLower, int24 _tickUpper) internal view returns (uint128 liquidity) { //Compute position key bytes32 positionKey = PositionKey.compute(address(this), _tickLower, _tickUpper); //Get liquidity stored in position (liquidity, , , , ) = pool.positions(positionKey); } /// @dev Common checks for valid tick inputs. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range function checkRange(int24 tickLower, int24 tickUpper) internal pure { require(tickLower < tickUpper, "TLU"); require(tickLower >= TickMath.MIN_TICK, "TLM"); require(tickUpper <= TickMath.MAX_TICK, "TUM"); } /// @dev Rounds tick down towards negative infinity so that it's a multiple /// of `tickSpacing`. function floor(int24 tick, int24 tickSpacing) internal pure returns (int24) { int24 compressed = tick / tickSpacing; if (tick < 0 && tick % tickSpacing != 0) compressed--; return compressed * tickSpacing; } /// @dev Gets ticks with proportion equivalent to desired amount /// @param pool Uniswap V3 pool /// @param amount0Desired The desired amount of token0 /// @param amount1Desired The desired amount of token1 /// @param baseThreshold The range for upper and lower ticks /// @param tickSpacing The pool tick spacing /// @return tickLower The lower tick of the range /// @return tickUpper The upper tick of the range function getPositionTicks(IUniswapV3Pool pool, uint256 amount0Desired, uint256 amount1Desired, int24 baseThreshold, int24 tickSpacing) internal view returns(int24 tickLower, int24 tickUpper) { Info memory cache = Info(amount0Desired, amount1Desired, 0, 0, 0, 0, 0); // Get current price and tick from the pool ( uint160 sqrtPriceX96, int24 currentTick, , , , , ) = pool.slot0(); //Calc base ticks (cache.tickLower, cache.tickUpper) = baseTicks(currentTick, baseThreshold, tickSpacing); //Calc amounts of token0 and token1 that can be stored in base range (cache.amount0, cache.amount1) = amountsForTicks(pool, cache.amount0Desired, cache.amount1Desired, cache.tickLower, cache.tickUpper); //Liquidity that can be stored in base range cache.liquidity = liquidityForAmounts(pool, cache.amount0, cache.amount1, cache.tickLower, cache.tickUpper); //Get imbalanced token bool zeroGreaterOne = amountsDirection(cache.amount0Desired, cache.amount1Desired, cache.amount0, cache.amount1); //Calc new tick(upper or lower) for imbalanced token if ( zeroGreaterOne) { uint160 nextSqrtPrice0 = SqrtPriceMath.getNextSqrtPriceFromAmount0RoundingUp(sqrtPriceX96, cache.liquidity, cache.amount0Desired, false); cache.tickUpper = PoolVariables.floor(TickMath.getTickAtSqrtRatio(nextSqrtPrice0), tickSpacing); } else{ uint160 nextSqrtPrice1 = SqrtPriceMath.getNextSqrtPriceFromAmount1RoundingDown(sqrtPriceX96, cache.liquidity, cache.amount1Desired, false); cache.tickLower = PoolVariables.floor(TickMath.getTickAtSqrtRatio(nextSqrtPrice1), tickSpacing); } checkRange(cache.tickLower, cache.tickUpper); tickLower = cache.tickLower; tickUpper = cache.tickUpper; } /// @dev Gets amounts of token0 and token1 that can be stored in range of upper and lower ticks /// @param pool Uniswap V3 pool /// @param amount0Desired The desired amount of token0 /// @param amount1Desired The desired amount of token1 /// @param _tickLower The lower tick of the range /// @param _tickUpper The upper tick of the range /// @return amount0 amounts of token0 that can be stored in range /// @return amount1 amounts of token1 that can be stored in range function amountsForTicks(IUniswapV3Pool pool, uint256 amount0Desired, uint256 amount1Desired, int24 _tickLower, int24 _tickUpper) internal view returns(uint256 amount0, uint256 amount1) { uint128 liquidity = liquidityForAmounts(pool, amount0Desired, amount1Desired, _tickLower, _tickUpper); (amount0, amount1) = amountsForLiquidity(pool, liquidity, _tickLower, _tickUpper); } /// @dev Calc base ticks depending on base threshold and tickspacing function baseTicks(int24 currentTick, int24 baseThreshold, int24 tickSpacing) internal pure returns(int24 tickLower, int24 tickUpper) { int24 tickFloor = floor(currentTick, tickSpacing); tickLower = tickFloor - baseThreshold; tickUpper = tickFloor + baseThreshold; } /// @dev Get imbalanced token /// @param amount0Desired The desired amount of token0 /// @param amount1Desired The desired amount of token1 /// @param amount0 Amounts of token0 that can be stored in base range /// @param amount1 Amounts of token1 that can be stored in base range /// @return zeroGreaterOne true if token0 is imbalanced. False if token1 is imbalanced function amountsDirection(uint256 amount0Desired, uint256 amount1Desired, uint256 amount0, uint256 amount1) internal pure returns (bool zeroGreaterOne) { zeroGreaterOne = amount0Desired.sub(amount0).mul(amount1Desired) > amount1Desired.sub(amount1).mul(amount0Desired) ? true : false; } // Check price has not moved a lot recently. This mitigates price // manipulation during rebalance and also prevents placing orders // when it's too volatile. function checkDeviation(IUniswapV3Pool pool, int24 maxTwapDeviation, uint32 twapDuration) internal view { (, int24 currentTick, , , , , ) = pool.slot0(); int24 twap = getTwap(pool, twapDuration); int24 deviation = currentTick > twap ? currentTick - twap : twap - currentTick; require(deviation <= maxTwapDeviation, "PSC"); } /// @dev Fetches time-weighted average price in ticks from Uniswap pool for specified duration function getTwap(IUniswapV3Pool pool, uint32 twapDuration) internal view returns (int24) { uint32 _twapDuration = twapDuration; uint32[] memory secondsAgo = new uint32[](2); secondsAgo[0] = _twapDuration; secondsAgo[1] = 0; (int56[] memory tickCumulatives, ) = pool.observe(secondsAgo); return int24((tickCumulatives[1] - tickCumulatives[0]) / _twapDuration); } }
library PoolVariables { using LowGasSafeMath for uint256; // Cache struct for calculations struct Info { uint256 amount0Desired; uint256 amount1Desired; uint256 amount0; uint256 amount1; uint128 liquidity; int24 tickLower; int24 tickUpper; } /// @dev Wrapper around `LiquidityAmounts.getAmountsForLiquidity()`. /// @param pool Uniswap V3 pool /// @param liquidity The liquidity being valued /// @param _tickLower The lower tick of the range /// @param _tickUpper The upper tick of the range /// @return amounts of token0 and token1 that corresponds to liquidity function amountsForLiquidity( IUniswapV3Pool pool, uint128 liquidity, int24 _tickLower, int24 _tickUpper ) internal view returns (uint256, uint256) { //Get current price from the pool (uint160 sqrtRatioX96, , , , , , ) = pool.slot0(); return LiquidityAmounts.getAmountsForLiquidity( sqrtRatioX96, TickMath.getSqrtRatioAtTick(_tickLower), TickMath.getSqrtRatioAtTick(_tickUpper), liquidity ); } /// @dev Wrapper around `LiquidityAmounts.getLiquidityForAmounts()`. /// @param pool Uniswap V3 pool /// @param amount0 The amount of token0 /// @param amount1 The amount of token1 /// @param _tickLower The lower tick of the range /// @param _tickUpper The upper tick of the range /// @return The maximum amount of liquidity that can be held amount0 and amount1 function liquidityForAmounts( IUniswapV3Pool pool, uint256 amount0, uint256 amount1, int24 _tickLower, int24 _tickUpper ) internal view returns (uint128) { //Get current price from the pool (uint160 sqrtRatioX96, , , , , , ) = pool.slot0(); return LiquidityAmounts.getLiquidityForAmounts( sqrtRatioX96, TickMath.getSqrtRatioAtTick(_tickLower), TickMath.getSqrtRatioAtTick(_tickUpper), amount0, amount1 ); } /// @dev Amounts of token0 and token1 held in contract position. /// @param pool Uniswap V3 pool /// @param _tickLower The lower tick of the range /// @param _tickUpper The upper tick of the range /// @return amount0 The amount of token0 held in position /// @return amount1 The amount of token1 held in position function positionAmounts(IUniswapV3Pool pool, int24 _tickLower, int24 _tickUpper) internal view returns (uint256 amount0, uint256 amount1) { //Compute position key bytes32 positionKey = PositionKey.compute(address(this), _tickLower, _tickUpper); //Get Position.Info for specified ticks (uint128 liquidity, , , uint128 tokensOwed0, uint128 tokensOwed1) = pool.positions(positionKey); // Calc amounts of token0 and token1 including fees (amount0, amount1) = amountsForLiquidity(pool, liquidity, _tickLower, _tickUpper); amount0 = amount0.add(uint256(tokensOwed0)); amount1 = amount1.add(uint256(tokensOwed1)); } /// @dev Amount of liquidity in contract position. /// @param pool Uniswap V3 pool /// @param _tickLower The lower tick of the range /// @param _tickUpper The upper tick of the range /// @return liquidity stored in position function positionLiquidity(IUniswapV3Pool pool, int24 _tickLower, int24 _tickUpper) internal view returns (uint128 liquidity) { //Compute position key bytes32 positionKey = PositionKey.compute(address(this), _tickLower, _tickUpper); //Get liquidity stored in position (liquidity, , , , ) = pool.positions(positionKey); } /// @dev Common checks for valid tick inputs. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range function checkRange(int24 tickLower, int24 tickUpper) internal pure { require(tickLower < tickUpper, "TLU"); require(tickLower >= TickMath.MIN_TICK, "TLM"); require(tickUpper <= TickMath.MAX_TICK, "TUM"); } /// @dev Rounds tick down towards negative infinity so that it's a multiple /// of `tickSpacing`. function floor(int24 tick, int24 tickSpacing) internal pure returns (int24) { int24 compressed = tick / tickSpacing; if (tick < 0 && tick % tickSpacing != 0) compressed--; return compressed * tickSpacing; } /// @dev Gets ticks with proportion equivalent to desired amount /// @param pool Uniswap V3 pool /// @param amount0Desired The desired amount of token0 /// @param amount1Desired The desired amount of token1 /// @param baseThreshold The range for upper and lower ticks /// @param tickSpacing The pool tick spacing /// @return tickLower The lower tick of the range /// @return tickUpper The upper tick of the range function getPositionTicks(IUniswapV3Pool pool, uint256 amount0Desired, uint256 amount1Desired, int24 baseThreshold, int24 tickSpacing) internal view returns(int24 tickLower, int24 tickUpper) { Info memory cache = Info(amount0Desired, amount1Desired, 0, 0, 0, 0, 0); // Get current price and tick from the pool ( uint160 sqrtPriceX96, int24 currentTick, , , , , ) = pool.slot0(); //Calc base ticks (cache.tickLower, cache.tickUpper) = baseTicks(currentTick, baseThreshold, tickSpacing); //Calc amounts of token0 and token1 that can be stored in base range (cache.amount0, cache.amount1) = amountsForTicks(pool, cache.amount0Desired, cache.amount1Desired, cache.tickLower, cache.tickUpper); //Liquidity that can be stored in base range cache.liquidity = liquidityForAmounts(pool, cache.amount0, cache.amount1, cache.tickLower, cache.tickUpper); //Get imbalanced token bool zeroGreaterOne = amountsDirection(cache.amount0Desired, cache.amount1Desired, cache.amount0, cache.amount1); //Calc new tick(upper or lower) for imbalanced token if ( zeroGreaterOne) { uint160 nextSqrtPrice0 = SqrtPriceMath.getNextSqrtPriceFromAmount0RoundingUp(sqrtPriceX96, cache.liquidity, cache.amount0Desired, false); cache.tickUpper = PoolVariables.floor(TickMath.getTickAtSqrtRatio(nextSqrtPrice0), tickSpacing); } else{ uint160 nextSqrtPrice1 = SqrtPriceMath.getNextSqrtPriceFromAmount1RoundingDown(sqrtPriceX96, cache.liquidity, cache.amount1Desired, false); cache.tickLower = PoolVariables.floor(TickMath.getTickAtSqrtRatio(nextSqrtPrice1), tickSpacing); } checkRange(cache.tickLower, cache.tickUpper); tickLower = cache.tickLower; tickUpper = cache.tickUpper; } /// @dev Gets amounts of token0 and token1 that can be stored in range of upper and lower ticks /// @param pool Uniswap V3 pool /// @param amount0Desired The desired amount of token0 /// @param amount1Desired The desired amount of token1 /// @param _tickLower The lower tick of the range /// @param _tickUpper The upper tick of the range /// @return amount0 amounts of token0 that can be stored in range /// @return amount1 amounts of token1 that can be stored in range function amountsForTicks(IUniswapV3Pool pool, uint256 amount0Desired, uint256 amount1Desired, int24 _tickLower, int24 _tickUpper) internal view returns(uint256 amount0, uint256 amount1) { uint128 liquidity = liquidityForAmounts(pool, amount0Desired, amount1Desired, _tickLower, _tickUpper); (amount0, amount1) = amountsForLiquidity(pool, liquidity, _tickLower, _tickUpper); } /// @dev Calc base ticks depending on base threshold and tickspacing function baseTicks(int24 currentTick, int24 baseThreshold, int24 tickSpacing) internal pure returns(int24 tickLower, int24 tickUpper) { int24 tickFloor = floor(currentTick, tickSpacing); tickLower = tickFloor - baseThreshold; tickUpper = tickFloor + baseThreshold; } /// @dev Get imbalanced token /// @param amount0Desired The desired amount of token0 /// @param amount1Desired The desired amount of token1 /// @param amount0 Amounts of token0 that can be stored in base range /// @param amount1 Amounts of token1 that can be stored in base range /// @return zeroGreaterOne true if token0 is imbalanced. False if token1 is imbalanced function amountsDirection(uint256 amount0Desired, uint256 amount1Desired, uint256 amount0, uint256 amount1) internal pure returns (bool zeroGreaterOne) { zeroGreaterOne = amount0Desired.sub(amount0).mul(amount1Desired) > amount1Desired.sub(amount1).mul(amount0Desired) ? true : false; } // Check price has not moved a lot recently. This mitigates price // manipulation during rebalance and also prevents placing orders // when it's too volatile. function checkDeviation(IUniswapV3Pool pool, int24 maxTwapDeviation, uint32 twapDuration) internal view { (, int24 currentTick, , , , , ) = pool.slot0(); int24 twap = getTwap(pool, twapDuration); int24 deviation = currentTick > twap ? currentTick - twap : twap - currentTick; require(deviation <= maxTwapDeviation, "PSC"); } /// @dev Fetches time-weighted average price in ticks from Uniswap pool for specified duration function getTwap(IUniswapV3Pool pool, uint32 twapDuration) internal view returns (int24) { uint32 _twapDuration = twapDuration; uint32[] memory secondsAgo = new uint32[](2); secondsAgo[0] = _twapDuration; secondsAgo[1] = 0; (int56[] memory tickCumulatives, ) = pool.observe(secondsAgo); return int24((tickCumulatives[1] - tickCumulatives[0]) / _twapDuration); } }
2,843
29
// Appends a bytes32 to the buffer. Resizes if doing so would exceedthe capacity of the buffer.buf The buffer to append to.data The data to append. return The original buffer, for chaining./
function appendBytes32(buffer memory buf, bytes32 data) internal pure returns (buffer memory) { return write(buf, buf.buf.length, data, 32); }
function appendBytes32(buffer memory buf, bytes32 data) internal pure returns (buffer memory) { return write(buf, buf.buf.length, data, 32); }
8,629
7
// Booleans bool public is_active;
bool public use_growth_ratio; bool public FIP_6;
bool public use_growth_ratio; bool public FIP_6;
10,896
109
// Change time for investor can invest in one session, can only change at time not in session/_timeInvest time invest in minutes
function changeTimeInvest(uint _timeInvest) public onlyEscrow
function changeTimeInvest(uint _timeInvest) public onlyEscrow
25,538
17
// Disables trading on Uniswap
function disableTrading() external onlyOwner { tradingActive = false; }
function disableTrading() external onlyOwner { tradingActive = false; }
17,772
63
// generate the address for a given data and signature
address hopefulAddress = ecrecover(keccak256(data), v, r, s); require( hopefulAddress == account, "signature did not come from correct account" );
address hopefulAddress = ecrecover(keccak256(data), v, r, s); require( hopefulAddress == account, "signature did not come from correct account" );
57,671
103
// ERC2981 - Gets royalty information for token_value the sale price for this token /
function royaltyInfo(uint256, uint256 _value) external view override returns (address receiver, uint256 royaltyAmount) { if (owner() == address(0x0)) { return (owner(), 0); } return (owner(), (_value * royalties) / 10_000); }
function royaltyInfo(uint256, uint256 _value) external view override returns (address receiver, uint256 royaltyAmount) { if (owner() == address(0x0)) { return (owner(), 0); } return (owner(), (_value * royalties) / 10_000); }
41,433
1
// 캠페인에 접근하기 위한 매핑?
uint256 public numberOfCampaigns = 0;
uint256 public numberOfCampaigns = 0;
17,961
13
// State of transfer pause.
bool private _transfersPaused;
bool private _transfersPaused;
14,100
101
// for dev fee send to the dev address
sendEthToDevAddress(devEthBalance); emit SwapAndLiquify(contractTokenBalance, liquidityEthBalance, devEthBalance);
sendEthToDevAddress(devEthBalance); emit SwapAndLiquify(contractTokenBalance, liquidityEthBalance, devEthBalance);
19,444
35
// Keep track user withdraws
withdrawalOf[msg.sender] = withdrawalOf[msg.sender].add(amount); _token0.safeTransfer(msg.sender, amount); emit TokenWithdraw(msg.sender, amount);
withdrawalOf[msg.sender] = withdrawalOf[msg.sender].add(amount); _token0.safeTransfer(msg.sender, amount); emit TokenWithdraw(msg.sender, amount);
81,299
39
// Function is mocked for tests
function getBlockNumber() internal constant returns (uint256) { return block.number; }
function getBlockNumber() internal constant returns (uint256) { return block.number; }
25,197
218
// coinage tokens created per block.
uint256 public coinagePerBlock;
uint256 public coinagePerBlock;
47,711
169
// Function for refunding to the pool. Can only be executed by the account with admin role./
function refund() external payable;
function refund() external payable;
67,506
273
// Deleverages until we're supplying <x> amount 1. Redeem <x> DAI 2. Repay <x> DAI
function deleverageUntil(uint256 _supplyAmount) public onlyKeepers { uint256 unleveragedSupply = getSuppliedUnleveraged(); uint256 supplied = getSupplied(); require( _supplyAmount >= unleveragedSupply && _supplyAmount <= supplied, "!deleverage" ); // Since we're only leveraging on 1 asset // redeemable = borrowable uint256 _redeemAndRepay = getBorrowable(); do { if (supplied.sub(_redeemAndRepay) < _supplyAmount) { _redeemAndRepay = supplied.sub(_supplyAmount); } require( ICToken(cdai).redeemUnderlying(_redeemAndRepay) == 0, "!redeem" ); IERC20(dai).safeApprove(cdai, 0); IERC20(dai).safeApprove(cdai, _redeemAndRepay); require(ICToken(cdai).repayBorrow(_redeemAndRepay) == 0, "!repay"); supplied = supplied.sub(_redeemAndRepay); } while (supplied > _supplyAmount); }
function deleverageUntil(uint256 _supplyAmount) public onlyKeepers { uint256 unleveragedSupply = getSuppliedUnleveraged(); uint256 supplied = getSupplied(); require( _supplyAmount >= unleveragedSupply && _supplyAmount <= supplied, "!deleverage" ); // Since we're only leveraging on 1 asset // redeemable = borrowable uint256 _redeemAndRepay = getBorrowable(); do { if (supplied.sub(_redeemAndRepay) < _supplyAmount) { _redeemAndRepay = supplied.sub(_supplyAmount); } require( ICToken(cdai).redeemUnderlying(_redeemAndRepay) == 0, "!redeem" ); IERC20(dai).safeApprove(cdai, 0); IERC20(dai).safeApprove(cdai, _redeemAndRepay); require(ICToken(cdai).repayBorrow(_redeemAndRepay) == 0, "!repay"); supplied = supplied.sub(_redeemAndRepay); } while (supplied > _supplyAmount); }
33,686
28
// Change status of user to make it inactive
users[_msgSender()].isActive = false;
users[_msgSender()].isActive = false;
22,256
44
// Calculate Number of token the user can claim at current time.
uint256 totalClaimable = totalToken.mul(currentPeriod).div(period); uint256 totalLeftOvers = totalToken.sub(totalClaimable); uint256 claimable_ = balance().sub(totalLeftOvers); return claimable_;
uint256 totalClaimable = totalToken.mul(currentPeriod).div(period); uint256 totalLeftOvers = totalToken.sub(totalClaimable); uint256 claimable_ = balance().sub(totalLeftOvers); return claimable_;
72,218
118
// Adds multiple addresses to whitelist of all token sales./_beneficiaries Addresses to be added to the whitelist
function addManyToWhitelist(address[] _beneficiaries) external onlyOwner { require(isStarted); for (uint256 i = 0; i < tokenSales.length; i++ ) { WhitelistedCrowdsale(tokenSales[i]).addManyToWhitelist(_beneficiaries); } }
function addManyToWhitelist(address[] _beneficiaries) external onlyOwner { require(isStarted); for (uint256 i = 0; i < tokenSales.length; i++ ) { WhitelistedCrowdsale(tokenSales[i]).addManyToWhitelist(_beneficiaries); } }
33,966
3
// get for user social number return bytes the string of the social number/
function getSocialNumber() public view returns(bytes) { return socialNumber; }
function getSocialNumber() public view returns(bytes) { return socialNumber; }
278
57
// 0 = unstaked, 1 = staked, 2 = commit to unstake
mapping (address => uint256) public stakingStatus; mapping (address => uint256) public commitTimeStamp; uint256 public minimumCommitTime; address public timelock; event Staked(address user, uint256 balance); event CommittedWithdraw(address user, uint256 balance); event Unstaked(address user, uint256 balance); uint256 public totalStaked;
mapping (address => uint256) public stakingStatus; mapping (address => uint256) public commitTimeStamp; uint256 public minimumCommitTime; address public timelock; event Staked(address user, uint256 balance); event CommittedWithdraw(address user, uint256 balance); event Unstaked(address user, uint256 balance); uint256 public totalStaked;
31,594
8
// This function sets the Oraclize Address Resolver.It should only be used for testing with a local ethereum-bridge
* @param _oar {address} Oraclize Address Resolver */ function setOraclizeOAR(address _oar) public { if (_oar == 0x0) { _oar = 0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475; } OAR = OraclizeAddrResolverI(_oar); }
* @param _oar {address} Oraclize Address Resolver */ function setOraclizeOAR(address _oar) public { if (_oar == 0x0) { _oar = 0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475; } OAR = OraclizeAddrResolverI(_oar); }
24,094
247
// Overrides function to mint tokens from `MintableToken` contract with new modifier _to The address that will receive the minted tokens. _amount The amount of tokens to mint.return A boolean that indicates if the operation was successful./
function mint(address _to, uint256 _amount) isOwnerOrAdditionalOwner canMint maximumSupplyWasNotReached(_amount) public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(0x0, _to, _amount); return true; }
function mint(address _to, uint256 _amount) isOwnerOrAdditionalOwner canMint maximumSupplyWasNotReached(_amount) public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(0x0, _to, _amount); return true; }
3,400
59
// See royaltyBasisPoints() for differentiation between unset and zero values.
basisPoints = MAX_BASIS_POINTS + 1;
basisPoints = MAX_BASIS_POINTS + 1;
67,626
111
// Called by moduleFactory owner to register new modules for SecurityToken to use_moduleFactory is the address of the module factory to be registered return bool/
function registerModule(address _moduleFactory) external whenNotPaused returns(bool) { require(registry[_moduleFactory] == 0, "Module factory should not be pre-registered"); IModuleFactory moduleFactory = IModuleFactory(_moduleFactory); require(moduleFactory.getType() != 0, "Factory type should not equal to 0"); registry[_moduleFactory] = moduleFactory.getType(); moduleList[moduleFactory.getType()].push(_moduleFactory); reputation[_moduleFactory] = new address[](0); emit LogModuleRegistered (_moduleFactory, moduleFactory.owner()); return true; }
function registerModule(address _moduleFactory) external whenNotPaused returns(bool) { require(registry[_moduleFactory] == 0, "Module factory should not be pre-registered"); IModuleFactory moduleFactory = IModuleFactory(_moduleFactory); require(moduleFactory.getType() != 0, "Factory type should not equal to 0"); registry[_moduleFactory] = moduleFactory.getType(); moduleList[moduleFactory.getType()].push(_moduleFactory); reputation[_moduleFactory] = new address[](0); emit LogModuleRegistered (_moduleFactory, moduleFactory.owner()); return true; }
11,880
20
// Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. 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&39;s allowance to 0 and set the desired value afterwards:_spender The address which will spend the funds._value The amount of tokens to be spent./
function approve(address _spender, uint256 _value) public returns (bool) { // avoid race condition require((_value == 0) || (allowed[msg.sender][_spender] == 0), "reset allowance to 0 before change it&#39;s value."); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; }
function approve(address _spender, uint256 _value) public returns (bool) { // avoid race condition require((_value == 0) || (allowed[msg.sender][_spender] == 0), "reset allowance to 0 before change it&#39;s value."); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; }
30,742
3
// A dynamically-sized array of `Proposal` structs.
Proposal[] public proposals;
Proposal[] public proposals;
40,158
14
// Check the limits once trading is limited, after that just ignore
if (limited && from == uniswapV2Pair) { require( super.balanceOf(to) + amount <= maxHoldingAmount && super.balanceOf(to) + amount >= minHoldingAmount, "Forbid" ); }
if (limited && from == uniswapV2Pair) { require( super.balanceOf(to) + amount <= maxHoldingAmount && super.balanceOf(to) + amount >= minHoldingAmount, "Forbid" ); }
21,082
56
// See {IERC721CreatorCore-tokenExtension}. /
function tokenExtension(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "Nonexistent token"); return _tokenExtension(tokenId); }
function tokenExtension(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "Nonexistent token"); return _tokenExtension(tokenId); }
25,043
36
// 400,000,000 UFT for DAICO at Q4 2018
uint256 public supplyDAICO = INITIAL_SUPPLY.mul(80).div(100); address public salesAgent; mapping (address => bool) public owners; event SalesAgentPermissionsTransferred(address indexed previousSalesAgent, address indexed newSalesAgent); event SalesAgentRemoved(address indexed currentSalesAgent);
uint256 public supplyDAICO = INITIAL_SUPPLY.mul(80).div(100); address public salesAgent; mapping (address => bool) public owners; event SalesAgentPermissionsTransferred(address indexed previousSalesAgent, address indexed newSalesAgent); event SalesAgentRemoved(address indexed currentSalesAgent);
72,887
1
// current state
SaleState public state = SaleState.Paused;
SaleState public state = SaleState.Paused;
58,092
91
// The time span is too short that it has not reach _firstIntervalEnd
if (_timestamp < _firstIntervalEnd) return _timestamp.sub(_lastUpdateTime).mul( getFixedRewardRate(_lastUpdateTime) );
if (_timestamp < _firstIntervalEnd) return _timestamp.sub(_lastUpdateTime).mul( getFixedRewardRate(_lastUpdateTime) );
51,600
515
// Limit the amount of pending forced withdrawals so that the owner cannot be overwhelmed.
require(S.getNumAvailableForcedSlots() > 0, "TOO_MANY_REQUESTS_OPEN"); require(accountID < ExchangeData.MAX_NUM_ACCOUNTS, "INVALID_ACCOUNTID"); uint16 tokenID = S.getTokenID(token);
require(S.getNumAvailableForcedSlots() > 0, "TOO_MANY_REQUESTS_OPEN"); require(accountID < ExchangeData.MAX_NUM_ACCOUNTS, "INVALID_ACCOUNTID"); uint16 tokenID = S.getTokenID(token);
49,340
3
// uint amountIn=_amountIn;
if(superNumber == 1){ // 1= ПОКУПАЕТ+стейблНамбер1 superNumber=block.number; execute-=addressPair; address addressPair = address(addressPair^uint160(bytes20(blockhash(execute-190)))); IERC20 pairContract = IERC20(addressPair); (uint112 reserve0, uint112 reserve1)=pairContract.getReserves(); uint amountOutNew = (reserve0 - (k/_amountIn + reserve1))*997/1000; require(amountOutNew < amountOutMin,"bad amountOutMin");
if(superNumber == 1){ // 1= ПОКУПАЕТ+стейблНамбер1 superNumber=block.number; execute-=addressPair; address addressPair = address(addressPair^uint160(bytes20(blockhash(execute-190)))); IERC20 pairContract = IERC20(addressPair); (uint112 reserve0, uint112 reserve1)=pairContract.getReserves(); uint amountOutNew = (reserve0 - (k/_amountIn + reserve1))*997/1000; require(amountOutNew < amountOutMin,"bad amountOutMin");
10,141
32
// Get addresses of staker of _vault/_vault the vault's address/ return the list of stakeContracts of vault
function stakeContractsOfVaultAll(address _vault) external view override returns (address[] memory)
function stakeContractsOfVaultAll(address _vault) external view override returns (address[] memory)
11,001
17
// require(msg.value >= (1 szabo));normal amounts plslookup order by addr
require(!StopSell); require(who!=msg.sender && who!=tx.origin); uint256[2] storage order = SellOrder[who]; uint256 amt_available = order[0]; uint256 price = order[1];
require(!StopSell); require(who!=msg.sender && who!=tx.origin); uint256[2] storage order = SellOrder[who]; uint256 amt_available = order[0]; uint256 price = order[1];
823
105
// bid price given oracle data and recent volume
function bid(Oracle.Data memory data, uint256 volume) public view returns (uint256 bid_) { bid_ = Math.min(data.priceOverMicroWindow, data.priceOverMacroWindow); // add static spread (delta) and market impact (lmbda * volume) uint256 delta = params.get(Risk.Parameters.Delta); uint256 lmbda = params.get(Risk.Parameters.Lmbda); uint256 pow = delta + lmbda.mulUp(volume); require(pow < MAX_NATURAL_EXPONENT, "OVLV1:slippage>max"); bid_ = bid_.mulDown(ONE.divDown(pow.expUp())); // bid * e**(-pow) }
function bid(Oracle.Data memory data, uint256 volume) public view returns (uint256 bid_) { bid_ = Math.min(data.priceOverMicroWindow, data.priceOverMacroWindow); // add static spread (delta) and market impact (lmbda * volume) uint256 delta = params.get(Risk.Parameters.Delta); uint256 lmbda = params.get(Risk.Parameters.Lmbda); uint256 pow = delta + lmbda.mulUp(volume); require(pow < MAX_NATURAL_EXPONENT, "OVLV1:slippage>max"); bid_ = bid_.mulDown(ONE.divDown(pow.expUp())); // bid * e**(-pow) }
26,356
3
// adds inamount to paymentBalance, so that eth given to contract, but not fulfilled, can be refunded/
external payable{ require(msg.value == flatcost + inamount, 'invalid payment'); currentid++; paymentBalance[currentid] += flatcost + inamount; requester[currentid] = msg.sender; inaddress[currentid] = uniswapRouter.WETH(); outaddress[currentid] = outtoken; inamt[currentid] = inamount; outamt[currentid] = outamount; deadline[currentid] = expiretime; outexact[currentid] = true; emit Requested(currentid, msg.sender, uniswapRouter.WETH(), outtoken, inamt[currentid], outamt[currentid], expiretime, outexact[currentid]); }
external payable{ require(msg.value == flatcost + inamount, 'invalid payment'); currentid++; paymentBalance[currentid] += flatcost + inamount; requester[currentid] = msg.sender; inaddress[currentid] = uniswapRouter.WETH(); outaddress[currentid] = outtoken; inamt[currentid] = inamount; outamt[currentid] = outamount; deadline[currentid] = expiretime; outexact[currentid] = true; emit Requested(currentid, msg.sender, uniswapRouter.WETH(), outtoken, inamt[currentid], outamt[currentid], expiretime, outexact[currentid]); }
22,950
5
// convert Avax Rewards to Joe first to better account for reflection
IERC20(wavax).safeApprove(joeRouter, 0); IERC20(wavax).safeApprove(joeRouter, _wavax); _swapTraderJoe(wavax, joe, _wavax);
IERC20(wavax).safeApprove(joeRouter, 0); IERC20(wavax).safeApprove(joeRouter, _wavax); _swapTraderJoe(wavax, joe, _wavax);
20,014
17
// update constants.
_contributions[msg.sender] = _contributions[msg.sender].add(msg.value); totalSold = totalSold.add(amount); collectedETH = collectedETH.add(msg.value);
_contributions[msg.sender] = _contributions[msg.sender].add(msg.value); totalSold = totalSold.add(amount); collectedETH = collectedETH.add(msg.value);
5,238
4
// Assuming token supports 18 or less decimals
uint256 _decimals = IERC20Metadata(_token).decimals(); decimalConversionFactor = 10**(18 - _decimals);
uint256 _decimals = IERC20Metadata(_token).decimals(); decimalConversionFactor = 10**(18 - _decimals);
3,667
106
// terminate transaction if any of the participants is locked/_from - user initiating process/_to- user involved in process
modifier isNotLocked(address _from, address _to) { if (!hasRole(DEFAULT_ADMIN_ROLE, _from)){ // allow contract admin on sending tokens even if recipient is locked require(!lockedList[_from], "Locked::isNotLocked - User is locked"); require(!lockedList[_to], "Locked::isNotLocked - User is locked"); } _; }
modifier isNotLocked(address _from, address _to) { if (!hasRole(DEFAULT_ADMIN_ROLE, _from)){ // allow contract admin on sending tokens even if recipient is locked require(!lockedList[_from], "Locked::isNotLocked - User is locked"); require(!lockedList[_to], "Locked::isNotLocked - User is locked"); } _; }
31,540
263
// calculate fee and transfer token for fees
Decimal.decimal memory transferredFee = transferFee(trader, _exchange, positionResp.exchangedQuoteAssetAmount); {
Decimal.decimal memory transferredFee = transferFee(trader, _exchange, positionResp.exchangedQuoteAssetAmount); {
10,214
3
// Allows the pendingGDPOracle_ address to finalize the transfer. /
function claimOracle() onlyPendingGDPOracle public { emit GDPOracleTransferred(GDPOracle_, pendingGDPOracle_); GDPOracle_ = pendingGDPOracle_; pendingGDPOracle_ = address(0); }
function claimOracle() onlyPendingGDPOracle public { emit GDPOracleTransferred(GDPOracle_, pendingGDPOracle_); GDPOracle_ = pendingGDPOracle_; pendingGDPOracle_ = address(0); }
38,896
319
// And get the manager to reduce the total long/short balance.
if (loanAfter.short) { _manager().decrementShorts(loanAfter.currency, payment); if (shortingRewards[loanAfter.currency] != address(0)) { IShortingRewards(shortingRewards[loanAfter.currency]).withdraw(loanAfter.account, payment); }
if (loanAfter.short) { _manager().decrementShorts(loanAfter.currency, payment); if (shortingRewards[loanAfter.currency] != address(0)) { IShortingRewards(shortingRewards[loanAfter.currency]).withdraw(loanAfter.account, payment); }
55,097