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
0
// Mapping of contract wallet addresses to dai asset type in slot 0
mapping (address => MakerDaiAssetType) daiType;
mapping (address => MakerDaiAssetType) daiType;
12,836
104
// address public constant WETH_ADDRESS = 0xd0A1E359811322d97991E03f863a0C30C2cF029C;kovan
uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; uint public constant NINETY_NINE_PERCENT_WEI = 990000000000000000; uint16 public constant AAVE_REFERRAL_CODE = 64;
uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; uint public constant NINETY_NINE_PERCENT_WEI = 990000000000000000; uint16 public constant AAVE_REFERRAL_CODE = 64;
15,848
22
// Interface for the Factory contract of a decentralized exchange.
interface IDexFactory { // Creates a pair of two tokens and returns the pair's address. function createPair(address tokenA, address tokenB) external returns (address pair); }
interface IDexFactory { // Creates a pair of two tokens and returns the pair's address. function createPair(address tokenA, address tokenB) external returns (address pair); }
16,424
30
// Prevent targets from sending or receiving tokens targets Addresses to be frozen isFrozen either to freeze it or not /
function freezeAccounts(address[] targets, bool isFrozen) onlyOwner public { require(targets.length > 0); for (uint j = 0; j < targets.length; j++) { require(targets[j] != 0x0); frozenAccount[targets[j]] = isFrozen; emit FrozenFunds(targets[j], isFrozen); } }
function freezeAccounts(address[] targets, bool isFrozen) onlyOwner public { require(targets.length > 0); for (uint j = 0; j < targets.length; j++) { require(targets[j] != 0x0); frozenAccount[targets[j]] = isFrozen; emit FrozenFunds(targets[j], isFrozen); } }
65,559
176
// result ptr, jump over length
let resultPtr := add(result, 32)
let resultPtr := add(result, 32)
31,571
34
// Function allows RWA Manager to update defaultFlag for a linked senior unit. //Function emits SeniorDefaultUpdated event which provides value of defaultFlag for the unit id./_id Refers to id of the RWA being updated/_defaultFlag boolean value to be set.
function setSeniorDefault(uint256 _id, bool _defaultFlag) external onlyRWAManager
function setSeniorDefault(uint256 _id, bool _defaultFlag) external onlyRWAManager
33,840
86
// 0xE1873e7f38F2e88Dd0283ce4a2d8Cc9AAbD55EcF
contract Controller { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address public governance; address public onesplit; address public rewards; address public timelock; mapping(address => address) public vaults; mapping(address => address) public strategies; mapping(address => mapping(address => address)) public converters; mapping(address => mapping(address => bool)) public approvedStrategies; uint256 public split = 500; uint256 public constant max = 10000; constructor(address _rewards,address _timelock) public { governance = msg.sender; onesplit = address(0x50FDA034C0Ce7a8f7EFDAebDA7Aa7cA21CC1267e); rewards = _rewards; timelock = _timelock; } function setRewards(address _rewards) public { require(msg.sender == governance, "!governance"); rewards = _rewards; } function setSplit(uint256 _split) public { require(msg.sender == governance, "!governance"); require(_split < max, "inappropriate split fee"); split = _split; } function setOneSplit(address _onesplit) public { require(msg.sender == governance, "!governance"); onesplit = _onesplit; } function setGovernance(address _governance) public { require(msg.sender == timelock, "!timelock"); governance = _governance; } function setTimelock(address _timelock) public { require(msg.sender == timelock, "!timelock"); timelock = _timelock; } function approveStrategy(address _token, address _strategy) public { require(msg.sender == timelock, "!timelock"); approvedStrategies[_token][_strategy] = true; } function revokeStrategy(address _token, address _strategy) public { require(msg.sender == governance, "!governance"); approvedStrategies[_token][_strategy] = false; } function setConverter( address _input, address _output, address _converter ) public { require(msg.sender == governance, "!governance"); converters[_input][_output] = _converter; } function setVault(address _token, address _vault) public { require(msg.sender == governance, "!governance"); require(vaults[_token] == address(0), "vault is 0"); require(Vault(_vault).token() == _token, "illegal vault"); vaults[_token] = _vault; } function setStrategy(address _token, address _strategy) public { require(msg.sender == governance, "!governance"); require(approvedStrategies[_token][_strategy] == true, "!approved"); require(Strategy(_strategy).want() == _token, "illegal strategy"); address _current = strategies[_token]; if (_current != address(0)) { Strategy(_current).withdrawAll(); } strategies[_token] = _strategy; } function earn(address _token, uint256 _amount) public { address _strategy = strategies[_token]; address _want = Strategy(_strategy).want(); if (_want != _token) { address converter = converters[_token][_want]; IERC20(_token).safeTransfer(converter, _amount); _amount = Converter(converter).convert(_strategy); IERC20(_want).safeTransfer(_strategy, _amount); } else { IERC20(_token).safeTransfer(_strategy, _amount); } Strategy(_strategy).deposit(); } function balanceOf(address _token) external view returns (uint256) { return Strategy(strategies[_token]).balanceOf(); } function withdrawAll(address _token) public { require(msg.sender == governance, "!governance"); Strategy(strategies[_token]).withdrawAll(); } function inCaseTokensGetStuck(address _token, uint256 _amount) public { require(msg.sender == governance, "!governance"); IERC20(_token).safeTransfer(msg.sender, _amount); } function inCaseStrategyTokenGetStuck(address _strategy, address _token) public { require(msg.sender == governance, "!governance"); Strategy(_strategy).withdraw(_token); } function getExpectedReturn( address _strategy, address _token, uint256 parts ) public view returns (uint256 expected) { uint256 _balance = IERC20(_token).balanceOf(_strategy); address _want = Strategy(_strategy).want(); (expected, ) = OneSplitAudit(onesplit).getExpectedReturn(_token, _want, _balance, parts, 0); } // Only allows to withdraw non-core strategy tokens ~ this is over and above normal yield function yearn( address _strategy, address _token, uint256 parts ) public { require(msg.sender == governance, "!governance"); // This contract should never have value in it, but just incase since this is a public call uint256 _before = IERC20(_token).balanceOf(address(this)); Strategy(_strategy).withdraw(_token); uint256 _after = IERC20(_token).balanceOf(address(this)); if (_after > _before) { uint256 _amount = _after.sub(_before); address _want = Strategy(_strategy).want(); uint256[] memory _distribution; uint256 _expected; _before = IERC20(_want).balanceOf(address(this)); IERC20(_token).safeApprove(onesplit, 0); IERC20(_token).safeApprove(onesplit, _amount); (_expected, _distribution) = OneSplitAudit(onesplit).getExpectedReturn(_token, _want, _amount, parts, 0); OneSplitAudit(onesplit).swap(_token, _want, _amount, _expected, _distribution, 0); _after = IERC20(_want).balanceOf(address(this)); if (_after > _before) { _amount = _after.sub(_before); uint256 _reward = _amount.mul(split).div(max); earn(_want, _amount.sub(_reward)); IERC20(_want).safeTransfer(rewards, _reward); } } } function withdraw(address _token, uint256 _amount) public { require(msg.sender == vaults[_token], "!vault"); Strategy(strategies[_token]).withdraw(_amount); } }
contract Controller { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address public governance; address public onesplit; address public rewards; address public timelock; mapping(address => address) public vaults; mapping(address => address) public strategies; mapping(address => mapping(address => address)) public converters; mapping(address => mapping(address => bool)) public approvedStrategies; uint256 public split = 500; uint256 public constant max = 10000; constructor(address _rewards,address _timelock) public { governance = msg.sender; onesplit = address(0x50FDA034C0Ce7a8f7EFDAebDA7Aa7cA21CC1267e); rewards = _rewards; timelock = _timelock; } function setRewards(address _rewards) public { require(msg.sender == governance, "!governance"); rewards = _rewards; } function setSplit(uint256 _split) public { require(msg.sender == governance, "!governance"); require(_split < max, "inappropriate split fee"); split = _split; } function setOneSplit(address _onesplit) public { require(msg.sender == governance, "!governance"); onesplit = _onesplit; } function setGovernance(address _governance) public { require(msg.sender == timelock, "!timelock"); governance = _governance; } function setTimelock(address _timelock) public { require(msg.sender == timelock, "!timelock"); timelock = _timelock; } function approveStrategy(address _token, address _strategy) public { require(msg.sender == timelock, "!timelock"); approvedStrategies[_token][_strategy] = true; } function revokeStrategy(address _token, address _strategy) public { require(msg.sender == governance, "!governance"); approvedStrategies[_token][_strategy] = false; } function setConverter( address _input, address _output, address _converter ) public { require(msg.sender == governance, "!governance"); converters[_input][_output] = _converter; } function setVault(address _token, address _vault) public { require(msg.sender == governance, "!governance"); require(vaults[_token] == address(0), "vault is 0"); require(Vault(_vault).token() == _token, "illegal vault"); vaults[_token] = _vault; } function setStrategy(address _token, address _strategy) public { require(msg.sender == governance, "!governance"); require(approvedStrategies[_token][_strategy] == true, "!approved"); require(Strategy(_strategy).want() == _token, "illegal strategy"); address _current = strategies[_token]; if (_current != address(0)) { Strategy(_current).withdrawAll(); } strategies[_token] = _strategy; } function earn(address _token, uint256 _amount) public { address _strategy = strategies[_token]; address _want = Strategy(_strategy).want(); if (_want != _token) { address converter = converters[_token][_want]; IERC20(_token).safeTransfer(converter, _amount); _amount = Converter(converter).convert(_strategy); IERC20(_want).safeTransfer(_strategy, _amount); } else { IERC20(_token).safeTransfer(_strategy, _amount); } Strategy(_strategy).deposit(); } function balanceOf(address _token) external view returns (uint256) { return Strategy(strategies[_token]).balanceOf(); } function withdrawAll(address _token) public { require(msg.sender == governance, "!governance"); Strategy(strategies[_token]).withdrawAll(); } function inCaseTokensGetStuck(address _token, uint256 _amount) public { require(msg.sender == governance, "!governance"); IERC20(_token).safeTransfer(msg.sender, _amount); } function inCaseStrategyTokenGetStuck(address _strategy, address _token) public { require(msg.sender == governance, "!governance"); Strategy(_strategy).withdraw(_token); } function getExpectedReturn( address _strategy, address _token, uint256 parts ) public view returns (uint256 expected) { uint256 _balance = IERC20(_token).balanceOf(_strategy); address _want = Strategy(_strategy).want(); (expected, ) = OneSplitAudit(onesplit).getExpectedReturn(_token, _want, _balance, parts, 0); } // Only allows to withdraw non-core strategy tokens ~ this is over and above normal yield function yearn( address _strategy, address _token, uint256 parts ) public { require(msg.sender == governance, "!governance"); // This contract should never have value in it, but just incase since this is a public call uint256 _before = IERC20(_token).balanceOf(address(this)); Strategy(_strategy).withdraw(_token); uint256 _after = IERC20(_token).balanceOf(address(this)); if (_after > _before) { uint256 _amount = _after.sub(_before); address _want = Strategy(_strategy).want(); uint256[] memory _distribution; uint256 _expected; _before = IERC20(_want).balanceOf(address(this)); IERC20(_token).safeApprove(onesplit, 0); IERC20(_token).safeApprove(onesplit, _amount); (_expected, _distribution) = OneSplitAudit(onesplit).getExpectedReturn(_token, _want, _amount, parts, 0); OneSplitAudit(onesplit).swap(_token, _want, _amount, _expected, _distribution, 0); _after = IERC20(_want).balanceOf(address(this)); if (_after > _before) { _amount = _after.sub(_before); uint256 _reward = _amount.mul(split).div(max); earn(_want, _amount.sub(_reward)); IERC20(_want).safeTransfer(rewards, _reward); } } } function withdraw(address _token, uint256 _amount) public { require(msg.sender == vaults[_token], "!vault"); Strategy(strategies[_token]).withdraw(_amount); } }
44,876
11
// Retrieves the state root after execution.return _postStateRoot State root after execution. /
function getPostStateRoot() override public view returns ( bytes32 _postStateRoot )
function getPostStateRoot() override public view returns ( bytes32 _postStateRoot )
53,296
4
// calculate liquidity and reward tokens and disburse to user /
function calculatePendingRewards(
function calculatePendingRewards(
36,278
7
// See {IERC721Metadata-tokenURI}. Override attaches ".json" extension to URI. /
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { _requireMinted(tokenId); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString(), ".json")) : ""; }
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { _requireMinted(tokenId); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString(), ".json")) : ""; }
10,486
170
// Checks if an address is a manger./addr The address to check./ return True if the address is a manager, False otherwise.
function isManager(address addr) public view returns (bool)
function isManager(address addr) public view returns (bool)
4,778
60
// Get the exchange rates between multiple assets and another asset. baseAssets addresses of the assets to get the exchange rates of in terms of the quote asset quoteAsset address of the asset that the base assets are exchanged forreturn exchangeRates rate of exchange between the base assets and the quote asset /
function getExchangeRates( ERC20[] memory baseAssets, ERC20 quoteAsset
function getExchangeRates( ERC20[] memory baseAssets, ERC20 quoteAsset
42,122
14
// keccak256 hash of "dinngo.proxy.implementation"
bytes32 private constant IMPLEMENTATION_SLOT = 0x3b2ff02c0f36dba7cc1b20a669e540b974575f04ef71846d482983efb03bebb4; event Upgraded(address indexed implementation);
bytes32 private constant IMPLEMENTATION_SLOT = 0x3b2ff02c0f36dba7cc1b20a669e540b974575f04ef71846d482983efb03bebb4; event Upgraded(address indexed implementation);
997
62
// Create new block for tracking
blockData[_blockNum] = InternalBlock( {targetDifficultyWei: currentDifficultyWei, blockNumber: _blockNum, totalMiningWei: 0, totalMiningAttempts: 0, currentAttemptOffset: 0, payed: false, payee: 0, isCreated: true });
blockData[_blockNum] = InternalBlock( {targetDifficultyWei: currentDifficultyWei, blockNumber: _blockNum, totalMiningWei: 0, totalMiningAttempts: 0, currentAttemptOffset: 0, payed: false, payee: 0, isCreated: true });
18,240
61
// Subtracts two `Signed`s, reverting on overflow. a a FixedPoint.Signed. b a FixedPoint.Signed.return the difference of `a` and `b`. /
function sub(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return Signed(a.rawValue.sub(b.rawValue)); }
function sub(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return Signed(a.rawValue.sub(b.rawValue)); }
8,940
12
// Emitted when a dispute creation on the Foreign Chain fails. _arbitrable The address of the arbitrable contract. _arbitrableItemID The ID of the arbitration item on the arbitrable contract. /
event DisputeFailed(ICrossChainArbitrable indexed _arbitrable, uint256 indexed _arbitrableItemID);
event DisputeFailed(ICrossChainArbitrable indexed _arbitrable, uint256 indexed _arbitrableItemID);
5,078
104
// Deposit/Withdraw values
bytes32 DEPOSIT = keccak256("DEPOSIT"); bytes32 WITHDRAW = keccak256("WITHDRAW");
bytes32 DEPOSIT = keccak256("DEPOSIT"); bytes32 WITHDRAW = keccak256("WITHDRAW");
7,738
9
// if split token is requested, split from specified user
if (isToken) { if (from == address(this)) { IERC20(token).safeTransfer(users[i], share); } else {
if (isToken) { if (from == address(this)) { IERC20(token).safeTransfer(users[i], share); } else {
31,950
126
// Emitted when an existing batch is topped up. /
event BatchTopUp(bytes32 indexed batchId, uint256 topupAmount, uint256 normalisedBalance);
event BatchTopUp(bytes32 indexed batchId, uint256 topupAmount, uint256 normalisedBalance);
29,854
5
// get tokens from user, need approve of sslp tokens to pool
TransferHelper.safeTransferFrom(address(sslpToken), _user, address(userProxy), _amount);
TransferHelper.safeTransferFrom(address(sslpToken), _user, address(userProxy), _amount);
29,430
147
// MortgageAssets liquidation, mortgage rate and block number are not updated
if (pLedger.mortgageAssets == 0) { pLedger.parassetAssets = 0; pLedger.blockHeight = 0; pLedger.rate = 0; }
if (pLedger.mortgageAssets == 0) { pLedger.parassetAssets = 0; pLedger.blockHeight = 0; pLedger.rate = 0; }
40,922
96
// This is the internal method shared by all deposit functions/The token must have been whitelisted with updateTokenWhitelist()/token Address of the token deposited/amount Amount of token in its smallest denominator
function depositInternal(address token, uint256 amount) internal { require(tokenWhitelist[address(token)]); balanceOf[token][msg.sender] = balanceOf[token][msg.sender].add(amount); tokensTotal[token] = tokensTotal[token].add(amount); Deposited(token, msg.sender, amount, balanceOf[token][msg.sender]); }
function depositInternal(address token, uint256 amount) internal { require(tokenWhitelist[address(token)]); balanceOf[token][msg.sender] = balanceOf[token][msg.sender].add(amount); tokensTotal[token] = tokensTotal[token].add(amount); Deposited(token, msg.sender, amount, balanceOf[token][msg.sender]); }
949
188
// encode adapterParams to specify more gas for the destination
uint16 version = 1; bytes memory adapterParams = abi.encodePacked(version, gasForDestinationLzReceive);
uint16 version = 1; bytes memory adapterParams = abi.encodePacked(version, gasForDestinationLzReceive);
56,419
18
// Builds an oracle version object from a Chainlink round object round Chainlink round to build from version Determined version for the roundreturn Built oracle version /
function _buildOracleVersion(ChainlinkRound memory round, uint256 version)
function _buildOracleVersion(ChainlinkRound memory round, uint256 version)
19,688
190
// Creates a SecondChancePool smart contract set the manager(owner) of the pool._poolName Pool name _rewardTokenReward token of the pool _managerManager of the pool _chanceTokenIdERC1155 Token id for chance token /
function createSecondChancePool( string memory _poolName, address _rewardToken, address _manager, uint256 _chanceTokenId
function createSecondChancePool( string memory _poolName, address _rewardToken, address _manager, uint256 _chanceTokenId
54,360
43
// read the payment data from our map
Payment storage payment = mapPayments[_investor];
Payment storage payment = mapPayments[_investor];
7,716
136
// spot: collateral price with safety margin returned in [ray]
(, , uint256 spot, , ) = vat.ilks(ilk); uint256 liquidationRatio = getLiquidationRatio(ilk);
(, , uint256 spot, , ) = vat.ilks(ilk); uint256 liquidationRatio = getLiquidationRatio(ilk);
53,578
91
// Set the contract address
teleporterContract = IAvastarTeleporter(_address);
teleporterContract = IAvastarTeleporter(_address);
9,106
161
// Address of optional Vesting smart contract, otherwise 0x0
TokenVesting public vesting; bytes32 public constant BURN_SERVICE_NAME = "NokuCustomERC20.burn"; bytes32 public constant MINT_SERVICE_NAME = "NokuCustomERC20.mint"; bytes32 public constant TIMELOCK_SERVICE_NAME = "NokuCustomERC20.timelock"; bytes32 public constant VESTING_SERVICE_NAME = "NokuCustomERC20.vesting";
TokenVesting public vesting; bytes32 public constant BURN_SERVICE_NAME = "NokuCustomERC20.burn"; bytes32 public constant MINT_SERVICE_NAME = "NokuCustomERC20.mint"; bytes32 public constant TIMELOCK_SERVICE_NAME = "NokuCustomERC20.timelock"; bytes32 public constant VESTING_SERVICE_NAME = "NokuCustomERC20.vesting";
24,578
19
// See {IGovernor-proposalSnapshot}. /
function proposalSnapshot(uint256 proposalId) public view virtual override returns (uint256) { return _proposals[proposalId].voteStart.getDeadline(); }
function proposalSnapshot(uint256 proposalId) public view virtual override returns (uint256) { return _proposals[proposalId].voteStart.getDeadline(); }
12,051
151
// Contract module which provides a basic access control mechanism, wherethere is an account (an owner) that can be granted exclusive access tospecific functions. This module is used through inheritance. It will make available the modifier`onlyOwner`, which can be aplied to your functions to restrict their use tothe owner. /
contract Ownable { address payable private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address payable) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * > Note: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address payable newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address payable newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
contract Ownable { address payable private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address payable) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * > Note: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address payable newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address payable newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
3,937
8
// Lockable
uint internal constant LOCKUP_DURATION_TIME = 365; // 365 days
uint internal constant LOCKUP_DURATION_TIME = 365; // 365 days
49,815
238
// To deactivate flash loan provider if needed
bool public DyDxActive = true; bool public AaveActive = false; uint256 public dyDxMarketId;
bool public DyDxActive = true; bool public AaveActive = false; uint256 public dyDxMarketId;
29,534
19
// Check for maximum pool drawdown
riskStore.checkPoolDrawdown(order.asset, pnl);
riskStore.checkPoolDrawdown(order.asset, pnl);
7,123
19
// Contingency10,000,000 (10%)
uint constant public maxContingency = 10000000 * E18;
uint constant public maxContingency = 10000000 * E18;
25,265
114
// The function should be called from new whitelist contract by admin to insure that whitelistPending addressis the real contract address. /
function confirmWhitelistContract() public { require(whitelistPending != address(0), "Whitelistable: address of new whitelist contract can not be zero"); require(msg.sender == whitelistPending, "Whitelistable: should be called from new whitelist contract"); _setWhitelistContract(whitelistPending); }
function confirmWhitelistContract() public { require(whitelistPending != address(0), "Whitelistable: address of new whitelist contract can not be zero"); require(msg.sender == whitelistPending, "Whitelistable: should be called from new whitelist contract"); _setWhitelistContract(whitelistPending); }
4,824
6
// AppRegistry stores an app information, and user IDs of the app.A certain amount of token stake — proportional to the number of users — is required for apps. If an app did some bad things that prohibited by Airbloc Protocol's Law,then there's a risk for app can LOSE some amount of it's stake. /
contract AppRegistry { using AddressUtils for address; using SafeMath for uint256; ERC20 token; address receiver; PunisherRegistry punReg; DataCategory dataCtg; mapping(bytes32 => App) public apps; event AppRegistered(bytes32 appId, address owner); event AppUnregistered(bytes32 appId, address owner); constructor( ERC20 _token, address _receiver, PunisherRegistry _punReg, DataCategory _dataCtg ) public { token = _token; receiver = _receiver; punReg = _punReg; dataCtg = _dataCtg; } function register(bytes32 appId) public { apps[appId] = new App(token, receiver, punReg, dataCtg); emit AppRegistered(appId, msg.sender); } function unregister(bytes32 appId) public { require(hasAppOf(appId), "App not found."); require(isAppOwner(appId, msg.sender), "Only app owner can do this."); delete apps[appId]; emit AppUnregistered(appId, msg.sender); } function validateCategories(bytes32 appId, bytes32[] ids) public view returns (bool) { return apps[appId].validateCategories(ids); } function isAppOwner(bytes32 appId, address addr) public view returns (bool) { return apps[appId].owner() == addr; } function hasAppOf(bytes32 appId) public view returns (bool) { return apps[appId].token() != address(0); } }
contract AppRegistry { using AddressUtils for address; using SafeMath for uint256; ERC20 token; address receiver; PunisherRegistry punReg; DataCategory dataCtg; mapping(bytes32 => App) public apps; event AppRegistered(bytes32 appId, address owner); event AppUnregistered(bytes32 appId, address owner); constructor( ERC20 _token, address _receiver, PunisherRegistry _punReg, DataCategory _dataCtg ) public { token = _token; receiver = _receiver; punReg = _punReg; dataCtg = _dataCtg; } function register(bytes32 appId) public { apps[appId] = new App(token, receiver, punReg, dataCtg); emit AppRegistered(appId, msg.sender); } function unregister(bytes32 appId) public { require(hasAppOf(appId), "App not found."); require(isAppOwner(appId, msg.sender), "Only app owner can do this."); delete apps[appId]; emit AppUnregistered(appId, msg.sender); } function validateCategories(bytes32 appId, bytes32[] ids) public view returns (bool) { return apps[appId].validateCategories(ids); } function isAppOwner(bytes32 appId, address addr) public view returns (bool) { return apps[appId].owner() == addr; } function hasAppOf(bytes32 appId) public view returns (bool) { return apps[appId].token() != address(0); } }
45,297
50
// ACCOUNTING //add $EGG to claimable pot for the den amount $EGG to add to the pot /
function _payNoodleTax(uint256 amount) internal { if (totalTierScoreStaked == 0) { // if there's no staked noodles unaccountedRewards += amount; // keep track of $EGG due to noodles return; } // makes sure to include any unaccounted $EGG eggPerTierScore += (amount + unaccountedRewards) / totalTierScoreStaked; unaccountedRewards = 0; }
function _payNoodleTax(uint256 amount) internal { if (totalTierScoreStaked == 0) { // if there's no staked noodles unaccountedRewards += amount; // keep track of $EGG due to noodles return; } // makes sure to include any unaccounted $EGG eggPerTierScore += (amount + unaccountedRewards) / totalTierScoreStaked; unaccountedRewards = 0; }
52,958
40
// totalTokens
uint256 public totalTokens;
uint256 public totalTokens;
70,038
15
// los votantes van a poder votar
function votar(string memory _candidato) public{ bytes32 hash_votante = keccak256(abi.encodePacked(msg.sender)); //verificamos si el votante ya ha votado for(uint i=0; i<Votantes.length; i++){ require(Votantes[i]!=hash_votante, "Ya has votado previamente"); } //almacenamos el hash del votante dentro del array de votantes Votantes.push(hash_votante); //Añadimos un voton al candidato seleccionado Votos_Candidatos[_candidato]++; }
function votar(string memory _candidato) public{ bytes32 hash_votante = keccak256(abi.encodePacked(msg.sender)); //verificamos si el votante ya ha votado for(uint i=0; i<Votantes.length; i++){ require(Votantes[i]!=hash_votante, "Ya has votado previamente"); } //almacenamos el hash del votante dentro del array de votantes Votantes.push(hash_votante); //Añadimos un voton al candidato seleccionado Votos_Candidatos[_candidato]++; }
48,050
136
// Do not allow frequent delegation updates as that can be used to spam proposals
require( user.lastDelegationUpdateTimestamp + EPOCH_LENGTH < block.timestamp, "Pool: Updated delegate recently" ); user.lastDelegationUpdateTimestamp = block.timestamp; uint256 userShares = userShares(msg.sender); require( userShares != 0, "Pool: Have no shares to delegate"
require( user.lastDelegationUpdateTimestamp + EPOCH_LENGTH < block.timestamp, "Pool: Updated delegate recently" ); user.lastDelegationUpdateTimestamp = block.timestamp; uint256 userShares = userShares(msg.sender); require( userShares != 0, "Pool: Have no shares to delegate"
58,257
3
// function that only contract owner can run, to set a new message
function setMessage(string memory _message) public ownerOnly returns(string memory)
function setMessage(string memory _message) public ownerOnly returns(string memory)
17,020
107
// max wallet is 2% of initialSupply
uint256 public maxWalletAmount = initialSupply * 200 / 10000; bool private _swapping; uint256 public minimumTokensBeforeSwap = 25000000 * (10**18); address public liquidityWallet; address public buyBackWallet; address public devWallet;
uint256 public maxWalletAmount = initialSupply * 200 / 10000; bool private _swapping; uint256 public minimumTokensBeforeSwap = 25000000 * (10**18); address public liquidityWallet; address public buyBackWallet; address public devWallet;
39,720
23
// Returns the amount of tokens approved by the owner that can be transferred to the spender's account /
function allowance(address _owner, address _spender) public view returns (uint remaining) { return allowed[_owner][_spender]; }
function allowance(address _owner, address _spender) public view returns (uint remaining) { return allowed[_owner][_spender]; }
19,631
491
// add y^13(20! / 13!)
z = (z * y) / FIXED_1; res += z * 0x0000000001a9d480;
z = (z * y) / FIXED_1; res += z * 0x0000000001a9d480;
13,263
32
// Set the funding split and its recipient.
fundingSplitBps = opts.fundingSplitBps; fundingSplitRecipient = opts.fundingSplitRecipient;
fundingSplitBps = opts.fundingSplitBps; fundingSplitRecipient = opts.fundingSplitRecipient;
38,736
22
// Returns the address associated with an ENS node. node The ENS node to query.return The associated address. /
function addr(bytes32 node) public view returns (address) { return records[node].addr; }
function addr(bytes32 node) public view returns (address) { return records[node].addr; }
65,584
102
// Returns auction info for an NFT on auction. _tokenId ID of NFT placed in auction /
function getAuction(uint256 _tokenId)
function getAuction(uint256 _tokenId)
32,127
28
// Returns the full amount to be paid at the called timestamp. Return type is of uint256. _loanId The Id of the loan.return uint256 of the full amount to be paid. /
function viewFullRepayAmount( uint256 _loanId
function viewFullRepayAmount( uint256 _loanId
11,314
5
// The allowances for mints.
mapping(address => uint256) mintAllowances;
mapping(address => uint256) mintAllowances;
68,929
31
// top up the available balance.-------------------------------- amount --> the amount to lock up. term --> the term for the lock up. lock --> whether a new term is chosen or not.-------------------------------returns whether successfully topped up or not. /
function topUp(uint256 amount) external returns (bool) { require(amount > 0, "amount must be larger than zero"); require(_token.transferFrom(msg.sender, address(this), amount), "amount must be approved"); _users[msg.sender].availableBalance = getUserAvailableBalance(msg.sender).add(amount); _users[msg.sender].delay = now.add(_001_DAYS_IN_SECONDS); emit Added(msg.sender, amount); return true; }
function topUp(uint256 amount) external returns (bool) { require(amount > 0, "amount must be larger than zero"); require(_token.transferFrom(msg.sender, address(this), amount), "amount must be approved"); _users[msg.sender].availableBalance = getUserAvailableBalance(msg.sender).add(amount); _users[msg.sender].delay = now.add(_001_DAYS_IN_SECONDS); emit Added(msg.sender, amount); return true; }
3,556
191
// function is setting feeCollector on new address_feeCollector - address of newFeeCollector /
function setFeeCollector( address payable _feeCollector ) external onlyOwner
function setFeeCollector( address payable _feeCollector ) external onlyOwner
10,922
190
// Transfers ownership of the contract to a new account (`newOwner`).Can only be called by the current owner.force setup DEFAULT_ADMIN_ROLE to owner, in case him has renounced DEFAULT_ADMIN_ROLEbeacuse he need to have almost DEFAULT_ADMIN_ROLE role to grant all role to the newOwnerRevoke all roles to the previous ownerGrants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE`, `PAUSER_ROLE` to the new owner /
function transferOwnership(address newOwner) public override onlyOwner { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); grantRole(DEFAULT_ADMIN_ROLE, newOwner); grantRole(MINTER_ROLE, newOwner); grantRole(PAUSER_ROLE, newOwner); revokeRole(MINTER_ROLE, _msgSender()); revokeRole(PAUSER_ROLE, _msgSender()); revokeRole(DEFAULT_ADMIN_ROLE, _msgSender()); super.transferOwnership(newOwner); }
function transferOwnership(address newOwner) public override onlyOwner { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); grantRole(DEFAULT_ADMIN_ROLE, newOwner); grantRole(MINTER_ROLE, newOwner); grantRole(PAUSER_ROLE, newOwner); revokeRole(MINTER_ROLE, _msgSender()); revokeRole(PAUSER_ROLE, _msgSender()); revokeRole(DEFAULT_ADMIN_ROLE, _msgSender()); super.transferOwnership(newOwner); }
9,500
4
// Emits an event when the owner successfully sets permissions on a token for the spender.
event Approval( address indexed owner, address indexed token, address indexed spender, uint160 amount, uint48 expiration );
event Approval( address indexed owner, address indexed token, address indexed spender, uint160 amount, uint48 expiration );
14,265
197
// Safe clbr transfer function, just in case if rounding error causes pool to not have enough CLBRs.
function safeClbrTransfer(address _to, uint256 _amount) internal { uint256 clbrBal = clbr.balanceOf(address(this)); if (_amount > clbrBal) { clbr.transfer(_to, clbrBal); } else { clbr.transfer(_to, _amount); } }
function safeClbrTransfer(address _to, uint256 _amount) internal { uint256 clbrBal = clbr.balanceOf(address(this)); if (_amount > clbrBal) { clbr.transfer(_to, clbrBal); } else { clbr.transfer(_to, _amount); } }
27,915
64
// Remove the array if no more assets are owned to prevent pollution
if (_assetsOf[from].length == 0) { delete _assetsOf[from]; }
if (_assetsOf[from].length == 0) { delete _assetsOf[from]; }
50,058
25
// Calculates the price of each token from all commitments.return Token price. /
function tokenPrice() public view returns (uint256) { return uint256(marketStatus.commitmentsTotal) .mul(1e18).div(uint256(marketInfo.totalTokens)); }
function tokenPrice() public view returns (uint256) { return uint256(marketStatus.commitmentsTotal) .mul(1e18).div(uint256(marketInfo.totalTokens)); }
73,401
9
// list of junior bond maturities (timestamps)
uint256[] public juniorBondsMaturities;
uint256[] public juniorBondsMaturities;
75,237
8
// Get the current allowance from `owner` for `spender` owner The address of the account which owns the tokens to be spent spender The address of the account which may transfer tokensreturn remaining The number of tokens allowed to be spent /
function allowance(address owner, address spender) external view
function allowance(address owner, address spender) external view
15,022
3
// ============ Internal Functions ============ //Populates the linear auction struct following an auction initiation._linearAuctionLinearAuction State object _currentSet The Set to rebalance from _nextSetThe Set to rebalance to _startingCurrentSetQuantity Quantity of currentSet to rebalance /
function initializeLinearAuction( State storage _linearAuction, ISetToken _currentSet, ISetToken _nextSet, uint256 _startingCurrentSetQuantity ) internal
function initializeLinearAuction( State storage _linearAuction, ISetToken _currentSet, ISetToken _nextSet, uint256 _startingCurrentSetQuantity ) internal
3,034
4
// Override the tokenURI function to set default metadata
function tokenURI(uint256 tokenId) public view virtual override returns (string memory)
function tokenURI(uint256 tokenId) public view virtual override returns (string memory)
28,135
0
// bytes4(keccak256("mint(Fee[], string)")) = 0xc29b240d
bytes4 private constant interfaceId = 0xc29b240d; uint256 public totalSupply; string public contractURI; string public tokenName; string public tokenSymbol; string public tokenBaseURI; mapping(uint256 => address) public creators;
bytes4 private constant interfaceId = 0xc29b240d; uint256 public totalSupply; string public contractURI; string public tokenName; string public tokenSymbol; string public tokenBaseURI; mapping(uint256 => address) public creators;
15,431
7
// We use 100 because that's the total length of our calldata (4 + 323) Counterintuitively, this call() must be positioned after the or() in the surrounding and() because and() evaluates its arguments from right to left.
call(gas(), token, 0, 0, 100, 0, 32) ) mstore(0x60, 0) // Restore the zero slot to zero. mstore(0x40, memPointer) // Restore the memPointer.
call(gas(), token, 0, 0, 100, 0, 32) ) mstore(0x60, 0) // Restore the zero slot to zero. mstore(0x40, memPointer) // Restore the memPointer.
44,888
44
// require(amount >= 1e18, "Must stake at least one YDF.");
require(token.balanceOf(msg.sender) >= amount, "Cannot stake more YDF than you hold unstaked."); if (stakeValue[msg.sender] == 0) totalStakers = totalStakers.add(1); _addStake(amount); require(token.transferFrom(msg.sender, address(this), amount), "Stake failed due to failed transfer."); emit OnStake(msg.sender, amount);
require(token.balanceOf(msg.sender) >= amount, "Cannot stake more YDF than you hold unstaked."); if (stakeValue[msg.sender] == 0) totalStakers = totalStakers.add(1); _addStake(amount); require(token.transferFrom(msg.sender, address(this), amount), "Stake failed due to failed transfer."); emit OnStake(msg.sender, amount);
29,653
3
// Create farmer and buyer...
address farmerAddress = 0xC5fdf4076b8F3A5357c5E395ab970B5B54098Fef; address buyerAddress = 0x821aEa9a577a9b44299B9c15c88cf3087F3b5544; fc.registerFarmer(farmerAddress,"Farmer","Giles",0,0); fc.registerFarmerField(farmerAddress, "COFFEE", 10); fc.registerBuyer(buyerAddress, "Con Sumer", "client location"); var orderId = fc.putAnOrder("COFFEE", 10, 2000, buyerAddress); Assert.equal(orderId, 2, "Incorrect order id");
address farmerAddress = 0xC5fdf4076b8F3A5357c5E395ab970B5B54098Fef; address buyerAddress = 0x821aEa9a577a9b44299B9c15c88cf3087F3b5544; fc.registerFarmer(farmerAddress,"Farmer","Giles",0,0); fc.registerFarmerField(farmerAddress, "COFFEE", 10); fc.registerBuyer(buyerAddress, "Con Sumer", "client location"); var orderId = fc.putAnOrder("COFFEE", 10, 2000, buyerAddress); Assert.equal(orderId, 2, "Incorrect order id");
36,326
179
// final byte (first byte of the next 32 bytes)
v := byte(0, mload(add(sig, 96)))
v := byte(0, mload(add(sig, 96)))
13,023
33
// Allow the caller to remove their own roles./ If the caller does not have a role, then it will be an no-op for the role.
function renounceRoles(uint256 roles) public payable virtual { _removeRoles(msg.sender, roles); }
function renounceRoles(uint256 roles) public payable virtual { _removeRoles(msg.sender, roles); }
8,296
607
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount); }
if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount); }
1,321
4
// The collection symbol.
string internal _symbol;
string internal _symbol;
8,972
191
// >>> include all other rewards in eth besides _claimableBasicInETH()
function _claimableInETH() internal override view returns (uint256 _claimable) { _claimable = super._claimableInETH(); uint256 _fxs = IERC20(fxs).balanceOf(address(this)); if (_fxs > 0) { address[] memory path = new address[](2); path[0] = fxs; path[1] = weth; uint256[] memory swap = Uni(dex[2]).getAmountsOut(_fxs, path); _claimable = _claimable.add(swap[1]); } }
function _claimableInETH() internal override view returns (uint256 _claimable) { _claimable = super._claimableInETH(); uint256 _fxs = IERC20(fxs).balanceOf(address(this)); if (_fxs > 0) { address[] memory path = new address[](2); path[0] = fxs; path[1] = weth; uint256[] memory swap = Uni(dex[2]).getAmountsOut(_fxs, path); _claimable = _claimable.add(swap[1]); } }
36,090
321
// Defines if the default behavior of `transfer` and `transferFrom` checks if the receiver smart contract supports ERC20 tokens When feature FEATURE_UNSAFE_TRANSFERS is enabled the transfers do not check if the receiver smart contract supports ERC20 tokens, i.e. `transfer` and `transferFrom` behave like `unsafeTransferFrom` When feature FEATURE_UNSAFE_TRANSFERS is disabled (default) the transfers check if the receiver smart contract supports ERC20 tokens, i.e. `transfer` and `transferFrom` behave like `safeTransferFrom` /
uint32 public constant FEATURE_UNSAFE_TRANSFERS = 0x0000_0004;
uint32 public constant FEATURE_UNSAFE_TRANSFERS = 0x0000_0004;
31,570
61
// save space, limits us to 2^24 tokens per user (~17m)
uint24[] indices; uint public burnCount;
uint24[] indices; uint public burnCount;
42,118
4
// event WithdrawEthFunds(uint256 indexed amount);
constructor( Category[] memory _categories, uint8 _categoryCounter, uint256 _perTransactionCap, address _nftContractAddress, address _leaderboardSignerAddress, address _reservedSignerAddress, address payable _withdrawAddress
constructor( Category[] memory _categories, uint8 _categoryCounter, uint256 _perTransactionCap, address _nftContractAddress, address _leaderboardSignerAddress, address _reservedSignerAddress, address payable _withdrawAddress
19,120
4
// Forwarder singleton we accept calls from /
address public trustedForwarder;
address public trustedForwarder;
65,377
154
// Paybacks Dai debt/If the _daiAmount is bigger than the whole debt, returns extra Dai/_cdpId Id of the CDP/_ilk Ilk of the CDP/_daiAmount Amount of Dai to payback/_owner Address that owns the DSProxy that owns the CDP
function paybackDebt(uint _cdpId, bytes32 _ilk, uint _daiAmount, address _owner) internal { address urn = manager.urns(_cdpId); uint wholeDebt = getAllDebt(VAT_ADDRESS, urn, urn, _ilk); if (_daiAmount > wholeDebt) { ERC20(DAI_ADDRESS).transfer(_owner, sub(_daiAmount, wholeDebt)); _daiAmount = wholeDebt; } if (ERC20(DAI_ADDRESS).allowance(address(this), DAI_JOIN_ADDRESS) == 0) { ERC20(DAI_ADDRESS).approve(DAI_JOIN_ADDRESS, uint(-1)); } daiJoin.join(urn, _daiAmount); manager.frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); }
function paybackDebt(uint _cdpId, bytes32 _ilk, uint _daiAmount, address _owner) internal { address urn = manager.urns(_cdpId); uint wholeDebt = getAllDebt(VAT_ADDRESS, urn, urn, _ilk); if (_daiAmount > wholeDebt) { ERC20(DAI_ADDRESS).transfer(_owner, sub(_daiAmount, wholeDebt)); _daiAmount = wholeDebt; } if (ERC20(DAI_ADDRESS).allowance(address(this), DAI_JOIN_ADDRESS) == 0) { ERC20(DAI_ADDRESS).approve(DAI_JOIN_ADDRESS, uint(-1)); } daiJoin.join(urn, _daiAmount); manager.frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); }
32,848
60
// Hold tokens for a group investor of investors until the unlock date. After the unlock date the investor can claim their tokens. Steps - Prepare a spreadsheet for token allocation- Deploy this contract, with the sum to tokens to be distributed, from the owner account- Call setInvestor for all investors from the owner account using a local script and CSV input- Move tokensToBeAllocated in this contract using StandardToken.transfer()- Call lock from the owner account- Wait until the freeze period is over- After the freeze time is over investors can call claim() from their address to get their tokens/
contract TokenVault is Ownable, Recoverable { using SafeMathLib for uint; /** How many investors we have now */ uint public investorCount; /** Sum from the spreadsheet how much tokens we should get on the contract. If the sum does not match at the time of the lock the vault is faulty and must be recreated.*/ uint public tokensToBeAllocated; /** How many tokens investors have claimed so far */ uint public totalClaimed; /** How many tokens our internal book keeping tells us to have at the time of lock() when all investor data has been loaded */ uint public tokensAllocatedTotal; /** How much we have allocated to the investors invested */ mapping(address => uint) public balances; /** How many tokens investors have claimed */ mapping(address => uint) public claimed; /** When our claim freeze is over (UNIX timestamp) */ uint public freezeEndsAt; /** When this vault was locked (UNIX timestamp) */ uint public lockedAt; /** We can also define our own token, which will override the ICO one ***/ StandardTokenExt public token; /** What is our current state. * * Loading: Investor data is being loaded and contract not yet locked * Holding: Holding tokens for investors * Distributing: Freeze time is over, investors can claim their tokens */ enum State{Unknown, Loading, Holding, Distributing} /** We allocated tokens for investor */ event Allocated(address investor, uint value); /** We distributed tokens to an investor */ event Distributed(address investors, uint count); event Locked(); /** * Create presale contract where lock up period is given days * * @param _owner Who can load investor data and lock * @param _freezeEndsAt UNIX timestamp when the vault unlocks * @param _token Token contract address we are distributing * @param _tokensToBeAllocated Total number of tokens this vault will hold - including decimal multiplcation * */ function TokenVault(address _owner, uint _freezeEndsAt, StandardTokenExt _token, uint _tokensToBeAllocated) { owner = _owner; // Invalid owenr if(owner == 0) { throw; } token = _token; // Check the address looks like a token contract if(!token.isToken()) { throw; } // Give argument if(_freezeEndsAt == 0) { throw; } // Sanity check on _tokensToBeAllocated if(_tokensToBeAllocated == 0) { throw; } freezeEndsAt = _freezeEndsAt; tokensToBeAllocated = _tokensToBeAllocated; } /// @dev Add a presale participating allocation function setInvestor(address investor, uint amount) public onlyOwner { if(lockedAt > 0) { // Cannot add new investors after the vault is locked throw; } if(amount == 0) throw; // No empty buys // Don't allow reset if(balances[investor] > 0) { throw; } balances[investor] = amount; investorCount++; tokensAllocatedTotal += amount; Allocated(investor, amount); } /// @dev Lock the vault /// - All balances have been loaded in correctly /// - Tokens are transferred on this vault correctly /// - Checks are in place to prevent creating a vault that is locked with incorrect token balances. function lock() onlyOwner { if(lockedAt > 0) { throw; // Already locked } // Spreadsheet sum does not match to what we have loaded to the investor data if(tokensAllocatedTotal != tokensToBeAllocated) { throw; } // Do not lock the vault if the given tokens are not on this contract if(token.balanceOf(address(this)) != tokensAllocatedTotal) { throw; } lockedAt = now; Locked(); } /// @dev In the case locking failed, then allow the owner to reclaim the tokens on the contract. function recoverFailedLock() onlyOwner { if(lockedAt > 0) { throw; } // Transfer all tokens on this contract back to the owner token.transfer(owner, token.balanceOf(address(this))); } /// @dev Get the current balance of tokens in the vault /// @return uint How many tokens there are currently in vault function getBalance() public constant returns (uint howManyTokensCurrentlyInVault) { return token.balanceOf(address(this)); } /// @dev Claim N bought tokens to the investor as the msg sender function claim() { address investor = msg.sender; if(lockedAt == 0) { throw; // We were never locked } if(now < freezeEndsAt) { throw; // Trying to claim early } if(balances[investor] == 0) { // Not our investor throw; } if(claimed[investor] > 0) { throw; // Already claimed } uint amount = balances[investor]; claimed[investor] = amount; totalClaimed += amount; token.transfer(investor, amount); Distributed(investor, amount); } /// @dev This function is prototyped in Recoverable contract function tokensToBeReturned(ERC20Basic token) public returns (uint) { return getBalance().minus(tokensAllocatedTotal); } /// @dev Resolve the contract umambigious state function getState() public constant returns(State) { if(lockedAt == 0) { return State.Loading; } else if(now > freezeEndsAt) { return State.Distributing; } else { return State.Holding; } } }
contract TokenVault is Ownable, Recoverable { using SafeMathLib for uint; /** How many investors we have now */ uint public investorCount; /** Sum from the spreadsheet how much tokens we should get on the contract. If the sum does not match at the time of the lock the vault is faulty and must be recreated.*/ uint public tokensToBeAllocated; /** How many tokens investors have claimed so far */ uint public totalClaimed; /** How many tokens our internal book keeping tells us to have at the time of lock() when all investor data has been loaded */ uint public tokensAllocatedTotal; /** How much we have allocated to the investors invested */ mapping(address => uint) public balances; /** How many tokens investors have claimed */ mapping(address => uint) public claimed; /** When our claim freeze is over (UNIX timestamp) */ uint public freezeEndsAt; /** When this vault was locked (UNIX timestamp) */ uint public lockedAt; /** We can also define our own token, which will override the ICO one ***/ StandardTokenExt public token; /** What is our current state. * * Loading: Investor data is being loaded and contract not yet locked * Holding: Holding tokens for investors * Distributing: Freeze time is over, investors can claim their tokens */ enum State{Unknown, Loading, Holding, Distributing} /** We allocated tokens for investor */ event Allocated(address investor, uint value); /** We distributed tokens to an investor */ event Distributed(address investors, uint count); event Locked(); /** * Create presale contract where lock up period is given days * * @param _owner Who can load investor data and lock * @param _freezeEndsAt UNIX timestamp when the vault unlocks * @param _token Token contract address we are distributing * @param _tokensToBeAllocated Total number of tokens this vault will hold - including decimal multiplcation * */ function TokenVault(address _owner, uint _freezeEndsAt, StandardTokenExt _token, uint _tokensToBeAllocated) { owner = _owner; // Invalid owenr if(owner == 0) { throw; } token = _token; // Check the address looks like a token contract if(!token.isToken()) { throw; } // Give argument if(_freezeEndsAt == 0) { throw; } // Sanity check on _tokensToBeAllocated if(_tokensToBeAllocated == 0) { throw; } freezeEndsAt = _freezeEndsAt; tokensToBeAllocated = _tokensToBeAllocated; } /// @dev Add a presale participating allocation function setInvestor(address investor, uint amount) public onlyOwner { if(lockedAt > 0) { // Cannot add new investors after the vault is locked throw; } if(amount == 0) throw; // No empty buys // Don't allow reset if(balances[investor] > 0) { throw; } balances[investor] = amount; investorCount++; tokensAllocatedTotal += amount; Allocated(investor, amount); } /// @dev Lock the vault /// - All balances have been loaded in correctly /// - Tokens are transferred on this vault correctly /// - Checks are in place to prevent creating a vault that is locked with incorrect token balances. function lock() onlyOwner { if(lockedAt > 0) { throw; // Already locked } // Spreadsheet sum does not match to what we have loaded to the investor data if(tokensAllocatedTotal != tokensToBeAllocated) { throw; } // Do not lock the vault if the given tokens are not on this contract if(token.balanceOf(address(this)) != tokensAllocatedTotal) { throw; } lockedAt = now; Locked(); } /// @dev In the case locking failed, then allow the owner to reclaim the tokens on the contract. function recoverFailedLock() onlyOwner { if(lockedAt > 0) { throw; } // Transfer all tokens on this contract back to the owner token.transfer(owner, token.balanceOf(address(this))); } /// @dev Get the current balance of tokens in the vault /// @return uint How many tokens there are currently in vault function getBalance() public constant returns (uint howManyTokensCurrentlyInVault) { return token.balanceOf(address(this)); } /// @dev Claim N bought tokens to the investor as the msg sender function claim() { address investor = msg.sender; if(lockedAt == 0) { throw; // We were never locked } if(now < freezeEndsAt) { throw; // Trying to claim early } if(balances[investor] == 0) { // Not our investor throw; } if(claimed[investor] > 0) { throw; // Already claimed } uint amount = balances[investor]; claimed[investor] = amount; totalClaimed += amount; token.transfer(investor, amount); Distributed(investor, amount); } /// @dev This function is prototyped in Recoverable contract function tokensToBeReturned(ERC20Basic token) public returns (uint) { return getBalance().minus(tokensAllocatedTotal); } /// @dev Resolve the contract umambigious state function getState() public constant returns(State) { if(lockedAt == 0) { return State.Loading; } else if(now > freezeEndsAt) { return State.Distributing; } else { return State.Holding; } } }
3,639
10
// Base AC emission rate for plus gauges. It's equal to the emission rate when there is no plus boosting, i.e. total plus staked <= PLUS_BOOST_THRESHOLD
uint256 public basePlusRate;
uint256 public basePlusRate;
75,489
94
// Calculate the new weighted multiplier when adding `_additionalPrimordialAmount` at `_additionalWeightedMultiplier` to the current `_currentPrimordialBalance` at `_currentWeightedMultiplier` _currentWeightedMultiplier Account's current weighted multiplier _currentPrimordialBalance Account's current primordial ion balance _additionalWeightedMultiplier The weighted multiplier to be added _additionalPrimordialAmount The primordial ion amount to be addedreturn the new primordial weighted multiplier /
function calculateWeightedMultiplier(uint256 _currentWeightedMultiplier, uint256 _currentPrimordialBalance, uint256 _additionalWeightedMultiplier, uint256 _additionalPrimordialAmount) public pure returns (uint256) { if (_currentWeightedMultiplier > 0) { uint256 _totalWeightedIons = (_currentWeightedMultiplier.mul(_currentPrimordialBalance)).add(_additionalWeightedMultiplier.mul(_additionalPrimordialAmount)); uint256 _totalIons = _currentPrimordialBalance.add(_additionalPrimordialAmount); return _totalWeightedIons.div(_totalIons); } else { return _additionalWeightedMultiplier; } }
function calculateWeightedMultiplier(uint256 _currentWeightedMultiplier, uint256 _currentPrimordialBalance, uint256 _additionalWeightedMultiplier, uint256 _additionalPrimordialAmount) public pure returns (uint256) { if (_currentWeightedMultiplier > 0) { uint256 _totalWeightedIons = (_currentWeightedMultiplier.mul(_currentPrimordialBalance)).add(_additionalWeightedMultiplier.mul(_additionalPrimordialAmount)); uint256 _totalIons = _currentPrimordialBalance.add(_additionalPrimordialAmount); return _totalWeightedIons.div(_totalIons); } else { return _additionalWeightedMultiplier; } }
47,054
7
// function findDonationIndex( Campaign storage campaign, address donor
// ) internal view returns (uint256) { // uint256 len = campaign.donators.length; // for (uint256 i = 0; i < len; i++) { // if (campaign.donators[i] == donor) { // return i; // } // } // return uint256(-1); // Not found // }
// ) internal view returns (uint256) { // uint256 len = campaign.donators.length; // for (uint256 i = 0; i < len; i++) { // if (campaign.donators[i] == donor) { // return i; // } // } // return uint256(-1); // Not found // }
24,268
62
// This is an alternative to {approve} that can be used as a mitigation forproblems described in {ERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address.- `spender` must have allowance for the caller of at least`subtractedValue`. /
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; }
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; }
5,315
18
// require(oraclizeQueryId == 0);
require(!_isAlreadyPlaying(msg.sender)); uint adminFee = address(this).balance * FEE * 80 /10000; manageAdr.transfer(adminFee); players[attendee]._account = msg.sender; attendee++; emit PlayerEntered(msg.sender, msg.value);
require(!_isAlreadyPlaying(msg.sender)); uint adminFee = address(this).balance * FEE * 80 /10000; manageAdr.transfer(adminFee); players[attendee]._account = msg.sender; attendee++; emit PlayerEntered(msg.sender, msg.value);
12,692
288
// Reduce the total supply.
totalSupply -= burnAmount; emit Transfer(holder, address(0), burnAmount);
totalSupply -= burnAmount; emit Transfer(holder, address(0), burnAmount);
18,039
138
// Set the fees to buying
_liquidityFee = liquidityFeeBuy; _rewardFee = rewardFeeBuy; _MarketingFee = MarketingFeeBuy;
_liquidityFee = liquidityFeeBuy; _rewardFee = rewardFeeBuy; _MarketingFee = MarketingFeeBuy;
25,890
23
// Check if offered item type == additional recipient item type.
offerTypeIsAdditionalRecipientsType := gt(route, 3)
offerTypeIsAdditionalRecipientsType := gt(route, 3)
21,126
1
// Array of addresses for all collection that were created by the identity. /
address[] private _collectionArray;
address[] private _collectionArray;
35,233
27
// trade by swap exact amount of token into market no checks on _inTotalAmount, _minOutTotalAmount, _maxPrice /
function swapExactIn( address _tokenIn, address _tokenOut, uint256 _inTotalAmount, uint256 _minOutTotalAmount, uint256 _maxPrice, bytes32 _marketFactoryId
function swapExactIn( address _tokenIn, address _tokenOut, uint256 _inTotalAmount, uint256 _minOutTotalAmount, uint256 _maxPrice, bytes32 _marketFactoryId
18,227
0
// constructor(address _address) public PoolBase(_address) {}
event Stake(address indexed user, uint256 amount); event Claim(address indexed user, uint256 pwdrAmount); event Withdraw(address indexed user, uint256 amount); event PwdrRewardAdded(address indexed user, uint256 pwdrReward); event EthRewardAdded(address indexed user, uint256 ethReward); struct UserInfo { uint256 staked; // How many PWDR-ETH LP tokens the user has staked uint256 rewardDebt; // Reward debt. Works the same as in the Slopes contract
event Stake(address indexed user, uint256 amount); event Claim(address indexed user, uint256 pwdrAmount); event Withdraw(address indexed user, uint256 amount); event PwdrRewardAdded(address indexed user, uint256 pwdrReward); event EthRewardAdded(address indexed user, uint256 ethReward); struct UserInfo { uint256 staked; // How many PWDR-ETH LP tokens the user has staked uint256 rewardDebt; // Reward debt. Works the same as in the Slopes contract
10,049
12
// The Collybus type does not change the behavior so we can use either of them
StaticRelayer staticRelayer = new StaticRelayer( address(collybus), IRelayer.RelayerType.SpotPrice, bytes32(uint256(uint160(tokenAddress))), 1e18 );
StaticRelayer staticRelayer = new StaticRelayer( address(collybus), IRelayer.RelayerType.SpotPrice, bytes32(uint256(uint160(tokenAddress))), 1e18 );
22,381
4
// transfer the tokens, if presenter is not set, normal behaviour/
function _transfer(address _from, address _to, uint256 _amount) internal override { // Transfer fund and responsibility to presenter if (presenter != address(0) && presenter != _msgSender()) { super._transfer(_from, presenter, _amount); ITokenPresenter(presenter).receiveTokens(_msgSender(), _from, _to, _amount); } else { super._transfer(_from, _to, _amount); } }
function _transfer(address _from, address _to, uint256 _amount) internal override { // Transfer fund and responsibility to presenter if (presenter != address(0) && presenter != _msgSender()) { super._transfer(_from, presenter, _amount); ITokenPresenter(presenter).receiveTokens(_msgSender(), _from, _to, _amount); } else { super._transfer(_from, _to, _amount); } }
17,562
8
// Mapping from all types of SFT owner to operator approvals
mapping(address => mapping(address => bool)) private _semiAllApprovals;
mapping(address => mapping(address => bool)) private _semiAllApprovals;
46,803
81
// Send calculated share of NFTSalePrice based on DAO membership share
IWETH(wETHAddress).transferFrom(address(this), msg.sender,
IWETH(wETHAddress).transferFrom(address(this), msg.sender,
24,399
270
// Event emitted when user NFT is withdrawn from the zkSync contract
event WithdrawalNFT(uint32 indexed tokenId);
event WithdrawalNFT(uint32 indexed tokenId);
78,437
302
// Stack too deep otherwise.
(uint capitalRequirement, uint skewLimit) = market.creatorLimits(); data.creatorLimits = BinaryOptionMarketManager.CreatorLimits(capitalRequirement, skewLimit); return data;
(uint capitalRequirement, uint skewLimit) = market.creatorLimits(); data.creatorLimits = BinaryOptionMarketManager.CreatorLimits(capitalRequirement, skewLimit); return data;
30,299
250
// slither-disable-next-line uninitialized-local
bytes memory editionNumber; if (limit != 0) { editionNumber = abi.encodePacked("/", Strings.toString(limit)); }
bytes memory editionNumber; if (limit != 0) { editionNumber = abi.encodePacked("/", Strings.toString(limit)); }
19,942
67
// Skip forward or rewind time by the specified number of seconds
function skip(uint256 time) internal virtual { vm.warp(block.timestamp + time); }
function skip(uint256 time) internal virtual { vm.warp(block.timestamp + time); }
15,917
1
// Primary actions
function execute() public virtual returns (bool); function cancel() public virtual returns (bool); function claim() public virtual payable returns (bool);
function execute() public virtual returns (bool); function cancel() public virtual returns (bool); function claim() public virtual payable returns (bool);
37,371
8
// Identifier for the batcher./ For version 1 of this configuration, this is represented as an address left-padded/ with zeros to 32 bytes.
bytes32 public batcherHash;
bytes32 public batcherHash;
23,800
24
// Create a new DeFi Smart Account for a user and run cast function in the new Smart Account. _owner Owner of the Smart Account. accountVersion Account Module version. _targets Array of Target to run cast function. _datas Array of Data(callData) to run cast function. _origin Where Smart Account is created. /
function buildWithCast( address _owner, uint accountVersion, address[] calldata _targets, bytes[] calldata _datas, address _origin
function buildWithCast( address _owner, uint accountVersion, address[] calldata _targets, bytes[] calldata _datas, address _origin
15,313
1
// 0x62d5b84bE28a183aBB507E125B384122D2C25fAE V1 - V5: OK
address public immutable bar;
address public immutable bar;
30,030
21
// Set Reserve Supply /
function setReserveSupply(uint256 _reserveSupply) public onlyOwner { reserveSupply = _reserveSupply; }
function setReserveSupply(uint256 _reserveSupply) public onlyOwner { reserveSupply = _reserveSupply; }
9,049