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
2
// The ERC20Extension is a contract to give erc20 functionalityto the internal token units held by DAO members inside the DAO itself. /
interface IERC20TransferStrategy { enum AclFlag { REGISTER_TRANSFER } enum ApprovalType { NONE, STANDARD, SPECIAL } function evaluateTransfer( DaoRegistry dao, address tokenAddr, address from, address to, uint256 amount, address caller ) external view returns (ApprovalType, uint256); }
interface IERC20TransferStrategy { enum AclFlag { REGISTER_TRANSFER } enum ApprovalType { NONE, STANDARD, SPECIAL } function evaluateTransfer( DaoRegistry dao, address tokenAddr, address from, address to, uint256 amount, address caller ) external view returns (ApprovalType, uint256); }
15,756
495
// Calculate PLY accrued by a borrower and possibly transfer it to them Borrowers will not begin to accrue until after the first interaction with the protocol. rewardType0: Ply, 1: Aurora auToken The market in which the borrower is interacting borrower The address of the borrower to distribute PLY to /
function distributeBorrowerReward(uint8 rewardType, address auToken, address borrower, Exp marketBorrowIndex, uint256 borrowBalanceStoredOfBorrower) internal virtual{ checkRewardType(rewardType); RewardMarketState storage borrowState = rewardBorrowState [rewardType][auToken]; Double borrowIndex = Double.wrap(borrowState.index); Double borrowerIndex = Double.wrap(rewardBorrowerIndex[rewardType][auToken][borrower]); rewardBorrowerIndex[rewardType][auToken][borrower] = Double.unwrap(borrowIndex); if (Double.unwrap(borrowerIndex) == 0 && Double.unwrap(borrowIndex) > 0) { borrowerIndex = Double.wrap(initialIndexConstant); } Double deltaIndex = sub_(borrowIndex, borrowerIndex); uint borrowerAmount = div_(borrowBalanceStoredOfBorrower, marketBorrowIndex); uint borrowerDelta = mul_(borrowerAmount, deltaIndex); uint borrowerAccrued = rewardAccrued[rewardType][borrower] + borrowerDelta; rewardAccrued[rewardType][borrower] = borrowerAccrued; emit DistributedBorrowerReward(rewardType, AuToken(auToken), borrower, borrowerDelta, Double.unwrap(borrowIndex)); }
function distributeBorrowerReward(uint8 rewardType, address auToken, address borrower, Exp marketBorrowIndex, uint256 borrowBalanceStoredOfBorrower) internal virtual{ checkRewardType(rewardType); RewardMarketState storage borrowState = rewardBorrowState [rewardType][auToken]; Double borrowIndex = Double.wrap(borrowState.index); Double borrowerIndex = Double.wrap(rewardBorrowerIndex[rewardType][auToken][borrower]); rewardBorrowerIndex[rewardType][auToken][borrower] = Double.unwrap(borrowIndex); if (Double.unwrap(borrowerIndex) == 0 && Double.unwrap(borrowIndex) > 0) { borrowerIndex = Double.wrap(initialIndexConstant); } Double deltaIndex = sub_(borrowIndex, borrowerIndex); uint borrowerAmount = div_(borrowBalanceStoredOfBorrower, marketBorrowIndex); uint borrowerDelta = mul_(borrowerAmount, deltaIndex); uint borrowerAccrued = rewardAccrued[rewardType][borrower] + borrowerDelta; rewardAccrued[rewardType][borrower] = borrowerAccrued; emit DistributedBorrowerReward(rewardType, AuToken(auToken), borrower, borrowerDelta, Double.unwrap(borrowIndex)); }
35,284
60
// Adds another token to the accepted coins for printingCalling conditions: - Address of the contract to be added- Only can be added by founding fathers/
function addAcceptedStableCoin(address _contract, address _oracleAddress) isOnline public returns (bool) { require( hasRole(FOUNDING_FATHER, msg.sender), "Caller is not a Founding Father" ); _acceptedStableCoins[_contract] = true; _contract_address_to_oracle[_contract] = _oracleAddress; return _acceptedStableCoins[_contract]; }
function addAcceptedStableCoin(address _contract, address _oracleAddress) isOnline public returns (bool) { require( hasRole(FOUNDING_FATHER, msg.sender), "Caller is not a Founding Father" ); _acceptedStableCoins[_contract] = true; _contract_address_to_oracle[_contract] = _oracleAddress; return _acceptedStableCoins[_contract]; }
31,853
3
// gets the unit of token used in price calculation _token token addressreturn unit of token /
function getTotalComponentRealUnits( address _token ) external view returns (uint256);
function getTotalComponentRealUnits( address _token ) external view returns (uint256);
38,318
233
// if the auction ended in the past, update endId
endId = checkedAuctions * auctionsCatsPerAuction + auctionsCatsPerAuction;
endId = checkedAuctions * auctionsCatsPerAuction + auctionsCatsPerAuction;
11,017
87
// The time when the first disputed was initiated for this bond
uint256 firstDisputeAt;
uint256 firstDisputeAt;
35,113
17
// Deposit ETH to Compound ETH Lending Pool and mint cETH.
uint256 obtainedEthAmount = address(this).balance;
uint256 obtainedEthAmount = address(this).balance;
41,765
97
// Max TX amount cannot be less than 0.1%
require(_maxTxAmount > ((totalSupply() * 1) / 1000), "Max TX is too low");
require(_maxTxAmount > ((totalSupply() * 1) / 1000), "Max TX is too low");
25,887
7
// Set the deposit data/_ipfsHash the deposit data
function setIpfsHashForEncryptedValidatorKey( string calldata _ipfsHash
function setIpfsHashForEncryptedValidatorKey( string calldata _ipfsHash
10,926
3
// 补充库存 refill the stock of the bucket ledgerType the type of the ledger /
function _refillStock(uint256 ledgerType) internal { BucketStock storage bucketStock = ledgerBucketStock[ledgerType]; bucketStock.currentBucketStock = uint16(bucketStock.stockSize); }
function _refillStock(uint256 ledgerType) internal { BucketStock storage bucketStock = ledgerBucketStock[ledgerType]; bucketStock.currentBucketStock = uint16(bucketStock.stockSize); }
6,235
16
// Event which is triggered whenever an owner approves a new allowance for a spender.
event Approval( address indexed _owner, address indexed _spender, uint _value );
event Approval( address indexed _owner, address indexed _spender, uint _value );
10,367
316
// Emitted when a Safe is gibbed./user The user who gibbed the Safe./to The recipient of the impounded collateral./assetAmount The amount of underling tokens impounded.
event SafeGibbed(address indexed user, address indexed to, uint256 assetAmount);
event SafeGibbed(address indexed user, address indexed to, uint256 assetAmount);
11,072
195
// caller rewards
uint256 _callerReward = 0; if (rewardLiquidityLockCaller) {
uint256 _callerReward = 0; if (rewardLiquidityLockCaller) {
36,934
2
// base mint price
uint256 public preMintPrice = 0.02 ether; uint256 public pubMintPrice = 0.06 ether; uint256 public MAX_TRADER_MINT = 500; uint256 public osMintCounter; uint256 public traderMintCounter; uint256 public pubMintCounter; mapping(address => bool) public osMintLog; mapping(address => bool) public traderMintLog;
uint256 public preMintPrice = 0.02 ether; uint256 public pubMintPrice = 0.06 ether; uint256 public MAX_TRADER_MINT = 500; uint256 public osMintCounter; uint256 public traderMintCounter; uint256 public pubMintCounter; mapping(address => bool) public osMintLog; mapping(address => bool) public traderMintLog;
8,162
71
// Users can withdraw their accumulated dividends/
function withdrawFunds() public { uint256 funds = userFunds[msg.sender]; require(funds > 0); userFunds[msg.sender] = 0; msg.sender.transfer(funds); WithdrewFunds(msg.sender); }
function withdrawFunds() public { uint256 funds = userFunds[msg.sender]; require(funds > 0); userFunds[msg.sender] = 0; msg.sender.transfer(funds); WithdrewFunds(msg.sender); }
78,379
217
// Mapping variables ------------------------------------------------------------------------
mapping(address => bool) public presalerList; mapping(address => uint256) public presalerListPurchases; mapping(address => uint256) public publicListPurchases;
mapping(address => bool) public presalerList; mapping(address => uint256) public presalerListPurchases; mapping(address => uint256) public publicListPurchases;
81,392
5
// Let beneficiary withdraw money, if the proposal is successfulWhen the account asks for money, the wallet gives all that is allowed.We create a sandbox where stores a snapshot of ready-to-withdraw money./
function withdrawMoney(address _adr) public onlyOwner returns(bool) { require(allowance[_adr] > 0); uint256 operatingAmount = allowance[_adr]; withdrawingAllowance[_adr] = operatingAmount; allowance[_adr] = allowance[_adr].sub(operatingAmount); if (_adr.send(withdrawingAllowance[_adr]) == true) { totalAllowance = totalAllowance.sub(withdrawingAllowance[_adr]); totalBalance = totalBalance.sub(withdrawingAllowance[_adr]); withdrawingAllowance[_adr] = 0; emit WithdrawMoney(_adr, totalAllowance, block.timestamp); return true; } else { allowance[_adr] = allowance[_adr].add(withdrawingAllowance[_adr]); withdrawingAllowance[_adr] = 0; return false; } }
function withdrawMoney(address _adr) public onlyOwner returns(bool) { require(allowance[_adr] > 0); uint256 operatingAmount = allowance[_adr]; withdrawingAllowance[_adr] = operatingAmount; allowance[_adr] = allowance[_adr].sub(operatingAmount); if (_adr.send(withdrawingAllowance[_adr]) == true) { totalAllowance = totalAllowance.sub(withdrawingAllowance[_adr]); totalBalance = totalBalance.sub(withdrawingAllowance[_adr]); withdrawingAllowance[_adr] = 0; emit WithdrawMoney(_adr, totalAllowance, block.timestamp); return true; } else { allowance[_adr] = allowance[_adr].add(withdrawingAllowance[_adr]); withdrawingAllowance[_adr] = 0; return false; } }
16,197
36
// take cards until value reaches 17 or more.
uint8 i; while (dealerValue < 17) { card = cards[numCards + i + 2] % 13; dealerValue += cardValues[card]; if (card == 0) numAces++; if (dealerValue > 21 && numAces > 0) { dealerValue -= 10; numAces--; }
uint8 i; while (dealerValue < 17) { card = cards[numCards + i + 2] % 13; dealerValue += cardValues[card]; if (card == 0) numAces++; if (dealerValue > 21 && numAces > 0) { dealerValue -= 10; numAces--; }
43,521
39
// Set address of owner.
_owner = owner;
_owner = owner;
9,990
16
// Get the broker DNA -> layers
uint256 dna = brokerDna(tokenId); require(dna > 0, "Broker DNA missing for token"); uint256 layerCount = (dna >> BROKER_LAYER_COUNT_DNA_POSITION) & BROKER_LAYER_COUNT_DNA_BITMASK; uint256[] memory layers = new uint256[](layerCount); for (uint256 layerIdx; layerIdx < layerCount; layerIdx++) { layers[layerIdx] = (dna >> (BROKER_LAYERS_DNA_SIZE * layerIdx + BROKER_LAYERS_DNA_POSITION)) & BROKER_LAYER_DNA_BITMASK; }
uint256 dna = brokerDna(tokenId); require(dna > 0, "Broker DNA missing for token"); uint256 layerCount = (dna >> BROKER_LAYER_COUNT_DNA_POSITION) & BROKER_LAYER_COUNT_DNA_BITMASK; uint256[] memory layers = new uint256[](layerCount); for (uint256 layerIdx; layerIdx < layerCount; layerIdx++) { layers[layerIdx] = (dna >> (BROKER_LAYERS_DNA_SIZE * layerIdx + BROKER_LAYERS_DNA_POSITION)) & BROKER_LAYER_DNA_BITMASK; }
44,424
39
// In this configuration, where reward address is set: that reward account is also a bailout account, the terminology is being changed to bondAccount
address bondAccount = gov.getConfigAsAddress(_host, this, _REWARD_ADDRESS_CONFIG_KEY);
address bondAccount = gov.getConfigAsAddress(_host, this, _REWARD_ADDRESS_CONFIG_KEY);
24,484
41
// emit event
emit NewEndorsement(id, msg.sender, _certificateTemplateId);
emit NewEndorsement(id, msg.sender, _certificateTemplateId);
14,436
210
// Deposit token into the accumulator/_token token to deposit/_amount amount to deposit
function depositToken(address _token, uint256 _amount) external { require(_amount > 0, "set an amount > 0"); IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount); emit TokenDeposited(_token, _amount); }
function depositToken(address _token, uint256 _amount) external { require(_amount > 0, "set an amount > 0"); IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount); emit TokenDeposited(_token, _amount); }
23,945
61
// ============ Internal Methods ============
function _transfer( address from, address to, uint256 tokenId
function _transfer( address from, address to, uint256 tokenId
39,069
17
// Remove the `RelayHub` from a list of authorized by this Relay Manager. relayManager The address of a Relay Manager. relayHub The address of a `RelayHub` to be unauthorized. /
function unauthorizeHubByOwner(address relayManager, address relayHub) external;
function unauthorizeHubByOwner(address relayManager, address relayHub) external;
7,236
35
// Convert NFTs from ERC20 to ERC721
address wrapperContractAddress = wrappedNFTFactory.getWrapperContractForNFTContractAddress(_nftContractAddresses[0]); WrappedNFT(wrapperContractAddress).transferFrom(msg.sender, address(this), _nftIds.length.mul(10**18)); _burnTokensAndWithdrawNfts(wrapperContractAddress, _nftIds, _destinationAddresses); emit UnwrapNFTs(_nftIds.length, _nftContractAddresses[0]);
address wrapperContractAddress = wrappedNFTFactory.getWrapperContractForNFTContractAddress(_nftContractAddresses[0]); WrappedNFT(wrapperContractAddress).transferFrom(msg.sender, address(this), _nftIds.length.mul(10**18)); _burnTokensAndWithdrawNfts(wrapperContractAddress, _nftIds, _destinationAddresses); emit UnwrapNFTs(_nftIds.length, _nftContractAddresses[0]);
13,272
7
// which token are we depositing? How much?
require(Token(_token).transferFrom(msg.sender, address(this), _amount));
require(Token(_token).transferFrom(msg.sender, address(this), _amount));
22,806
6
// How many mints within the current minting period
mapping(address => MintingPeriod) mintingPeriodConfig;
mapping(address => MintingPeriod) mintingPeriodConfig;
7,825
185
// Prevents execution if the caller isn't the tranche
modifier onlyMintAuthority() { require( msg.sender == address(tranche), "caller is not an authorized minter" ); _; }
modifier onlyMintAuthority() { require( msg.sender == address(tranche), "caller is not an authorized minter" ); _; }
5,186
148
// Update the given pool's CORIS allocation point and deposit fee. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner poolExists(_pid) { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; }
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner poolExists(_pid) { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; }
26,834
9
// Enumerable Additions
uint oldIndex = tokenTokenIndexes[_tokenId];
uint oldIndex = tokenTokenIndexes[_tokenId];
21,015
31
// Amount of wei raised (token)
uint256 public tokenRaised;
uint256 public tokenRaised;
31,821
375
// certificateId {uint} - The id of the certificate expiration {uint} - The expiration time of the signature (in seconds) purpose {bytes32} - The sha-256 hash of the purpose data /
function signCertificateAsPeer(uint certificateId, uint expiration, bytes32 purpose) public { SignLib.signCertificateAsPeer(cd, certificateId, expiration, purpose); }
function signCertificateAsPeer(uint certificateId, uint expiration, bytes32 purpose) public { SignLib.signCertificateAsPeer(cd, certificateId, expiration, purpose); }
46,373
57
// Queries totalSupply as of a defined checkpoint _checkpointId Checkpoint ID to query as of /
function totalSupplyAt(uint256 _checkpointId) public view returns(uint256);
function totalSupplyAt(uint256 _checkpointId) public view returns(uint256);
19,841
39
// Shh - currently unused
minter; mintAmount; if (!markets[mToken].isListed) { return uint(Error.MARKET_NOT_LISTED); }
minter; mintAmount; if (!markets[mToken].isListed) { return uint(Error.MARKET_NOT_LISTED); }
15,987
155
// read again in case of updates
_balanceOfWant = balanceOfWant();
_balanceOfWant = balanceOfWant();
33,263
67
// Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. _beneficiary Address performing the token purchase _weiAmount Value in wei involved in the purchase /
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { require(_beneficiary != address(0)); require(_weiAmount != 0); }
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { require(_beneficiary != address(0)); require(_weiAmount != 0); }
52,212
64
// Treasury contract.// Treasury for CCs deposits for particular fund with bmc-days calculations./ Accept BMC deposits from Continuous Contributors via oracle and/ calculates bmc-days metric for each CC&39;s role.
contract Treasury is OracleContractAdapter, ServiceAllowance, TreasuryEmitter { /* ERROR CODES */ uint constant PERCENT_PRECISION = 10000; uint constant TREASURY_ERROR_SCOPE = 108000; uint constant TREASURY_ERROR_TOKEN_NOT_SET_ALLOWANCE = TREASURY_ERROR_SCOPE + 1; using SafeMath for uint; struct LockedDeposits { uint counter; mapping(uint => uint) index2Date; mapping(uint => uint) date2deposit; } struct Period { uint transfersCount; uint totalBmcDays; uint bmcDaysPerDay; uint startDate; mapping(bytes32 => uint) user2bmcDays; mapping(bytes32 => uint) user2lastTransferIdx; mapping(bytes32 => uint) user2balance; mapping(uint => uint) transfer2date; } /* FIELDS */ address token; address profiterole; uint periodsCount; mapping(uint => Period) periods; mapping(uint => uint) periodDate2periodIdx; mapping(bytes32 => uint) user2lastPeriodParticipated; mapping(bytes32 => LockedDeposits) user2lockedDeposits; /* MODIFIERS */ /// @dev Only profiterole contract allowed to invoke guarded functions modifier onlyProfiterole { require(profiterole == msg.sender); _; } /* PUBLIC */ function Treasury(address _token) public { require(address(_token) != 0x0); token = _token; periodsCount = 1; } function init(address _profiterole) public onlyContractOwner returns (uint) { require(_profiterole != 0x0); profiterole = _profiterole; return OK; } /// @notice Do not accept Ether transfers function() payable public { revert(); } /* EXTERNAL */ /// @notice Deposits tokens on behalf of users /// Allowed only for oracle. /// /// @param _userKey aggregated user key (user ID + role ID) /// @param _value amount of tokens to deposit /// @param _feeAmount amount of tokens that will be taken from _value as fee /// @param _feeAddress destination address for fee transfer /// @param _lockupDate lock up date for deposit. Until that date the deposited value couldn&#39;t be withdrawn /// /// @return result code of an operation function deposit(bytes32 _userKey, uint _value, uint _feeAmount, address _feeAddress, uint _lockupDate) external onlyOracle returns (uint) { require(_userKey != bytes32(0)); require(_value != 0); require(_feeAmount < _value); ERC20 _token = ERC20(token); if (_token.allowance(msg.sender, address(this)) < _value) { return TREASURY_ERROR_TOKEN_NOT_SET_ALLOWANCE; } uint _depositedAmount = _value - _feeAmount; _makeDepositForPeriod(_userKey, _depositedAmount, _lockupDate); uint _periodsCount = periodsCount; user2lastPeriodParticipated[_userKey] = _periodsCount; delete periods[_periodsCount].startDate; if (!_token.transferFrom(msg.sender, address(this), _value)) { revert(); } if (!(_feeAddress == 0x0 || _feeAmount == 0 || _token.transfer(_feeAddress, _feeAmount))) { revert(); } TreasuryDeposited(_userKey, _depositedAmount, _lockupDate); return OK; } /// @notice Withdraws deposited tokens on behalf of users /// Allowed only for oracle /// /// @param _userKey aggregated user key (user ID + role ID) /// @param _value an amount of tokens that is requrested to withdraw /// @param _withdrawAddress address to withdraw; should not be 0x0 /// @param _feeAmount amount of tokens that will be taken from _value as fee /// @param _feeAddress destination address for fee transfer /// /// @return result of an operation function withdraw(bytes32 _userKey, uint _value, address _withdrawAddress, uint _feeAmount, address _feeAddress) external onlyOracle returns (uint) { require(_userKey != bytes32(0)); require(_value != 0); require(_feeAmount < _value); _makeWithdrawForPeriod(_userKey, _value); uint _periodsCount = periodsCount; user2lastPeriodParticipated[_userKey] = periodsCount; delete periods[_periodsCount].startDate; ERC20 _token = ERC20(token); if (!(_feeAddress == 0x0 || _feeAmount == 0 || _token.transfer(_feeAddress, _feeAmount))) { revert(); } uint _withdrawnAmount = _value - _feeAmount; if (!_token.transfer(_withdrawAddress, _withdrawnAmount)) { revert(); } TreasuryWithdrawn(_userKey, _withdrawnAmount); return OK; } /// @notice Gets shares (in percents) the user has on provided date /// /// @param _userKey aggregated user key (user ID + role ID) /// @param _date date where period ends /// /// @return percent from total amount of bmc-days the treasury has on this date. /// Use PERCENT_PRECISION to get right precision function getSharesPercentForPeriod(bytes32 _userKey, uint _date) public view returns (uint) { uint _periodIdx = periodDate2periodIdx[_date]; if (_date != 0 && _periodIdx == 0) { return 0; } if (_date == 0) { _date = now; _periodIdx = periodsCount; } uint _bmcDays = _getBmcDaysAmountForUser(_userKey, _date, _periodIdx); uint _totalBmcDeposit = _getTotalBmcDaysAmount(_date, _periodIdx); return _totalBmcDeposit != 0 ? _bmcDays * PERCENT_PRECISION / _totalBmcDeposit : 0; } /// @notice Gets user balance that is deposited /// @param _userKey aggregated user key (user ID + role ID) /// @return an amount of tokens deposited on behalf of user function getUserBalance(bytes32 _userKey) public view returns (uint) { uint _lastPeriodForUser = user2lastPeriodParticipated[_userKey]; if (_lastPeriodForUser == 0) { return 0; } if (_lastPeriodForUser <= periodsCount.sub(1)) { return periods[_lastPeriodForUser].user2balance[_userKey]; } return periods[periodsCount].user2balance[_userKey]; } /// @notice Gets amount of locked deposits for user /// @param _userKey aggregated user key (user ID + role ID) /// @return an amount of tokens locked function getLockedUserBalance(bytes32 _userKey) public returns (uint) { return _syncLockedDepositsAmount(_userKey); } /// @notice Gets list of locked up deposits with dates when they will be available to withdraw /// @param _userKey aggregated user key (user ID + role ID) /// @return { /// "_lockupDates": "list of lockup dates of deposits", /// "_deposits": "list of deposits" /// } function getLockedUserDeposits(bytes32 _userKey) public view returns (uint[] _lockupDates, uint[] _deposits) { LockedDeposits storage _lockedDeposits = user2lockedDeposits[_userKey]; uint _lockedDepositsCounter = _lockedDeposits.counter; _lockupDates = new uint[](_lockedDepositsCounter); _deposits = new uint[](_lockedDepositsCounter); uint _pointer = 0; for (uint _idx = 1; _idx < _lockedDepositsCounter; ++_idx) { uint _lockDate = _lockedDeposits.index2Date[_idx]; if (_lockDate > now) { _lockupDates[_pointer] = _lockDate; _deposits[_pointer] = _lockedDeposits.date2deposit[_lockDate]; ++_pointer; } } } /// @notice Gets total amount of bmc-day accumulated due provided date /// @param _date date where period ends /// @return an amount of bmc-days function getTotalBmcDaysAmount(uint _date) public view returns (uint) { return _getTotalBmcDaysAmount(_date, periodsCount); } /// @notice Makes a checkpoint to start counting a new period /// @dev Should be used only by Profiterole contract function addDistributionPeriod() public onlyProfiterole returns (uint) { uint _periodsCount = periodsCount; uint _nextPeriod = _periodsCount.add(1); periodDate2periodIdx[now] = _periodsCount; Period storage _previousPeriod = periods[_periodsCount]; uint _totalBmcDeposit = _getTotalBmcDaysAmount(now, _periodsCount); periods[_nextPeriod].startDate = now; periods[_nextPeriod].bmcDaysPerDay = _previousPeriod.bmcDaysPerDay; periods[_nextPeriod].totalBmcDays = _totalBmcDeposit; periodsCount = _nextPeriod; return OK; } function isTransferAllowed(address, address, address, address, uint) public view returns (bool) { return true; } /* INTERNAL */ function _makeDepositForPeriod(bytes32 _userKey, uint _value, uint _lockupDate) internal { Period storage _transferPeriod = periods[periodsCount]; _transferPeriod.user2bmcDays[_userKey] = _getBmcDaysAmountForUser(_userKey, now, periodsCount); _transferPeriod.totalBmcDays = _getTotalBmcDaysAmount(now, periodsCount); _transferPeriod.bmcDaysPerDay = _transferPeriod.bmcDaysPerDay.add(_value); uint _userBalance = getUserBalance(_userKey); uint _updatedTransfersCount = _transferPeriod.transfersCount.add(1); _transferPeriod.transfersCount = _updatedTransfersCount; _transferPeriod.transfer2date[_transferPeriod.transfersCount] = now; _transferPeriod.user2balance[_userKey] = _userBalance.add(_value); _transferPeriod.user2lastTransferIdx[_userKey] = _updatedTransfersCount; _registerLockedDeposits(_userKey, _value, _lockupDate); } function _makeWithdrawForPeriod(bytes32 _userKey, uint _value) internal { uint _userBalance = getUserBalance(_userKey); uint _lockedBalance = _syncLockedDepositsAmount(_userKey); require(_userBalance.sub(_lockedBalance) >= _value); uint _periodsCount = periodsCount; Period storage _transferPeriod = periods[_periodsCount]; _transferPeriod.user2bmcDays[_userKey] = _getBmcDaysAmountForUser(_userKey, now, _periodsCount); uint _totalBmcDeposit = _getTotalBmcDaysAmount(now, _periodsCount); _transferPeriod.totalBmcDays = _totalBmcDeposit; _transferPeriod.bmcDaysPerDay = _transferPeriod.bmcDaysPerDay.sub(_value); uint _updatedTransferCount = _transferPeriod.transfersCount.add(1); _transferPeriod.transfer2date[_updatedTransferCount] = now; _transferPeriod.user2lastTransferIdx[_userKey] = _updatedTransferCount; _transferPeriod.user2balance[_userKey] = _userBalance.sub(_value); _transferPeriod.transfersCount = _updatedTransferCount; } function _registerLockedDeposits(bytes32 _userKey, uint _amount, uint _lockupDate) internal { if (_lockupDate <= now) { return; } LockedDeposits storage _lockedDeposits = user2lockedDeposits[_userKey]; uint _lockedBalance = _lockedDeposits.date2deposit[_lockupDate]; if (_lockedBalance == 0) { uint _lockedDepositsCounter = _lockedDeposits.counter.add(1); _lockedDeposits.counter = _lockedDepositsCounter; _lockedDeposits.index2Date[_lockedDepositsCounter] = _lockupDate; } _lockedDeposits.date2deposit[_lockupDate] = _lockedBalance.add(_amount); } function _syncLockedDepositsAmount(bytes32 _userKey) internal returns (uint _lockedSum) { LockedDeposits storage _lockedDeposits = user2lockedDeposits[_userKey]; uint _lockedDepositsCounter = _lockedDeposits.counter; for (uint _idx = 1; _idx <= _lockedDepositsCounter; ++_idx) { uint _lockDate = _lockedDeposits.index2Date[_idx]; if (_lockDate <= now) { _lockedDeposits.index2Date[_idx] = _lockedDeposits.index2Date[_lockedDepositsCounter]; delete _lockedDeposits.index2Date[_lockedDepositsCounter]; delete _lockedDeposits.date2deposit[_lockDate]; _lockedDepositsCounter = _lockedDepositsCounter.sub(1); continue; } _lockedSum = _lockedSum.add(_lockedDeposits.date2deposit[_lockDate]); } _lockedDeposits.counter = _lockedDepositsCounter; } function _getBmcDaysAmountForUser(bytes32 _userKey, uint _date, uint _periodIdx) internal view returns (uint) { uint _lastPeriodForUserIdx = user2lastPeriodParticipated[_userKey]; if (_lastPeriodForUserIdx == 0) { return 0; } Period storage _transferPeriod = _lastPeriodForUserIdx <= _periodIdx ? periods[_lastPeriodForUserIdx] : periods[_periodIdx]; uint _lastTransferDate = _transferPeriod.transfer2date[_transferPeriod.user2lastTransferIdx[_userKey]]; // NOTE: It is an intended substraction separation to correctly round dates uint _daysLong = (_date / 1 days) - (_lastTransferDate / 1 days); uint _bmcDays = _transferPeriod.user2bmcDays[_userKey]; return _bmcDays.add(_transferPeriod.user2balance[_userKey] * _daysLong); } /* PRIVATE */ function _getTotalBmcDaysAmount(uint _date, uint _periodIdx) private view returns (uint) { Period storage _depositPeriod = periods[_periodIdx]; uint _transfersCount = _depositPeriod.transfersCount; uint _lastRecordedDate = _transfersCount != 0 ? _depositPeriod.transfer2date[_transfersCount] : _depositPeriod.startDate; if (_lastRecordedDate == 0) { return 0; } // NOTE: It is an intended substraction separation to correctly round dates uint _daysLong = (_date / 1 days).sub((_lastRecordedDate / 1 days)); uint _totalBmcDeposit = _depositPeriod.totalBmcDays.add(_depositPeriod.bmcDaysPerDay.mul(_daysLong)); return _totalBmcDeposit; } }
contract Treasury is OracleContractAdapter, ServiceAllowance, TreasuryEmitter { /* ERROR CODES */ uint constant PERCENT_PRECISION = 10000; uint constant TREASURY_ERROR_SCOPE = 108000; uint constant TREASURY_ERROR_TOKEN_NOT_SET_ALLOWANCE = TREASURY_ERROR_SCOPE + 1; using SafeMath for uint; struct LockedDeposits { uint counter; mapping(uint => uint) index2Date; mapping(uint => uint) date2deposit; } struct Period { uint transfersCount; uint totalBmcDays; uint bmcDaysPerDay; uint startDate; mapping(bytes32 => uint) user2bmcDays; mapping(bytes32 => uint) user2lastTransferIdx; mapping(bytes32 => uint) user2balance; mapping(uint => uint) transfer2date; } /* FIELDS */ address token; address profiterole; uint periodsCount; mapping(uint => Period) periods; mapping(uint => uint) periodDate2periodIdx; mapping(bytes32 => uint) user2lastPeriodParticipated; mapping(bytes32 => LockedDeposits) user2lockedDeposits; /* MODIFIERS */ /// @dev Only profiterole contract allowed to invoke guarded functions modifier onlyProfiterole { require(profiterole == msg.sender); _; } /* PUBLIC */ function Treasury(address _token) public { require(address(_token) != 0x0); token = _token; periodsCount = 1; } function init(address _profiterole) public onlyContractOwner returns (uint) { require(_profiterole != 0x0); profiterole = _profiterole; return OK; } /// @notice Do not accept Ether transfers function() payable public { revert(); } /* EXTERNAL */ /// @notice Deposits tokens on behalf of users /// Allowed only for oracle. /// /// @param _userKey aggregated user key (user ID + role ID) /// @param _value amount of tokens to deposit /// @param _feeAmount amount of tokens that will be taken from _value as fee /// @param _feeAddress destination address for fee transfer /// @param _lockupDate lock up date for deposit. Until that date the deposited value couldn&#39;t be withdrawn /// /// @return result code of an operation function deposit(bytes32 _userKey, uint _value, uint _feeAmount, address _feeAddress, uint _lockupDate) external onlyOracle returns (uint) { require(_userKey != bytes32(0)); require(_value != 0); require(_feeAmount < _value); ERC20 _token = ERC20(token); if (_token.allowance(msg.sender, address(this)) < _value) { return TREASURY_ERROR_TOKEN_NOT_SET_ALLOWANCE; } uint _depositedAmount = _value - _feeAmount; _makeDepositForPeriod(_userKey, _depositedAmount, _lockupDate); uint _periodsCount = periodsCount; user2lastPeriodParticipated[_userKey] = _periodsCount; delete periods[_periodsCount].startDate; if (!_token.transferFrom(msg.sender, address(this), _value)) { revert(); } if (!(_feeAddress == 0x0 || _feeAmount == 0 || _token.transfer(_feeAddress, _feeAmount))) { revert(); } TreasuryDeposited(_userKey, _depositedAmount, _lockupDate); return OK; } /// @notice Withdraws deposited tokens on behalf of users /// Allowed only for oracle /// /// @param _userKey aggregated user key (user ID + role ID) /// @param _value an amount of tokens that is requrested to withdraw /// @param _withdrawAddress address to withdraw; should not be 0x0 /// @param _feeAmount amount of tokens that will be taken from _value as fee /// @param _feeAddress destination address for fee transfer /// /// @return result of an operation function withdraw(bytes32 _userKey, uint _value, address _withdrawAddress, uint _feeAmount, address _feeAddress) external onlyOracle returns (uint) { require(_userKey != bytes32(0)); require(_value != 0); require(_feeAmount < _value); _makeWithdrawForPeriod(_userKey, _value); uint _periodsCount = periodsCount; user2lastPeriodParticipated[_userKey] = periodsCount; delete periods[_periodsCount].startDate; ERC20 _token = ERC20(token); if (!(_feeAddress == 0x0 || _feeAmount == 0 || _token.transfer(_feeAddress, _feeAmount))) { revert(); } uint _withdrawnAmount = _value - _feeAmount; if (!_token.transfer(_withdrawAddress, _withdrawnAmount)) { revert(); } TreasuryWithdrawn(_userKey, _withdrawnAmount); return OK; } /// @notice Gets shares (in percents) the user has on provided date /// /// @param _userKey aggregated user key (user ID + role ID) /// @param _date date where period ends /// /// @return percent from total amount of bmc-days the treasury has on this date. /// Use PERCENT_PRECISION to get right precision function getSharesPercentForPeriod(bytes32 _userKey, uint _date) public view returns (uint) { uint _periodIdx = periodDate2periodIdx[_date]; if (_date != 0 && _periodIdx == 0) { return 0; } if (_date == 0) { _date = now; _periodIdx = periodsCount; } uint _bmcDays = _getBmcDaysAmountForUser(_userKey, _date, _periodIdx); uint _totalBmcDeposit = _getTotalBmcDaysAmount(_date, _periodIdx); return _totalBmcDeposit != 0 ? _bmcDays * PERCENT_PRECISION / _totalBmcDeposit : 0; } /// @notice Gets user balance that is deposited /// @param _userKey aggregated user key (user ID + role ID) /// @return an amount of tokens deposited on behalf of user function getUserBalance(bytes32 _userKey) public view returns (uint) { uint _lastPeriodForUser = user2lastPeriodParticipated[_userKey]; if (_lastPeriodForUser == 0) { return 0; } if (_lastPeriodForUser <= periodsCount.sub(1)) { return periods[_lastPeriodForUser].user2balance[_userKey]; } return periods[periodsCount].user2balance[_userKey]; } /// @notice Gets amount of locked deposits for user /// @param _userKey aggregated user key (user ID + role ID) /// @return an amount of tokens locked function getLockedUserBalance(bytes32 _userKey) public returns (uint) { return _syncLockedDepositsAmount(_userKey); } /// @notice Gets list of locked up deposits with dates when they will be available to withdraw /// @param _userKey aggregated user key (user ID + role ID) /// @return { /// "_lockupDates": "list of lockup dates of deposits", /// "_deposits": "list of deposits" /// } function getLockedUserDeposits(bytes32 _userKey) public view returns (uint[] _lockupDates, uint[] _deposits) { LockedDeposits storage _lockedDeposits = user2lockedDeposits[_userKey]; uint _lockedDepositsCounter = _lockedDeposits.counter; _lockupDates = new uint[](_lockedDepositsCounter); _deposits = new uint[](_lockedDepositsCounter); uint _pointer = 0; for (uint _idx = 1; _idx < _lockedDepositsCounter; ++_idx) { uint _lockDate = _lockedDeposits.index2Date[_idx]; if (_lockDate > now) { _lockupDates[_pointer] = _lockDate; _deposits[_pointer] = _lockedDeposits.date2deposit[_lockDate]; ++_pointer; } } } /// @notice Gets total amount of bmc-day accumulated due provided date /// @param _date date where period ends /// @return an amount of bmc-days function getTotalBmcDaysAmount(uint _date) public view returns (uint) { return _getTotalBmcDaysAmount(_date, periodsCount); } /// @notice Makes a checkpoint to start counting a new period /// @dev Should be used only by Profiterole contract function addDistributionPeriod() public onlyProfiterole returns (uint) { uint _periodsCount = periodsCount; uint _nextPeriod = _periodsCount.add(1); periodDate2periodIdx[now] = _periodsCount; Period storage _previousPeriod = periods[_periodsCount]; uint _totalBmcDeposit = _getTotalBmcDaysAmount(now, _periodsCount); periods[_nextPeriod].startDate = now; periods[_nextPeriod].bmcDaysPerDay = _previousPeriod.bmcDaysPerDay; periods[_nextPeriod].totalBmcDays = _totalBmcDeposit; periodsCount = _nextPeriod; return OK; } function isTransferAllowed(address, address, address, address, uint) public view returns (bool) { return true; } /* INTERNAL */ function _makeDepositForPeriod(bytes32 _userKey, uint _value, uint _lockupDate) internal { Period storage _transferPeriod = periods[periodsCount]; _transferPeriod.user2bmcDays[_userKey] = _getBmcDaysAmountForUser(_userKey, now, periodsCount); _transferPeriod.totalBmcDays = _getTotalBmcDaysAmount(now, periodsCount); _transferPeriod.bmcDaysPerDay = _transferPeriod.bmcDaysPerDay.add(_value); uint _userBalance = getUserBalance(_userKey); uint _updatedTransfersCount = _transferPeriod.transfersCount.add(1); _transferPeriod.transfersCount = _updatedTransfersCount; _transferPeriod.transfer2date[_transferPeriod.transfersCount] = now; _transferPeriod.user2balance[_userKey] = _userBalance.add(_value); _transferPeriod.user2lastTransferIdx[_userKey] = _updatedTransfersCount; _registerLockedDeposits(_userKey, _value, _lockupDate); } function _makeWithdrawForPeriod(bytes32 _userKey, uint _value) internal { uint _userBalance = getUserBalance(_userKey); uint _lockedBalance = _syncLockedDepositsAmount(_userKey); require(_userBalance.sub(_lockedBalance) >= _value); uint _periodsCount = periodsCount; Period storage _transferPeriod = periods[_periodsCount]; _transferPeriod.user2bmcDays[_userKey] = _getBmcDaysAmountForUser(_userKey, now, _periodsCount); uint _totalBmcDeposit = _getTotalBmcDaysAmount(now, _periodsCount); _transferPeriod.totalBmcDays = _totalBmcDeposit; _transferPeriod.bmcDaysPerDay = _transferPeriod.bmcDaysPerDay.sub(_value); uint _updatedTransferCount = _transferPeriod.transfersCount.add(1); _transferPeriod.transfer2date[_updatedTransferCount] = now; _transferPeriod.user2lastTransferIdx[_userKey] = _updatedTransferCount; _transferPeriod.user2balance[_userKey] = _userBalance.sub(_value); _transferPeriod.transfersCount = _updatedTransferCount; } function _registerLockedDeposits(bytes32 _userKey, uint _amount, uint _lockupDate) internal { if (_lockupDate <= now) { return; } LockedDeposits storage _lockedDeposits = user2lockedDeposits[_userKey]; uint _lockedBalance = _lockedDeposits.date2deposit[_lockupDate]; if (_lockedBalance == 0) { uint _lockedDepositsCounter = _lockedDeposits.counter.add(1); _lockedDeposits.counter = _lockedDepositsCounter; _lockedDeposits.index2Date[_lockedDepositsCounter] = _lockupDate; } _lockedDeposits.date2deposit[_lockupDate] = _lockedBalance.add(_amount); } function _syncLockedDepositsAmount(bytes32 _userKey) internal returns (uint _lockedSum) { LockedDeposits storage _lockedDeposits = user2lockedDeposits[_userKey]; uint _lockedDepositsCounter = _lockedDeposits.counter; for (uint _idx = 1; _idx <= _lockedDepositsCounter; ++_idx) { uint _lockDate = _lockedDeposits.index2Date[_idx]; if (_lockDate <= now) { _lockedDeposits.index2Date[_idx] = _lockedDeposits.index2Date[_lockedDepositsCounter]; delete _lockedDeposits.index2Date[_lockedDepositsCounter]; delete _lockedDeposits.date2deposit[_lockDate]; _lockedDepositsCounter = _lockedDepositsCounter.sub(1); continue; } _lockedSum = _lockedSum.add(_lockedDeposits.date2deposit[_lockDate]); } _lockedDeposits.counter = _lockedDepositsCounter; } function _getBmcDaysAmountForUser(bytes32 _userKey, uint _date, uint _periodIdx) internal view returns (uint) { uint _lastPeriodForUserIdx = user2lastPeriodParticipated[_userKey]; if (_lastPeriodForUserIdx == 0) { return 0; } Period storage _transferPeriod = _lastPeriodForUserIdx <= _periodIdx ? periods[_lastPeriodForUserIdx] : periods[_periodIdx]; uint _lastTransferDate = _transferPeriod.transfer2date[_transferPeriod.user2lastTransferIdx[_userKey]]; // NOTE: It is an intended substraction separation to correctly round dates uint _daysLong = (_date / 1 days) - (_lastTransferDate / 1 days); uint _bmcDays = _transferPeriod.user2bmcDays[_userKey]; return _bmcDays.add(_transferPeriod.user2balance[_userKey] * _daysLong); } /* PRIVATE */ function _getTotalBmcDaysAmount(uint _date, uint _periodIdx) private view returns (uint) { Period storage _depositPeriod = periods[_periodIdx]; uint _transfersCount = _depositPeriod.transfersCount; uint _lastRecordedDate = _transfersCount != 0 ? _depositPeriod.transfer2date[_transfersCount] : _depositPeriod.startDate; if (_lastRecordedDate == 0) { return 0; } // NOTE: It is an intended substraction separation to correctly round dates uint _daysLong = (_date / 1 days).sub((_lastRecordedDate / 1 days)); uint _totalBmcDeposit = _depositPeriod.totalBmcDays.add(_depositPeriod.bmcDaysPerDay.mul(_daysLong)); return _totalBmcDeposit; } }
34,550
118
// This contract handles the vesting tokens for a given beneficiary following a linear vesting schedule. Any tokens transferred to this contract will follow the vesting schedule as if they were locked from the beginning.Consequently, if the vesting has already started, any amount of tokens sent to this contract will (at least partly)be immediately releasable. /
contract TokenVestingWallet { uint64 public immutable start; uint64 public immutable duration; address public token; address public beneficiary; uint256 public released; event TokensReleased(address _token, uint256 _amount); event BeneficiaryChanged(address _oldBeneficiary, address _newBeneficiary); /** * @dev Set the token, beneficiary, start timestamp and vesting duration of the vesting wallet. */ constructor( address _token, address _beneficiary, uint64 _startTimestamp, uint64 _durationSeconds ) { require(_token != address(0), "TokenVestingWallet: token is zero address"); require(_beneficiary != address(0), "TokenVestingWallet: beneficiary is zero address"); token = _token; beneficiary = _beneficiary; start = _startTimestamp; duration = _durationSeconds; } /** * @dev Allow beneficiary to change wallet address * * Emits a {BeneficiaryChanged} event. */ function setBeneficiary(address _beneficiary) public { require(msg.sender == beneficiary, "TokenVestingWallet: only beneficiary"); require(_beneficiary != address(0), "TokenVestingWallet: beneficiary is zero address"); emit BeneficiaryChanged(beneficiary, _beneficiary); beneficiary = _beneficiary; } /** * @dev Release the tokens that have already vested to the beneficiary wallet. This function can be called by anyone. * Emits a {TokensReleased} event. */ function release() public { uint256 releasable = vestedAmount(uint64(block.timestamp)) - released; if (releasable > 0) { released += releasable; emit TokensReleased(token, releasable); SafeERC20.safeTransfer(IERC20(token), beneficiary, releasable); } } /** * @dev Calculates the amount of tokens that have already vested. Implementation is a linear vesting curve. */ function vestedAmount(uint64 timestamp) public view returns (uint256) { uint256 totalAllocation = IERC20(token).balanceOf(address(this)) + released; if (timestamp < start) { return 0; } else if (timestamp > start + duration) { return totalAllocation; } else { return (totalAllocation * (timestamp - start)) / duration; } } }
contract TokenVestingWallet { uint64 public immutable start; uint64 public immutable duration; address public token; address public beneficiary; uint256 public released; event TokensReleased(address _token, uint256 _amount); event BeneficiaryChanged(address _oldBeneficiary, address _newBeneficiary); /** * @dev Set the token, beneficiary, start timestamp and vesting duration of the vesting wallet. */ constructor( address _token, address _beneficiary, uint64 _startTimestamp, uint64 _durationSeconds ) { require(_token != address(0), "TokenVestingWallet: token is zero address"); require(_beneficiary != address(0), "TokenVestingWallet: beneficiary is zero address"); token = _token; beneficiary = _beneficiary; start = _startTimestamp; duration = _durationSeconds; } /** * @dev Allow beneficiary to change wallet address * * Emits a {BeneficiaryChanged} event. */ function setBeneficiary(address _beneficiary) public { require(msg.sender == beneficiary, "TokenVestingWallet: only beneficiary"); require(_beneficiary != address(0), "TokenVestingWallet: beneficiary is zero address"); emit BeneficiaryChanged(beneficiary, _beneficiary); beneficiary = _beneficiary; } /** * @dev Release the tokens that have already vested to the beneficiary wallet. This function can be called by anyone. * Emits a {TokensReleased} event. */ function release() public { uint256 releasable = vestedAmount(uint64(block.timestamp)) - released; if (releasable > 0) { released += releasable; emit TokensReleased(token, releasable); SafeERC20.safeTransfer(IERC20(token), beneficiary, releasable); } } /** * @dev Calculates the amount of tokens that have already vested. Implementation is a linear vesting curve. */ function vestedAmount(uint64 timestamp) public view returns (uint256) { uint256 totalAllocation = IERC20(token).balanceOf(address(this)) + released; if (timestamp < start) { return 0; } else if (timestamp > start + duration) { return totalAllocation; } else { return (totalAllocation * (timestamp - start)) / duration; } } }
74,202
44
// Set the address of the sale contract.`saleContract` can make token transferseven when the token contract state is locked.Transfer lock serves the purpose of preventingthe creation of fake Uniswap pools.Added by CryptoTask./
function setSaleContract(address saleContract) public { require(msg.sender == _owner && _saleContract == address(0), "Caller must be owner and _saleContract yet unset"); _saleContract = saleContract; }
function setSaleContract(address saleContract) public { require(msg.sender == _owner && _saleContract == address(0), "Caller must be owner and _saleContract yet unset"); _saleContract = saleContract; }
1,921
58
// Remember that only owner can call so be careful when use on contracts generated from other contracts. tokenAddress The token contract address tokenAmount Number of tokens to be sent /
function recoverERC20(address tokenAddress, uint256 tokenAmount) public virtual onlyOwner { IERC20(tokenAddress).transfer(owner(), tokenAmount); }
function recoverERC20(address tokenAddress, uint256 tokenAmount) public virtual onlyOwner { IERC20(tokenAddress).transfer(owner(), tokenAmount); }
26,106
404
// Reverts unless the roleId represents an initialized, shared roleId. /
modifier onlyShared(uint256 roleId) { require(roles[roleId].roleType == RoleType.Shared, "Must be called on an initialized Shared role"); _; }
modifier onlyShared(uint256 roleId) { require(roles[roleId].roleType == RoleType.Shared, "Must be called on an initialized Shared role"); _; }
12,099
14
// Offsets into fulfillRandomnessRequest's _proof of various values Public key. Skips byte array's length prefix.
uint256 public constant PUBLIC_KEY_OFFSET = 0x20;
uint256 public constant PUBLIC_KEY_OFFSET = 0x20;
28,081
14
// Can't wait to get generics/templates or interfaces
function VoteOwner(int8 vote, uint PostNumber) external isDIAccount
function VoteOwner(int8 vote, uint PostNumber) external isDIAccount
39,049
1
// Constants /
uint constant public MAX_OWNER_COUNT = 50;
uint constant public MAX_OWNER_COUNT = 50;
9,790
175
// The number of project tokens minted for the beneficiary.
uint256 projectTokenCount;
uint256 projectTokenCount;
15,482
19
// Calculates the quantity of shares for an investor's order _fundNum Fund number _qty Quantity of sharesreturn uint Number of shares /
function calcQty(uint _fundNum, uint _qty) external view
function calcQty(uint _fundNum, uint _qty) external view
44,766
0
// Use Zeppelin MerkleProof Library to verify Merkle proofs
using MerkleProof for bytes32[];
using MerkleProof for bytes32[];
43,737
55
// Update the current owner
_setRouterOwner(_router, config.proposed, config.owner);
_setRouterOwner(_router, config.proposed, config.owner);
23,813
295
// Get the proposed root parameters.
bytes32 merkleRoot = _PROPOSED_ROOT_.merkleRoot; uint256 epoch = _PROPOSED_ROOT_.epoch; bytes memory ipfsCid = _PROPOSED_ROOT_.ipfsCid; require(merkleRoot != bytes32(0), 'MD1RootUpdates: Proposed root is zero (unset)'); require(epoch == getNextRootEpoch(), 'MD1RootUpdates: Proposed epoch is not next root epoch'); require( block.timestamp >= _WAITING_PERIOD_END_, 'MD1RootUpdates: Waiting period has not elapsed' );
bytes32 merkleRoot = _PROPOSED_ROOT_.merkleRoot; uint256 epoch = _PROPOSED_ROOT_.epoch; bytes memory ipfsCid = _PROPOSED_ROOT_.ipfsCid; require(merkleRoot != bytes32(0), 'MD1RootUpdates: Proposed root is zero (unset)'); require(epoch == getNextRootEpoch(), 'MD1RootUpdates: Proposed epoch is not next root epoch'); require( block.timestamp >= _WAITING_PERIOD_END_, 'MD1RootUpdates: Waiting period has not elapsed' );
77,512
140
// Last length to repeat
uint256 len; (err, symbol) = _decode(s, lencode); if (err != ErrorCode.ERR_NONE) {
uint256 len; (err, symbol) = _decode(s, lencode); if (err != ErrorCode.ERR_NONE) {
27,795
19
// Calculate the new domain's id and create it
uint256 domainId = uint256( keccak256(abi.encodePacked(parentId, labelHash)) ); _createDomain(parentId, domainId, minter, controller); _setTokenURI(domainId, metadataUri); if (locked) { _setDomainLock(domainId, minter, true); }
uint256 domainId = uint256( keccak256(abi.encodePacked(parentId, labelHash)) ); _createDomain(parentId, domainId, minter, controller); _setTokenURI(domainId, metadataUri); if (locked) { _setDomainLock(domainId, minter, true); }
47,376
294
// See {safeTransferFrom}.Check the state hash and call safeTransferFrom. /
function safeCheckedTransferFrom( address from, address to, uint256 tokenId, uint256 expectedStateHash ) external { require(expectedStateHash == tokenIdToStateHash[tokenId], "ComposableTopDown: stateHash mismatch (1)"); safeTransferFrom(from, to, tokenId); }
function safeCheckedTransferFrom( address from, address to, uint256 tokenId, uint256 expectedStateHash ) external { require(expectedStateHash == tokenIdToStateHash[tokenId], "ComposableTopDown: stateHash mismatch (1)"); safeTransferFrom(from, to, tokenId); }
59,155
33
// Passes execution into virtual function. Can only be called by assigned asset proxy. return success. function is final, and must not be overridden. /
function __transferWithReference(address _to, uint _value, string _reference, address _sender) public onlyProxy returns (bool) { return _transferWithReference(_to, _value, _reference, _sender); }
function __transferWithReference(address _to, uint _value, string _reference, address _sender) public onlyProxy returns (bool) { return _transferWithReference(_to, _value, _reference, _sender); }
67,684
97
// Returns True if specified entity is validated and not expired
* @param self {object} - The data containing the entity mappings * @param id {uint} - The id of the entity to check * @return {bool} - True if the entity is validated */ function isValid(Data storage self, uint id) view public returns (bool) { return isValidated(self, id) && !isExpired(self, id) && !isClosed(self, id); }
* @param self {object} - The data containing the entity mappings * @param id {uint} - The id of the entity to check * @return {bool} - True if the entity is validated */ function isValid(Data storage self, uint id) view public returns (bool) { return isValidated(self, id) && !isExpired(self, id) && !isClosed(self, id); }
46,284
148
// map: assetAddress -> Market /
mapping(address => Market) public markets;
mapping(address => Market) public markets;
12,105
49
// The ilk's price feed
function pip(bytes32 ilk) external view returns (address) { return ilkData[ilk].pip; }
function pip(bytes32 ilk) external view returns (address) { return ilkData[ilk].pip; }
23,988
63
// Require that all auctions have a duration of at least one minute.
require(_auction.duration >= 1 minutes); tokenIdToAuction[_tokenId] = _auction; emit AuctionCreated( uint256(_tokenId), uint256(_auction.startingPrice), uint256(_auction.endingPrice), uint256(_auction.duration) );
require(_auction.duration >= 1 minutes); tokenIdToAuction[_tokenId] = _auction; emit AuctionCreated( uint256(_tokenId), uint256(_auction.startingPrice), uint256(_auction.endingPrice), uint256(_auction.duration) );
56,563
110
// Bonus muliplier for early Test makers.
uint256 public constant BONUS_MULTIPLIER = 0;
uint256 public constant BONUS_MULTIPLIER = 0;
29,445
64
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) internal allTokensIndex;
mapping(uint256 => uint256) internal allTokensIndex;
5,661
5
// Subtracts two unsigned integers, reverts on overflow(i.e. if subtrahend is greater than minuend). /
function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; }
function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; }
33,890
530
// send reward to warrior owner
failedBooty += sendBooty(warriorToOwner[CryptoUtils._unpackIdValue(packedWarrior)], _computePVPReward(booty, contendersCut));
failedBooty += sendBooty(warriorToOwner[CryptoUtils._unpackIdValue(packedWarrior)], _computePVPReward(booty, contendersCut));
79,006
82
// Tracking the next sequential mint
uint256 internal _nextSequential;
uint256 internal _nextSequential;
33,877
4
// todo: compare gas cost of vk in memory to storage(refer to Verifier_GM17.sol).
vk.a = Pairing.G1Point(_vk[0], _vk[1]); vk.b = Pairing.G2Point([_vk[2], _vk[3]], [_vk[4], _vk[5]]); vk.gamma = Pairing.G2Point([_vk[6], _vk[7]], [_vk[8], _vk[9]]); vk.delta = Pairing.G2Point([_vk[10], _vk[11]], [_vk[12], _vk[13]]); vk.gamma_abc = new Pairing.G1Point[]((_vk.length - 14) / 2); uint j = 0; for (uint i = 14; i < _vk.length; i += 2) { vk.gamma_abc[j++] = Pairing.G1Point(_vk[i], _vk[i + 1]); }
vk.a = Pairing.G1Point(_vk[0], _vk[1]); vk.b = Pairing.G2Point([_vk[2], _vk[3]], [_vk[4], _vk[5]]); vk.gamma = Pairing.G2Point([_vk[6], _vk[7]], [_vk[8], _vk[9]]); vk.delta = Pairing.G2Point([_vk[10], _vk[11]], [_vk[12], _vk[13]]); vk.gamma_abc = new Pairing.G1Point[]((_vk.length - 14) / 2); uint j = 0; for (uint i = 14; i < _vk.length; i += 2) { vk.gamma_abc[j++] = Pairing.G1Point(_vk[i], _vk[i + 1]); }
22,142
65
// Exclude owner, dev wallet, liq wallet, and this contract from fee
_isExcludedFromFee[owner()] = true; _isExcludedFromFee[_devWalletAddress] = true; _isExcludedFromFee[_msWalletAddress] = true; _isExcludedFromFee[_vetWalletAddress] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), owner(), _tTotal);
_isExcludedFromFee[owner()] = true; _isExcludedFromFee[_devWalletAddress] = true; _isExcludedFromFee[_msWalletAddress] = true; _isExcludedFromFee[_vetWalletAddress] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), owner(), _tTotal);
9,309
26
// Assert that passed main UTXO parameter is the same as in storage and can be used for further processing.
require( keccak256( abi.encodePacked( mainUtxo.txHash, mainUtxo.txOutputIndex, mainUtxo.txOutputValue ) ) == mainUtxoHash, "Invalid main UTXO data" );
require( keccak256( abi.encodePacked( mainUtxo.txHash, mainUtxo.txOutputIndex, mainUtxo.txOutputValue ) ) == mainUtxoHash, "Invalid main UTXO data" );
10,782
144
// pauses the token contract, when contract is paused investors cannot transfer tokens anymore This function can only be called by a wallet set as agent of the token emits a `Paused` event /
function pause() external;
function pause() external;
13,633
4
// returns coffee array
function getAllCoffee() public view returns (Coffee[] memory){ return coffee; }
function getAllCoffee() public view returns (Coffee[] memory){ return coffee; }
8,088
1
// ------------DERIVATIVE MOCK UP------------
function invest() public payable returns(bool success) {return true;} // function changeStatus(DerivativeStatus _status) pure returns(bool) {return true;} function getPrice() public view returns(uint) { return 10**decimals; } function _initialize (address /*_componentList*/) internal { } function updateComponent(bytes32 /*_name*/) public onlyOwner returns (address) { return address(0x0); } function approveComponent(bytes32 /*_name*/) internal { } function getETHBalance() public view returns(uint) { return address(this).balance; }
function invest() public payable returns(bool success) {return true;} // function changeStatus(DerivativeStatus _status) pure returns(bool) {return true;} function getPrice() public view returns(uint) { return 10**decimals; } function _initialize (address /*_componentList*/) internal { } function updateComponent(bytes32 /*_name*/) public onlyOwner returns (address) { return address(0x0); } function approveComponent(bytes32 /*_name*/) internal { } function getETHBalance() public view returns(uint) { return address(this).balance; }
48,914
137
// These should never fail as we know precisely how VanillaV1Token01.transferFrom is implemented
if (vnl.balanceOf(freezer) != previouslyFrozen + convertedAmount) { revert FreezerBalanceMismatch(); }
if (vnl.balanceOf(freezer) != previouslyFrozen + convertedAmount) { revert FreezerBalanceMismatch(); }
27,975
23
// Reset random attack and defense strength
updatePlayerTokenStrength(_battle.players[0], [_calculateAttackStrength(_battle.rarityIdNFT[0]), _calculateDefenseStrength(_battle.rarityIdNFT[0])]); updatePlayerTokenStrength(_battle.players[1], [_calculateAttackStrength(_battle.rarityIdNFT[1]), _calculateDefenseStrength(_battle.rarityIdNFT[1])]);
updatePlayerTokenStrength(_battle.players[0], [_calculateAttackStrength(_battle.rarityIdNFT[0]), _calculateDefenseStrength(_battle.rarityIdNFT[0])]); updatePlayerTokenStrength(_battle.players[1], [_calculateAttackStrength(_battle.rarityIdNFT[1]), _calculateDefenseStrength(_battle.rarityIdNFT[1])]);
2,289
14
// Address this contract verifies with the registryAddress for allowed operators
address public filterRegistrant;
address public filterRegistrant;
24,433
58
// Count NFTs tracked by this contract/ return A count of valid NFTs tracked by this contract, where each one of/them has an assigned and queryable owner not equal to the zero address/Required for ERC-721 compliance.
function totalSupply() external view returns (uint256) { return tokenIds.length; }
function totalSupply() external view returns (uint256) { return tokenIds.length; }
20,876
71
// method which allows to transfer a predefined amount of tokens from a predefined address to a predefined address from - the address to transfer the tokens from to - the address to transfer the tokens to amount - the amount of tokens to transferreturn true if the transfer was successful only callable if the token is not paused only callable if the balance of the receiver is lower than the max amount of tokens per wallet checks if blacklisting is enabled and if the sender and receiver are not blacklisted checks if whitelisting is enabled and if the sender and
function transferFrom( address from, address to, uint256 amount ) public virtual override whenNotPaused validateTransfer(from, to)
function transferFrom( address from, address to, uint256 amount ) public virtual override whenNotPaused validateTransfer(from, to)
31,073
80
// maximum number of token that can be removed from pool
function maxCanRemove( address token ) public view returns ( uint ) { uint minimum = totalTokens.mul( tokenInfo[ token ].lowAP ).div( 1e9 ); uint balance = IERC20( token ).balanceOf( address(this) ); return balance.sub( minimum ); }
function maxCanRemove( address token ) public view returns ( uint ) { uint minimum = totalTokens.mul( tokenInfo[ token ].lowAP ).div( 1e9 ); uint balance = IERC20( token ).balanceOf( address(this) ); return balance.sub( minimum ); }
19,423
10
// Changes the duration of the time lock for transactions. _secondsTimeLockedDuration needed after a transaction is confirmed and before itbecomes executable, in seconds. /
function changeTimeLock( uint32 _secondsTimeLocked ) public onlyWallet
function changeTimeLock( uint32 _secondsTimeLocked ) public onlyWallet
38,012
13
// annualRate: percent10^18
function EmbiggenToken(uint _initialSupply, uint annualRate, string _name, string _symbol, uint8 _decimals) { initialSupply = _initialSupply; initializedTime = (block.timestamp / 3600) * 3600; hourRate = annualRate / (365 * 24); require(hourRate <= 223872113856833); // This ensures that (earnedInterset * baseInterest) won't overflow a uint for any plausible time period balances[msg.sender] = UserBalance({ latestBalance: _initialSupply, lastCalculated: (block.timestamp / 3600) * 3600 }); name = _name; symbol = _symbol; decimals = _decimals; }
function EmbiggenToken(uint _initialSupply, uint annualRate, string _name, string _symbol, uint8 _decimals) { initialSupply = _initialSupply; initializedTime = (block.timestamp / 3600) * 3600; hourRate = annualRate / (365 * 24); require(hourRate <= 223872113856833); // This ensures that (earnedInterset * baseInterest) won't overflow a uint for any plausible time period balances[msg.sender] = UserBalance({ latestBalance: _initialSupply, lastCalculated: (block.timestamp / 3600) * 3600 }); name = _name; symbol = _symbol; decimals = _decimals; }
8,641
32
// Transfers royalties to `admin` and `creator` of asset and transfers remaining payment to `currentOwner`. _tokenId ID of the token _payment Value paid by the new owner _currentOwner Address of current owner of the asset /
function _transferPayments(uint256 _tokenId, uint256 _payment, address _currentOwner) private { uint256 royaltyAmount = _payment / ROYALTY_PERCENTAGE; uint256 paymentAmount = _payment - royaltyAmount; payable(taxCollectors[_tokenId]).transfer(royaltyAmount); payable(_currentOwner).transfer(paymentAmount); }
function _transferPayments(uint256 _tokenId, uint256 _payment, address _currentOwner) private { uint256 royaltyAmount = _payment / ROYALTY_PERCENTAGE; uint256 paymentAmount = _payment - royaltyAmount; payable(taxCollectors[_tokenId]).transfer(royaltyAmount); payable(_currentOwner).transfer(paymentAmount); }
13,702
0
// Address to which any funds sent to this contract will be forwarded Event logs to log movement of Ether//Default function; Gets called when Ether is deposited, and forwards it to the destination address /
function() payable public { emit LogForwarded(msg.sender, msg.value); destinationAddress.transfer(msg.value); }
function() payable public { emit LogForwarded(msg.sender, msg.value); destinationAddress.transfer(msg.value); }
29,683
22
// This is a consecutive sale
shares[_shareId].ownerAddress.transfer(commission1percent * 85); // 85% goes to the previous shareholder companies[shares[_shareId].companyId].ownerAddress.transfer(commission1percent * 10); // 10% goes to the company owner cfoAddress.transfer(commission1percent * 5); // 5% goes to the dev
shares[_shareId].ownerAddress.transfer(commission1percent * 85); // 85% goes to the previous shareholder companies[shares[_shareId].companyId].ownerAddress.transfer(commission1percent * 10); // 10% goes to the company owner cfoAddress.transfer(commission1percent * 5); // 5% goes to the dev
39,124
522
// Required number of transitions is over allowed number, return false indicating it didn't fully transition
return false;
return false;
14,338
132
// Rebase Monetary Supply Policy This is an implementation of the Rebase Ideal Money protocol. Rebase operates symmetrically on expansion and contraction. It will both split and combine coins to maintain a stable unit price.This component regulates the token supply of the Rebase ERC20 token in response to market oracles. /
contract RebasePolicy is Ownable { using SafeMath for uint256; using SafeMathInt for int256; using UInt256Lib for uint256; event LogRebase( uint256 indexed epoch, uint256 exchangeRate, uint256 cpi, int256 requestedSupplyAdjustment, uint256 timestampSec ); Rebase public rebaseC; // Provides the current CPI, as an 18 decimal fixed point number. IOracle public cpiOracle; // Market oracle provides the token/USD exchange rate as an 18 decimal fixed point number. // (eg) An oracle value of 1.5e18 it would mean 1 Rebase is trading for $1.50. IOracle public marketOracle; // CPI value at the time of launch, as an 18 decimal fixed point number. uint256 private baseCpi; // If the current exchange rate is within this fractional distance from the target, no supply // update is performed. Fixed point number--same format as the rate. // (ie) abs(rate - targetRate) / targetRate < deviationThreshold, then no supply change. // DECIMALS Fixed point number. uint256 public deviationThreshold; // The rebase lag parameter, used to dampen the applied supply adjustment by 1 / rebaseLag // Check setRebaseLag comments for more details. // Natural number, no decimal places. uint256 public rebaseLag; // More than this much time must pass between rebase operations. uint256 public minRebaseTimeIntervalSec; // Block timestamp of last rebase operation uint256 public lastRebaseTimestampSec; // The rebase window begins this many seconds into the minRebaseTimeInterval period. // For example if minRebaseTimeInterval is 24hrs, it represents the time of day in seconds. uint256 public rebaseWindowOffsetSec; // The length of the time window where a rebase operation is allowed to execute, in seconds. uint256 public rebaseWindowLengthSec; // The number of rebase cycles since inception uint256 public epoch; uint256 private constant DECIMALS = 18; // Due to the expression in computeSupplyDelta(), MAX_RATE * MAX_SUPPLY must fit into an int256. // Both are 18 decimals fixed point numbers. uint256 private constant MAX_RATE = 10**6 * 10**DECIMALS; // MAX_SUPPLY = MAX_INT256 / MAX_RATE uint256 private constant MAX_SUPPLY = ~(uint256(1) << 255) / MAX_RATE; // This module orchestrates the rebase execution and downstream notification. address public orchestrator; modifier onlyOrchestrator() { require(msg.sender == orchestrator); _; } /** * @notice Initiates a new rebase operation, provided the minimum time period has elapsed. * * @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag * Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate * and targetRate is CpiOracleRate / baseCpi */ function rebase() external onlyOrchestrator { require(inRebaseWindow()); // This comparison also ensures there is no reentrancy. require(lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) < now); // Snap the rebase time to the start of this window. lastRebaseTimestampSec = now.sub( now.mod(minRebaseTimeIntervalSec)).add(rebaseWindowOffsetSec); epoch = epoch.add(1); uint256 cpi; bool cpiValid; (cpi, cpiValid) = cpiOracle.getData(); require(cpiValid); uint256 targetRate = cpi.mul(10 ** DECIMALS).div(baseCpi); uint256 exchangeRate; bool rateValid; (exchangeRate, rateValid) = marketOracle.getData(); require(rateValid); if (exchangeRate > MAX_RATE) { exchangeRate = MAX_RATE; } int256 supplyDelta = computeSupplyDelta(exchangeRate, targetRate); // Apply the Dampening factor. supplyDelta = supplyDelta.div(rebaseLag.toInt256Safe()); if (supplyDelta > 0 && rebaseC.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY) { supplyDelta = (MAX_SUPPLY.sub(rebaseC.totalSupply())).toInt256Safe(); } uint256 supplyAfterRebase = rebaseC.rebase(epoch, supplyDelta); assert(supplyAfterRebase <= MAX_SUPPLY); emit LogRebase(epoch, exchangeRate, cpi, supplyDelta, now); } /** * @notice Sets the reference to the CPI oracle. * @param cpiOracle_ The address of the cpi oracle contract. */ function setCpiOracle(IOracle cpiOracle_) external onlyOwner { cpiOracle = cpiOracle_; } /** * @notice Sets the reference to the market oracle. * @param marketOracle_ The address of the market oracle contract. */ function setMarketOracle(IOracle marketOracle_) external onlyOwner { marketOracle = marketOracle_; } /** * @notice Sets the reference to the orchestrator. * @param orchestrator_ The address of the orchestrator contract. */ function setOrchestrator(address orchestrator_) external onlyOwner { orchestrator = orchestrator_; } /** * @notice Sets the deviation threshold fraction. If the exchange rate given by the market * oracle is within this fractional distance from the targetRate, then no supply * modifications are made. DECIMALS fixed point number. * @param deviationThreshold_ The new exchange rate threshold fraction. */ function setDeviationThreshold(uint256 deviationThreshold_) external onlyOwner { deviationThreshold = deviationThreshold_; } /** * @notice Sets the rebase lag parameter. It is used to dampen the applied supply adjustment by 1 / rebaseLag If the rebase lag R, equals 1, the smallest value for R, then the full supply correction is applied on each rebase cycle. If it is greater than 1, then a correction of 1/R of is applied on each rebase. * @param rebaseLag_ The new rebase lag parameter. */ function setRebaseLag(uint256 rebaseLag_) external onlyOwner { require(rebaseLag_ > 0); rebaseLag = rebaseLag_; } /** * @notice Sets the parameters which control the timing and frequency of * rebase operations. * a) the minimum time period that must elapse between rebase cycles. * b) the rebase window offset parameter. * c) the rebase window length parameter. * @param minRebaseTimeIntervalSec_ More than this much time must pass between rebase * operations, in seconds. * @param rebaseWindowOffsetSec_ The number of seconds from the beginning of the rebase interval, where the rebase window begins. * @param rebaseWindowLengthSec_ The length of the rebase window in seconds. */ function setRebaseTimingParameters( uint256 minRebaseTimeIntervalSec_, uint256 rebaseWindowOffsetSec_, uint256 rebaseWindowLengthSec_) external onlyOwner { require(minRebaseTimeIntervalSec_ > 0); require(rebaseWindowOffsetSec_ < minRebaseTimeIntervalSec_); minRebaseTimeIntervalSec = minRebaseTimeIntervalSec_; rebaseWindowOffsetSec = rebaseWindowOffsetSec_; rebaseWindowLengthSec = rebaseWindowLengthSec_; } /** * @dev ZOS upgradable contract initialization method. * It is called at the time of contract creation to invoke parent class initializers and * initialize the contract's state variables. */ function initialize(address owner_, Rebase rebaseC_, uint256 baseCpi_) public initializer { Ownable.initialize(owner_); // deviationThreshold = 0.05e18 = 5e16 deviationThreshold = 5 * 10 ** (DECIMALS-2); rebaseLag = 30; minRebaseTimeIntervalSec = 1 days; rebaseWindowOffsetSec = 72000; // 8PM UTC rebaseWindowLengthSec = 15 minutes; lastRebaseTimestampSec = 0; epoch = 0; rebaseC = rebaseC_; baseCpi = baseCpi_; } /** * @return If the latest block timestamp is within the rebase time window it, returns true. * Otherwise, returns false. */ function inRebaseWindow() public view returns (bool) { return ( now.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec && now.mod(minRebaseTimeIntervalSec) < (rebaseWindowOffsetSec.add(rebaseWindowLengthSec)) ); } /** * @return Computes the total supply adjustment in response to the exchange rate * and the targetRate. */ function computeSupplyDelta(uint256 rate, uint256 targetRate) private view returns (int256) { if (withinDeviationThreshold(rate, targetRate)) { return 0; } // supplyDelta = totalSupply * (rate - targetRate) / targetRate int256 targetRateSigned = targetRate.toInt256Safe(); return rebaseC.totalSupply().toInt256Safe() .mul(rate.toInt256Safe().sub(targetRateSigned)) .div(targetRateSigned); } /** * @param rate The current exchange rate, an 18 decimal fixed point number. * @param targetRate The target exchange rate, an 18 decimal fixed point number. * @return If the rate is within the deviation threshold from the target rate, returns true. * Otherwise, returns false. */ function withinDeviationThreshold(uint256 rate, uint256 targetRate) private view returns (bool) { uint256 absoluteDeviationThreshold = targetRate.mul(deviationThreshold) .div(10 ** DECIMALS); return (rate >= targetRate && rate.sub(targetRate) < absoluteDeviationThreshold) || (rate < targetRate && targetRate.sub(rate) < absoluteDeviationThreshold); } }
contract RebasePolicy is Ownable { using SafeMath for uint256; using SafeMathInt for int256; using UInt256Lib for uint256; event LogRebase( uint256 indexed epoch, uint256 exchangeRate, uint256 cpi, int256 requestedSupplyAdjustment, uint256 timestampSec ); Rebase public rebaseC; // Provides the current CPI, as an 18 decimal fixed point number. IOracle public cpiOracle; // Market oracle provides the token/USD exchange rate as an 18 decimal fixed point number. // (eg) An oracle value of 1.5e18 it would mean 1 Rebase is trading for $1.50. IOracle public marketOracle; // CPI value at the time of launch, as an 18 decimal fixed point number. uint256 private baseCpi; // If the current exchange rate is within this fractional distance from the target, no supply // update is performed. Fixed point number--same format as the rate. // (ie) abs(rate - targetRate) / targetRate < deviationThreshold, then no supply change. // DECIMALS Fixed point number. uint256 public deviationThreshold; // The rebase lag parameter, used to dampen the applied supply adjustment by 1 / rebaseLag // Check setRebaseLag comments for more details. // Natural number, no decimal places. uint256 public rebaseLag; // More than this much time must pass between rebase operations. uint256 public minRebaseTimeIntervalSec; // Block timestamp of last rebase operation uint256 public lastRebaseTimestampSec; // The rebase window begins this many seconds into the minRebaseTimeInterval period. // For example if minRebaseTimeInterval is 24hrs, it represents the time of day in seconds. uint256 public rebaseWindowOffsetSec; // The length of the time window where a rebase operation is allowed to execute, in seconds. uint256 public rebaseWindowLengthSec; // The number of rebase cycles since inception uint256 public epoch; uint256 private constant DECIMALS = 18; // Due to the expression in computeSupplyDelta(), MAX_RATE * MAX_SUPPLY must fit into an int256. // Both are 18 decimals fixed point numbers. uint256 private constant MAX_RATE = 10**6 * 10**DECIMALS; // MAX_SUPPLY = MAX_INT256 / MAX_RATE uint256 private constant MAX_SUPPLY = ~(uint256(1) << 255) / MAX_RATE; // This module orchestrates the rebase execution and downstream notification. address public orchestrator; modifier onlyOrchestrator() { require(msg.sender == orchestrator); _; } /** * @notice Initiates a new rebase operation, provided the minimum time period has elapsed. * * @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag * Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate * and targetRate is CpiOracleRate / baseCpi */ function rebase() external onlyOrchestrator { require(inRebaseWindow()); // This comparison also ensures there is no reentrancy. require(lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) < now); // Snap the rebase time to the start of this window. lastRebaseTimestampSec = now.sub( now.mod(minRebaseTimeIntervalSec)).add(rebaseWindowOffsetSec); epoch = epoch.add(1); uint256 cpi; bool cpiValid; (cpi, cpiValid) = cpiOracle.getData(); require(cpiValid); uint256 targetRate = cpi.mul(10 ** DECIMALS).div(baseCpi); uint256 exchangeRate; bool rateValid; (exchangeRate, rateValid) = marketOracle.getData(); require(rateValid); if (exchangeRate > MAX_RATE) { exchangeRate = MAX_RATE; } int256 supplyDelta = computeSupplyDelta(exchangeRate, targetRate); // Apply the Dampening factor. supplyDelta = supplyDelta.div(rebaseLag.toInt256Safe()); if (supplyDelta > 0 && rebaseC.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY) { supplyDelta = (MAX_SUPPLY.sub(rebaseC.totalSupply())).toInt256Safe(); } uint256 supplyAfterRebase = rebaseC.rebase(epoch, supplyDelta); assert(supplyAfterRebase <= MAX_SUPPLY); emit LogRebase(epoch, exchangeRate, cpi, supplyDelta, now); } /** * @notice Sets the reference to the CPI oracle. * @param cpiOracle_ The address of the cpi oracle contract. */ function setCpiOracle(IOracle cpiOracle_) external onlyOwner { cpiOracle = cpiOracle_; } /** * @notice Sets the reference to the market oracle. * @param marketOracle_ The address of the market oracle contract. */ function setMarketOracle(IOracle marketOracle_) external onlyOwner { marketOracle = marketOracle_; } /** * @notice Sets the reference to the orchestrator. * @param orchestrator_ The address of the orchestrator contract. */ function setOrchestrator(address orchestrator_) external onlyOwner { orchestrator = orchestrator_; } /** * @notice Sets the deviation threshold fraction. If the exchange rate given by the market * oracle is within this fractional distance from the targetRate, then no supply * modifications are made. DECIMALS fixed point number. * @param deviationThreshold_ The new exchange rate threshold fraction. */ function setDeviationThreshold(uint256 deviationThreshold_) external onlyOwner { deviationThreshold = deviationThreshold_; } /** * @notice Sets the rebase lag parameter. It is used to dampen the applied supply adjustment by 1 / rebaseLag If the rebase lag R, equals 1, the smallest value for R, then the full supply correction is applied on each rebase cycle. If it is greater than 1, then a correction of 1/R of is applied on each rebase. * @param rebaseLag_ The new rebase lag parameter. */ function setRebaseLag(uint256 rebaseLag_) external onlyOwner { require(rebaseLag_ > 0); rebaseLag = rebaseLag_; } /** * @notice Sets the parameters which control the timing and frequency of * rebase operations. * a) the minimum time period that must elapse between rebase cycles. * b) the rebase window offset parameter. * c) the rebase window length parameter. * @param minRebaseTimeIntervalSec_ More than this much time must pass between rebase * operations, in seconds. * @param rebaseWindowOffsetSec_ The number of seconds from the beginning of the rebase interval, where the rebase window begins. * @param rebaseWindowLengthSec_ The length of the rebase window in seconds. */ function setRebaseTimingParameters( uint256 minRebaseTimeIntervalSec_, uint256 rebaseWindowOffsetSec_, uint256 rebaseWindowLengthSec_) external onlyOwner { require(minRebaseTimeIntervalSec_ > 0); require(rebaseWindowOffsetSec_ < minRebaseTimeIntervalSec_); minRebaseTimeIntervalSec = minRebaseTimeIntervalSec_; rebaseWindowOffsetSec = rebaseWindowOffsetSec_; rebaseWindowLengthSec = rebaseWindowLengthSec_; } /** * @dev ZOS upgradable contract initialization method. * It is called at the time of contract creation to invoke parent class initializers and * initialize the contract's state variables. */ function initialize(address owner_, Rebase rebaseC_, uint256 baseCpi_) public initializer { Ownable.initialize(owner_); // deviationThreshold = 0.05e18 = 5e16 deviationThreshold = 5 * 10 ** (DECIMALS-2); rebaseLag = 30; minRebaseTimeIntervalSec = 1 days; rebaseWindowOffsetSec = 72000; // 8PM UTC rebaseWindowLengthSec = 15 minutes; lastRebaseTimestampSec = 0; epoch = 0; rebaseC = rebaseC_; baseCpi = baseCpi_; } /** * @return If the latest block timestamp is within the rebase time window it, returns true. * Otherwise, returns false. */ function inRebaseWindow() public view returns (bool) { return ( now.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec && now.mod(minRebaseTimeIntervalSec) < (rebaseWindowOffsetSec.add(rebaseWindowLengthSec)) ); } /** * @return Computes the total supply adjustment in response to the exchange rate * and the targetRate. */ function computeSupplyDelta(uint256 rate, uint256 targetRate) private view returns (int256) { if (withinDeviationThreshold(rate, targetRate)) { return 0; } // supplyDelta = totalSupply * (rate - targetRate) / targetRate int256 targetRateSigned = targetRate.toInt256Safe(); return rebaseC.totalSupply().toInt256Safe() .mul(rate.toInt256Safe().sub(targetRateSigned)) .div(targetRateSigned); } /** * @param rate The current exchange rate, an 18 decimal fixed point number. * @param targetRate The target exchange rate, an 18 decimal fixed point number. * @return If the rate is within the deviation threshold from the target rate, returns true. * Otherwise, returns false. */ function withinDeviationThreshold(uint256 rate, uint256 targetRate) private view returns (bool) { uint256 absoluteDeviationThreshold = targetRate.mul(deviationThreshold) .div(10 ** DECIMALS); return (rate >= targetRate && rate.sub(targetRate) < absoluteDeviationThreshold) || (rate < targetRate && targetRate.sub(rate) < absoluteDeviationThreshold); } }
36,885
149
// Returns the max wallet amount. /
function maxWalletAmount() public view returns (uint256) { return totalSupply().mul(maxWalletAmountRate).div(MAX_BP_RATE); }
function maxWalletAmount() public view returns (uint256) { return totalSupply().mul(maxWalletAmountRate).div(MAX_BP_RATE); }
25,136
59
// console.log("A");
return _stop1+pos_in_range;
return _stop1+pos_in_range;
45,563
163
// to mint the required amount of fee shares, solve:/ /
return _existingShares .mul(_balance) .div(_balance.sub(_totalFeeUnderlying)) .sub(_existingShares);
return _existingShares .mul(_balance) .div(_balance.sub(_totalFeeUnderlying)) .sub(_existingShares);
2,241
29
// market is not listed, cannot join
return Error.MARKET_NOT_LISTED;
return Error.MARKET_NOT_LISTED;
7,490
124
// Update internal statuses for lottery
_lotteries[_lotteryId].finalNumber = finalNumber; _lotteries[_lotteryId].status = Status.Claimable; if (_autoInjection) { pendingInjectionNextLottery = amountToWithdrawToTreasury; amountToWithdrawToTreasury = 0; }
_lotteries[_lotteryId].finalNumber = finalNumber; _lotteries[_lotteryId].status = Status.Claimable; if (_autoInjection) { pendingInjectionNextLottery = amountToWithdrawToTreasury; amountToWithdrawToTreasury = 0; }
53,501
69
// Deposit tokens to specific account with time-lock./tokenAddr The contract address of a ERC20/ERC223 token./account The owner of deposited tokens./amount Amount to deposit./releaseTime Time-lock period./ return True if it is successful, revert otherwise.
function depositERC20 ( address tokenAddr, address account, uint256 amount, uint256 releaseTime ) external returns (bool) { require(account != address(0x0)); require(tokenAddr != 0x0); require(msg.value == 0); require(amount > 0);
function depositERC20 ( address tokenAddr, address account, uint256 amount, uint256 releaseTime ) external returns (bool) { require(account != address(0x0)); require(tokenAddr != 0x0); require(msg.value == 0); require(amount > 0);
33,946
12
// ERC165 Standard for support of interfaces. /
function supportsInterface(bytes4 interfaceId) external pure override returns (bool)
function supportsInterface(bytes4 interfaceId) external pure override returns (bool)
21,155
2
// Called by other registries when migrating upkeeps. Only callable by other registries. encodedUpkeeps abi encoding of upkeeps to import - decoded by the transcoder /
function receiveUpkeeps(bytes calldata encodedUpkeeps) external;
function receiveUpkeeps(bytes calldata encodedUpkeeps) external;
17,570
214
// Accepts the given amount of collateral token as a deposit and/ mints underwriter tokens representing pool's ownership./Before calling this function, collateral token needs to have the/required amount accepted to transfer to the asset pool./ return The amount of minted underwriter tokens
function deposit(uint256 amount) external returns (uint256);
function deposit(uint256 amount) external returns (uint256);
61,581
201
// ignore first byte
fee.toUint24(ACTION_SIZE), address(this), amount, slippage, 0 ); return uniswapRouter.exactInputSingle(params);
fee.toUint24(ACTION_SIZE), address(this), amount, slippage, 0 ); return uniswapRouter.exactInputSingle(params);
61,126
5
// ERC20 token used in _The Space_. Total supply capped at 100M, minted to deployer. /
contract SpaceToken is ERC20 { constructor( address incentives, uint256 incentivesTokens, address treasury, uint256 treasuryTokens, address team, uint256 teamTokens, address lp, uint256 lpTokens ) ERC20("The Space", "SPACE") { // Early Incentives _mint(incentives, incentivesTokens * (10**uint256(decimals()))); // Community Treasury _mint(treasury, treasuryTokens * (10**uint256(decimals()))); // Team _mint(team, teamTokens * (10**uint256(decimals()))); // Liquidity Pool _mint(lp, lpTokens * (10**uint256(decimals()))); } }
contract SpaceToken is ERC20 { constructor( address incentives, uint256 incentivesTokens, address treasury, uint256 treasuryTokens, address team, uint256 teamTokens, address lp, uint256 lpTokens ) ERC20("The Space", "SPACE") { // Early Incentives _mint(incentives, incentivesTokens * (10**uint256(decimals()))); // Community Treasury _mint(treasury, treasuryTokens * (10**uint256(decimals()))); // Team _mint(team, teamTokens * (10**uint256(decimals()))); // Liquidity Pool _mint(lp, lpTokens * (10**uint256(decimals()))); } }
28,881
1
// Address of vault contract
address public vault;
address public vault;
8,993
108
// set the valid range of input amount _minAmount the minimum input amount limit _maxAmount the maximum input amount limit /
function setInputAmountRange(uint256 _minAmount,uint256 _maxAmount) public onlyOwner{ minAmount = _minAmount; maxAmount = _maxAmount; }
function setInputAmountRange(uint256 _minAmount,uint256 _maxAmount) public onlyOwner{ minAmount = _minAmount; maxAmount = _maxAmount; }
54,804
19
// Get the virtual price, to help calculate profitreturn the virtual price, scaled to the POOL_PRECISION_DECIMALS /
function getVirtualPrice() external view returns (uint256) { return swapStorage.getVirtualPrice(); }
function getVirtualPrice() external view returns (uint256) { return swapStorage.getVirtualPrice(); }
24,626
56
// update config "minReceiveCommission" /
function updateMinReceiveCommission(uint256 _amount) public onlyOwner{ require(0 < _amount && _amount != minReceiveCommission); minReceiveCommission = _amount; }
function updateMinReceiveCommission(uint256 _amount) public onlyOwner{ require(0 < _amount && _amount != minReceiveCommission); minReceiveCommission = _amount; }
20,134
180
// Returns true if input is a non-fungible token
function isNonFungibleItem(uint256 id) public pure returns(bool) { // A base type has the NF bit but does has an index. return (id & TYPE_NF_BIT == TYPE_NF_BIT) && (id & NF_INDEX_MASK != 0); }
function isNonFungibleItem(uint256 id) public pure returns(bool) { // A base type has the NF bit but does has an index. return (id & TYPE_NF_BIT == TYPE_NF_BIT) && (id & NF_INDEX_MASK != 0); }
29,028
3
// Address where the other half of the ETH generated from token swaps will be sent
address public teamAddress;
address public teamAddress;
29,536
97
// This will give us the ID of the cheapest token in the pool We will estimate the return for trading 1000 DAI The higher the return, the lower the price of the other token
uint256 targetID = 0; // Our target ID is DAI first CurvePool pool = CurvePool(curveAddress); uint256 daiAmount = uint256(1000).mul(10**tokenList[0].decimals); uint256 highAmount = daiAmount; for(uint256 i = 1; i < tokenList.length; i++){ uint256 estimate = pool.get_dy_underlying(tokenList[0].curveID, tokenList[i].curveID, daiAmount);
uint256 targetID = 0; // Our target ID is DAI first CurvePool pool = CurvePool(curveAddress); uint256 daiAmount = uint256(1000).mul(10**tokenList[0].decimals); uint256 highAmount = daiAmount; for(uint256 i = 1; i < tokenList.length; i++){ uint256 estimate = pool.get_dy_underlying(tokenList[0].curveID, tokenList[i].curveID, daiAmount);
13,012