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
319
// In case of shortfall, adjust debt
mapping(address => uint256) public haircuts;
mapping(address => uint256) public haircuts;
47,577
17
// mix two dna _dna1 frog dna _dna2 frog dna /
function _mixDna(uint256 _dna1, uint256 _dna2) internal view returns (uint256) { uint256 randomSeed = uint256(keccak256(abi.encodePacked(block.timestamp, msg.sender))) % (10 ** 10); uint256[10] memory dnaArray; uint256 i; for (i = 10; i > 0; i--) { uint256 randSeedValue = randomSeed % 10; if (randSeedValue >= 5) { // use frog1 DNA dnaArray[i - 1] = uint16(_dna1 % 100); } else { // use frog2 DNA dnaArray[i - 1] = uint16(_dna2 % 100); } _dna1 = _dna1 / 100; _dna2 = _dna2 / 100; randomSeed = randomSeed / 10; } // recombine DNA uint256 newDNA = 0; for (i = 0; i < 10; i++) { newDNA = newDNA + dnaArray[i]; if (i != 9) { newDNA = newDNA * 100; } } return newDNA; }
function _mixDna(uint256 _dna1, uint256 _dna2) internal view returns (uint256) { uint256 randomSeed = uint256(keccak256(abi.encodePacked(block.timestamp, msg.sender))) % (10 ** 10); uint256[10] memory dnaArray; uint256 i; for (i = 10; i > 0; i--) { uint256 randSeedValue = randomSeed % 10; if (randSeedValue >= 5) { // use frog1 DNA dnaArray[i - 1] = uint16(_dna1 % 100); } else { // use frog2 DNA dnaArray[i - 1] = uint16(_dna2 % 100); } _dna1 = _dna1 / 100; _dna2 = _dna2 / 100; randomSeed = randomSeed / 10; } // recombine DNA uint256 newDNA = 0; for (i = 0; i < 10; i++) { newDNA = newDNA + dnaArray[i]; if (i != 9) { newDNA = newDNA * 100; } } return newDNA; }
16,010
118
// Adds to a user's timelock balance.It will attempt to sweep before updating the balance./ Note that this will overwrite the previous unlock timestamp./user The user whose timelock balance should increase/amount The amount to increase by/timestamp The new unlock timestamp
function _mintTimelock(address user, uint256 amount, uint256 timestamp) internal { // Sweep the old balance, if any address[] memory users = new address[](1); users[0] = user; _sweepTimelockBalances(users); timelockTotalSupply = timelockTotalSupply.add(amount); _timelockBalances[user] = _timelockBalances[user].add(amount); _unlockTimestamps[user] = timestamp; // if the funds should already be unlocked if (timestamp <= _currentTime()) { _sweepTimelockBalances(users); } }
function _mintTimelock(address user, uint256 amount, uint256 timestamp) internal { // Sweep the old balance, if any address[] memory users = new address[](1); users[0] = user; _sweepTimelockBalances(users); timelockTotalSupply = timelockTotalSupply.add(amount); _timelockBalances[user] = _timelockBalances[user].add(amount); _unlockTimestamps[user] = timestamp; // if the funds should already be unlocked if (timestamp <= _currentTime()) { _sweepTimelockBalances(users); } }
7,026
32
// - Caller must have the {ADMIN} role /
function createTiers( Tier[] calldata newTiers, string[][] calldata tierHashes ) external onlyRole(ADMIN) { require( newTiers.length == tierHashes.length, "Teller: array length mismatch" ); for (uint256 i; i < newTiers.length; i++) {
function createTiers( Tier[] calldata newTiers, string[][] calldata tierHashes ) external onlyRole(ADMIN) { require( newTiers.length == tierHashes.length, "Teller: array length mismatch" ); for (uint256 i; i < newTiers.length; i++) {
22,940
3
// Completer takes it all
addresses = new address[](1); addresses[0] = completer; amounts = new uint256[](1); amounts[0] = amount; return (addresses, amounts);
addresses = new address[](1); addresses[0] = completer; amounts = new uint256[](1); amounts[0] = amount; return (addresses, amounts);
16,362
74
// Underlying token
function token() external view override returns (address) { return curveLpToken; }
function token() external view override returns (address) { return curveLpToken; }
52,474
28
// limbo address of Limbo/ flan address of Flan/ eye address of EYE token/ proposalFactory authenticates and instantiates valid proposals for voting/ sushiFactory is the SushiSwap Factory contract/ uniFactory is the UniSwapV2 Factory contract/ precisionOrderOfMagnitude when comparing fractional values, it's not necessary to get every last digit right/ sushiLPs valid EYE containing LP tokens elligible for earning Fate through staking/ uniLPs valid EYE containing LP tokens elligible for earning Fate through staking
function seed( address limbo, address flan, address eye, address proposalFactory, address sushiFactory, address uniFactory, uint256 precisionOrderOfMagnitude, address[] memory sushiLPs, address[] memory uniLPs
function seed( address limbo, address flan, address eye, address proposalFactory, address sushiFactory, address uniFactory, uint256 precisionOrderOfMagnitude, address[] memory sushiLPs, address[] memory uniLPs
26,941
1
// ! ],! "expected": [! "1", "12", "55", "53", "22", "34", "45", "21", "12", "7"! ]
//! }, { //! "name": "complex2", //! "input": [ //! { //! "entry": "complex", //! "calldata": [ //! "37", "11", "2", "59", "0", "63", "41", "27", "17", "9" //! ] //! }
//! }, { //! "name": "complex2", //! "input": [ //! { //! "entry": "complex", //! "calldata": [ //! "37", "11", "2", "59", "0", "63", "41", "27", "17", "9" //! ] //! }
8,048
187
// emit an improved atomic approve event
emit Approved(msg.sender, _from, _allowance + _value, _allowance);
emit Approved(msg.sender, _from, _allowance + _value, _allowance);
50,586
106
// multiplier applied to carrots received from burning a horsey
uint8 public carrotsMultiplier = 1;
uint8 public carrotsMultiplier = 1;
46,159
20
// Destroy tokens Remove `_value` tokens from the system irreversibly _value The amount of money will be burnedreturn True if `_value` is burned successfully /
function burn(uint256 _value) public returns(bool) { balances[msg.sender] = balances[msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); emit Burn(msg.sender, _value); return true; }
function burn(uint256 _value) public returns(bool) { balances[msg.sender] = balances[msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); emit Burn(msg.sender, _value); return true; }
19,354
167
// canManage(): true if _who is the owner or manager of _point
function canManage(uint32 _point, address _who) view external returns (bool result)
function canManage(uint32 _point, address _who) view external returns (bool result)
57,656
14
// Read the order index from memory and place it on the stack.
uint256 orderIndex = criteriaResolver.orderIndex;
uint256 orderIndex = criteriaResolver.orderIndex;
17,564
63
// Lock tokens in the address from being transfered until the specified time/addr The address to restrict/timestamp The time the tokens will be locked until as a Unix timetsamp./ Unix timestamp is the number of seconds since the Unix epoch of 00:00:00 UTC on 1 January 1970.
function setLockUntil(address addr, uint256 timestamp) public validAddress(addr) onlyTransferAdmin { _lockUntil[addr] = timestamp; emit AddressTimeLock(msg.sender, addr, timestamp); }
function setLockUntil(address addr, uint256 timestamp) public validAddress(addr) onlyTransferAdmin { _lockUntil[addr] = timestamp; emit AddressTimeLock(msg.sender, addr, timestamp); }
5,667
30
// to receive eth from the contract
address public walletOwnerAddress;
address public walletOwnerAddress;
11,651
110
// Uniswap and SushiswapUNISWAP = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; SUSHISWAP = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F;
address private constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public dex;
address private constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public dex;
34,209
58
// Remember that only owner can call so be careful when use on contracts generated from other contracts. tokenAddress The token contract address tokenAmount Number of tokens to be sent /
function recoverERC20(address tokenAddress, uint256 tokenAmount) public virtual onlyOwner { IERC20(tokenAddress).transfer(owner(), tokenAmount); }
function recoverERC20(address tokenAddress, uint256 tokenAmount) public virtual onlyOwner { IERC20(tokenAddress).transfer(owner(), tokenAmount); }
4,767
128
// job proposal delay
mapping(address => uint) public jobProposalDelay;
mapping(address => uint) public jobProposalDelay;
8,926
25
// transfer atoken from user to contract
if (positionsOpen[sender] == 1) { uint256 newAmount = IERC20(apositionAsset).balanceOf(sender); IERC20(apositionAsset).transferFrom(sender, address(this), newAmount); LENDING_POOL.withdraw(positionAsset, newAmount, address(this)); } else {
if (positionsOpen[sender] == 1) { uint256 newAmount = IERC20(apositionAsset).balanceOf(sender); IERC20(apositionAsset).transferFrom(sender, address(this), newAmount); LENDING_POOL.withdraw(positionAsset, newAmount, address(this)); } else {
43,947
14
// Burns the transferred option tokens, stores the strike asset (ether), and pushes underlyingTokens to the receiver address.
(inputStrikes, inputOptions) = optionToken.exerciseOptions( receiver, inputOptions, new bytes(0) ); return (inputStrikes, inputOptions);
(inputStrikes, inputOptions) = optionToken.exerciseOptions( receiver, inputOptions, new bytes(0) ); return (inputStrikes, inputOptions);
39,591
95
// Estimate the stake payout for an incomplete day g Cache of stored globals stakeSharesParam Param from stake to calculate bonuses for day Day to calculate bonuses forreturn Payout in Suns /
function _estimatePayoutRewardsDay(GlobalsCache memory g, uint256 stakeSharesParam, uint256 day) internal view returns (uint256 payout)
function _estimatePayoutRewardsDay(GlobalsCache memory g, uint256 stakeSharesParam, uint256 day) internal view returns (uint256 payout)
76,720
103
// If the atomic call failed, emit an event signifying a transfer failure.
if (!ok) { emit ExternalError(address(_DAI), _revertReason(2)); } else {
if (!ok) { emit ExternalError(address(_DAI), _revertReason(2)); } else {
9,719
11
// Allows the upgrade the M5 logic contract and token at the same transaction newM5Token The address of a new M5 token newM5Logic The address of the new contract /
function upgradeM5(address newM5Token, address newM5Logic) public onlyUpgradeManager { // solium-disable-line require(newM5Token != address(0)); require(newM5Logic != address(0)); emit M5TokenUpgrade(M5Token_, newM5Token); emit M5LogicUpgrade(M5Logic_, newM5Logic); M5Token_ = newM5Token; M5Logic_ = newM5Logic; }
function upgradeM5(address newM5Token, address newM5Logic) public onlyUpgradeManager { // solium-disable-line require(newM5Token != address(0)); require(newM5Logic != address(0)); emit M5TokenUpgrade(M5Token_, newM5Token); emit M5LogicUpgrade(M5Logic_, newM5Logic); M5Token_ = newM5Token; M5Logic_ = newM5Logic; }
24,497
20
// Votes at the `proposals` with using `weights` tokens in the `ballotNum`-th ballot. Returns a boolean value indicating whether the operation succeeded.
* Emits an one or multiple {Vote} event(s). * * Requirements: * * - the caller MUST NOT vote the ballot before. * - `ballotNum` cannot be out of the range of array. * - each element of `proposals` cannot be out of the range of array. * - the caller MUST have a balance of at least sum of `weights`. */ function voteAt( uint256 ballotNum, uint256[] calldata proposals_, uint256[] calldata weights_ ) external override returns (bool) { Ballot storage ballot = _ballots[ballotNum]; Voter storage sender = ballot.voters[_msgSender()]; // conditions require(!ballot.ended, "The ballot is ended."); require(ballot.currentTime + ballot.timeLimit > now, "Exceed time limit."); require(!sender.voted, "You already voted."); require(_sum(weights_) <= sender.weights, "Exceed the rights."); sender.voted = true; // If 'i' is out of the range of the array, // this will throw automatically and revert all changes for (uint256 i = 0; i < proposals_.length; i++) { ballot.proposals[proposals_[i]].voteCounts.push(weights_[i]); emit Vote(_msgSender(), ballotNum, proposals_[i], weights_[i]); } return true; }
* Emits an one or multiple {Vote} event(s). * * Requirements: * * - the caller MUST NOT vote the ballot before. * - `ballotNum` cannot be out of the range of array. * - each element of `proposals` cannot be out of the range of array. * - the caller MUST have a balance of at least sum of `weights`. */ function voteAt( uint256 ballotNum, uint256[] calldata proposals_, uint256[] calldata weights_ ) external override returns (bool) { Ballot storage ballot = _ballots[ballotNum]; Voter storage sender = ballot.voters[_msgSender()]; // conditions require(!ballot.ended, "The ballot is ended."); require(ballot.currentTime + ballot.timeLimit > now, "Exceed time limit."); require(!sender.voted, "You already voted."); require(_sum(weights_) <= sender.weights, "Exceed the rights."); sender.voted = true; // If 'i' is out of the range of the array, // this will throw automatically and revert all changes for (uint256 i = 0; i < proposals_.length; i++) { ballot.proposals[proposals_[i]].voteCounts.push(weights_[i]); emit Vote(_msgSender(), ballotNum, proposals_[i], weights_[i]); } return true; }
18,153
128
// Returns an Ethereum Signed Typed Data, created from a`domainSeparator` and a `structHash`. This produces hash correspondingto the one signed with theJSON-RPC method as part of EIP-712.
* See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); }
* See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); }
88
54
// StochToken StochToken TeamStandard ERC20 token without burning and mintable optional functions implemented.For full specification of ERC-20 standard see: /
contract StochToken is ERC20, Ownable { string private _name = "STOCH"; string private _symbol = "STOCH"; uint8 private _decimals = 18; uint256 private _totalSupply = 20000000 * 10e17; // 20 million fixed supply address private _stochContract = address(0); // modifier onlyRedeemed(address recipient_) { require(_stochContract == address(0) || _stochContract == recipient_, "Redeemed Only, trade restricted"); _; } /** * @dev Constructor. * @param tokenOwnerAddress address that gets 100% of token supply */ constructor(address payable tokenOwnerAddress) public payable { // set tokenOwnerAddress as owner of all tokens _mint(tokenOwnerAddress, _totalSupply); } /** * @dev Transfer tokens. * @param recipient address of token receiver. * @param amount The amount of token to be transfered. */ function transfer(address recipient, uint256 amount) public override onlyRedeemed(recipient) returns (bool) { _transfer(msg.sender, recipient, amount); return true; } // optional functions from ERC20 stardard /** * @return the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint8) { return _decimals; } /** * Set the stoch contract address, so receipient must be redeem contract always */ function enableRedeemed(address stochContract) public onlyOwner { _stochContract = stochContract; } }
contract StochToken is ERC20, Ownable { string private _name = "STOCH"; string private _symbol = "STOCH"; uint8 private _decimals = 18; uint256 private _totalSupply = 20000000 * 10e17; // 20 million fixed supply address private _stochContract = address(0); // modifier onlyRedeemed(address recipient_) { require(_stochContract == address(0) || _stochContract == recipient_, "Redeemed Only, trade restricted"); _; } /** * @dev Constructor. * @param tokenOwnerAddress address that gets 100% of token supply */ constructor(address payable tokenOwnerAddress) public payable { // set tokenOwnerAddress as owner of all tokens _mint(tokenOwnerAddress, _totalSupply); } /** * @dev Transfer tokens. * @param recipient address of token receiver. * @param amount The amount of token to be transfered. */ function transfer(address recipient, uint256 amount) public override onlyRedeemed(recipient) returns (bool) { _transfer(msg.sender, recipient, amount); return true; } // optional functions from ERC20 stardard /** * @return the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint8) { return _decimals; } /** * Set the stoch contract address, so receipient must be redeem contract always */ function enableRedeemed(address stochContract) public onlyOwner { _stochContract = stochContract; } }
14,670
26
// Add the new token pair to the poolDO NOT add the same LP token more than once. Rewards will be messed up if you do._l1TokenAddress _l2TokenAddress/
function registerPool( address _l1TokenAddress, address _l2TokenAddress ) public onlyOwner()
function registerPool( address _l1TokenAddress, address _l2TokenAddress ) public onlyOwner()
25,285
18
// Retrieve the tokens owned by the caller.
function myTokens() public view returns (uint256);
function myTokens() public view returns (uint256);
10,949
84
// function to get tokens contract hold /
function totalTokenBalance(address contractAddress) public view returns(uint)
function totalTokenBalance(address contractAddress) public view returns(uint)
11,895
63
// Increment a particular maker's nonce, thereby invalidating all orders that were not signedwith the original nonce. /
function incrementNonce() external { uint newNonce = ++nonces[msg.sender]; emit NonceIncremented(msg.sender, newNonce); }
function incrementNonce() external { uint newNonce = ++nonces[msg.sender]; emit NonceIncremented(msg.sender, newNonce); }
40,004
10
// the challenger arrives
c.challenger = msg.sender;
c.challenger = msg.sender;
43,953
258
// Returns the subtraction of two signed integers, reverting on overflow. /
function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; _require((b >= 0 && c <= a) || (b < 0 && c > a), Errors.SUB_OVERFLOW); return c; }
function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; _require((b >= 0 && c <= a) || (b < 0 && c > a), Errors.SUB_OVERFLOW); return c; }
5,691
93
// Decode literals and length/distance pairs
while (symbol != 256) { (err, symbol) = _decode(s, lencode); if (err != ErrorCode.ERR_NONE) {
while (symbol != 256) { (err, symbol) = _decode(s, lencode); if (err != ErrorCode.ERR_NONE) {
5,328
56
// Don't accept ETH
function () payable external { revert(); }
function () payable external { revert(); }
9,870
117
// split the contract balance into thirds
uint256 halfOfLiquify = contractTokenBalance.div(4); uint256 otherHalfOfLiquify = contractTokenBalance.div(4); uint256 portionForFees = contractTokenBalance.sub(halfOfLiquify).sub(otherHalfOfLiquify);
uint256 halfOfLiquify = contractTokenBalance.div(4); uint256 otherHalfOfLiquify = contractTokenBalance.div(4); uint256 portionForFees = contractTokenBalance.sub(halfOfLiquify).sub(otherHalfOfLiquify);
8,856
7
// Deposit into the DAI pool
poolManager.deposit("DAI", _borrowAmount);
poolManager.deposit("DAI", _borrowAmount);
52,565
9
// do += so that acrues across share cycles.
members[syndicateMembers[i]].profitShare+=SafeMath.mul(members[syndicateMembers[i]].numShares,profitPerShare);
members[syndicateMembers[i]].profitShare+=SafeMath.mul(members[syndicateMembers[i]].numShares,profitPerShare);
16,515
65
// Check real amount to avoid taxed token
uint256 previousBalance_ = stakedToken.balanceOf(address(this)); stakedToken.safeTransferFrom(address(msg.sender), address(this), _amount); uint256 newBalance_ = stakedToken.balanceOf(address(this)); addedAmount_ = newBalance_ - previousBalance_; user.amount += addedAmount_; currentStakedPerPool += addedAmount_;
uint256 previousBalance_ = stakedToken.balanceOf(address(this)); stakedToken.safeTransferFrom(address(msg.sender), address(this), _amount); uint256 newBalance_ = stakedToken.balanceOf(address(this)); addedAmount_ = newBalance_ - previousBalance_; user.amount += addedAmount_; currentStakedPerPool += addedAmount_;
35,118
17
// individual cap in wei
uint256 public individualCapInWei;
uint256 public individualCapInWei;
46,526
11
// allow approved address to repay borrowed reserves with reserves _amount uint256 _token address /
function repayDebtWithReserve(uint256 _amount, address _token) external override { require(permissions[STATUS.RESERVEDEBTOR][msg.sender], notApproved); require(permissions[STATUS.RESERVETOKEN][_token], notAccepted); IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount); uint256 value = tokenValue(_token, _amount); sBLKD.changeDebt(value, msg.sender, false); totalDebt = totalDebt.sub(value); totalReserves = totalReserves.add(value); emit RepayDebt(msg.sender, _token, _amount, value); }
function repayDebtWithReserve(uint256 _amount, address _token) external override { require(permissions[STATUS.RESERVEDEBTOR][msg.sender], notApproved); require(permissions[STATUS.RESERVETOKEN][_token], notAccepted); IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount); uint256 value = tokenValue(_token, _amount); sBLKD.changeDebt(value, msg.sender, false); totalDebt = totalDebt.sub(value); totalReserves = totalReserves.add(value); emit RepayDebt(msg.sender, _token, _amount, value); }
37,413
34
// Event emitted when comptroller is changed /
event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller);
event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller);
13,542
289
// now we see if we want to add or remove balance if the desired borrow is less than our current borrow we are in deficit. so we want to reduce position
if (desiredBorrow < borrows) { deficit = true; position = borrows.sub(desiredBorrow); //safemath check done in if statement } else {
if (desiredBorrow < borrows) { deficit = true; position = borrows.sub(desiredBorrow); //safemath check done in if statement } else {
44,687
12
// Set 'contract address', for liquid staking smart contract liquidStakingContract: liquidStaking contract address
* Emits a {SetLiquidStakingContract} event with '_contract' set to the liquidStaking contract address. * */ function setLiquidStakingContract(address liquidStakingContract) public virtual override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "UT4"); _liquidStakingContract = liquidStakingContract; emit SetLiquidStakingContract(liquidStakingContract); }
* Emits a {SetLiquidStakingContract} event with '_contract' set to the liquidStaking contract address. * */ function setLiquidStakingContract(address liquidStakingContract) public virtual override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "UT4"); _liquidStakingContract = liquidStakingContract; emit SetLiquidStakingContract(liquidStakingContract); }
42,728
57
// buy Bancor or Uniswap pool_amount amount of pool token_type pool type_poolTokenpool token address/
function buyPool ( uint256 _amount, uint _type, IERC20 _poolToken ) external payable returns( address[] memory connectorsAddress,
function buyPool ( uint256 _amount, uint _type, IERC20 _poolToken ) external payable returns( address[] memory connectorsAddress,
12,188
16
// wasAlreadyProved is false since Gateway is called for the first time for a block height
emit GatewayProven( remoteGateway, _blockHeight, storageRoot, false ); return true;
emit GatewayProven( remoteGateway, _blockHeight, storageRoot, false ); return true;
49,916
103
// if all epochs passed, return
if (passed == TOTAL_EPOCHS) {
if (passed == TOTAL_EPOCHS) {
43,357
246
// } else if(_option == 5){ presaleBatch[_fromBatch] = _state;
} else if(_option == 6){
} else if(_option == 6){
45,664
41
// Public Functions // Generate message hash from the input params_intentHash Intent hash. _nonce Nonce of the message sender. _gasPrice Gas price. return messageHash_ Message hash. /
function messageDigest( bytes32 _intentHash, uint256 _nonce, uint256 _gasPrice, uint256 _gasLimit, address _sender, bytes32 _hashLock ) public pure
function messageDigest( bytes32 _intentHash, uint256 _nonce, uint256 _gasPrice, uint256 _gasLimit, address _sender, bytes32 _hashLock ) public pure
34,992
371
// we take only accrued yield to distribute it with HolyRedeemer later, cap to accruedYield amount
if (harvestAmountUSDC > accruedYieldUSDC) { harvestAmountUSDC = accruedYieldUSDC; }
if (harvestAmountUSDC > accruedYieldUSDC) { harvestAmountUSDC = accruedYieldUSDC; }
41,496
69
// Our channel don't have balance, because we're always rebalancing into stake amount.
struct Channel { uint256 settled; // total amount already settled by provider uint256 stake; // amount staked by identity to guarante channel size, it also serves as channel balance uint256 lastUsedNonce; // last known nonce, is used to protect signature based calls from replay attack uint256 timelock; // blocknumber after which channel balance can be decreased }
struct Channel { uint256 settled; // total amount already settled by provider uint256 stake; // amount staked by identity to guarante channel size, it also serves as channel balance uint256 lastUsedNonce; // last known nonce, is used to protect signature based calls from replay attack uint256 timelock; // blocknumber after which channel balance can be decreased }
21,861
20
// number of people who can receive the reward
uint8 maxBackers;
uint8 maxBackers;
18,106
7
// Internal call to repay tokens to the bank on behalf of the current executor./token The token to repay to the bank./amount The amount to repay.
function doRepay(address token, uint amount) internal { if (amount > 0) { ensureApprove(token, address(bank)); bank.repay(token, amount); } }
function doRepay(address token, uint amount) internal { if (amount > 0) { ensureApprove(token, address(bank)); bank.repay(token, amount); } }
42,374
161
// new function to burn tokens from a centralized owner _who The address which will be burned. _value The amount of tokens to burn.return A boolean that indicates if the operation was successful. /
function forcedBurn(address _who, uint256 _value) public onlyBurner
function forcedBurn(address _who, uint256 _value) public onlyBurner
40,923
17
// https:eips.ethereum.org/EIPS/eip-721 tokenURI/ CosmoMasks contract Extends ERC721 Non-Fungible Token Standard basic implementation /
contract CosmoMasksLimitedPack is Ownable, CosmoMasksERC721 { using SafeMath for uint256; // This is the provenance record of all CosmoMasks artwork in existence uint256 public constant MAX_SUPPLY = 610; string public constant PROVENANCE = "d2fa4e09c05d4e578b4132118a2fb2a74247e60a1e8a95734ac3274f74923ffe"; address private _cosmoToken; address proxyRegistryAddress; string private _contractURI; constructor(address _proxyRegistryAddress) public CosmoMasksERC721("CosmoMasks Limited Pack", "COSMAS-LP") { proxyRegistryAddress = _proxyRegistryAddress; _setBaseURI("https://TheCosmoMasks.com/cosmomasks-limited-pack-metadata/"); _setURL("https://TheCosmoMasks.com/"); _contractURI = "https://TheCosmoMasks.com/cosmomasks-limited-pack-contract-metadata.json"; } function getCosmoToken() public view returns (address) { return _cosmoToken; } function contractURI() public view returns (string memory) { return _contractURI; } /** * @dev Mints CosmoMasks */ function mint(address to, uint256 numberOfMasks) public onlyOwner { require(totalSupply() < MAX_SUPPLY, "CosmoMasks: sale has already ended"); require(totalSupply().add(numberOfMasks) <= MAX_SUPPLY, "CosmoMasks: Exceeds MAX_SUPPLY"); for (uint256 i = 0; i < numberOfMasks; i++) { uint256 mintIndex = totalSupply(); _safeMint(to, mintIndex); ICosmoTokenMint(_cosmoToken).mintToFund(1e24); } } function isApprovedForAll(address owner, address operator) public view override returns (bool) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(owner)) == operator) { return true; } return super.isApprovedForAll(owner, operator); } function setCosmoToken(address token) public onlyOwner { require(_cosmoToken == address(0), "CosmoMasks: CosmosToken has already setted"); require(token != address(0), "CosmoMasks: CosmoToken is the zero address"); _cosmoToken = token; } function setBaseURI(string memory baseURI_) public onlyOwner { _setBaseURI(baseURI_); } function setContractURI(string memory contractURI_) public onlyOwner { _contractURI = contractURI_; } function setURL(string memory newUrl) public onlyOwner { _setURL(newUrl); } }
contract CosmoMasksLimitedPack is Ownable, CosmoMasksERC721 { using SafeMath for uint256; // This is the provenance record of all CosmoMasks artwork in existence uint256 public constant MAX_SUPPLY = 610; string public constant PROVENANCE = "d2fa4e09c05d4e578b4132118a2fb2a74247e60a1e8a95734ac3274f74923ffe"; address private _cosmoToken; address proxyRegistryAddress; string private _contractURI; constructor(address _proxyRegistryAddress) public CosmoMasksERC721("CosmoMasks Limited Pack", "COSMAS-LP") { proxyRegistryAddress = _proxyRegistryAddress; _setBaseURI("https://TheCosmoMasks.com/cosmomasks-limited-pack-metadata/"); _setURL("https://TheCosmoMasks.com/"); _contractURI = "https://TheCosmoMasks.com/cosmomasks-limited-pack-contract-metadata.json"; } function getCosmoToken() public view returns (address) { return _cosmoToken; } function contractURI() public view returns (string memory) { return _contractURI; } /** * @dev Mints CosmoMasks */ function mint(address to, uint256 numberOfMasks) public onlyOwner { require(totalSupply() < MAX_SUPPLY, "CosmoMasks: sale has already ended"); require(totalSupply().add(numberOfMasks) <= MAX_SUPPLY, "CosmoMasks: Exceeds MAX_SUPPLY"); for (uint256 i = 0; i < numberOfMasks; i++) { uint256 mintIndex = totalSupply(); _safeMint(to, mintIndex); ICosmoTokenMint(_cosmoToken).mintToFund(1e24); } } function isApprovedForAll(address owner, address operator) public view override returns (bool) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(owner)) == operator) { return true; } return super.isApprovedForAll(owner, operator); } function setCosmoToken(address token) public onlyOwner { require(_cosmoToken == address(0), "CosmoMasks: CosmosToken has already setted"); require(token != address(0), "CosmoMasks: CosmoToken is the zero address"); _cosmoToken = token; } function setBaseURI(string memory baseURI_) public onlyOwner { _setBaseURI(baseURI_); } function setContractURI(string memory contractURI_) public onlyOwner { _contractURI = contractURI_; } function setURL(string memory newUrl) public onlyOwner { _setURL(newUrl); } }
44,335
93
// check if it is better to keep it in local storage instead
IStakeManager stakeManager = IStakeManager(registry.getStakeManagerAddress()); uint256 _reward = stakeManager.checkSignatures( end.sub(start).add(1),
IStakeManager stakeManager = IStakeManager(registry.getStakeManagerAddress()); uint256 _reward = stakeManager.checkSignatures( end.sub(start).add(1),
29,856
4
// Exponentiation-by-squaring
while (n > 1) { if (n % 2 == 0) { x = decMul(x, x); n = n.div(2); } else { // if (n % 2 != 0)
while (n > 1) { if (n % 2 == 0) { x = decMul(x, x); n = n.div(2); } else { // if (n % 2 != 0)
4,034
31
// @inheritdoc IAutoCompoundingRewards /
function program(Token pool) external view returns (ProgramData memory) { return _programs[pool]; }
function program(Token pool) external view returns (ProgramData memory) { return _programs[pool]; }
29,976
59
// Consider: IFPD - Interest for provisional default PSPD = Pool size at provisional default IRPD = Reserves & insurance at provisional default IR = Current reserves and insurance PDU = Provisional default utilization We have: Borrows + IFPD = PDUPSPD => Borrows + IFPD = PDU(Principal + Cash + IRPD) => Borrows + IFPD = PDU(Principal + Cash + IR + IFPD(insuranceFactor + reserveFactor)) => IFPD(1 + PDU(reserveFactor + insuranceFactor)) = PDUPoolSize - Borrows => IFPD = (PDUPoolSize - Borrows) / (1 + PDU(reserveFactor + insuranceFactor))
uint256 numerator = _poolSize(_info).mulDecimal(provisionalDefaultUtilization) - _info.borrows; uint256 denominator = Decimal.ONE + provisionalDefaultUtilization.mulDecimal(reserveFactor + insuranceFactor); uint256 interestForProvisionalDefault = numerator.divDecimal(denominator); uint256 interestPerSec = _info.borrows * interestRate;
uint256 numerator = _poolSize(_info).mulDecimal(provisionalDefaultUtilization) - _info.borrows; uint256 denominator = Decimal.ONE + provisionalDefaultUtilization.mulDecimal(reserveFactor + insuranceFactor); uint256 interestForProvisionalDefault = numerator.divDecimal(denominator); uint256 interestPerSec = _info.borrows * interestRate;
1,201
16
// Price feed age greater than last medianizer age
require(age_[i] > zzz, "Median/stale-message");
require(age_[i] > zzz, "Median/stale-message");
49,755
17
// A mapping of the hash of the claim being revoked to the revocation block number
mapping(bytes32 => uint256) public documentRevoked; event DocumentIssued(bytes32 indexed document); event DocumentRevoked(bytes32 indexed document);
mapping(bytes32 => uint256) public documentRevoked; event DocumentIssued(bytes32 indexed document); event DocumentRevoked(bytes32 indexed document);
5,208
31
// Returns a named element based on the supplied attributes and contents/attributes and contents is usually generated from abi.encodePacked, attributes is expecting a leading space/name The name of the element/attributes The attributes of the element, as bytes, with a leading space/contents The contents of the element, as bytes/ return a bytes collection representing the whole element
function createElement(string memory name, bytes memory attributes, bytes memory contents) internal pure returns (bytes memory) { return abi.encodePacked( "<", attributes.length == 0 ? bytes(name) : abi.encodePacked(name, attributes), contents.length == 0 ? bytes("/>") : abi.encodePacked(">", contents, "</", name, ">") ); }
function createElement(string memory name, bytes memory attributes, bytes memory contents) internal pure returns (bytes memory) { return abi.encodePacked( "<", attributes.length == 0 ? bytes(name) : abi.encodePacked(name, attributes), contents.length == 0 ? bytes("/>") : abi.encodePacked(">", contents, "</", name, ">") ); }
32,947
9
// HasMouth
TIERS[3] = [9000, 1000];
TIERS[3] = [9000, 1000];
47,430
43
// Get quotation for Trade(token) using IUniswap router interface calls getAmountsOut to get a quotation for TRADE lender, address of the lender roundId, Id of the round rewardAPY, rewardAPYreturn quotation of amount TRADE for stable /
function _getQuotation( address lender, uint roundId, uint16 rewardAPY
function _getQuotation( address lender, uint roundId, uint16 rewardAPY
17,551
31
// Burn Tokens
totalSupply -= _amountOfTokens;
totalSupply -= _amountOfTokens;
75,979
41
// SNX won't actually be sold (burns are only distributed in available ETH) but this is a proxy for the return value of SNX that would be sold
uint256 weiPerOneSnx = getWeiPerOneSnxOnRedeem(); uint256 debtValueInWei = calculateDebtValueInWei(contractDebtValue); pricePerToken = calculateNetAssetValueOnRedeem( weiPerOneSnx, snxBalanceOwned, debtValueInWei ) .mul(DEC_18) .div(totalSupply);
uint256 weiPerOneSnx = getWeiPerOneSnxOnRedeem(); uint256 debtValueInWei = calculateDebtValueInWei(contractDebtValue); pricePerToken = calculateNetAssetValueOnRedeem( weiPerOneSnx, snxBalanceOwned, debtValueInWei ) .mul(DEC_18) .div(totalSupply);
930
65
// Creates `_sharesAmount` shares and assigns them to `_recipient`, increasing the total amount of shares. This doesn't increase the token total supply. /
function _mintShares(address _recipient, uint256 _sharesAmount) internal { require(_recipient != address(0), "XALD: mint to the zero address"); _totalShares = _totalShares.add(_sharesAmount); _shares[_recipient] = _shares[_recipient].add(_sharesAmount); emit MintShare(_recipient, _sharesAmount); }
function _mintShares(address _recipient, uint256 _sharesAmount) internal { require(_recipient != address(0), "XALD: mint to the zero address"); _totalShares = _totalShares.add(_sharesAmount); _shares[_recipient] = _shares[_recipient].add(_sharesAmount); emit MintShare(_recipient, _sharesAmount); }
48,262
13
// Arrays of 31 bytes or less have an even value in their slot, while longer arrays have an odd value. The actual length is the slot divided by two for odd values, and the lowest order byte divided by two for even values. If the slot is even, bitwise and the slot with 255 and divide by two to get the length. If the slot is odd, bitwise and the slot with -1 and divide by two.
let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) let newlength := add(slength, mlength)
let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) let newlength := add(slength, mlength)
8,860
45
// higher fee on sells within first X hours post-launch
if(_launchFeeEnd > block.timestamp) { _taxFee = 9; _teamFee = 6; }
if(_launchFeeEnd > block.timestamp) { _taxFee = 9; _teamFee = 6; }
16,288
15
// Crafting token game The game holds multiple CraftableTokens (craftables), which can becrafted by players. Crafting advanced tokens (those with ingredients)requires the player to hold the required amount of said ingredient, which will beconsumed in the crafting process. New craftables (with their ingredients) can beadded by all players. /
contract Crafty is RBAC, Initializable { // Storage for craftables. Some of them may have been zeroed-out (by a deleteCraftable // call), so validation of each CraftableToken should be performed by readers. CraftableToken[] private craftables; event CraftableAdded(address addr); event CraftableDeleted(address addr); // Role Based Access Control (RBAC) string public constant ROLE_ADMIN = "admin"; // Initializer for integration with ZeppelinOS function initialize(address _initialAdmin) isInitializer public { addRole(_initialAdmin, ROLE_ADMIN); } // Player API /** * @dev Returns the total number of craftables in the game. */ function getTotalCraftables() public view returns (uint256) { return craftables.length; } /** * @dev Returns one of the game's craftables. * @param _index The index of the requested craftable (from 0 to getTotalCraftables() - 1). */ function getCraftable(uint256 _index) public view returns (CraftableToken) { require(_index < craftables.length); return craftables[_index]; } /** * @dev Adds a new craftable to the game. * @param _name The name of the craftable. * @param _symbol The symbol of the craftable. * @param _tokenURI A URI ponting to craftable metadata (i.e. a thumbnail). * @param _ingredients A non-empty array with the different ERC20s required to craft the new token. * @param _ingredientAmounts The amount of required tokens for each ERC20. * @return The address of the newly created token. */ function addCraftable( string _name, string _symbol, string _tokenURI, ERC20[] _ingredients, uint256[] _ingredientAmounts ) public returns (CraftableToken) { require(_ingredients.length == _ingredientAmounts.length); require(_ingredients.length > 0); CraftableToken newCraftable = new CraftableToken(); newCraftable.initialize( address(this), _name, _symbol, _tokenURI, _ingredients, _ingredientAmounts); craftables.push(newCraftable); emit CraftableAdded(newCraftable); return newCraftable; } /** * @dev Adds a pre-created craftable token to the game. No tests are * performed on the craftable to make sure its valid. Only admin * users can do this. After this call, ownsership of the token must be * transferred to the Crafty contract, to allow it to mint tokens. * @param _craftable The address of the craftable token to add. */ function addPrecreatedCraftable(CraftableToken _craftable) onlyRole(ROLE_ADMIN) public { craftables.push(_craftable); emit CraftableAdded(_craftable); } /** * @dev Crafts a craftable. The player must have allowed Crafty to use his * ingredient tokens, which will be transferred to the game contract during crafting. * @param _craftable The craftable to craft. */ function craft(CraftableToken _craftable) public { address player = msg.sender; uint256 totalSteps = _craftable.getTotalRecipeSteps(); for (uint i = 0; i < totalSteps; ++i) { ERC20 ingredient; uint256 amountNeeded; (ingredient, amountNeeded) = _craftable.getRecipeStep(i); ingredient.transferFrom(player, address(this), amountNeeded); } // Issue the crafted token - for ingredient-less tokens, a higher number of // tokens are minted. uint256 tokensToMint = (totalSteps == 0) ? 100 : 1; _craftable.mint(player, tokensToMint); } // Admin API /** * @dev Adds a new admin. * @param _user The address of the new admin. */ function addAdminRole(address _user) onlyRole(ROLE_ADMIN) public { addRole(_user, ROLE_ADMIN); } /** * @dev Deletes a craftable from the game. * @param _index The index in the craftables array of the craftable to delete. */ function deleteCraftable(uint256 _index) onlyRole(ROLE_ADMIN) public { require(_index < craftables.length); emit CraftableDeleted(craftables[_index]); delete craftables[_index]; } }
contract Crafty is RBAC, Initializable { // Storage for craftables. Some of them may have been zeroed-out (by a deleteCraftable // call), so validation of each CraftableToken should be performed by readers. CraftableToken[] private craftables; event CraftableAdded(address addr); event CraftableDeleted(address addr); // Role Based Access Control (RBAC) string public constant ROLE_ADMIN = "admin"; // Initializer for integration with ZeppelinOS function initialize(address _initialAdmin) isInitializer public { addRole(_initialAdmin, ROLE_ADMIN); } // Player API /** * @dev Returns the total number of craftables in the game. */ function getTotalCraftables() public view returns (uint256) { return craftables.length; } /** * @dev Returns one of the game's craftables. * @param _index The index of the requested craftable (from 0 to getTotalCraftables() - 1). */ function getCraftable(uint256 _index) public view returns (CraftableToken) { require(_index < craftables.length); return craftables[_index]; } /** * @dev Adds a new craftable to the game. * @param _name The name of the craftable. * @param _symbol The symbol of the craftable. * @param _tokenURI A URI ponting to craftable metadata (i.e. a thumbnail). * @param _ingredients A non-empty array with the different ERC20s required to craft the new token. * @param _ingredientAmounts The amount of required tokens for each ERC20. * @return The address of the newly created token. */ function addCraftable( string _name, string _symbol, string _tokenURI, ERC20[] _ingredients, uint256[] _ingredientAmounts ) public returns (CraftableToken) { require(_ingredients.length == _ingredientAmounts.length); require(_ingredients.length > 0); CraftableToken newCraftable = new CraftableToken(); newCraftable.initialize( address(this), _name, _symbol, _tokenURI, _ingredients, _ingredientAmounts); craftables.push(newCraftable); emit CraftableAdded(newCraftable); return newCraftable; } /** * @dev Adds a pre-created craftable token to the game. No tests are * performed on the craftable to make sure its valid. Only admin * users can do this. After this call, ownsership of the token must be * transferred to the Crafty contract, to allow it to mint tokens. * @param _craftable The address of the craftable token to add. */ function addPrecreatedCraftable(CraftableToken _craftable) onlyRole(ROLE_ADMIN) public { craftables.push(_craftable); emit CraftableAdded(_craftable); } /** * @dev Crafts a craftable. The player must have allowed Crafty to use his * ingredient tokens, which will be transferred to the game contract during crafting. * @param _craftable The craftable to craft. */ function craft(CraftableToken _craftable) public { address player = msg.sender; uint256 totalSteps = _craftable.getTotalRecipeSteps(); for (uint i = 0; i < totalSteps; ++i) { ERC20 ingredient; uint256 amountNeeded; (ingredient, amountNeeded) = _craftable.getRecipeStep(i); ingredient.transferFrom(player, address(this), amountNeeded); } // Issue the crafted token - for ingredient-less tokens, a higher number of // tokens are minted. uint256 tokensToMint = (totalSteps == 0) ? 100 : 1; _craftable.mint(player, tokensToMint); } // Admin API /** * @dev Adds a new admin. * @param _user The address of the new admin. */ function addAdminRole(address _user) onlyRole(ROLE_ADMIN) public { addRole(_user, ROLE_ADMIN); } /** * @dev Deletes a craftable from the game. * @param _index The index in the craftables array of the craftable to delete. */ function deleteCraftable(uint256 _index) onlyRole(ROLE_ADMIN) public { require(_index < craftables.length); emit CraftableDeleted(craftables[_index]); delete craftables[_index]; } }
11,940
2
// Sale Stages Enabled / Disabled
bool public whitelistMintEnabled = false; bool public publicMintEnabled = false;
bool public whitelistMintEnabled = false; bool public publicMintEnabled = false;
56,736
30
// Unpauses a token, done by Krypital token_id - just token id /
function unpauseToken(uint token_id) public onlyOLevel hasKT(token_id){ KT storage currKT = KTs[token_id]; currKT.paused = false; emit UnpauseToken(token_id); }
function unpauseToken(uint token_id) public onlyOLevel hasKT(token_id){ KT storage currKT = KTs[token_id]; currKT.paused = false; emit UnpauseToken(token_id); }
31,918
10
// External view Function Interface to implement on final contract /
function name() virtual external view returns (string memory tokenName); function symbol() virtual external view returns (string memory tokenSymbol); function decimals() virtual external view returns (uint8 tokenDecimals);
function name() virtual external view returns (string memory tokenName); function symbol() virtual external view returns (string memory tokenSymbol); function decimals() virtual external view returns (uint8 tokenDecimals);
13,165
10
// Check that the owner is the transaction sender
require(domains[name] == msg.sender); records[name] = record;
require(domains[name] == msg.sender); records[name] = record;
28,491
40
// Gets the eligible stake balance of the specified address./ An eligible stake is a stake that passed the initialization period/ and is not currently undelegating. Also, the operator had to approve/ the specified operator contract.// Operator with a minimum required amount of eligible stake can join the/ network and participate in new work selection.//_operator address of stake operator./_operatorContract address of operator contract./ return an uint256 representing the eligible stake balance.
function eligibleStake( address _operator, address _operatorContract
function eligibleStake( address _operator, address _operatorContract
7,815
0
// a bidding must be active for atleast 10 minutes to let all players place their bid
uint constant BID_ACTIVE_TIME = 600;
uint constant BID_ACTIVE_TIME = 600;
43,132
155
// This function allows for the wallet to send a batch of transactions instead of one,/ it calls executeTransaction() so that the daily limit is enforced./_transactionBatch data encoding the transactions to be sent,/ following executeTransaction's format i.e. (destination, value, data)
function batchExecuteTransaction(bytes memory _transactionBatch) public onlyOwnerOrSelf { uint256 batchLength = _transactionBatch.length + 32; // because the pos starts from 32 uint256 remainingBytesLength = _transactionBatch.length; // remaining bytes to be processed uint256 pos = 32; //the first 32 bytes denote the byte array length, start from actual data address destination; // destination address uint256 value; // trasanction value uint256 dataLength; // externall call data length bytes memory data; // call data while (pos < batchLength) { // there should always be at least 84 bytes remaining: the minimun #bytes required to encode a Tx remainingBytesLength = remainingBytesLength.sub(84); assembly { // shift right by 96 bits (256 - 160) to get the destination address (and zero the excessive bytes) destination := shr(96, mload(add(_transactionBatch, pos))) // get value: pos + 20 bytes (destinnation address) value := mload(add(_transactionBatch, add(pos, 20))) // get data: pos + 20 (destination address) + 32 (value) bytes // the first 32 bytes denote the byte array length dataLength := mload(add(_transactionBatch, add(pos, 52))) data := add(_transactionBatch, add(pos, 52)) } // pos += 20 + 32 + 32 + dataLength, reverts in case of overflow pos = pos.add(dataLength).add(84); // revert in case the encoded dataLength is gonna cause an out of bound access require(pos <= batchLength, "out of bounds"); // if length is 0 ignore the data field if (dataLength == 0) { data = bytes(""); } // call executeTransaction(), if one of them reverts then the whole batch reverts. executeTransaction(destination, value, data); } }
function batchExecuteTransaction(bytes memory _transactionBatch) public onlyOwnerOrSelf { uint256 batchLength = _transactionBatch.length + 32; // because the pos starts from 32 uint256 remainingBytesLength = _transactionBatch.length; // remaining bytes to be processed uint256 pos = 32; //the first 32 bytes denote the byte array length, start from actual data address destination; // destination address uint256 value; // trasanction value uint256 dataLength; // externall call data length bytes memory data; // call data while (pos < batchLength) { // there should always be at least 84 bytes remaining: the minimun #bytes required to encode a Tx remainingBytesLength = remainingBytesLength.sub(84); assembly { // shift right by 96 bits (256 - 160) to get the destination address (and zero the excessive bytes) destination := shr(96, mload(add(_transactionBatch, pos))) // get value: pos + 20 bytes (destinnation address) value := mload(add(_transactionBatch, add(pos, 20))) // get data: pos + 20 (destination address) + 32 (value) bytes // the first 32 bytes denote the byte array length dataLength := mload(add(_transactionBatch, add(pos, 52))) data := add(_transactionBatch, add(pos, 52)) } // pos += 20 + 32 + 32 + dataLength, reverts in case of overflow pos = pos.add(dataLength).add(84); // revert in case the encoded dataLength is gonna cause an out of bound access require(pos <= batchLength, "out of bounds"); // if length is 0 ignore the data field if (dataLength == 0) { data = bytes(""); } // call executeTransaction(), if one of them reverts then the whole batch reverts. executeTransaction(destination, value, data); } }
16,991
166
// Hash has been marked for consumption. If this hash was pre-approved free storage
if (consumeHash && msg.sender != currentOwner) { approvedHashes[currentOwner][dataHash] = 0; }
if (consumeHash && msg.sender != currentOwner) { approvedHashes[currentOwner][dataHash] = 0; }
25,687
10
// Update director's boardseat
Boardseat memory director = directors[msg.sender]; director.shares = director.shares.add(amount); directors[msg.sender] = director;
Boardseat memory director = directors[msg.sender]; director.shares = director.shares.add(amount); directors[msg.sender] = director;
41,241
34
// Create a new bounty
Bounty memory newBounty = Bounty(true, true, amount, title, description);
Bounty memory newBounty = Bounty(true, true, amount, title, description);
1,392
0
// fileTypes, fileNames are comma separated string. ex) fileTypes: hash => "photo, photo, photo"/
mapping(bytes32 => string) public fileTypes; mapping(bytes32 => string) public fileNames; mapping(bytes32 => uint256) public registrationDates; bool private _initialized;
mapping(bytes32 => string) public fileTypes; mapping(bytes32 => string) public fileNames; mapping(bytes32 => uint256) public registrationDates; bool private _initialized;
41,109
12
// Fetch the total number of assets /
function assetsLength() public view returns (uint256) { return registry.numAssets() - numberOfDeprecatedAssets; }
function assetsLength() public view returns (uint256) { return registry.numAssets() - numberOfDeprecatedAssets; }
8,338
254
// Mints new ESDS tokens to a specified `account` Non-reentrant Owner only - governance hook ESDS maxes out at ~79b total supply (2^96/10^18) due to its 96-bit limitation Will revert if totalSupply exceeds this maximum account Account to mint ESDS to amount Amount of ESDS to mint /
function mintStake(address account, uint256 amount) public onlyOwner { address stake = registry().stake(); IManagedToken(stake).mint(amount); IERC20(stake).safeTransfer(account, amount); emit MintStake(account, amount); }
function mintStake(address account, uint256 amount) public onlyOwner { address stake = registry().stake(); IManagedToken(stake).mint(amount); IERC20(stake).safeTransfer(account, amount); emit MintStake(account, amount); }
63,176
14
// Add user to the white list.
function addToWhiteList(address _add) public onlyOwner { whiteList[_add] = true; emit AddToWhiteList(_add, owner, now); }
function addToWhiteList(address _add) public onlyOwner { whiteList[_add] = true; emit AddToWhiteList(_add, owner, now); }
23,454
92
// total amount of underlying transferred from vault
uint public override totalDebt;
uint public override totalDebt;
61,848
201
// Mint Functions For PreSale & Public
function mint(uint chosenAmount) public payable isSaleOpen { require(_TOTALSUPPLY >= chosenAmount, "Chosen amount is greater than supply"); require(isSalePaused == false, "Sale is not active at the moment"); require(totalSupply() + chosenAmount <= _TOTALSUPPLY, "Quantity must be lesser then MaxSupply"); require(chosenAmount <= publicSaleMaxQuantity && chosenAmount > 0, "Chosen Amount Should be greater then 0 and less then max quantity"); require(publicSaleprice.mul(chosenAmount) == msg.value, "Sent ether value is incorrect"); for (uint i = 0; i < chosenAmount; i++) { _safeMint(msg.sender, totalsupply()); tokenId++; } }
function mint(uint chosenAmount) public payable isSaleOpen { require(_TOTALSUPPLY >= chosenAmount, "Chosen amount is greater than supply"); require(isSalePaused == false, "Sale is not active at the moment"); require(totalSupply() + chosenAmount <= _TOTALSUPPLY, "Quantity must be lesser then MaxSupply"); require(chosenAmount <= publicSaleMaxQuantity && chosenAmount > 0, "Chosen Amount Should be greater then 0 and less then max quantity"); require(publicSaleprice.mul(chosenAmount) == msg.value, "Sent ether value is incorrect"); for (uint i = 0; i < chosenAmount; i++) { _safeMint(msg.sender, totalsupply()); tokenId++; } }
45,057
165
// Check what we received
address[] memory rewardTokens = supportedRewardTokens(); uint256[] memory rewardAmounts = new uint256[](rewardTokens.length); uint256 receivedRewardTokensCount; for(uint256 i = 0; i < rewardTokens.length; i++) { address rtkn = rewardTokens[i]; uint256 newBalance = IERC20(rtkn).balanceOf(address(this)); if(newBalance > rewardBalances[rtkn]) { receivedRewardTokensCount++; rewardAmounts[i] = newBalance.sub(rewardBalances[rtkn]); rewardBalances[rtkn] = newBalance;
address[] memory rewardTokens = supportedRewardTokens(); uint256[] memory rewardAmounts = new uint256[](rewardTokens.length); uint256 receivedRewardTokensCount; for(uint256 i = 0; i < rewardTokens.length; i++) { address rtkn = rewardTokens[i]; uint256 newBalance = IERC20(rtkn).balanceOf(address(this)); if(newBalance > rewardBalances[rtkn]) { receivedRewardTokensCount++; rewardAmounts[i] = newBalance.sub(rewardBalances[rtkn]); rewardBalances[rtkn] = newBalance;
50,340
4
// Environment TraitsSmart Contract - 4.00%Near Future- 8.00%Reneqade Node- 16.00%Depths of Defi - 32.00%Gas Belt - 40.00% /
_ENVIRONMENT_PROBABILITY_.push(400); _ENVIRONMENT_PROBABILITY_.push(800); _ENVIRONMENT_PROBABILITY_.push(1600); _ENVIRONMENT_PROBABILITY_.push(3200); _ENVIRONMENT_PROBABILITY_.push(4000);
_ENVIRONMENT_PROBABILITY_.push(400); _ENVIRONMENT_PROBABILITY_.push(800); _ENVIRONMENT_PROBABILITY_.push(1600); _ENVIRONMENT_PROBABILITY_.push(3200); _ENVIRONMENT_PROBABILITY_.push(4000);
28,286
5
// remove a locker It should emit a LockerRemoved event
function removeLocker(address pool) external;
function removeLocker(address pool) external;
37,858
37
// Utility functions used internally/
function _random(uint tokenId) private view returns (bytes32) { return (keccak256(abi.encodePacked(tokenId, block.timestamp, blockhash(block.number - 1)))); }
function _random(uint tokenId) private view returns (bytes32) { return (keccak256(abi.encodePacked(tokenId, block.timestamp, blockhash(block.number - 1)))); }
21,758
158
// Mints sets to both the manager and the protocol. Protocol takes a percentage fee of the total amount of Setsminted to manager._setToken SetToken instance _feeQuantityAmount of Sets to be minted as feesreturnuint256 Amount of Sets accrued to manager as feereturnuint256 Amount of Sets accrued to protocol as fee /
function _mintManagerAndProtocolFee(ISetToken _setToken, uint256 _feeQuantity) internal returns (uint256, uint256) { address protocolFeeRecipient = controller.feeRecipient(); uint256 protocolFee = controller.getModuleFee(address(this), PROTOCOL_STREAMING_FEE_INDEX); uint256 protocolFeeAmount = _feeQuantity.preciseMul(protocolFee); uint256 managerFeeAmount = _feeQuantity.sub(protocolFeeAmount); _setToken.mint(_feeRecipient(_setToken), managerFeeAmount); if (protocolFeeAmount > 0) { _setToken.mint(protocolFeeRecipient, protocolFeeAmount); } return (managerFeeAmount, protocolFeeAmount); }
function _mintManagerAndProtocolFee(ISetToken _setToken, uint256 _feeQuantity) internal returns (uint256, uint256) { address protocolFeeRecipient = controller.feeRecipient(); uint256 protocolFee = controller.getModuleFee(address(this), PROTOCOL_STREAMING_FEE_INDEX); uint256 protocolFeeAmount = _feeQuantity.preciseMul(protocolFee); uint256 managerFeeAmount = _feeQuantity.sub(protocolFeeAmount); _setToken.mint(_feeRecipient(_setToken), managerFeeAmount); if (protocolFeeAmount > 0) { _setToken.mint(protocolFeeRecipient, protocolFeeAmount); } return (managerFeeAmount, protocolFeeAmount); }
23,107
68
// If we want to rebrand, we can. /
function setName(string _name) onlyAdministrator() public
function setName(string _name) onlyAdministrator() public
6,676
262
// Assign OWNER_ROLE and DELEGATION_ADMIN_ROLE to the sender.
_setupRole(OWNER_ROLE, msg.sender); _setupRole(DELEGATION_ADMIN_ROLE, msg.sender);
_setupRole(OWNER_ROLE, msg.sender); _setupRole(DELEGATION_ADMIN_ROLE, msg.sender);
76,042
87
// no author for root post 0
voteCost = _voteCost; postCost = _postCost; nextPostCost = _postCost; epochLength = _epochLength; endTimestamp = now + epochLength;
voteCost = _voteCost; postCost = _postCost; nextPostCost = _postCost; epochLength = _epochLength; endTimestamp = now + epochLength;
37,092
133
// Minimum gain required to buy WETH is about 0.01 tokens
31,536
1,229
// Redeems pool tokens on Uniswap/_vaultProxy The VaultProxy of the calling fund/_encodedCallArgs Encoded order parameters/_encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function redeem( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { (
function redeem( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { (
83,199
25
// We're done!
return;
return;
10,205
159
// `msg.sender` approves `_spender` to spend `_value` tokens/_spender The address of the account able to transfer the tokens/_value The amount of tokens to be approved for transfer/ return success Whether the approval was successful or not
function approve(address _spender, uint256 _value) virtual public returns (bool success);
function approve(address _spender, uint256 _value) virtual public returns (bool success);
2,601
46
// This function checks if two strings are equal. Note, Solidity handles bytes32 and string as a different data type
* @param {string} _a * first string * @param {string} _b * second string *@return {bool} *boolean value */ function stringsEqual(string storage _a, string memory _b) internal returns(bool) { bytes storage a = bytes(_a); bytes memory b = bytes(_b); if (a.length != b.length) return false; for (uint i = 0; i < a.length; i++) { if (a[i] != b[i]) return false; } return true; }
* @param {string} _a * first string * @param {string} _b * second string *@return {bool} *boolean value */ function stringsEqual(string storage _a, string memory _b) internal returns(bool) { bytes storage a = bytes(_a); bytes memory b = bytes(_b); if (a.length != b.length) return false; for (uint i = 0; i < a.length; i++) { if (a[i] != b[i]) return false; } return true; }
14,925
274
// if `ownership.addr != address(0)`. The `addr` already has it's upper 96 bits clearned, since it is written to memory with regular Solidity.
if mload(ownership) { currOwnershipAddr := mload(ownership) }
if mload(ownership) { currOwnershipAddr := mload(ownership) }
34,714
32
// let's return _refund back to the relayer
_relayer.transfer(_refund);
_relayer.transfer(_refund);
29,390