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
136
// Function to setPrice to lower for auction, can only lower the price than 0.19 ETH/
function setPrice( uint256 price ) external onlyOwner
function setPrice( uint256 price ) external onlyOwner
30,516
52
// Hook that is called after any transfer of tokens. This includesminting and burning.- when `from` is zero, `amount` tokens have been minted for `to`.- when `to` is zero, `amount` of ``from``'s tokens have been burned.- `from` and `to` are never both zero.Calling conditions: - when `from` and `to` are both non-zero, `amount` of ``from``'s tokenshas been transferred to `to`.To learn more about hooks, head to xref:ROOT:extending-contracts.adocusing-hooks[Using Hooks]. /
function _afterTokenTransfer( address from, address to, uint256 amount
function _afterTokenTransfer( address from, address to, uint256 amount
13,801
8
// Loop over relevant grid entries
for(uint i=0; i<_width; i++) { for(uint j=0; j<_height; j++) { if (grid[_x+i][_y+j]) {
for(uint i=0; i<_width; i++) { for(uint j=0; j<_height; j++) { if (grid[_x+i][_y+j]) {
13,774
120
// Withdraw all ERC-1155 tokens /
function withdraw() public updateReward(msg.sender) { uint8 length = 0; for (uint8 i = 0; i < nftTokens.length; i++) { uint256 balance = nftTokenMap[nftTokens[i]].balances[msg.sender]; if(balance > 0) { length++; } } uint256[] memory tokenIds = new uint256[](length); uint256[] memory amounts = new uint256[](length); uint8 j = 0; for (uint8 i = 0; i < nftTokens.length; i++) { uint256 tokenId = nftTokens[i]; uint256 balance = nftTokenMap[tokenId].balances[msg.sender]; if(balance > 0) { tokenIds[j] = tokenId; amounts[j] = balance; j++; } } withdrawNFT(tokenIds, amounts); }
function withdraw() public updateReward(msg.sender) { uint8 length = 0; for (uint8 i = 0; i < nftTokens.length; i++) { uint256 balance = nftTokenMap[nftTokens[i]].balances[msg.sender]; if(balance > 0) { length++; } } uint256[] memory tokenIds = new uint256[](length); uint256[] memory amounts = new uint256[](length); uint8 j = 0; for (uint8 i = 0; i < nftTokens.length; i++) { uint256 tokenId = nftTokens[i]; uint256 balance = nftTokenMap[tokenId].balances[msg.sender]; if(balance > 0) { tokenIds[j] = tokenId; amounts[j] = balance; j++; } } withdrawNFT(tokenIds, amounts); }
20,546
160
// Restricted Functions
function mintSecondary(address account, uint amount) external; function mintSecondaryRewards(uint amount) external; function burnSecondary(address account, uint amount) external;
function mintSecondary(address account, uint amount) external; function mintSecondaryRewards(uint amount) external; function burnSecondary(address account, uint amount) external;
27,930
3
// Boolean check for if an address is an instrument /
mapping(address => bool) public isInstrument; mapping(string => address) public getAdapter; address[] public adapters;
mapping(address => bool) public isInstrument; mapping(string => address) public getAdapter; address[] public adapters;
40,149
213
// reset lockup
totalLockedUpRewards = totalLockedUpRewards.sub(user.rewardLockedUp); user.rewardLockedUp = 0; user.nextHarvestUntil = block.timestamp.add(pool.harvestInterval);
totalLockedUpRewards = totalLockedUpRewards.sub(user.rewardLockedUp); user.rewardLockedUp = 0; user.nextHarvestUntil = block.timestamp.add(pool.harvestInterval);
12,092
202
// Will update the base URL of token's URI _newBaseMetadataURI New base URL of token's URI /
function _setBaseMetadataURI(string memory _newBaseMetadataURI) public virtual only(WHITELIST_ADMIN_ROLE)
function _setBaseMetadataURI(string memory _newBaseMetadataURI) public virtual only(WHITELIST_ADMIN_ROLE)
14,286
168
// split the liquify amount into halves
uint256 half = liquifyAmount.div(2); uint256 otherHalf = liquifyAmount.sub(half);
uint256 half = liquifyAmount.div(2); uint256 otherHalf = liquifyAmount.sub(half);
1,351
10
// An on-chain "source of truth" for what DAOs should be index into DAOstack's subgraph. /
contract DAOTracker is Ownable { // `blacklist` the DAO from the subgraph's cache. // Only able to be set by the owner of the DAOTracker. mapping(address=>bool) public blacklisted; event TrackDAO( address indexed _avatar, address _controller, address _reputation, address _daoToken, address _sender, string _arcVersion ); event BlacklistDAO( address indexed _avatar, string _explanationHash ); event ResetDAO( address indexed _avatar, string _explanationHash ); modifier onlyAvatarOwner(Avatar avatar) { require(avatar.owner() == msg.sender, "The caller must be the owner of the Avatar."); _; } modifier notBlacklisted(Avatar avatar) { require(blacklisted[address(avatar)] == false, "The avatar has been blacklisted."); _; } /** * @dev track a new organization. This function will tell the subgraph * to start ingesting events from the DAO's contracts. * NOTE: This function should be called as early as possible in the DAO deployment * process. **Smart Contract Events that are emitted from blocks prior to this function's * event being emitted WILL NOT be ingested into the subgraph**, leading to an incorrect * cache. If this happens to you, please contact the subgraph maintainer. Your DAO will * need to be added to the subgraph's startup config, and the cache will need to be rebuilt. * @param _avatar the organization avatar * @param _controller the organization controller */ function track(Avatar _avatar, Controller _controller, string memory _arcVersion) public onlyAvatarOwner(_avatar) notBlacklisted(_avatar) { // Only allow the information to be set once. In the case of a controller upgrades, // the subgraph will be updated via the UpgradeController event. require(_avatar != Avatar(0)); require(_controller != Controller(0)); emit TrackDAO( address(_avatar), address(_controller), address(_avatar.nativeReputation()), address(_avatar.nativeToken()), msg.sender, _arcVersion ); } /** * @dev blacklist a DAO from the cache. This should be callable by maintainer of the cache. * Blacklisting can be used to defend against DoS attacks, or to remove spam. In order * for this blacklisting to take affect within the cache, it would need to be rebuilt. * @param _avatar the organization avatar * @param _explanationHash A hash of a document explaining why this DAO was blacklisted */ function blacklist(Avatar _avatar, string memory _explanationHash) public onlyOwner { require(_avatar != Avatar(0)); blacklisted[address(_avatar)] = true; emit BlacklistDAO(address(_avatar), _explanationHash); } /** * @dev reset a DAO in the cache. This should be callable by the maintainer of the cache. * @param _avatar the organization avatar * @param _explanationHash A hash of a document explaining why this DAO was reset */ function reset(Avatar _avatar, string memory _explanationHash) public onlyOwner { require(_avatar != Avatar(0)); blacklisted[address(_avatar)] = false; emit ResetDAO(address(_avatar), _explanationHash); } }
contract DAOTracker is Ownable { // `blacklist` the DAO from the subgraph's cache. // Only able to be set by the owner of the DAOTracker. mapping(address=>bool) public blacklisted; event TrackDAO( address indexed _avatar, address _controller, address _reputation, address _daoToken, address _sender, string _arcVersion ); event BlacklistDAO( address indexed _avatar, string _explanationHash ); event ResetDAO( address indexed _avatar, string _explanationHash ); modifier onlyAvatarOwner(Avatar avatar) { require(avatar.owner() == msg.sender, "The caller must be the owner of the Avatar."); _; } modifier notBlacklisted(Avatar avatar) { require(blacklisted[address(avatar)] == false, "The avatar has been blacklisted."); _; } /** * @dev track a new organization. This function will tell the subgraph * to start ingesting events from the DAO's contracts. * NOTE: This function should be called as early as possible in the DAO deployment * process. **Smart Contract Events that are emitted from blocks prior to this function's * event being emitted WILL NOT be ingested into the subgraph**, leading to an incorrect * cache. If this happens to you, please contact the subgraph maintainer. Your DAO will * need to be added to the subgraph's startup config, and the cache will need to be rebuilt. * @param _avatar the organization avatar * @param _controller the organization controller */ function track(Avatar _avatar, Controller _controller, string memory _arcVersion) public onlyAvatarOwner(_avatar) notBlacklisted(_avatar) { // Only allow the information to be set once. In the case of a controller upgrades, // the subgraph will be updated via the UpgradeController event. require(_avatar != Avatar(0)); require(_controller != Controller(0)); emit TrackDAO( address(_avatar), address(_controller), address(_avatar.nativeReputation()), address(_avatar.nativeToken()), msg.sender, _arcVersion ); } /** * @dev blacklist a DAO from the cache. This should be callable by maintainer of the cache. * Blacklisting can be used to defend against DoS attacks, or to remove spam. In order * for this blacklisting to take affect within the cache, it would need to be rebuilt. * @param _avatar the organization avatar * @param _explanationHash A hash of a document explaining why this DAO was blacklisted */ function blacklist(Avatar _avatar, string memory _explanationHash) public onlyOwner { require(_avatar != Avatar(0)); blacklisted[address(_avatar)] = true; emit BlacklistDAO(address(_avatar), _explanationHash); } /** * @dev reset a DAO in the cache. This should be callable by the maintainer of the cache. * @param _avatar the organization avatar * @param _explanationHash A hash of a document explaining why this DAO was reset */ function reset(Avatar _avatar, string memory _explanationHash) public onlyOwner { require(_avatar != Avatar(0)); blacklisted[address(_avatar)] = false; emit ResetDAO(address(_avatar), _explanationHash); } }
38,586
18
// Use this to adjust the threshold at which running a debt causes a harvest trigger. See `setDebtThreshold()` for more details.
uint256 public debtThreshold = 0;
uint256 public debtThreshold = 0;
2,554
269
// Admin can set start and end time through this function. _startTime Auction start time. _endTime Auction end time. /
function setAuctionTime(uint256 _startTime, uint256 _endTime) external { require(hasAdminRole(msg.sender)); require(_startTime < 10000000000, "DutchAuction: enter an unix timestamp in seconds, not miliseconds"); require(_endTime < 10000000000, "DutchAuction: enter an unix timestamp in seconds, not miliseconds"); require(_startTime >= block.timestamp, "DutchAuction: start time is before current time"); require(_endTime > _startTime, "DutchAuction: end time must be older than start time"); require(marketStatus.commitmentsTotal == 0, "DutchAuction: auction cannot have already started"); marketInfo.startTime = BoringMath.to64(_startTime); marketInfo.endTime = BoringMath.to64(_endTime); emit AuctionTimeUpdated(_startTime,_endTime); }
function setAuctionTime(uint256 _startTime, uint256 _endTime) external { require(hasAdminRole(msg.sender)); require(_startTime < 10000000000, "DutchAuction: enter an unix timestamp in seconds, not miliseconds"); require(_endTime < 10000000000, "DutchAuction: enter an unix timestamp in seconds, not miliseconds"); require(_startTime >= block.timestamp, "DutchAuction: start time is before current time"); require(_endTime > _startTime, "DutchAuction: end time must be older than start time"); require(marketStatus.commitmentsTotal == 0, "DutchAuction: auction cannot have already started"); marketInfo.startTime = BoringMath.to64(_startTime); marketInfo.endTime = BoringMath.to64(_endTime); emit AuctionTimeUpdated(_startTime,_endTime); }
29,123
19
// Set allowance for other address Allows `_spender` to spend no more than `_value` tokens on your behalf_spender The address authorized to spend _value the max amount they can spend /
function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; }
function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; }
36,893
4
// Read the status of [addr]
function readAllowList(address addr) external view returns (uint256);
function readAllowList(address addr) external view returns (uint256);
35,247
17
// wallet
bytes32 public constant TEAM = bytes32('team'); bytes32 public constant SPARE = bytes32('spare'); bytes32 public constant REWARD = bytes32('reward');
bytes32 public constant TEAM = bytes32('team'); bytes32 public constant SPARE = bytes32('spare'); bytes32 public constant REWARD = bytes32('reward');
10,962
1
// struct
struct CardData{ string name; uint256 rank; uint256 level; }
struct CardData{ string name; uint256 rank; uint256 level; }
27,115
66
// SPDX-License-Identifier: MIT// Publius LP Silo/
contract LPSilo is SiloEntrance { struct WithdrawState { uint256 newLP; uint256 beansAdded; uint256 beansTransferred; uint256 beansRemoved; uint256 stalkRemoved; uint256 i; } using SafeMath for uint256; using SafeMath for uint32; event LPDeposit(address indexed account, uint256 season, uint256 lp, uint256 seeds); event LPRemove(address indexed account, uint32[] crates, uint256[] crateLP, uint256 lp); event LPWithdraw(address indexed account, uint256 season, uint256 lp); /** * Getters **/ function totalDepositedLP() public view returns (uint256) { return s.lp.deposited; } function totalWithdrawnLP() public view returns (uint256) { return s.lp.withdrawn; } function lpDeposit(address account, uint32 id) public view returns (uint256, uint256) { return (s.a[account].lp.deposits[id], s.a[account].lp.depositSeeds[id]); } function lpWithdrawal(address account, uint32 i) public view returns (uint256) { return s.a[account].lp.withdrawals[i]; } /** * Internal **/ function _depositLP(uint256 amount, uint32 _s) internal { updateSilo(msg.sender); uint256 lpb = lpToLPBeans(amount); require(lpb > 0, "Silo: No Beans under LP."); incrementDepositedLP(amount); uint256 seeds = lpb.mul(C.getSeedsPerLPBean()); if (season() == _s) depositSiloAssets(msg.sender, seeds, lpb.mul(10000)); else depositSiloAssets(msg.sender, seeds, lpb.mul(10000).add(season().sub(_s).mul(seeds))); addLPDeposit(msg.sender, _s, amount, lpb.mul(C.getSeedsPerLPBean())); LibCheck.lpBalanceCheck(); } function _withdrawLP(uint32[] calldata crates, uint256[] calldata amounts) internal { updateSilo(msg.sender); require(crates.length == amounts.length, "Silo: Crates, amounts are diff lengths."); ( uint256 lpRemoved, uint256 stalkRemoved, uint256 seedsRemoved ) = removeLPDeposits(crates, amounts); uint32 arrivalSeason = season() + C.getSiloWithdrawSeasons(); addLPWithdrawal(msg.sender, arrivalSeason, lpRemoved); decrementDepositedLP(lpRemoved); withdrawSiloAssets(msg.sender, seedsRemoved, stalkRemoved); updateBalanceOfRainStalk(msg.sender); LibCheck.lpBalanceCheck(); } function incrementDepositedLP(uint256 amount) private { s.lp.deposited = s.lp.deposited.add(amount); } function decrementDepositedLP(uint256 amount) private { s.lp.deposited = s.lp.deposited.sub(amount); } function addLPDeposit(address account, uint32 _s, uint256 amount, uint256 seeds) private { s.a[account].lp.deposits[_s] += amount; s.a[account].lp.depositSeeds[_s] += seeds; emit LPDeposit(msg.sender, _s, amount, seeds); } function removeLPDeposits(uint32[] calldata crates, uint256[] calldata amounts) private returns (uint256 lpRemoved, uint256 stalkRemoved, uint256 seedsRemoved) { for (uint256 i = 0; i < crates.length; i++) { (uint256 crateBeans, uint256 crateSeeds) = removeLPDeposit( msg.sender, crates[i], amounts[i] ); lpRemoved = lpRemoved.add(crateBeans); stalkRemoved = stalkRemoved.add(crateSeeds.mul(C.getStalkPerLPSeed()).add( stalkReward(crateSeeds, season()-crates[i])) ); seedsRemoved = seedsRemoved.add(crateSeeds); } emit LPRemove(msg.sender, crates, amounts, lpRemoved); } function removeLPDeposit(address account, uint32 id, uint256 amount) private returns (uint256, uint256) { require(id <= season(), "Silo: Future crate."); (uint256 crateAmount, uint256 crateBase) = lpDeposit(account, id); require(crateAmount >= amount, "Silo: Crate balance too low."); require(crateAmount > 0, "Silo: Crate empty."); if (amount < crateAmount) { uint256 base = amount.mul(crateBase).div(crateAmount); s.a[account].lp.deposits[id] -= amount; s.a[account].lp.depositSeeds[id] -= base; return (amount, base); } else { delete s.a[account].lp.deposits[id]; delete s.a[account].lp.depositSeeds[id]; return (crateAmount, crateBase); } } function addLPWithdrawal(address account, uint32 arrivalSeason, uint256 amount) private { s.a[account].lp.withdrawals[arrivalSeason] = s.a[account].lp.withdrawals[arrivalSeason].add(amount); s.lp.withdrawn = s.lp.withdrawn.add(amount); emit LPWithdraw(msg.sender, arrivalSeason, amount); } }
contract LPSilo is SiloEntrance { struct WithdrawState { uint256 newLP; uint256 beansAdded; uint256 beansTransferred; uint256 beansRemoved; uint256 stalkRemoved; uint256 i; } using SafeMath for uint256; using SafeMath for uint32; event LPDeposit(address indexed account, uint256 season, uint256 lp, uint256 seeds); event LPRemove(address indexed account, uint32[] crates, uint256[] crateLP, uint256 lp); event LPWithdraw(address indexed account, uint256 season, uint256 lp); /** * Getters **/ function totalDepositedLP() public view returns (uint256) { return s.lp.deposited; } function totalWithdrawnLP() public view returns (uint256) { return s.lp.withdrawn; } function lpDeposit(address account, uint32 id) public view returns (uint256, uint256) { return (s.a[account].lp.deposits[id], s.a[account].lp.depositSeeds[id]); } function lpWithdrawal(address account, uint32 i) public view returns (uint256) { return s.a[account].lp.withdrawals[i]; } /** * Internal **/ function _depositLP(uint256 amount, uint32 _s) internal { updateSilo(msg.sender); uint256 lpb = lpToLPBeans(amount); require(lpb > 0, "Silo: No Beans under LP."); incrementDepositedLP(amount); uint256 seeds = lpb.mul(C.getSeedsPerLPBean()); if (season() == _s) depositSiloAssets(msg.sender, seeds, lpb.mul(10000)); else depositSiloAssets(msg.sender, seeds, lpb.mul(10000).add(season().sub(_s).mul(seeds))); addLPDeposit(msg.sender, _s, amount, lpb.mul(C.getSeedsPerLPBean())); LibCheck.lpBalanceCheck(); } function _withdrawLP(uint32[] calldata crates, uint256[] calldata amounts) internal { updateSilo(msg.sender); require(crates.length == amounts.length, "Silo: Crates, amounts are diff lengths."); ( uint256 lpRemoved, uint256 stalkRemoved, uint256 seedsRemoved ) = removeLPDeposits(crates, amounts); uint32 arrivalSeason = season() + C.getSiloWithdrawSeasons(); addLPWithdrawal(msg.sender, arrivalSeason, lpRemoved); decrementDepositedLP(lpRemoved); withdrawSiloAssets(msg.sender, seedsRemoved, stalkRemoved); updateBalanceOfRainStalk(msg.sender); LibCheck.lpBalanceCheck(); } function incrementDepositedLP(uint256 amount) private { s.lp.deposited = s.lp.deposited.add(amount); } function decrementDepositedLP(uint256 amount) private { s.lp.deposited = s.lp.deposited.sub(amount); } function addLPDeposit(address account, uint32 _s, uint256 amount, uint256 seeds) private { s.a[account].lp.deposits[_s] += amount; s.a[account].lp.depositSeeds[_s] += seeds; emit LPDeposit(msg.sender, _s, amount, seeds); } function removeLPDeposits(uint32[] calldata crates, uint256[] calldata amounts) private returns (uint256 lpRemoved, uint256 stalkRemoved, uint256 seedsRemoved) { for (uint256 i = 0; i < crates.length; i++) { (uint256 crateBeans, uint256 crateSeeds) = removeLPDeposit( msg.sender, crates[i], amounts[i] ); lpRemoved = lpRemoved.add(crateBeans); stalkRemoved = stalkRemoved.add(crateSeeds.mul(C.getStalkPerLPSeed()).add( stalkReward(crateSeeds, season()-crates[i])) ); seedsRemoved = seedsRemoved.add(crateSeeds); } emit LPRemove(msg.sender, crates, amounts, lpRemoved); } function removeLPDeposit(address account, uint32 id, uint256 amount) private returns (uint256, uint256) { require(id <= season(), "Silo: Future crate."); (uint256 crateAmount, uint256 crateBase) = lpDeposit(account, id); require(crateAmount >= amount, "Silo: Crate balance too low."); require(crateAmount > 0, "Silo: Crate empty."); if (amount < crateAmount) { uint256 base = amount.mul(crateBase).div(crateAmount); s.a[account].lp.deposits[id] -= amount; s.a[account].lp.depositSeeds[id] -= base; return (amount, base); } else { delete s.a[account].lp.deposits[id]; delete s.a[account].lp.depositSeeds[id]; return (crateAmount, crateBase); } } function addLPWithdrawal(address account, uint32 arrivalSeason, uint256 amount) private { s.a[account].lp.withdrawals[arrivalSeason] = s.a[account].lp.withdrawals[arrivalSeason].add(amount); s.lp.withdrawn = s.lp.withdrawn.add(amount); emit LPWithdraw(msg.sender, arrivalSeason, amount); } }
22,109
36
// Storage of strategies and templates
contract Subscriptions is StrategyData { DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); string public constant ERR_EMPTY_STRATEGY = "Strategy does not exist"; string public constant ERR_SENDER_NOT_OWNER = "Sender is not strategy owner"; string public constant ERR_USER_POS_EMPTY = "No user positions"; /// @dev The order of strategies might change as they are deleted Strategy[] public strategies; /// @dev Templates are fixed and are non removable Template[] public templates; /// @dev Keeps track of all the users strategies (their indexes in the array) mapping (address => uint[]) public usersPos; /// @dev Increments on state change, used for easier off chain tracking of changes uint public updateCounter; /// @notice Creates a new strategy with an existing template /// @param _templateId Id of the template used for strategy /// @param _active If the strategy is turned on at the start /// @param _subData Subscription data for actions /// @param _triggerData Subscription data for triggers function createStrategy( uint _templateId, bool _active, bytes[][] memory _subData, bytes[][] memory _triggerData ) public returns (uint) { strategies.push( Strategy({ templateId: _templateId, proxy: msg.sender, active: _active, subData: _subData, triggerData: _triggerData, posInUserArr: (usersPos[msg.sender].length - 1) }) ); usersPos[msg.sender].push(strategies.length - 1); updateCounter++; logger.Log(address(this), msg.sender, "CreateStrategy", abi.encode(strategies.length - 1)); return strategies.length - 1; } /// @notice Creates a new template to use in strategies /// @dev Templates once created can't be changed /// @param _name Name of template, used mainly for logging /// @param _triggerIds Array of trigger ids which translate to trigger addresses /// @param _actionIds Array of actions ids which translate to action addresses /// @param _paramMapping Array that holds metadata of how inputs are mapped to sub/return data function createTemplate( string memory _name, bytes32[] memory _triggerIds, bytes32[] memory _actionIds, uint8[][] memory _paramMapping ) public returns (uint) { templates.push( Template({ name: _name, triggerIds: _triggerIds, actionIds: _actionIds, paramMapping: _paramMapping }) ); updateCounter++; logger.Log(address(this), msg.sender, "CreateTemplate", abi.encode(templates.length - 1)); return templates.length - 1; } /// @notice Updates the users strategy /// @dev Only callable by proxy who created the strategy /// @param _startegyId Id of the strategy to update /// @param _templateId Id of the template used for strategy /// @param _active If the strategy is turned on at the start /// @param _subData Subscription data for actions /// @param _triggerData Subscription data for triggers function updateStrategy( uint _startegyId, uint _templateId, bool _active, bytes[][] memory _subData, bytes[][] memory _triggerData ) public { Strategy storage s = strategies[_startegyId]; require(s.proxy != address(0), ERR_EMPTY_STRATEGY); require(msg.sender == s.proxy, ERR_SENDER_NOT_OWNER); s.templateId = _templateId; s.active = _active; s.subData = _subData; s.triggerData = _triggerData; updateCounter++; logger.Log(address(this), msg.sender, "UpdateStrategy", abi.encode(_startegyId)); } /// @notice Unsubscribe an existing strategy /// @dev Only callable by proxy who created the strategy /// @param _subId Subscription id function removeStrategy(uint256 _subId) public { Strategy memory s = strategies[_subId]; require(s.proxy != address(0), ERR_EMPTY_STRATEGY); require(msg.sender == s.proxy, ERR_SENDER_NOT_OWNER); uint lastSub = strategies.length - 1; _removeUserPos(msg.sender, s.posInUserArr); strategies[_subId] = strategies[lastSub]; // last strategy put in place of the deleted one strategies.pop(); // delete last strategy, because it moved logger.Log(address(this), msg.sender, "Unsubscribe", abi.encode(_subId)); } function _removeUserPos(address _user, uint _index) internal { require(usersPos[_user].length > 0, ERR_USER_POS_EMPTY); uint lastPos = usersPos[_user].length - 1; usersPos[_user][_index] = usersPos[_user][lastPos]; usersPos[_user].pop(); } ///////////////////// VIEW ONLY FUNCTIONS //////////////////////////// function getTemplateFromStrategy(uint _strategyId) public view returns (Template memory) { uint templateId = strategies[_strategyId].templateId; return templates[templateId]; } function getStrategy(uint _strategyId) public view returns (Strategy memory) { return strategies[_strategyId]; } function getTemplate(uint _templateId) public view returns (Template memory) { return templates[_templateId]; } function getStrategyCount() public view returns (uint256) { return strategies.length; } function getTemplateCount() public view returns (uint256) { return templates.length; } function getStrategies() public view returns (Strategy[] memory) { return strategies; } function getTemplates() public view returns (Template[] memory) { return templates; } function userHasStrategies(address _user) public view returns (bool) { return usersPos[_user].length > 0; } function getUserStrategies(address _user) public view returns (Strategy[] memory) { Strategy[] memory userStrategies = new Strategy[](usersPos[_user].length); for (uint i = 0; i < usersPos[_user].length; ++i) { userStrategies[i] = strategies[usersPos[_user][i]]; } return userStrategies; } function getPaginatedStrategies(uint _page, uint _perPage) public view returns (Strategy[] memory) { Strategy[] memory strategiesPerPage = new Strategy[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; end = (end > strategiesPerPage.length) ? strategiesPerPage.length : end; uint count = 0; for (uint i = start; i < end; i++) { strategiesPerPage[count] = strategies[i]; count++; } return strategiesPerPage; } function getPaginatedTemplates(uint _page, uint _perPage) public view returns (Template[] memory) { Template[] memory templatesPerPage = new Template[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; end = (end > templatesPerPage.length) ? templatesPerPage.length : end; uint count = 0; for (uint i = start; i < end; i++) { templatesPerPage[count] = templates[i]; count++; } return templatesPerPage; } }
contract Subscriptions is StrategyData { DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); string public constant ERR_EMPTY_STRATEGY = "Strategy does not exist"; string public constant ERR_SENDER_NOT_OWNER = "Sender is not strategy owner"; string public constant ERR_USER_POS_EMPTY = "No user positions"; /// @dev The order of strategies might change as they are deleted Strategy[] public strategies; /// @dev Templates are fixed and are non removable Template[] public templates; /// @dev Keeps track of all the users strategies (their indexes in the array) mapping (address => uint[]) public usersPos; /// @dev Increments on state change, used for easier off chain tracking of changes uint public updateCounter; /// @notice Creates a new strategy with an existing template /// @param _templateId Id of the template used for strategy /// @param _active If the strategy is turned on at the start /// @param _subData Subscription data for actions /// @param _triggerData Subscription data for triggers function createStrategy( uint _templateId, bool _active, bytes[][] memory _subData, bytes[][] memory _triggerData ) public returns (uint) { strategies.push( Strategy({ templateId: _templateId, proxy: msg.sender, active: _active, subData: _subData, triggerData: _triggerData, posInUserArr: (usersPos[msg.sender].length - 1) }) ); usersPos[msg.sender].push(strategies.length - 1); updateCounter++; logger.Log(address(this), msg.sender, "CreateStrategy", abi.encode(strategies.length - 1)); return strategies.length - 1; } /// @notice Creates a new template to use in strategies /// @dev Templates once created can't be changed /// @param _name Name of template, used mainly for logging /// @param _triggerIds Array of trigger ids which translate to trigger addresses /// @param _actionIds Array of actions ids which translate to action addresses /// @param _paramMapping Array that holds metadata of how inputs are mapped to sub/return data function createTemplate( string memory _name, bytes32[] memory _triggerIds, bytes32[] memory _actionIds, uint8[][] memory _paramMapping ) public returns (uint) { templates.push( Template({ name: _name, triggerIds: _triggerIds, actionIds: _actionIds, paramMapping: _paramMapping }) ); updateCounter++; logger.Log(address(this), msg.sender, "CreateTemplate", abi.encode(templates.length - 1)); return templates.length - 1; } /// @notice Updates the users strategy /// @dev Only callable by proxy who created the strategy /// @param _startegyId Id of the strategy to update /// @param _templateId Id of the template used for strategy /// @param _active If the strategy is turned on at the start /// @param _subData Subscription data for actions /// @param _triggerData Subscription data for triggers function updateStrategy( uint _startegyId, uint _templateId, bool _active, bytes[][] memory _subData, bytes[][] memory _triggerData ) public { Strategy storage s = strategies[_startegyId]; require(s.proxy != address(0), ERR_EMPTY_STRATEGY); require(msg.sender == s.proxy, ERR_SENDER_NOT_OWNER); s.templateId = _templateId; s.active = _active; s.subData = _subData; s.triggerData = _triggerData; updateCounter++; logger.Log(address(this), msg.sender, "UpdateStrategy", abi.encode(_startegyId)); } /// @notice Unsubscribe an existing strategy /// @dev Only callable by proxy who created the strategy /// @param _subId Subscription id function removeStrategy(uint256 _subId) public { Strategy memory s = strategies[_subId]; require(s.proxy != address(0), ERR_EMPTY_STRATEGY); require(msg.sender == s.proxy, ERR_SENDER_NOT_OWNER); uint lastSub = strategies.length - 1; _removeUserPos(msg.sender, s.posInUserArr); strategies[_subId] = strategies[lastSub]; // last strategy put in place of the deleted one strategies.pop(); // delete last strategy, because it moved logger.Log(address(this), msg.sender, "Unsubscribe", abi.encode(_subId)); } function _removeUserPos(address _user, uint _index) internal { require(usersPos[_user].length > 0, ERR_USER_POS_EMPTY); uint lastPos = usersPos[_user].length - 1; usersPos[_user][_index] = usersPos[_user][lastPos]; usersPos[_user].pop(); } ///////////////////// VIEW ONLY FUNCTIONS //////////////////////////// function getTemplateFromStrategy(uint _strategyId) public view returns (Template memory) { uint templateId = strategies[_strategyId].templateId; return templates[templateId]; } function getStrategy(uint _strategyId) public view returns (Strategy memory) { return strategies[_strategyId]; } function getTemplate(uint _templateId) public view returns (Template memory) { return templates[_templateId]; } function getStrategyCount() public view returns (uint256) { return strategies.length; } function getTemplateCount() public view returns (uint256) { return templates.length; } function getStrategies() public view returns (Strategy[] memory) { return strategies; } function getTemplates() public view returns (Template[] memory) { return templates; } function userHasStrategies(address _user) public view returns (bool) { return usersPos[_user].length > 0; } function getUserStrategies(address _user) public view returns (Strategy[] memory) { Strategy[] memory userStrategies = new Strategy[](usersPos[_user].length); for (uint i = 0; i < usersPos[_user].length; ++i) { userStrategies[i] = strategies[usersPos[_user][i]]; } return userStrategies; } function getPaginatedStrategies(uint _page, uint _perPage) public view returns (Strategy[] memory) { Strategy[] memory strategiesPerPage = new Strategy[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; end = (end > strategiesPerPage.length) ? strategiesPerPage.length : end; uint count = 0; for (uint i = start; i < end; i++) { strategiesPerPage[count] = strategies[i]; count++; } return strategiesPerPage; } function getPaginatedTemplates(uint _page, uint _perPage) public view returns (Template[] memory) { Template[] memory templatesPerPage = new Template[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; end = (end > templatesPerPage.length) ? templatesPerPage.length : end; uint count = 0; for (uint i = start; i < end; i++) { templatesPerPage[count] = templates[i]; count++; } return templatesPerPage; } }
11,527
455
// Settle a balance while applying a decrease. /
function _decreaseCurrentAndNextBalances( address maybeStaker, bool isActiveBalance, uint256 amount ) private returns (uint256)
function _decreaseCurrentAndNextBalances( address maybeStaker, bool isActiveBalance, uint256 amount ) private returns (uint256)
30,111
81
// Artist percentage calc
uint256 artistAmount = _distributeArtistFunds(totalAmount, tokenId); uint256 previousOwnerProceedsFromSale = totalAmount.sub(wildcardsAmount).sub(artistAmount); if ( totalPatronOwnedTokenCost[tokenPatron] == price[tokenId].mul(patronageNumerator[tokenId]) ) { previousOwnerProceedsFromSale = previousOwnerProceedsFromSale.add( deposit[tokenPatron]
uint256 artistAmount = _distributeArtistFunds(totalAmount, tokenId); uint256 previousOwnerProceedsFromSale = totalAmount.sub(wildcardsAmount).sub(artistAmount); if ( totalPatronOwnedTokenCost[tokenPatron] == price[tokenId].mul(patronageNumerator[tokenId]) ) { previousOwnerProceedsFromSale = previousOwnerProceedsFromSale.add( deposit[tokenPatron]
3,301
14
// Inserts a 31 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returnsthe new word. Assumes `value` can be represented using 31 bits. /
function insertUint31( bytes32 word, uint256 value, uint256 offset
function insertUint31( bytes32 word, uint256 value, uint256 offset
21,921
337
// UniV3 Swap extends libraries/libraries
library UniV3SwapExtends { using Path for bytes; using SafeMath for uint256; using SafeMathExtends for uint256; //x96 uint256 constant internal x96 = 2 ** 96; //fee denominator uint256 constant internal denominator = 1000000; //Swap Router ISwapRouter constant internal SRT = ISwapRouter(0xE592427A0AEce92De3Edee1F18E0157C05861564); /// @notice Estimated to obtain the target token amount /// @dev Only allow the asset transaction path that has been set to be estimated /// @param self Mapping path /// @param from Source token address /// @param to Target token address /// @param amountIn Source token amount /// @return amountOut Target token amount function estimateAmountOut( mapping(address => mapping(address => bytes)) storage self, address from, address to, uint256 amountIn ) internal view returns (uint256 amountOut){ if (amountIn == 0) {return 0;} bytes memory path = self[from][to]; amountOut = amountIn; while (true) { (address fromToken, address toToken, uint24 fee) = path.getFirstPool().decodeFirstPool(); address _pool = PoolAddress.getPool(fromToken, toToken, fee); (uint160 sqrtPriceX96,,,,,,) = IUniswapV3Pool(_pool).slot0(); address token0 = fromToken < toToken ? fromToken : toToken; amountOut = amountOut.mul(denominator.sub(uint256(fee))).div(denominator); if (token0 == toToken) { amountOut = amountOut.sqrt().mul(x96).div(sqrtPriceX96) ** 2; } else { amountOut = amountOut.sqrt().mul(sqrtPriceX96).div(x96) ** 2; } bool hasMultiplePools = path.hasMultiplePools(); if (hasMultiplePools) { path = path.skipToken(); } else { break; } } } /// @notice Estimate the amount of source tokens that need to be provided /// @dev Only allow the governance identity to set the underlying asset token address /// @param self Mapping path /// @param from Source token address /// @param to Target token address /// @param amountOut Expected target token amount /// @return amountIn Source token amount function estimateAmountIn( mapping(address => mapping(address => bytes)) storage self, address from, address to, uint256 amountOut ) internal view returns (uint256 amountIn){ if (amountOut == 0) {return 0;} bytes memory path = self[from][to]; amountIn = amountOut; while (true) { (address fromToken, address toToken, uint24 fee) = path.getFirstPool().decodeFirstPool(); address _pool = PoolAddress.getPool(fromToken, toToken, fee); (uint160 sqrtPriceX96,,,,,,) = IUniswapV3Pool(_pool).slot0(); address token0 = fromToken < toToken ? fromToken : toToken; if (token0 == toToken) { amountIn = amountIn.sqrt().mul(sqrtPriceX96).div(x96) ** 2; } else { amountIn = amountIn.sqrt().mul(x96).div(sqrtPriceX96) ** 2; } amountIn = amountIn.mul(denominator).div(denominator.sub(uint256(fee))); bool hasMultiplePools = path.hasMultiplePools(); if (hasMultiplePools) { path = path.skipToken(); } else { break; } } } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @dev Initiate a transaction with a known input amount and return the output amount /// @param self Mapping path /// @param from Input token address /// @param to Output token address /// @param amountIn Token in amount /// @param recipient Recipient address /// @param amountOutMinimum Expected to get minimum token out amount /// @return Token out amount function exactInput( mapping(address => mapping(address => bytes)) storage self, address from, address to, uint256 amountIn, address recipient, uint256 amountOutMinimum ) internal returns (uint256){ bytes memory path = self[from][to]; return SRT.exactInput( ISwapRouter.ExactInputParams({ path : path, recipient : recipient, deadline : block.timestamp, amountIn : amountIn, amountOutMinimum : amountOutMinimum })); } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @dev Initiate a transaction with a known output amount and return the input amount /// @param self Mapping path /// @param from Input token address /// @param to Output token address /// @param recipient Recipient address /// @param amountOut Token out amount /// @param amountInMaximum Expect to input the maximum amount of tokens /// @return Token in amount function exactOutput( mapping(address => mapping(address => bytes)) storage self, address from, address to, address recipient, uint256 amountOut, uint256 amountInMaximum ) internal returns (uint256){ bytes memory path = self[to][from]; return SRT.exactOutput( ISwapRouter.ExactOutputParams({ path : path, recipient : recipient, deadline : block.timestamp, amountOut : amountOut, amountInMaximum : amountInMaximum })); } }
library UniV3SwapExtends { using Path for bytes; using SafeMath for uint256; using SafeMathExtends for uint256; //x96 uint256 constant internal x96 = 2 ** 96; //fee denominator uint256 constant internal denominator = 1000000; //Swap Router ISwapRouter constant internal SRT = ISwapRouter(0xE592427A0AEce92De3Edee1F18E0157C05861564); /// @notice Estimated to obtain the target token amount /// @dev Only allow the asset transaction path that has been set to be estimated /// @param self Mapping path /// @param from Source token address /// @param to Target token address /// @param amountIn Source token amount /// @return amountOut Target token amount function estimateAmountOut( mapping(address => mapping(address => bytes)) storage self, address from, address to, uint256 amountIn ) internal view returns (uint256 amountOut){ if (amountIn == 0) {return 0;} bytes memory path = self[from][to]; amountOut = amountIn; while (true) { (address fromToken, address toToken, uint24 fee) = path.getFirstPool().decodeFirstPool(); address _pool = PoolAddress.getPool(fromToken, toToken, fee); (uint160 sqrtPriceX96,,,,,,) = IUniswapV3Pool(_pool).slot0(); address token0 = fromToken < toToken ? fromToken : toToken; amountOut = amountOut.mul(denominator.sub(uint256(fee))).div(denominator); if (token0 == toToken) { amountOut = amountOut.sqrt().mul(x96).div(sqrtPriceX96) ** 2; } else { amountOut = amountOut.sqrt().mul(sqrtPriceX96).div(x96) ** 2; } bool hasMultiplePools = path.hasMultiplePools(); if (hasMultiplePools) { path = path.skipToken(); } else { break; } } } /// @notice Estimate the amount of source tokens that need to be provided /// @dev Only allow the governance identity to set the underlying asset token address /// @param self Mapping path /// @param from Source token address /// @param to Target token address /// @param amountOut Expected target token amount /// @return amountIn Source token amount function estimateAmountIn( mapping(address => mapping(address => bytes)) storage self, address from, address to, uint256 amountOut ) internal view returns (uint256 amountIn){ if (amountOut == 0) {return 0;} bytes memory path = self[from][to]; amountIn = amountOut; while (true) { (address fromToken, address toToken, uint24 fee) = path.getFirstPool().decodeFirstPool(); address _pool = PoolAddress.getPool(fromToken, toToken, fee); (uint160 sqrtPriceX96,,,,,,) = IUniswapV3Pool(_pool).slot0(); address token0 = fromToken < toToken ? fromToken : toToken; if (token0 == toToken) { amountIn = amountIn.sqrt().mul(sqrtPriceX96).div(x96) ** 2; } else { amountIn = amountIn.sqrt().mul(x96).div(sqrtPriceX96) ** 2; } amountIn = amountIn.mul(denominator).div(denominator.sub(uint256(fee))); bool hasMultiplePools = path.hasMultiplePools(); if (hasMultiplePools) { path = path.skipToken(); } else { break; } } } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @dev Initiate a transaction with a known input amount and return the output amount /// @param self Mapping path /// @param from Input token address /// @param to Output token address /// @param amountIn Token in amount /// @param recipient Recipient address /// @param amountOutMinimum Expected to get minimum token out amount /// @return Token out amount function exactInput( mapping(address => mapping(address => bytes)) storage self, address from, address to, uint256 amountIn, address recipient, uint256 amountOutMinimum ) internal returns (uint256){ bytes memory path = self[from][to]; return SRT.exactInput( ISwapRouter.ExactInputParams({ path : path, recipient : recipient, deadline : block.timestamp, amountIn : amountIn, amountOutMinimum : amountOutMinimum })); } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @dev Initiate a transaction with a known output amount and return the input amount /// @param self Mapping path /// @param from Input token address /// @param to Output token address /// @param recipient Recipient address /// @param amountOut Token out amount /// @param amountInMaximum Expect to input the maximum amount of tokens /// @return Token in amount function exactOutput( mapping(address => mapping(address => bytes)) storage self, address from, address to, address recipient, uint256 amountOut, uint256 amountInMaximum ) internal returns (uint256){ bytes memory path = self[to][from]; return SRT.exactOutput( ISwapRouter.ExactOutputParams({ path : path, recipient : recipient, deadline : block.timestamp, amountOut : amountOut, amountInMaximum : amountInMaximum })); } }
10,633
161
// Get info about the v1 dsec token from its address and check that it exists
SaffronLPTokenInfo memory token_info = saffron_LP_token_info[dsec_token_address]; require(token_info.exists, "balance token lookup failed"); SaffronLPBalanceToken sbt = SaffronLPBalanceToken(dsec_token_address); require(sbt.balanceOf(msg.sender) >= dsec_amount, "insufficient dsec balance");
SaffronLPTokenInfo memory token_info = saffron_LP_token_info[dsec_token_address]; require(token_info.exists, "balance token lookup failed"); SaffronLPBalanceToken sbt = SaffronLPBalanceToken(dsec_token_address); require(sbt.balanceOf(msg.sender) >= dsec_amount, "insufficient dsec balance");
27,480
80
// TODO 180 days
uint64 finalTime = 180 days + maxTime; if (_now > finalTime) { bonusToken = totalSupplyBonus; totalSupplyBonus = 0; }
uint64 finalTime = 180 days + maxTime; if (_now > finalTime) { bonusToken = totalSupplyBonus; totalSupplyBonus = 0; }
54,147
97
// get rewards for an address
function earned(address _account) external view returns(uint256);
function earned(address _account) external view returns(uint256);
22,150
327
// Check if an Update is an Improper Update;if so, slash the Updater and set the contract to FAILED state. An Improper Update is an update building off of the Home's `committedRoot`for which the `_newRoot` does not currently exist in the Home's queue.This would mean that message(s) that were not trulydispatched on Home were falsely included in the signed root. An Improper Update will only be accepted as valid by the ReplicaIf an Improper Update is attempted on Home,the Updater will be slashed immediately.If an Improper Update is submitted to the Replica,it should be relayed to the Home contract using this
function improperUpdate( bytes32 _oldRoot, bytes32 _newRoot, bytes memory _signature
function improperUpdate( bytes32 _oldRoot, bytes32 _newRoot, bytes memory _signature
22,428
0
// If the contract is being run on the test network, then `timerAddress` will be the 0x0 address. Note: this variable should be set on construction and never modified.
address public timerAddress;
address public timerAddress;
14,225
56
// Send Ether to buy tokens/
function() payable public { require(msg.value > 0); buy(msg.sender, msg.value); }
function() payable public { require(msg.value > 0); buy(msg.sender, msg.value); }
29,360
5
// Returns the timestamp at which the data feed was last updated./
function lastUpdated() external view returns (uint256);
function lastUpdated() external view returns (uint256);
15,628
342
// Do zero-burns to poke the Uniswap pools so earned fees are updated
pool.burn(tickLower, tickUpper, 0); (uint256 collect0, uint256 collect1) = pool.collect( address(this), tickLower, tickUpper, type(uint128).max, type(uint128).max );
pool.burn(tickLower, tickUpper, 0); (uint256 collect0, uint256 collect1) = pool.collect( address(this), tickLower, tickUpper, type(uint128).max, type(uint128).max );
32,778
2
// 0x0
bytes32 parentProposalHash,
bytes32 parentProposalHash,
50,609
6
// Internal wrapper function for a closing routewhich returns WETH to the owner in the end. /
function _closingRouteWETH( uint256 _ethAmount, uint256 _totalDebtBalancer, address _caller ) internal
function _closingRouteWETH( uint256 _ethAmount, uint256 _totalDebtBalancer, address _caller ) internal
21,139
15
// DINO contract address
address public nftAddress;
address public nftAddress;
21,426
12
// Computes the number of years between two dates. E.g. 6.54321 years./startDate start date expressed in seconds/endDate end date expressed in seconds/ return number of years between the two dates. Returns 0 if result is negative
function yearsBetween(uint startDate, uint endDate) internal pure returns (int128) { if (startDate == 0 || endDate == 0) { revert IncorrectDates(startDate, endDate); } if (endDate <= startDate) { return 0; } return toYears(endDate - startDate); }
function yearsBetween(uint startDate, uint endDate) internal pure returns (int128) { if (startDate == 0 || endDate == 0) { revert IncorrectDates(startDate, endDate); } if (endDate <= startDate) { return 0; } return toYears(endDate - startDate); }
17,177
23
// Create the new contract
FXB fxb = new FXB({ _symbol: _bondSymbol, _name: _bondName, _maturityTimestamp: _coercedMaturityTimestamp, _fraxErc20: FRAX });
FXB fxb = new FXB({ _symbol: _bondSymbol, _name: _bondName, _maturityTimestamp: _coercedMaturityTimestamp, _fraxErc20: FRAX });
35,377
32
// the creator of the contract is the initial CTO as well
ctoAddress = msg.sender;
ctoAddress = msg.sender;
30,120
59
// Contract initializer. factory Address of the initial factory. data Data to send as msg.data to the implementation to initialize the proxied contract.It should include the signature and the parameters of the function to be called, as described inThis parameter is optional, if no data is given the initialization call to proxied contract will be skipped. /
function initialize(address factory, bytes memory data) public payable { require(_factory() == address(0)); assert(FACTORY_SLOT == bytes32(uint256(keccak256('eip1967.proxy.factory')) - 1)); _setFactory(factory); if(data.length > 0) { (bool success,) = _implementation().delegatecall(data); require(success); } }
function initialize(address factory, bytes memory data) public payable { require(_factory() == address(0)); assert(FACTORY_SLOT == bytes32(uint256(keccak256('eip1967.proxy.factory')) - 1)); _setFactory(factory); if(data.length > 0) { (bool success,) = _implementation().delegatecall(data); require(success); } }
6,558
137
// Returns whether the given address has the permission for the given token/_id The id of the token to check/_address The address of the user to check/_permission The permission to check/ return Whether the user has the permission or not
function hasPermission( uint256 _id, address _address, Permission _permission ) external view returns (bool);
function hasPermission( uint256 _id, address _address, Permission _permission ) external view returns (bool);
61,770
20
// Responsible for access rights to the contract MISOAccessControls public accessControls;
function setContracts( address _tokenFactory, address _market, address _launcher, address _farmFactory
function setContracts( address _tokenFactory, address _market, address _launcher, address _farmFactory
5,782
1
// Only gameAddress can burn Shujinko
address public gameControllerAddress;
address public gameControllerAddress;
41,187
128
// Unstakes seth LP tokens, then redeems them/_vaultProxy The VaultProxy of the calling fund/_actionData Data specific to this action/_assetData Parsed spend assets and incoming assets data for this action
function unstakeAndRedeem( address _vaultProxy, bytes calldata _actionData, bytes calldata _assetData ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _assetData)
function unstakeAndRedeem( address _vaultProxy, bytes calldata _actionData, bytes calldata _assetData ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _assetData)
11,585
85
// get the projected exchange rate of a token to SASH
function getBondExchangeRateTokentoSASH(uint256 amount_in, address[] memory path) view public override returns (uint){ require(path.length == 3); uint256[] memory amounts= getAmountsOut (amount_in, path); uint256 amount_USD_in = amounts[amounts.length-1]; require (amount_USD_in >= 1e18, "Amount must be higher than 1 USD."); uint256 supply_multiplier = IERC20(token_contract[0]).totalSupply()/1e24; uint256 supply_multiplier_power = logX(16,1,supply_multiplier); return(amount_USD_in*1e3/powerX(supply_multiplier_power,105,2)); }
function getBondExchangeRateTokentoSASH(uint256 amount_in, address[] memory path) view public override returns (uint){ require(path.length == 3); uint256[] memory amounts= getAmountsOut (amount_in, path); uint256 amount_USD_in = amounts[amounts.length-1]; require (amount_USD_in >= 1e18, "Amount must be higher than 1 USD."); uint256 supply_multiplier = IERC20(token_contract[0]).totalSupply()/1e24; uint256 supply_multiplier_power = logX(16,1,supply_multiplier); return(amount_USD_in*1e3/powerX(supply_multiplier_power,105,2)); }
15,493
44
// Addition to StandardToken methods. Increase the amount of tokens that an owner allowed to a spender and execute a call with the sent data.approve should be called when allowed[_spender] == 0. To increment allowed value is better to use this function to avoid 2 calls (and wait until the first transaction is mined) From MonolithDAO Token.sol_spender The address which will spend the funds. _addedValue The amount of tokens to increase the allowance by. _data ABI-encoded contract call to call `_spender` address. /
function increaseApprovalAndCall( address _spender, uint _addedValue, bytes _data ) public payable returns (bool)
function increaseApprovalAndCall( address _spender, uint _addedValue, bytes _data ) public payable returns (bool)
19,632
3
// distributes ETH to Liquid Split NFT holders
function withdraw() internal { address[] memory sortedAccounts = getHolders(); uint32[] memory percentAllocations = getPercentAllocations( sortedAccounts ); // atomically deposit funds into split, update recipients to reflect current supercharged NFT holders, // and distribute payoutSplit.transfer(address(this).balance); splitMain.updateAndDistributeETH( payoutSplit, _uniqueAddresses(sortedAccounts), percentAllocations, 0, address(0) ); }
function withdraw() internal { address[] memory sortedAccounts = getHolders(); uint32[] memory percentAllocations = getPercentAllocations( sortedAccounts ); // atomically deposit funds into split, update recipients to reflect current supercharged NFT holders, // and distribute payoutSplit.transfer(address(this).balance); splitMain.updateAndDistributeETH( payoutSplit, _uniqueAddresses(sortedAccounts), percentAllocations, 0, address(0) ); }
22,135
4
// order The order data struct.return Hash of the order. /
function hashOrder(Order memory order) internal pure returns (bytes32 result) { /** * Calculate the following hash in solidity assembly to save gas. * * keccak256( * abi.encodePacked( * bytes32(order.trader), * bytes32(order.relayer), * bytes32(order.baseToken), * bytes32(order.quoteToken), * order.baseTokenAmount, * order.quoteTokenAmount, * order.gasTokenAmount, * order.data * ) * ); */ assembly { result := keccak256(order, 256) } return result; }
function hashOrder(Order memory order) internal pure returns (bytes32 result) { /** * Calculate the following hash in solidity assembly to save gas. * * keccak256( * abi.encodePacked( * bytes32(order.trader), * bytes32(order.relayer), * bytes32(order.baseToken), * bytes32(order.quoteToken), * order.baseTokenAmount, * order.quoteTokenAmount, * order.gasTokenAmount, * order.data * ) * ); */ assembly { result := keccak256(order, 256) } return result; }
33,787
35
// function depositInfo( address sender , address token ) external view returns ( uint depositBalance ,uint depositTotal , uint leftDays ,uint lockedReward , uint freeReward , uint gottedReward ) ;
function MinToken0Deposit() external view returns( uint256 ) ; function MinToken1Deposit() external view returns( uint256 ) ; function RewardToken() external view returns( address ) ; function RewardAmount() external view returns( uint256 ) ; function RewardBeginTime() external view returns( uint256 ) ; function DepositEndTime() external view returns( uint256 ) ; function StakeEndTime() external view returns( uint256 ) ;
function MinToken0Deposit() external view returns( uint256 ) ; function MinToken1Deposit() external view returns( uint256 ) ; function RewardToken() external view returns( address ) ; function RewardAmount() external view returns( uint256 ) ; function RewardBeginTime() external view returns( uint256 ) ; function DepositEndTime() external view returns( uint256 ) ; function StakeEndTime() external view returns( uint256 ) ;
44,594
5
// Throws if one of the provided gas limits is greater then the maximum allowed gas limit in the AMB contract. _length expected length of the _gasLimits array. _gasLimits array of gas limit values to check, should contain exactly _length elements. /
modifier validGasLimits(uint256 _length, uint256[] calldata _gasLimits) { require(_gasLimits.length == _length); uint256 maxGasLimit = bridge.maxGasPerTx(); for (uint256 i = 0; i < _length; i++) { require(_gasLimits[i] <= maxGasLimit); } _; }
modifier validGasLimits(uint256 _length, uint256[] calldata _gasLimits) { require(_gasLimits.length == _length); uint256 maxGasLimit = bridge.maxGasPerTx(); for (uint256 i = 0; i < _length; i++) { require(_gasLimits[i] <= maxGasLimit); } _; }
30,108
220
// Tells whether a signature is seen as valid by this contract through ERC-1271 _hash Arbitrary length data signed on the behalf of address (this) _signature Signature byte array associated with _datareturn The ERC-1271 magic value if the signature is valid /
function isValidSignature(bytes32 _hash, bytes _signature) public view returns (bytes4) { // Short-circuit in case the hash was presigned. Optimization as performing calls // and ecrecover is more expensive than an SLOAD. if (isPresigned[_hash]) { return returnIsValidSignatureMagicNumber(true); } bool isValid; if (designatedSigner == address(0)) { isValid = false; } else { isValid = SignatureValidator.isValidSignature(_hash, designatedSigner, _signature); } return returnIsValidSignatureMagicNumber(isValid); }
function isValidSignature(bytes32 _hash, bytes _signature) public view returns (bytes4) { // Short-circuit in case the hash was presigned. Optimization as performing calls // and ecrecover is more expensive than an SLOAD. if (isPresigned[_hash]) { return returnIsValidSignatureMagicNumber(true); } bool isValid; if (designatedSigner == address(0)) { isValid = false; } else { isValid = SignatureValidator.isValidSignature(_hash, designatedSigner, _signature); } return returnIsValidSignatureMagicNumber(isValid); }
5,634
64
// getBountyArbiter(): Returns the arbiter of the bounty/_bountyId the index of the bounty/ return Returns an address for the arbiter of the bounty
function getBountyArbiter(uint _bountyId) public constant validateBountyArrayIndex(_bountyId) returns (address)
function getBountyArbiter(uint _bountyId) public constant validateBountyArrayIndex(_bountyId) returns (address)
6,847
14
// Balancer uses the ETH to buy tokens back, then sends 4% of tokens to the caller and burns other tokens
uint _locked = balancer.rebalance(callerRewardDivisor); emit Rebalance(_locked);
uint _locked = balancer.rebalance(callerRewardDivisor); emit Rebalance(_locked);
35,568
117
// Deactivates the Allocator. Only the Guardian can call this.Add any logic you need during deactivation, say interactions with Extender or something else, in the virtual method `_deactivate`. Be careful to specifically use the internal or public function depending on what you need. panic should panic logic be executed /
function deactivate(bool panic) public override onlyGuardian { // effects _deactivate(panic); status = AllocatorStatus.OFFLINE; emit AllocatorDeactivated(panic); }
function deactivate(bool panic) public override onlyGuardian { // effects _deactivate(panic); status = AllocatorStatus.OFFLINE; emit AllocatorDeactivated(panic); }
63,702
5
// The amount of tokens to mint
uint256 amount;
uint256 amount;
20,118
4
// Holds all smart vault fee percentages.@custom:member managementFeePct Management fee of the smart vault.@custom:member depositFeePct Deposit fee of the smart vault.@custom:member performanceFeePct Performance fee of the smart vault. /
struct SmartVaultFees { uint16 managementFeePct; uint16 depositFeePct; uint16 performanceFeePct; }
struct SmartVaultFees { uint16 managementFeePct; uint16 depositFeePct; uint16 performanceFeePct; }
30,981
62
// first try to get all shares from receipts
for (uint256 i = 0; i < receiptIds.length; i++) { uint256 receiptId = receiptIds[i]; if (_receiptContract.ownerOf(receiptId) != msg.sender) revert NotReceiptOwner(); uint256 receiptShares = StrategyRouterLib.calculateSharesFromReceipt( receiptId, _currentCycleId, _receiptContract, cycles ); unlockedShares += receiptShares;
for (uint256 i = 0; i < receiptIds.length; i++) { uint256 receiptId = receiptIds[i]; if (_receiptContract.ownerOf(receiptId) != msg.sender) revert NotReceiptOwner(); uint256 receiptShares = StrategyRouterLib.calculateSharesFromReceipt( receiptId, _currentCycleId, _receiptContract, cycles ); unlockedShares += receiptShares;
34,272
16
// Require NFT address = ERC721
_requireIERC721(nftAddress);
_requireIERC721(nftAddress);
15,137
12
// -----
uint256 public totalSupply; uint256 mazl = 10; uint256 vScale = 10000;
uint256 public totalSupply; uint256 mazl = 10; uint256 vScale = 10000;
48,319
163
// There is ongoing vesting request for this account - only reset vesting request
DepositWithdrawalRequest storage request = chain.usersData[acc].transactor.depositWithdrawalRequest; request.exist = false; request.notaryBlock = 0;
DepositWithdrawalRequest storage request = chain.usersData[acc].transactor.depositWithdrawalRequest; request.exist = false; request.notaryBlock = 0;
18,583
110
// recalculate the amount of LINK available for payouts /
function updateAvailableFunds() public
function updateAvailableFunds() public
3,263
21
// Set whether or not we deduct 3% from every transaction. This may only be called by `contractOwner`.
function setDeductTaxes(bool _deductTaxes) public { require(msg.sender == contractOwner, "This function is callable only by the contract owner."); require(_deductTaxes != deductTaxes, "deductTaxes is already that value"); deductTaxes = _deductTaxes; emit SetDeductTaxes(_deductTaxes); }
function setDeductTaxes(bool _deductTaxes) public { require(msg.sender == contractOwner, "This function is callable only by the contract owner."); require(_deductTaxes != deductTaxes, "deductTaxes is already that value"); deductTaxes = _deductTaxes; emit SetDeductTaxes(_deductTaxes); }
42,103
461
// A mapping of the vesting contract mapped by reward token.
mapping(address => address) public rewardVestingsList; address public collector;
mapping(address => address) public rewardVestingsList; address public collector;
78,107
209
// Enables trading for everyone
function SetupEnableTrading() public onlyTeam{ require(tradingEnabled&&whiteListTrading); whiteListTrading=false; }
function SetupEnableTrading() public onlyTeam{ require(tradingEnabled&&whiteListTrading); whiteListTrading=false; }
9,545
45
// call on onERC721Received.
require(EIP721TokenReceiverInterface(_to).onERC721Received(msg.sender, _from, _tokenId, data) == ONERC721RECEIVED_FUNCTION_SIGNATURE);
require(EIP721TokenReceiverInterface(_to).onERC721Received(msg.sender, _from, _tokenId, data) == ONERC721RECEIVED_FUNCTION_SIGNATURE);
50,999
19
// Get whether an action is currently active./actionInfo Data required to create an action./ return Boolean value that is `true` if the action is currently active, `false` otherwise.
function isActionActive(ActionInfo calldata actionInfo) external view returns (bool);
function isActionActive(ActionInfo calldata actionInfo) external view returns (bool);
33,884
0
// Store the last implementation address for each controller + beacon pair.
mapping(address => mapping (address => address)) private _lastImplementation;
mapping(address => mapping (address => address)) private _lastImplementation;
17,523
117
// Utility Public Functions//Retrieves the current cycle (index-1 based).return The current cycle (index-1 based). /
function getCurrentCycle() external view returns (uint16) { return _getCycle(block.timestamp); }
function getCurrentCycle() external view returns (uint16) { return _getCycle(block.timestamp); }
1,845
7
// grant the exchange fWETH spending approval
fWETH.approve(address(exchange), _amount);
fWETH.approve(address(exchange), _amount);
28,859
134
// this function is used to view appointation/_stakerAddress: address of initiater of this PET./_petId: id of PET in staker portfolio./_appointeeAddress: eth wallet address of apointee./ return tells whether this address is a appointee or not
function viewAppointation( address _stakerAddress, uint256 _petId, address _appointeeAddress
function viewAppointation( address _stakerAddress, uint256 _petId, address _appointeeAddress
27,736
2
// solhint-enable var-name-mixedcase
constructor ( address _exchange, address _exchangeV2, address _weth ) public
constructor ( address _exchange, address _exchangeV2, address _weth ) public
17,206
12
// Creator of the proposal
address proposer;
address proposer;
9,098
7
// events
event AddedExempt(address exempted); event RemovedExempt(address exempted); event RemovedTotalExempt(address exempted); event UpdatedExempt(address exempted, bool isValid); event UpdatedTotalExempt(address exempted, bool isValid); event UpdatedReserve(address reserve); event TaxRecordSet(address _addr, uint timestamp, uint balance, uint tax); event UpdatedStartingTaxes(uint[] startingTaxes); event UpdatedThresholds(uint[] thresholds); event InitializedExempts(uint initialized);
event AddedExempt(address exempted); event RemovedExempt(address exempted); event RemovedTotalExempt(address exempted); event UpdatedExempt(address exempted, bool isValid); event UpdatedTotalExempt(address exempted, bool isValid); event UpdatedReserve(address reserve); event TaxRecordSet(address _addr, uint timestamp, uint balance, uint tax); event UpdatedStartingTaxes(uint[] startingTaxes); event UpdatedThresholds(uint[] thresholds); event InitializedExempts(uint initialized);
435
22
// if trade started above but ended below, only penalize amount going below peg
if (initialDeviation == 0) { uint256 amountToPeg = _getAmountToPegARTH(reserveARTH, reserveOther); incentivizedAmount = amount.sub( amountToPeg, 'UniswapIncentive: Underflow' ); }
if (initialDeviation == 0) { uint256 amountToPeg = _getAmountToPegARTH(reserveARTH, reserveOther); incentivizedAmount = amount.sub( amountToPeg, 'UniswapIncentive: Underflow' ); }
50,961
4
// Handling grey listing
function isGreyListed(address account) public view returns (bool){ return _greyList[account]; }
function isGreyListed(address account) public view returns (bool){ return _greyList[account]; }
1,989
9
// SignedMathHelpers contract is recommended to use only in Shortcuts passed to EnsoWallet Based on OpenZepplin Contracts 4.7.3: /
contract SignedMathHelpers { uint256 public constant VERSION = 1; /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) external pure returns (int256) { return a + b; } /** * @dev Returns the subtraction of two signed integers, reverting on * underflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) external pure returns (int256) { return a - b; } /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) external pure returns (int256) { return a * b; } /** * @dev Returns the integer division of two signed integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(int256 a, int256 b) external pure returns (int256) { return a / b; } /** * @dev Returns the largest of two signed numbers. */ function max(int256 a, int256 b) external pure returns (int256) { return a > b ? a : b; } /** * @dev Returns the smallest of two signed numbers. */ function min(int256 a, int256 b) external pure returns (int256) { return a < b ? a : b; } /** * @dev Returns the average of two signed numbers without overflow. * The result is rounded towards zero. */ function average(int256 a, int256 b) external pure returns (int256) { int256 x = (a & b) + ((a ^ b) >> 1); return x + (int256(uint256(x) >> 255) & (a ^ b)); } /** * @dev Returns the absolute unsigned value of a signed value. */ function abs(int256 n) external pure returns (uint256) { unchecked { return uint256(n >= 0 ? n : -n); } } /** * @dev Returns the results a math operation if a condition is met. Otherwise returns the 'a' value without any modification. */ function conditional(bool condition, bytes4 method, int256 a, int256 b) external view returns (int256) { if (condition) { (bool success, bytes memory n) = address(this).staticcall(abi.encodeWithSelector(method, a, b)); if (success) return abi.decode(n, (int256)); } return a; } }
contract SignedMathHelpers { uint256 public constant VERSION = 1; /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) external pure returns (int256) { return a + b; } /** * @dev Returns the subtraction of two signed integers, reverting on * underflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) external pure returns (int256) { return a - b; } /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) external pure returns (int256) { return a * b; } /** * @dev Returns the integer division of two signed integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(int256 a, int256 b) external pure returns (int256) { return a / b; } /** * @dev Returns the largest of two signed numbers. */ function max(int256 a, int256 b) external pure returns (int256) { return a > b ? a : b; } /** * @dev Returns the smallest of two signed numbers. */ function min(int256 a, int256 b) external pure returns (int256) { return a < b ? a : b; } /** * @dev Returns the average of two signed numbers without overflow. * The result is rounded towards zero. */ function average(int256 a, int256 b) external pure returns (int256) { int256 x = (a & b) + ((a ^ b) >> 1); return x + (int256(uint256(x) >> 255) & (a ^ b)); } /** * @dev Returns the absolute unsigned value of a signed value. */ function abs(int256 n) external pure returns (uint256) { unchecked { return uint256(n >= 0 ? n : -n); } } /** * @dev Returns the results a math operation if a condition is met. Otherwise returns the 'a' value without any modification. */ function conditional(bool condition, bytes4 method, int256 a, int256 b) external view returns (int256) { if (condition) { (bool success, bytes memory n) = address(this).staticcall(abi.encodeWithSelector(method, a, b)); if (success) return abi.decode(n, (int256)); } return a; } }
282
3
// Uniswap V2 factory
address private constant FACTORY = 0xE4A575550C2b460d2307b82dCd7aFe84AD1484dd; address public owner; event Log(string message, uint val);
address private constant FACTORY = 0xE4A575550C2b460d2307b82dCd7aFe84AD1484dd; address public owner; event Log(string message, uint val);
3,205
104
// Get oraclize funding order by order id _orderId oraclize order idreturn beneficiaty address, paid funds amount and bonus amount/
function getOrder(bytes32 _orderId) public view returns(address, uint256, uint256)
function getOrder(bytes32 _orderId) public view returns(address, uint256, uint256)
51,878
70
// Send profits to Treasury
address _tr = getTreasury(); require(_tr.call.value(_profits)()); emit ProfitsSent(now, _tr, _profits);
address _tr = getTreasury(); require(_tr.call.value(_profits)()); emit ProfitsSent(now, _tr, _profits);
82,957
1
// Function interface for the lookup function supported by the off-chain gateway. This function is executed off-chain by the off-chain gateway. name DNS-encoded name to resolve. data ABI-encoded data for the underlying resolution function (e.g. addr(bytes32), text(bytes32,string)).return result ABI-encode result of the lookup.return expires Time at which the signature expires.return sig A signer's signature authenticating the result. /
function resolve(bytes calldata name, bytes calldata data) external view returns ( bytes memory result, uint64 expires, bytes memory sig );
function resolve(bytes calldata name, bytes calldata data) external view returns ( bytes memory result, uint64 expires, bytes memory sig );
31,875
0
// DATA VARIABLES /Blocks all state changes throughout the contract if falsemapping(address=>uint256)memory pay;
mapping(address=>bool) private ra; mapping(address=>uint256) private ib; mapping(address=>bool) private funded; mapping(address=>bool) private praposal; mapping(address=>bool) private votes; mapping(address=>address) private votemap; mapping(address=>uint256) private rv; mapping(address=>uint256) private duepay;
mapping(address=>bool) private ra; mapping(address=>uint256) private ib; mapping(address=>bool) private funded; mapping(address=>bool) private praposal; mapping(address=>bool) private votes; mapping(address=>address) private votemap; mapping(address=>uint256) private rv; mapping(address=>uint256) private duepay;
15,628
54
// Burn 50% token
_for_next_round = dividendRound[currentRoundDividend].totalToken*BURN_TOKEN_PERCENT/100; dividendRound[currentRoundDividend+1].totalToken = _for_next_round; burnFrom(address(this),_for_next_round); burnFrom(devTeam2,_for_next_round*4/6);
_for_next_round = dividendRound[currentRoundDividend].totalToken*BURN_TOKEN_PERCENT/100; dividendRound[currentRoundDividend+1].totalToken = _for_next_round; burnFrom(address(this),_for_next_round); burnFrom(devTeam2,_for_next_round*4/6);
34,175
10
// Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirementon the return value: the return value is optional (but if data is returned, it must not be false). token The token targeted by the call. data The call data (encoded using abi.encode or one of its variants). /
function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require( abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed" ); } }
function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require( abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed" ); } }
7,662
1
// Create campaign function
function createCampaign( address _owner, string memory _title, string memory _description, uint256 _target, uint256 _deadline, string memory _image
function createCampaign( address _owner, string memory _title, string memory _description, uint256 _target, uint256 _deadline, string memory _image
26,845
161
// Staking balance mapping
mapping(address => uint256) public stakingBalance;
mapping(address => uint256) public stakingBalance;
18,581
24
// Owner of contract withdraws funds. At this point Mentaport account will get paid the commision of 97.5%.
* - Emits a {Withdraw} event. */ function withdraw() external nonReentrant onlyOwner { // This will pay Mentaport 2.5% of the initial sale (bool success, ) = payable(_mentaportAccount).call{ value: (address(this).balance * 25) / 1000 }(""); require(success); // This will payout the owner 97.5% of the contract balance. // Do not remove this otherwise you will not be able to withdraw the funds. // ============================================================================= (bool successRest, ) = payable(owner()).call{ value: address(this).balance }(""); require(successRest); emit Withdraw(); }
* - Emits a {Withdraw} event. */ function withdraw() external nonReentrant onlyOwner { // This will pay Mentaport 2.5% of the initial sale (bool success, ) = payable(_mentaportAccount).call{ value: (address(this).balance * 25) / 1000 }(""); require(success); // This will payout the owner 97.5% of the contract balance. // Do not remove this otherwise you will not be able to withdraw the funds. // ============================================================================= (bool successRest, ) = payable(owner()).call{ value: address(this).balance }(""); require(successRest); emit Withdraw(); }
22,419
27
// Shows the ranks parameters/Read-only calls/ Saves gas by not using rank names/Number - Rank number in the ranks array/ return string Name/ string[] Parameters names/ uint32[] Parameters values/ bool - is Changeable?
function showRankOfNumber(uint256 Number) public view returns ( string memory, string[] memory, uint256[] memory, bool )
function showRankOfNumber(uint256 Number) public view returns ( string memory, string[] memory, uint256[] memory, bool )
41,460
7
// Structure representing what to send and where. token Address of the token we are sending. proxy Id representing approved proxy address. param1 Address of the sender or imprint. to Address of the receiver. value Amount of ERC20 or ID of ERC721. /
struct ActionData
struct ActionData
47,341
37
// Used as sanity check by other contracts
bool public isContestContract = true;
bool public isContestContract = true;
44,278
146
// Admin share
adminKeyVault_ = adminKeyVault_.add(_adminAmount);
adminKeyVault_ = adminKeyVault_.add(_adminAmount);
11,411
56
// Give the reciever the sender's balance for this swap
swap_balances[from_swaps[i]][from_swap_user_index].owner = _to;
swap_balances[from_swaps[i]][from_swap_user_index].owner = _to;
27,110
1
// TeamMint
for(uint256 i; i < teamMembersLength; i++){ _safeMint( teamMembers[i], supply + i ); }
for(uint256 i; i < teamMembersLength; i++){ _safeMint( teamMembers[i], supply + i ); }
17,834
16
// add stakeholder
_addStake(target, value); __isStakeholder[target] = true; __totalStakeholders = __totalStakeholders.add(1);
_addStake(target, value); __isStakeholder[target] = true; __totalStakeholders = __totalStakeholders.add(1);
40,690
25
// ERC20 Optional Views
function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8);
function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8);
12,021
73
// Redeem tokens. These tokens are withdrawn from the Owner address.The balance must be enough to cover the redeem or the call will fail. amount Amount of the token to be subtracted from the _totalSupply and the Owner balance.return Operation succeeded. /
function redeem(uint amount) public onlyOwner returns (bool)
function redeem(uint amount) public onlyOwner returns (bool)
53,421
14
// whenPaused() is used if the contract MUST NOT be paused ("unpaused").
modifier whenPaused() { require(paused(), "ERR: Contract is not currently paused."); _; }
modifier whenPaused() { require(paused(), "ERR: Contract is not currently paused."); _; }
38,963
25
// Get the transaction proposal information. platformName a platform name. txid transaction id.return status completion status of proposal.return fromAccount account of to platform.return toAccount account of to platform.return value transfer amount.return voters notarial voters.return weight The weight value of the completed time. /
function getProposal(bytes32 platformName, string txid) external view returns (bool status, address fromAccount, address toAccount, uint value, address[] voters, uint weight);
function getProposal(bytes32 platformName, string txid) external view returns (bool status, address fromAccount, address toAccount, uint value, address[] voters, uint weight);
2,951
6
// int256[] memory timer = new uint256[](numberOfCampaigns);
campaign.timer = [_stage0time,_stage1time,_stage2time,_stage3time]; campaign.profit = 0; campaign.img = _img; numberOfCampaigns++; return numberOfCampaigns - 1;
campaign.timer = [_stage0time,_stage1time,_stage2time,_stage3time]; campaign.profit = 0; campaign.img = _img; numberOfCampaigns++; return numberOfCampaigns - 1;
13,261
30
// Active bets holds a single bet waiting to be settled for each playerThis is used so that the users choice is commited before the block is revealed
mapping (address => betStruct) public activeBets; mapping (address => uint) public numberOfBets;
mapping (address => betStruct) public activeBets; mapping (address => uint) public numberOfBets;
14,624
6
// the optional functions; to access them see {ERC20Detailed}./ Returns the amount of tokens in existence. /
function totalSupply() external view returns (uint256);
function totalSupply() external view returns (uint256);
11
24
// The following function is added to mitigate ERC20 API: An Attack Vector on Approve/TransferFrom Methods
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(addedValue <= balances[msg.sender].sub(allowed[msg.sender][spender]), 'Amount exceeds balance.'); allowed[msg.sender][spender] = allowed[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, allowed[msg.sender][spender].add(addedValue)); return true; }
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(addedValue <= balances[msg.sender].sub(allowed[msg.sender][spender]), 'Amount exceeds balance.'); allowed[msg.sender][spender] = allowed[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, allowed[msg.sender][spender].add(addedValue)); return true; }
70,364
5
// Returns the scaled total supply of the scaled balance token. Represents sum(debt/index)return The scaled total supply /
function scaledTotalSupply() external view returns (uint256);
function scaledTotalSupply() external view returns (uint256);
25,383
96
// The rate is the conversion between wei and the smallest and indivisibletoken unit. So, if you are using a rate of 1 with a ERC20Detailed tokenwith 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK. token Address of the token being sold /
constructor (IERC20 token) Ownable() public { require(address(token) != address(0), "Crowdsale: token is the zero address"); _rates[0xdAC17F958D2ee523a2206206994597C13D831ec7].rate = 2e12; _rates[0xdAC17F958D2ee523a2206206994597C13D831ec7].adapter = 1; _rates[0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48].rate = 2e12; _rates[0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48].adapter = 1; _token = token; }
constructor (IERC20 token) Ownable() public { require(address(token) != address(0), "Crowdsale: token is the zero address"); _rates[0xdAC17F958D2ee523a2206206994597C13D831ec7].rate = 2e12; _rates[0xdAC17F958D2ee523a2206206994597C13D831ec7].adapter = 1; _rates[0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48].rate = 2e12; _rates[0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48].adapter = 1; _token = token; }
39,376