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
225
// require(msg.sender == creator, "You aren't creator of this token Id!");
require(!cancelTransfer, "TokenId creator may only burn it or send a copy.");
require(!cancelTransfer, "TokenId creator may only burn it or send a copy.");
4,721
18
// define gas limit for eth distribution per transfer
function setGasLimit(uint gasLimit) public onlyAdmins
function setGasLimit(uint gasLimit) public onlyAdmins
36,277
63
// Due to rounding issues of some tokens, we use the differential token balance of this contract
_ctx[i] += _getBalanceOf(IERC20(_zap.roots[i])) - beforeAmount;
_ctx[i] += _getBalanceOf(IERC20(_zap.roots[i])) - beforeAmount;
53,632
235
// 🐧 we use different reward function, so instead the code above:
uint256 totalSushiReward = totalRewardAtBlock(block.number).sub(totalRewardAtBlock(pool.lastRewardBlock)); uint256 totalSushiRewardForPool = totalSushiReward.mul(pool.allocPoint).div(totalAllocPoint); accSushiPerShare = accSushiPerShare.add(totalSushiRewardForPool.mul(1e12).div(lpSupply));
uint256 totalSushiReward = totalRewardAtBlock(block.number).sub(totalRewardAtBlock(pool.lastRewardBlock)); uint256 totalSushiRewardForPool = totalSushiReward.mul(pool.allocPoint).div(totalAllocPoint); accSushiPerShare = accSushiPerShare.add(totalSushiRewardForPool.mul(1e12).div(lpSupply));
8,085
243
// Withdraw from vault.
uint256[] memory redeemedIds = withdrawNFTsTo(amount, specificIds, to); emit Redeemed(redeemedIds, specificIds, to); return redeemedIds;
uint256[] memory redeemedIds = withdrawNFTsTo(amount, specificIds, to); emit Redeemed(redeemedIds, specificIds, to); return redeemedIds;
29,994
377
// voteStatus returns the reputation voted for a proposal for a specific voting choice._proposalId the ID of the proposal_choice the index in the return voted reputation for the given choice/
function voteStatus(bytes32 _proposalId,uint _choice) external view returns(uint) { return proposals[_proposalId].votes[_choice]; }
function voteStatus(bytes32 _proposalId,uint _choice) external view returns(uint) { return proposals[_proposalId].votes[_choice]; }
37,186
0
// ========== ERRORS ========== // ========== IMMUTABLE PARAMETERS ========== //The token that the option is on/ return _payout The address of the payout token
function payout() public pure returns (ERC20 _payout) { return ERC20(_getArgAddress(0x41)); }
function payout() public pure returns (ERC20 _payout) { return ERC20(_getArgAddress(0x41)); }
30,102
237
// Will only trigger during construction. Batch transferring (minting) is not available afterwards.
revert("ERC721Enumerable: consecutive transfers not supported");
revert("ERC721Enumerable: consecutive transfers not supported");
21,416
120
// Destroys `amount` tokens from `account`, reducing thetotal supply.
* Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); }
* Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); }
40,273
90
// ======== INTERNAL/PRIVATE FUNCTIONS ======== //Compute all winners and losers for the first round.
function _firstRoundFight() private { // Get all hero powers. uint heroPower0 = participants[0].heroPower; uint heroPower1 = participants[1].heroPower; uint heroPower2 = participants[2].heroPower; uint heroPower3 = participants[3].heroPower; uint heroPower4 = participants[4].heroPower; uint heroPower5 = participants[5].heroPower; uint heroPower6 = participants[6].heroPower; uint heroPower7 = participants[7].heroPower; // Random number. uint rand; // 0 Vs 1 rand = _getRandomNumber(100); if ( (heroPower0 > heroPower1 && rand < 60) || (heroPower0 == heroPower1 && rand < 50) || (heroPower0 < heroPower1 && rand < 40) ) { firstRoundWinners[0] = 0; firstRoundLosers[0] = 1; } else { firstRoundWinners[0] = 1; firstRoundLosers[0] = 0; } // 2 Vs 3 rand = _getRandomNumber(100); if ( (heroPower2 > heroPower3 && rand < 60) || (heroPower2 == heroPower3 && rand < 50) || (heroPower2 < heroPower3 && rand < 40) ) { firstRoundWinners[1] = 2; firstRoundLosers[1] = 3; } else { firstRoundWinners[1] = 3; firstRoundLosers[1] = 2; } // 4 Vs 5 rand = _getRandomNumber(100); if ( (heroPower4 > heroPower5 && rand < 60) || (heroPower4 == heroPower5 && rand < 50) || (heroPower4 < heroPower5 && rand < 40) ) { firstRoundWinners[2] = 4; firstRoundLosers[2] = 5; } else { firstRoundWinners[2] = 5; firstRoundLosers[2] = 4; } // 6 Vs 7 rand = _getRandomNumber(100); if ( (heroPower6 > heroPower7 && rand < 60) || (heroPower6 == heroPower7 && rand < 50) || (heroPower6 < heroPower7 && rand < 40) ) { firstRoundWinners[3] = 6; firstRoundLosers[3] = 7; } else { firstRoundWinners[3] = 7; firstRoundLosers[3] = 6; } }
function _firstRoundFight() private { // Get all hero powers. uint heroPower0 = participants[0].heroPower; uint heroPower1 = participants[1].heroPower; uint heroPower2 = participants[2].heroPower; uint heroPower3 = participants[3].heroPower; uint heroPower4 = participants[4].heroPower; uint heroPower5 = participants[5].heroPower; uint heroPower6 = participants[6].heroPower; uint heroPower7 = participants[7].heroPower; // Random number. uint rand; // 0 Vs 1 rand = _getRandomNumber(100); if ( (heroPower0 > heroPower1 && rand < 60) || (heroPower0 == heroPower1 && rand < 50) || (heroPower0 < heroPower1 && rand < 40) ) { firstRoundWinners[0] = 0; firstRoundLosers[0] = 1; } else { firstRoundWinners[0] = 1; firstRoundLosers[0] = 0; } // 2 Vs 3 rand = _getRandomNumber(100); if ( (heroPower2 > heroPower3 && rand < 60) || (heroPower2 == heroPower3 && rand < 50) || (heroPower2 < heroPower3 && rand < 40) ) { firstRoundWinners[1] = 2; firstRoundLosers[1] = 3; } else { firstRoundWinners[1] = 3; firstRoundLosers[1] = 2; } // 4 Vs 5 rand = _getRandomNumber(100); if ( (heroPower4 > heroPower5 && rand < 60) || (heroPower4 == heroPower5 && rand < 50) || (heroPower4 < heroPower5 && rand < 40) ) { firstRoundWinners[2] = 4; firstRoundLosers[2] = 5; } else { firstRoundWinners[2] = 5; firstRoundLosers[2] = 4; } // 6 Vs 7 rand = _getRandomNumber(100); if ( (heroPower6 > heroPower7 && rand < 60) || (heroPower6 == heroPower7 && rand < 50) || (heroPower6 < heroPower7 && rand < 40) ) { firstRoundWinners[3] = 6; firstRoundLosers[3] = 7; } else { firstRoundWinners[3] = 7; firstRoundLosers[3] = 6; } }
77,072
164
// ´:°•.°+.•´.:˚.°.˚•´.°:°•.°•.•´.:˚.°.˚•´.°:°•.°+.•´.://INTERNAL TRANSFER FUNCTIONS //.•°:°.´+˚.°.˚:.´•.+°.•°:´.´•.•°.•°:°.´:•˚°.°.˚:.´+°.•//Moves `amount` of tokens from `from` to `to`.
function _transfer(address from, address to, uint256 amount) internal virtual { _beforeTokenTransfer(from, to, amount); /// @solidity memory-safe-assembly assembly { let from_ := shl(96, from) // Compute the balance slot and load its value. mstore(0x0c, or(from_, _BALANCE_SLOT_SEED)) let fromBalanceSlot := keccak256(0x0c, 0x20) let fromBalance := sload(fromBalanceSlot) // Revert if insufficient balance. if gt(amount, fromBalance) { mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`. revert(0x1c, 0x04) } // Subtract and store the updated balance. sstore(fromBalanceSlot, sub(fromBalance, amount)) // Compute the balance slot of `to`. mstore(0x00, to) let toBalanceSlot := keccak256(0x0c, 0x20) // Add and store the updated balance of `to`. // Will not overflow because the sum of all user balances // cannot exceed the maximum uint256 value. sstore(toBalanceSlot, add(sload(toBalanceSlot), amount)) // Emit the {Transfer} event. mstore(0x20, amount) log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, from_), shr(96, mload(0x0c))) } _afterTokenTransfer(from, to, amount); }
function _transfer(address from, address to, uint256 amount) internal virtual { _beforeTokenTransfer(from, to, amount); /// @solidity memory-safe-assembly assembly { let from_ := shl(96, from) // Compute the balance slot and load its value. mstore(0x0c, or(from_, _BALANCE_SLOT_SEED)) let fromBalanceSlot := keccak256(0x0c, 0x20) let fromBalance := sload(fromBalanceSlot) // Revert if insufficient balance. if gt(amount, fromBalance) { mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`. revert(0x1c, 0x04) } // Subtract and store the updated balance. sstore(fromBalanceSlot, sub(fromBalance, amount)) // Compute the balance slot of `to`. mstore(0x00, to) let toBalanceSlot := keccak256(0x0c, 0x20) // Add and store the updated balance of `to`. // Will not overflow because the sum of all user balances // cannot exceed the maximum uint256 value. sstore(toBalanceSlot, add(sload(toBalanceSlot), amount)) // Emit the {Transfer} event. mstore(0x20, amount) log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, from_), shr(96, mload(0x0c))) } _afterTokenTransfer(from, to, amount); }
17,351
338
// `PARENT_TOKEN` is the Token address that was cloned to produce this token;it will be 0x0 for a token that was not cloned
IClonedTokenParent private PARENT_TOKEN;
IClonedTokenParent private PARENT_TOKEN;
27,917
76
// Called by the admin to burn options tokens and transfer underlying tokens to the caller./_amount The amount of options tokens that will be burned and underlying tokens transferred to the caller
function burn(uint256 _amount) external onlyAdmin { // transfer underlying tokens to the caller _safeTransfer(underlyingToken, msg.sender, _amount); // burn option tokens _burn(msg.sender, _amount); }
function burn(uint256 _amount) external onlyAdmin { // transfer underlying tokens to the caller _safeTransfer(underlyingToken, msg.sender, _amount); // burn option tokens _burn(msg.sender, _amount); }
15,913
14
// Ensure this contract is approved to move the token
require( IERC721(_nftAddress).ownerOf(_tokenId) == _msgSender() && IERC721(_nftAddress).isApprovedForAll( _msgSender(), address(this) ), "FomoAuction.createAuction: Not owner and or contract not approved" ); _createAuction(
require( IERC721(_nftAddress).ownerOf(_tokenId) == _msgSender() && IERC721(_nftAddress).isApprovedForAll( _msgSender(), address(this) ), "FomoAuction.createAuction: Not owner and or contract not approved" ); _createAuction(
22,984
3
// Store mathProblems in memory rather than contract's storage
address[5] memory mathProblems = mathProblem.getMathProblems(); Assert.equal(mathProblems[expectedNumberId], expectedSolver, "Owner of the expected pet should be this contract");
address[5] memory mathProblems = mathProblem.getMathProblems(); Assert.equal(mathProblems[expectedNumberId], expectedSolver, "Owner of the expected pet should be this contract");
30,424
226
// Lists of (timestamp, quantity) pairs per account, sorted in ascending time order. These are the times at which each given quantity of havvens vests.
mapping(address => uint[2][]) public vestingSchedules;
mapping(address => uint[2][]) public vestingSchedules;
35,832
81
// Strategies approved for use by the Vault
struct Strategy { bool isSupported; uint256 _deprecated; // Deprecated storage slot }
struct Strategy { bool isSupported; uint256 _deprecated; // Deprecated storage slot }
60,710
130
// Convert signed 64.64 fixed point number into signed 64-bit integer numberrounding down.x signed 64.64-bit fixed point numberreturn signed 64-bit integer number /
function toInt (int128 x) internal pure returns (int64) { return int64 (x >> 64); }
function toInt (int128 x) internal pure returns (int64) { return int64 (x >> 64); }
23,934
30
// RECEIVE/Method for receiving an Ethereum contract that issues an event.
receive() external payable {} // PUBLIC FUNCTIONS /** * @notice Method for voting "for" or "against" a given proposal * @dev This method calls the _castVote function defined in the Governor.sol contract. * @dev Since proposals in the CompanyDAO protocol can be prematurely finalized, after each successful invocation of this method, a check is performed for the occurrence of such conditions. * @param proposalId Pool proposal ID * @param support "True" for voting "for", "False" for voting "against" */ function castVote( uint256 proposalId, bool support ) external nonReentrant whenNotPaused { _castVote(proposalId, support); service.registry().log( msg.sender, address(this), 0, abi.encodeWithSelector(IPool.castVote.selector, proposalId, support) ); }
receive() external payable {} // PUBLIC FUNCTIONS /** * @notice Method for voting "for" or "against" a given proposal * @dev This method calls the _castVote function defined in the Governor.sol contract. * @dev Since proposals in the CompanyDAO protocol can be prematurely finalized, after each successful invocation of this method, a check is performed for the occurrence of such conditions. * @param proposalId Pool proposal ID * @param support "True" for voting "for", "False" for voting "against" */ function castVote( uint256 proposalId, bool support ) external nonReentrant whenNotPaused { _castVote(proposalId, support); service.registry().log( msg.sender, address(this), 0, abi.encodeWithSelector(IPool.castVote.selector, proposalId, support) ); }
34,058
17
// Resets happen in regular intervals and `lastResetMin` should be aligned to that
allowance.lastResetMin = currentMin - ((currentMin - allowance.lastResetMin) % allowance.resetTimeMin);
allowance.lastResetMin = currentMin - ((currentMin - allowance.lastResetMin) % allowance.resetTimeMin);
6,505
26
// returns INSUR rewards in base asset
_rewardsBase = _priceFeed.howManyTokensAinB( address(base), insurToken, swapRewardsVia, _rewards, true );
_rewardsBase = _priceFeed.howManyTokensAinB( address(base), insurToken, swapRewardsVia, _rewards, true );
36,405
96
// toBytesPrefixedprefix a bytes32 value with "\x19Ethereum Signed Message:" and hash the result/
function toBytesPrefixed(bytes32 hash) internal pure returns (bytes32)
function toBytesPrefixed(bytes32 hash) internal pure returns (bytes32)
72,509
5
// @note Place the length of the result value into the output
mstore(result, returndatasize())
mstore(result, returndatasize())
17,689
264
// fallback function, used to buy tokens and refill the contract for oraclize
function () public payable { address _sender = msg.sender; uint256 _funds = msg.value; if (betexStorage.isWhitelisted(_sender)) { buyTokens(_sender, _funds); } else if (!refillers[_sender] && !(owner == _sender)) { revert(); } }
function () public payable { address _sender = msg.sender; uint256 _funds = msg.value; if (betexStorage.isWhitelisted(_sender)) { buyTokens(_sender, _funds); } else if (!refillers[_sender] && !(owner == _sender)) { revert(); } }
24,255
512
// Packs together two uint112 and one uint32 into a bytes32 /
function _pack( uint256 _leastSignificant, uint256 _midSignificant, uint256 _mostSignificant
function _pack( uint256 _leastSignificant, uint256 _midSignificant, uint256 _mostSignificant
32,405
12
// CONTRACT /
contract TokenERC20Interface { function totalSupply() public constant returns (uint coinLifeTimeTotalSupply); function balanceOf(address tokenOwner) public constant returns (uint coinBalance); function allowance(address tokenOwner, address spender) public constant returns (uint coinsRemaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address _from, address to, uint tokens) public returns (bool success); event Transfer(address indexed _from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); }
contract TokenERC20Interface { function totalSupply() public constant returns (uint coinLifeTimeTotalSupply); function balanceOf(address tokenOwner) public constant returns (uint coinBalance); function allowance(address tokenOwner, address spender) public constant returns (uint coinsRemaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address _from, address to, uint tokens) public returns (bool success); event Transfer(address indexed _from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); }
40,579
13
// Buys a martian for a specific price (payable)/The martian must be for sale before other user calls this method. If the same user had the higher bid before, it gets refunded into the pending withdrawals. On success, emits the MartianBought event. Executes a ERC721 safeTransferFrom/tokenId The id of the martian to be bought
function buyMartian(uint tokenId) external payable { require(msg.sender != nonFungibleContract.ownerOf(tokenId), "You cant buy your own martian"); Offer memory offer = martianIdToOfferForSale[tokenId]; require(offer.isForSale, "Item is not for sale"); require(offer.seller == nonFungibleContract.ownerOf(tokenId), "Seller is no longer the owner of the item"); require(msg.value >= offer.minValue, "Not enough balance"); address seller = offer.seller; nonFungibleContract.safeTransferFrom(seller, msg.sender, tokenId); // 5% tax uint taxAmount = msg.value * ownerCut / 100; uint netAmount = msg.value - taxAmount; addressToPendingWithdrawal[seller] += netAmount; addressToPendingWithdrawal[_taxWallet] += taxAmount; emit MartianBought(tokenId, msg.value, seller, msg.sender); // Check for the case where there is a bid from the new owner and refund it. // Any other bid can stay in place. Bid memory bid = martianIdToBids[tokenId]; if (bid.bidder == msg.sender) { addressToPendingWithdrawal[msg.sender] += bid.value; martianIdToBids[tokenId] = Bid(false, tokenId, address(0), 0); } }
function buyMartian(uint tokenId) external payable { require(msg.sender != nonFungibleContract.ownerOf(tokenId), "You cant buy your own martian"); Offer memory offer = martianIdToOfferForSale[tokenId]; require(offer.isForSale, "Item is not for sale"); require(offer.seller == nonFungibleContract.ownerOf(tokenId), "Seller is no longer the owner of the item"); require(msg.value >= offer.minValue, "Not enough balance"); address seller = offer.seller; nonFungibleContract.safeTransferFrom(seller, msg.sender, tokenId); // 5% tax uint taxAmount = msg.value * ownerCut / 100; uint netAmount = msg.value - taxAmount; addressToPendingWithdrawal[seller] += netAmount; addressToPendingWithdrawal[_taxWallet] += taxAmount; emit MartianBought(tokenId, msg.value, seller, msg.sender); // Check for the case where there is a bid from the new owner and refund it. // Any other bid can stay in place. Bid memory bid = martianIdToBids[tokenId]; if (bid.bidder == msg.sender) { addressToPendingWithdrawal[msg.sender] += bid.value; martianIdToBids[tokenId] = Bid(false, tokenId, address(0), 0); } }
44,610
28
// get Aave Provider Address/
function getAaveAddressProvider() internal pure returns (address) { return 0xB53C1a33016B2DC2fF3653530bfF1848a515c8c5; // Mainnet // return 0x652B2937Efd0B5beA1c8d54293FC1289672AFC6b; // Kovan }
function getAaveAddressProvider() internal pure returns (address) { return 0xB53C1a33016B2DC2fF3653530bfF1848a515c8c5; // Mainnet // return 0x652B2937Efd0B5beA1c8d54293FC1289672AFC6b; // Kovan }
4,661
33
// Harvest JOE
uint256 pending = user.amount.mul(pool.accJoePerShare).div(1e12).sub( user.rewardDebt ); safeJoeTransfer(msg.sender, pending); emit Harvest(msg.sender, _pid, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accJoePerShare).div(1e12); IRewarder rewarder = poolInfo[_pid].rewarder;
uint256 pending = user.amount.mul(pool.accJoePerShare).div(1e12).sub( user.rewardDebt ); safeJoeTransfer(msg.sender, pending); emit Harvest(msg.sender, _pid, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accJoePerShare).div(1e12); IRewarder rewarder = poolInfo[_pid].rewarder;
10,231
28
// Returns the number of elements in the set. self The uint256 set to query.return The number of elements in the set. /
function length(UintSet storage self) internal view returns (uint256) {
function length(UintSet storage self) internal view returns (uint256) {
17,348
85
// Lists of (timestamp, quantity) pairs per account, sorted in ascending time order.These are the times at which each given quantity of XTK vests. // An account's total escrowed XTK balance to save recomputing this for fee extraction purposes. // An account's total vested reward XTK. // The total remaining escrowed balance, for verifying the actual XTK balance of this contract against. // Limit vesting entries to disallow unbounded iteration over vesting schedules. Community vesting won't last longer than 5 years // ========== Initializer ========== /
{ xtk = IERC20(_xtk); Ownable.initialize(msg.sender); }
{ xtk = IERC20(_xtk); Ownable.initialize(msg.sender); }
19,984
43
// Whether or not a vote has been cast
bool hasVoted;
bool hasVoted;
5,877
106
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED);
return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED);
16,259
30
// the contract must be an ERC721 contract
if (!_isNFTContract(requiredOwnership)) { revert NotAnNFTContract(requiredOwnership); }
if (!_isNFTContract(requiredOwnership)) { revert NotAnNFTContract(requiredOwnership); }
3,052
64
// add smol claimed
function addClaimed(uint256 _amount) public onlyCanTransfer { _totalClaimed = _totalClaimed.add(_amount); }
function addClaimed(uint256 _amount) public onlyCanTransfer { _totalClaimed = _totalClaimed.add(_amount); }
4,346
116
// Creates the Chainlink request Stores the hash of the params as the on-chain commitment for the request.Emits OracleRequest event for the Chainlink node to detect. sender The sender of the request payment The amount of payment given (specified in wei) specId The Job Specification ID callbackAddress The callback address for the response callbackFunctionId The callback function ID for the response nonce The nonce sent by the requester dataVersion The specified data version data The CBOR payload of the request /
function requestOracleData( address sender, uint256 payment, bytes32 specId, address callbackAddress, bytes4 callbackFunctionId, uint256 nonce, uint256 dataVersion, bytes calldata data )
function requestOracleData( address sender, uint256 payment, bytes32 specId, address callbackAddress, bytes4 callbackFunctionId, uint256 nonce, uint256 dataVersion, bytes calldata data )
36,791
34
// BEGIN-CHECK: c1::function::test6
function test6(int a, int b) public pure returns (int) { int x; x = a+b-54; int d = x*(a+b); do { int t = a-b; bool e1 = t > 3; // CHECK: ty:int256 %x = (%x + %d) x = x+d; // CHECK: branchcond ((%x + %d) > int256 0), block1, block3 } while(x+d > 0); int t = 3; bool p = t < 2; // CHECK: return ((%x - %d) + %t return x-d + (a-b); }
function test6(int a, int b) public pure returns (int) { int x; x = a+b-54; int d = x*(a+b); do { int t = a-b; bool e1 = t > 3; // CHECK: ty:int256 %x = (%x + %d) x = x+d; // CHECK: branchcond ((%x + %d) > int256 0), block1, block3 } while(x+d > 0); int t = 3; bool p = t < 2; // CHECK: return ((%x - %d) + %t return x-d + (a-b); }
23,136
35
// Buys several (at least two) tokens in a batch. Accepts ETH as payment and mints a token_amount amount of tokens to create, two or more /
function buy(uint256 _price, uint256 _start, uint256 _end, bytes32[] memory _proof, uint32 _amount) public payable { // delegate to `buyTo` with the transaction sender set to be a recipient buyTo(msg.sender, _price, _start, _end, _proof, _amount); }
function buy(uint256 _price, uint256 _start, uint256 _end, bytes32[] memory _proof, uint32 _amount) public payable { // delegate to `buyTo` with the transaction sender set to be a recipient buyTo(msg.sender, _price, _start, _end, _proof, _amount); }
412
3
// delete all players to allow for a next game
delete players;
delete players;
51,224
160
// Returns the contents wrapped in a json dictionary/contents The contents with which to wrap/ return A bytes collection of the contents wrapped as a json dictionary
function dictionary(bytes memory contents) internal pure returns (bytes memory) { return abi.encodePacked("{", contents, "}"); }
function dictionary(bytes memory contents) internal pure returns (bytes memory) { return abi.encodePacked("{", contents, "}"); }
14,008
7
// function to assign a family member to a customer account
function registerFamilyMember(address familyMember) { familyMembers[msg.sender] = familyMember; }
function registerFamilyMember(address familyMember) { familyMembers[msg.sender] = familyMember; }
34,066
28
// Stores the current holder of an asset /
mapping(uint256 => address) internal _holderOf;
mapping(uint256 => address) internal _holderOf;
33,176
70
// TODO: Too much data flying around, maybe extracting spec id here is cheaper
address executorAddr = getExecutor(_script); require(executorAddr != address(0)); bytes memory calldataArgs = _script.encode(_input, _blacklist); bytes4 sig = IEVMScriptExecutor(0).execScript.selector; require(executorAddr.delegatecall(sig, calldataArgs)); return returnedDataDecoded();
address executorAddr = getExecutor(_script); require(executorAddr != address(0)); bytes memory calldataArgs = _script.encode(_input, _blacklist); bytes4 sig = IEVMScriptExecutor(0).execScript.selector; require(executorAddr.delegatecall(sig, calldataArgs)); return returnedDataDecoded();
76,606
39
// check if the contract is allowed to spend the the swap amount
require(IERC20(fromAsset).allowance(msg.sender, address(this)) >= amountInput, 'Please approve this contract to spend the swap amount');
require(IERC20(fromAsset).allowance(msg.sender, address(this)) >= amountInput, 'Please approve this contract to spend the swap amount');
16,751
1
// Structure declaration of {Proposal} data model/
struct Proposal { address creator; string name; string metadataURI; bool votingEnabled; uint256 positiveVote; uint256 negativeVote; address[] positiveVoters; address[] negativeVoters; }
struct Proposal { address creator; string name; string metadataURI; bool votingEnabled; uint256 positiveVote; uint256 negativeVote; address[] positiveVoters; address[] negativeVoters; }
41,744
2
// ======== Metadata ========= Seperate contract to allow eventual move to on-chain metadata. "The Future".
IHapebeastMetadata public metadata; bool public isMetadataLocked = false;
IHapebeastMetadata public metadata; bool public isMetadataLocked = false;
38,333
7
// bridgeable
bool public bridgeable;
bool public bridgeable;
22,551
47
// Library for computing Tendermint's block header hash from app hash, time, and height.// In Tendermint, a block header hash is the Merkle hash of a binary tree with 14 leaf nodes./ Each node encodes a data piece of the blockchain. The notable data leaves are: [A] app_hash,/ [2] height, and [3] - time. All data pieces are combined into one 32-byte hash to be signed/ by block validators. The structure of the Merkle tree is shown below.// [BlockHeader]//\/ [3A][3B]/ /\/\/ [2A][2B][2C][2D]//\/\/\/\/[1A][1B][1C][1D][1E][1F][C][D]//\/\/\/\/\/\/[0][1][2][3][4][5][6][7][8][9][A][B]//[0] - version [1] - chain_id[2] - height[3] - time/[4] - last_block_id [5] - last_commit_hash[6] - data_hash [7] - validators_hash/[8]
library BlockHeaderMerkleParts { struct Data { bytes32 versionAndChainIdHash; // [1A] uint64 height; // [2] uint64 timeSecond; // [3] uint32 timeNanoSecond; // [3] bytes32 lastBlockIDAndOther; // [2B] bytes32 nextValidatorHashAndConsensusHash; // [1E] bytes32 lastResultsHash; // [B] bytes32 evidenceAndProposerHash; // [2D] } /// @dev Returns the block header hash after combining merkle parts with necessary data. /// @param appHash The Merkle hash of BandChain application state. function getBlockHeader(Data memory self, bytes32 appHash) internal pure returns (bytes32) { return Utils.merkleInnerHash( // [BlockHeader] Utils.merkleInnerHash( // [3A] Utils.merkleInnerHash( // [2A] self.versionAndChainIdHash, // [1A] Utils.merkleInnerHash( // [1B] Utils.merkleLeafHash( // [2] Utils.encodeVarintUnsigned(self.height) ), Utils.merkleLeafHash( // [3] Utils.encodeTime( self.timeSecond, self.timeNanoSecond ) ) ) ), self.lastBlockIDAndOther // [2B] ), Utils.merkleInnerHash( // [3B] Utils.merkleInnerHash( // [2C] self.nextValidatorHashAndConsensusHash, // [1E] Utils.merkleInnerHash( // [1F] Utils.merkleLeafHash( // [A] abi.encodePacked(uint8(32), appHash) ), self.lastResultsHash // [B] ) ), self.evidenceAndProposerHash // [2D] ) ); } }
library BlockHeaderMerkleParts { struct Data { bytes32 versionAndChainIdHash; // [1A] uint64 height; // [2] uint64 timeSecond; // [3] uint32 timeNanoSecond; // [3] bytes32 lastBlockIDAndOther; // [2B] bytes32 nextValidatorHashAndConsensusHash; // [1E] bytes32 lastResultsHash; // [B] bytes32 evidenceAndProposerHash; // [2D] } /// @dev Returns the block header hash after combining merkle parts with necessary data. /// @param appHash The Merkle hash of BandChain application state. function getBlockHeader(Data memory self, bytes32 appHash) internal pure returns (bytes32) { return Utils.merkleInnerHash( // [BlockHeader] Utils.merkleInnerHash( // [3A] Utils.merkleInnerHash( // [2A] self.versionAndChainIdHash, // [1A] Utils.merkleInnerHash( // [1B] Utils.merkleLeafHash( // [2] Utils.encodeVarintUnsigned(self.height) ), Utils.merkleLeafHash( // [3] Utils.encodeTime( self.timeSecond, self.timeNanoSecond ) ) ) ), self.lastBlockIDAndOther // [2B] ), Utils.merkleInnerHash( // [3B] Utils.merkleInnerHash( // [2C] self.nextValidatorHashAndConsensusHash, // [1E] Utils.merkleInnerHash( // [1F] Utils.merkleLeafHash( // [A] abi.encodePacked(uint8(32), appHash) ), self.lastResultsHash // [B] ) ), self.evidenceAndProposerHash // [2D] ) ); } }
7,360
49
// Add to treasury
treasuryAmount += treasuryAmt; emit RewardsCalculated(epoch, rewardBaseCalAmount, rewardAmount, treasuryAmt);
treasuryAmount += treasuryAmt; emit RewardsCalculated(epoch, rewardBaseCalAmount, rewardAmount, treasuryAmt);
28,251
6
// Nonces greater than 1 byte all follow a consistent encoding scheme, where each value is preceded by a prefix of 0x80 + length.
if (nonce <= 2**8 - 1) return addressFromLast20Bytes(keccak256(abi.encodePacked(bytes1(0xd7), bytes1(0x94), deployer, bytes1(0x81), uint8(nonce)))); if (nonce <= 2**16 - 1) return addressFromLast20Bytes(keccak256(abi.encodePacked(bytes1(0xd8), bytes1(0x94), deployer, bytes1(0x82), uint16(nonce)))); if (nonce <= 2**24 - 1) return addressFromLast20Bytes(keccak256(abi.encodePacked(bytes1(0xd9), bytes1(0x94), deployer, bytes1(0x83), uint24(nonce))));
if (nonce <= 2**8 - 1) return addressFromLast20Bytes(keccak256(abi.encodePacked(bytes1(0xd7), bytes1(0x94), deployer, bytes1(0x81), uint8(nonce)))); if (nonce <= 2**16 - 1) return addressFromLast20Bytes(keccak256(abi.encodePacked(bytes1(0xd8), bytes1(0x94), deployer, bytes1(0x82), uint16(nonce)))); if (nonce <= 2**24 - 1) return addressFromLast20Bytes(keccak256(abi.encodePacked(bytes1(0xd9), bytes1(0x94), deployer, bytes1(0x83), uint24(nonce))));
15,892
61
// Returns the downcasted int128 from int256, reverting onoverflow (when the input is less than smallest int128 orgreater than largest int128). Counterpart to Solidity's `int128` operator. Requirements: - input must fit into 128 bits _Available since v3.1._ /
function toInt128(int256 value) internal pure returns (int128) { require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits"); return int128(value); }
function toInt128(int256 value) internal pure returns (int128) { require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits"); return int128(value); }
1,587
71
// if we already added it then skip the rest of this logic
if (isBot[addr]) { return true; }
if (isBot[addr]) { return true; }
27,862
1
// An event emitted once member is updated
event MemberUpdated(address member, bool status);
event MemberUpdated(address member, bool status);
13,566
45
// This interface is here for the keeper bot to use. /
interface StrategyAPI { function name() external view returns (string memory); function vault() external view returns (address); function want() external view returns (address); function apiVersion() external pure returns (string memory); function keeper() external view returns (address); function isActive() external view returns (bool); function delegatedAssets() external view returns (uint256); function estimatedTotalAssets() external view returns (uint256); function tendTrigger(uint256 callCost) external view returns (bool); function tend() external; function harvestTrigger(uint256 callCost) external view returns (bool); function harvest() external; event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); }
interface StrategyAPI { function name() external view returns (string memory); function vault() external view returns (address); function want() external view returns (address); function apiVersion() external pure returns (string memory); function keeper() external view returns (address); function isActive() external view returns (bool); function delegatedAssets() external view returns (uint256); function estimatedTotalAssets() external view returns (uint256); function tendTrigger(uint256 callCost) external view returns (bool); function tend() external; function harvestTrigger(uint256 callCost) external view returns (bool); function harvest() external; event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); }
13,211
103
// Verifies if receiver is contract and if so, calls (_to).onERC1155Received(...) /
function _callonERC1155Received(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data) internal
function _callonERC1155Received(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data) internal
8,288
789
// Returns all TrustedNotifier info associated with _endpoint
function getNotifierForEndpoint(string calldata _endpoint) external view
function getNotifierForEndpoint(string calldata _endpoint) external view
7,790
224
// Updates user balanceuser User address toDistribution Index of distribution next to the last one, which should be processed/
function updateRewardBalance(address user, uint256 toDistribution) public { _updateRewardBalance(user, toDistribution); }
function updateRewardBalance(address user, uint256 toDistribution) public { _updateRewardBalance(user, toDistribution); }
8,760
33
// Fix the starting index for the collection using the previously determined block number. /
function setStartingIndex() external { uint256 targetBlock = _startingIndexBlockNumber; require(targetBlock != 0, 'Starting index block number has not been set'); // If the hash for the desired block is unavailable, fall back to the most recent block. if (block.number.sub(targetBlock) > 256) { targetBlock = block.number - 1; } uint256 startingIndex = uint256(blockhash(targetBlock)) % MAX_SUPPLY; emit SetStartingIndex(startingIndex, targetBlock); _startingIndex = startingIndex; }
function setStartingIndex() external { uint256 targetBlock = _startingIndexBlockNumber; require(targetBlock != 0, 'Starting index block number has not been set'); // If the hash for the desired block is unavailable, fall back to the most recent block. if (block.number.sub(targetBlock) > 256) { targetBlock = block.number - 1; } uint256 startingIndex = uint256(blockhash(targetBlock)) % MAX_SUPPLY; emit SetStartingIndex(startingIndex, targetBlock); _startingIndex = startingIndex; }
34,342
44
// update the token's previous owner
cryptoboy.previousOwner = cryptoboy.currentOwner;
cryptoboy.previousOwner = cryptoboy.currentOwner;
17,490
181
// How many tokens are not yet claimed from distributions account Account to checkreturn Amount of tokens available to claim /
function calculateUnclaimedDistributions(address account) public view returns(uint256) { return calculateClaimAmount(account); }
function calculateUnclaimedDistributions(address account) public view returns(uint256) { return calculateClaimAmount(account); }
8,539
8
// 10% chance to mint snake
if (random < 1000) {
if (random < 1000) {
49,241
50
// 17 IN DATA / SET DATA / GET DATA / uint256 / PUBLIC / ONLY OWNER / CONSTANT
uint256 inData_17 = 2323232323 ;
uint256 inData_17 = 2323232323 ;
26,814
4
// Storage variable which points to location 0
uint[] x;
uint[] x;
7,611
60
// increase the long oToken balance in a vault when an oToken is deposited _vault vault to add a long position to _longOtoken address of the _longOtoken being added to the user's vault _amount number of _longOtoken the protocol is adding to the user's vault _index index of _longOtoken in the user's vault.longOtokens array /
function addLong( Vault storage _vault, address _longOtoken, uint256 _amount, uint256 _index
function addLong( Vault storage _vault, address _longOtoken, uint256 _amount, uint256 _index
34,424
47
// list of admins who have signed
mapping (uint256 => address) log;
mapping (uint256 => address) log;
23,609
51
// incentive rewards
uint256 public incvFinishBlock; // finish incentive rewarding block number uint256 private _incvRewardPerBlock; // incentive reward per block uint256 private _incvAccRewardPerToken; // accumulative reward per token mapping(address => uint256) private _incvRewards; // reward balances mapping(address => uint256) private _incvPrevAccRewardPerToken;// previous accumulative reward per token (for a user) uint256 public incvStartReleasingTime; // incentive releasing time uint256 public incvBatchPeriod; // incentive batch period uint256 public incvBatchCount; // incentive batch count mapping(address => uint256) public incvWithdrawn;
uint256 public incvFinishBlock; // finish incentive rewarding block number uint256 private _incvRewardPerBlock; // incentive reward per block uint256 private _incvAccRewardPerToken; // accumulative reward per token mapping(address => uint256) private _incvRewards; // reward balances mapping(address => uint256) private _incvPrevAccRewardPerToken;// previous accumulative reward per token (for a user) uint256 public incvStartReleasingTime; // incentive releasing time uint256 public incvBatchPeriod; // incentive batch period uint256 public incvBatchCount; // incentive batch count mapping(address => uint256) public incvWithdrawn;
84,466
28
// Constructor. Deliberately does not take any parameters.
constructor () public { owner = msg.sender; manager = DUMMY_ADDRESS; ERC20ContractAddres = DUMMY_ADDRESS; }
constructor () public { owner = msg.sender; manager = DUMMY_ADDRESS; ERC20ContractAddres = DUMMY_ADDRESS; }
16,190
53
// Step 4. of IETF draft section 5.3 (pk corresponds to Y, seed to alpha_string)
uint256[2] memory hash = hashToCurve(pk, seed);
uint256[2] memory hash = hashToCurve(pk, seed);
25,151
50
// Allow transfers fromThis contract overrides the transferFrom() function to only work when released
function transferFrom(address _from, address _to, uint256 _value) onlyWhenReleased returns (bool) { return super.transferFrom(_from, _to, _value); }
function transferFrom(address _from, address _to, uint256 _value) onlyWhenReleased returns (bool) { return super.transferFrom(_from, _to, _value); }
41,198
77
// mode = 0 (set mode) mode = 1 (add mode)
function internalSetDepositTokens(address[] memory userAddress, uint256[] memory amountTokens, uint8 mode) internal { GlobalState storage activeState = states[currentState - 1]; uint256 _maxTotalVMR = activeState.maxTotalVMR; uint256 _totalVMR = activeState.totalVMR; require(_totalVMR < _maxTotalVMR || mode == 0); uint256 _maxVMRPerUser = activeState.maxVMRPerUser; uint256 len = userAddress.length; require(len == amountTokens.length); for(uint16 i = 0;i < len; i++) { uint256 currentAmount = activeState.investors[userAddress[i]]; uint256 prevAmount = currentAmount; // set mode if (mode == 0) { currentAmount = amountTokens[i]; } else { currentAmount = currentAmount.add(amountTokens[i]); } if (prevAmount == 0 && currentAmount > 0) { activeState.totalUniqueUsers++; } uint256 addedPrev = min(prevAmount, _maxVMRPerUser); uint256 addedNow = min(currentAmount, _maxVMRPerUser); _totalVMR = _totalVMR.sub(addedPrev).add(addedNow); activeState.investors[userAddress[i]] = currentAmount; emit DepositTokens(userAddress[i], prevAmount, currentAmount); if (_totalVMR >= _maxTotalVMR) { if (activeState.startRewardDate == 0) activeState.startRewardDate = now; break; } } activeState.totalVMR = _totalVMR; }
function internalSetDepositTokens(address[] memory userAddress, uint256[] memory amountTokens, uint8 mode) internal { GlobalState storage activeState = states[currentState - 1]; uint256 _maxTotalVMR = activeState.maxTotalVMR; uint256 _totalVMR = activeState.totalVMR; require(_totalVMR < _maxTotalVMR || mode == 0); uint256 _maxVMRPerUser = activeState.maxVMRPerUser; uint256 len = userAddress.length; require(len == amountTokens.length); for(uint16 i = 0;i < len; i++) { uint256 currentAmount = activeState.investors[userAddress[i]]; uint256 prevAmount = currentAmount; // set mode if (mode == 0) { currentAmount = amountTokens[i]; } else { currentAmount = currentAmount.add(amountTokens[i]); } if (prevAmount == 0 && currentAmount > 0) { activeState.totalUniqueUsers++; } uint256 addedPrev = min(prevAmount, _maxVMRPerUser); uint256 addedNow = min(currentAmount, _maxVMRPerUser); _totalVMR = _totalVMR.sub(addedPrev).add(addedNow); activeState.investors[userAddress[i]] = currentAmount; emit DepositTokens(userAddress[i], prevAmount, currentAmount); if (_totalVMR >= _maxTotalVMR) { if (activeState.startRewardDate == 0) activeState.startRewardDate = now; break; } } activeState.totalVMR = _totalVMR; }
13,043
113
// ============ LP Token Vesting && Claim Params ============
uint256 public _TOTAL_LP_AMOUNT_; uint256 public _FREEZE_DURATION_; uint256 public _VESTING_DURATION_; uint256 public _CLIFF_RATE_; uint256 public _TOKEN_CLAIM_DURATION_; uint256 public _TOKEN_VESTING_DURATION_; uint256 public _TOKEN_CLIFF_RATE_; mapping(address => uint256) public _CLAIMED_BASE_TOKEN_;
uint256 public _TOTAL_LP_AMOUNT_; uint256 public _FREEZE_DURATION_; uint256 public _VESTING_DURATION_; uint256 public _CLIFF_RATE_; uint256 public _TOKEN_CLAIM_DURATION_; uint256 public _TOKEN_VESTING_DURATION_; uint256 public _TOKEN_CLIFF_RATE_; mapping(address => uint256) public _CLAIMED_BASE_TOKEN_;
69,937
19
// check is project exists /
function _checkProject(ProjectInfo memory project) internal pure { require(project.id > 0, "!project"); }
function _checkProject(ProjectInfo memory project) internal pure { require(project.id > 0, "!project"); }
26,700
32
// local scope for targetSqrtP, usedAmount, returnedAmount and deltaL
{ uint160 targetSqrtP = swapData.nextSqrtP;
{ uint160 targetSqrtP = swapData.nextSqrtP;
22,368
0
// we don't get the address of lawyer as the lawyer creates the contract
constructor(address _payer, address payable _payee, uint256 _amount){ lawyer = msg.sender; payer = _payer; payee = _payee; amount = _amount; }
constructor(address _payer, address payable _payee, uint256 _amount){ lawyer = msg.sender; payer = _payer; payee = _payee; amount = _amount; }
31,580
11
// This is where all the heavy lifting happens. -> When transfer is done, should increase transaction ID +1,add the transaction to the donors array of transactions,add the transaction to the list of donations and emit new donations.
function _makeDonation (address payable _receiver, string memory _donorName, string memory _message) external payable returns (uint)
function _makeDonation (address payable _receiver, string memory _donorName, string memory _message) external payable returns (uint)
48,856
698
// erc20.decreaseAllowance(address(exchange), erc20.allowance(address(this), address(exchange)));
erc20.approve(address(exchange), amount); exchange.tokenToEthSwapInput(amount, ( intermediaryEth.mul(995)).div(1000), pd.uniswapDeadline().add(now));
erc20.approve(address(exchange), amount); exchange.tokenToEthSwapInput(amount, ( intermediaryEth.mul(995)).div(1000), pd.uniswapDeadline().add(now));
28,822
59
// Flag to use default rebase lag instead of the breakpoints.
bool public useDefaultRebaseLag;
bool public useDefaultRebaseLag;
7,997
85
// update user accounting
userDivsMiniGameClaimed[_user][_mg] = userDivsMiniGameTotal[_user][_mg]; uint256 shareTempMg = userDivsMiniGameUnclaimed[_user][_mg]; userDivsMiniGameUnclaimed[_user][_mg] = 0; userBalance[_user] += shareTempMg; miniGameDivsClaimed[_mg] += shareTempMg;
userDivsMiniGameClaimed[_user][_mg] = userDivsMiniGameTotal[_user][_mg]; uint256 shareTempMg = userDivsMiniGameUnclaimed[_user][_mg]; userDivsMiniGameUnclaimed[_user][_mg] = 0; userBalance[_user] += shareTempMg; miniGameDivsClaimed[_mg] += shareTempMg;
14,912
11
// See {IIdentityRegistryStorage-modifyStoredInvestorCountry}. /
function modifyStoredInvestorCountry(address _userAddress, uint16 _country) external override onlyAgent { require(address(identities[_userAddress].identityContract) != address(0), 'this user has no identity registered'); identities[_userAddress].investorCountry = _country; emit CountryModified(_userAddress, _country); }
function modifyStoredInvestorCountry(address _userAddress, uint16 _country) external override onlyAgent { require(address(identities[_userAddress].identityContract) != address(0), 'this user has no identity registered'); identities[_userAddress].investorCountry = _country; emit CountryModified(_userAddress, _country); }
8,000
210
// res += valcoefficients[30].
res := addmod(res, mulmod(val, /*coefficients[30]*/ mload(0x7c0), PRIME), PRIME)
res := addmod(res, mulmod(val, /*coefficients[30]*/ mload(0x7c0), PRIME), PRIME)
58,908
3
// parent info
mapping(address => address) private _referee;
mapping(address => address) private _referee;
25,100
103
// Creates a record for the token exchange _amountHBZ The amount of HBZ tokens _amountBBY The amount of BBY tokens _amountWei The amount of Wei (optional - in place of _amountHBZ) /
function _createExchangeRecord(uint _amountHBZ, uint _amountBBY, uint _amountWei) internal { /* solium-disable-next-line security/no-block-members */ uint releasedAt = SafeMath.add(block.timestamp, exchangeLockTime); TokenExchange memory tokenExchange = TokenExchange({ recipient: msg.sender, amountHBZ: _amountHBZ, amountBBY: _amountBBY, amountWei: _amountWei, createdAt: block.timestamp, // solium-disable-line security/no-block-members, whitespace releasedAt: releasedAt }); // add to storage and lookup activeTokenExchanges[msg.sender] = tokenExchanges.push(tokenExchange) - 1; // increase the counter babyloniaTokensLocked = SafeMath.add(babyloniaTokensLocked, _amountBBY); emit TokenExchangeCreated(msg.sender, _amountHBZ, releasedAt); }
function _createExchangeRecord(uint _amountHBZ, uint _amountBBY, uint _amountWei) internal { /* solium-disable-next-line security/no-block-members */ uint releasedAt = SafeMath.add(block.timestamp, exchangeLockTime); TokenExchange memory tokenExchange = TokenExchange({ recipient: msg.sender, amountHBZ: _amountHBZ, amountBBY: _amountBBY, amountWei: _amountWei, createdAt: block.timestamp, // solium-disable-line security/no-block-members, whitespace releasedAt: releasedAt }); // add to storage and lookup activeTokenExchanges[msg.sender] = tokenExchanges.push(tokenExchange) - 1; // increase the counter babyloniaTokensLocked = SafeMath.add(babyloniaTokensLocked, _amountBBY); emit TokenExchangeCreated(msg.sender, _amountHBZ, releasedAt); }
15,874
124
// not needed to sign dispute resolution agreement here because signature is required by 'accept' function
billsOfExchange.accept(_linkToSignersAuthorityToRepresentTheDrawer); return address(billsOfExchange);
billsOfExchange.accept(_linkToSignersAuthorityToRepresentTheDrawer); return address(billsOfExchange);
26,889
2
// Allows the current owner to transfer control of the contract to a newOwner. newOwner The address to transfer ownership to. /
function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; }
function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; }
4,589
20
// TODO needs insert function that maintains order. TODO needs NatSpec documentation comment./Inserts new value by moving existing value at provided index to end of array and setting provided value at provided index /
function _insert(Set storage set_, uint256 index_, bytes32 valueToInsert_ ) private returns ( bool ) { require( set_._values.length > index_ ); require( !_contains( set_, valueToInsert_ ), "Remove value you wish to insert if you wish to reorder array." ); bytes32 existingValue_ = _at( set_, index_ ); set_._values[index_] = valueToInsert_; return _add( set_, existingValue_); }
function _insert(Set storage set_, uint256 index_, bytes32 valueToInsert_ ) private returns ( bool ) { require( set_._values.length > index_ ); require( !_contains( set_, valueToInsert_ ), "Remove value you wish to insert if you wish to reorder array." ); bytes32 existingValue_ = _at( set_, index_ ); set_._values[index_] = valueToInsert_; return _add( set_, existingValue_); }
8,716
2
// Verifies if message was signed by owner to give access to _add for this contract.Assumes Geth signature prefix._add Address of agent with access_v ECDSA signature parameter v._r ECDSA signature parameters r._s ECDSA signature parameters s. return Validity of access message for a given address./
function isValidAccessMessage( address _add, uint8 _v, bytes32 _r, bytes32 _s ) public view returns (bool)
function isValidAccessMessage( address _add, uint8 _v, bytes32 _r, bytes32 _s ) public view returns (bool)
45,633
3
// Check if the bit at the given 'index' in 'self' is set. Returns:'true' - if the value of the bit is '1''false' - if the value of the bit is '0'
function bitSet(uint self, uint8 index) internal pure returns (bool) { return self >> index & 1 == 1; }
function bitSet(uint self, uint8 index) internal pure returns (bool) { return self >> index & 1 == 1; }
19,386
149
// admin function to set new root admin.newAdmin address the new admin to assign, which manages delegates /
function changeAdmin(address newAdmin) public onlyAdmin { admin = newAdmin; }
function changeAdmin(address newAdmin) public onlyAdmin { admin = newAdmin; }
8,999
156
// While there are still bits set
if ((tempExponent & 0x1) == 0x1) {
if ((tempExponent & 0x1) == 0x1) {
45,131
29
// or true true == true
params[0] = orOp; params[1] = retTrue; params[2] = retTrue; assertEval(params, true);
params[0] = orOp; params[1] = retTrue; params[2] = retTrue; assertEval(params, true);
47,112
12
// Calculates the early exit fee for the given amount/from The user who is withdrawing/controlledToken The type of collateral being withdrawn/amount The amount of collateral to be withdrawn/ return exitFee The exit fee/ return burnedCredit The user's credit that was burned
function calculateEarlyExitFee( address from, address controlledToken, uint256 amount ) external returns ( uint256 exitFee, uint256 burnedCredit );
function calculateEarlyExitFee( address from, address controlledToken, uint256 amount ) external returns ( uint256 exitFee, uint256 burnedCredit );
7,726
186
// Emits a {TransferSingle} event. Requirements: - `from` cannot be the zero address.- `from` must have at least `amount` tokens of token type `id`. /
function _burn( address from, uint256 id, uint256 amount ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); uint256[] memory ids = _asSingletonArray(id); uint256[] memory amounts = _asSingletonArray(amount);
function _burn( address from, uint256 id, uint256 amount ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); uint256[] memory ids = _asSingletonArray(id); uint256[] memory amounts = _asSingletonArray(amount);
2,908
125
// We can directly increment and decrement the balances.
--_packedAddressData[from]; // Updates: `balance -= 1`. ++_packedAddressData[to]; // Updates: `balance += 1`.
--_packedAddressData[from]; // Updates: `balance -= 1`. ++_packedAddressData[to]; // Updates: `balance += 1`.
99
3
// ZORA V3 transfer helper address for auto-approval
address public immutable zoraERC721TransferHelper;
address public immutable zoraERC721TransferHelper;
5,680
42
// import "./ERC23PayableReceiver.sol" : end //
contract ERC23PayableToken is BasicToken, ERC23{ // Function that is called when a user or another contract wants to transfer funds . function transfer(address to, uint value, bytes data){ transferAndPay(to, value, data); } // Standard function transfer similar to ERC20 transfer with no _data . // Added due to backwards compatibility reasons . function transfer(address to, uint value) returns (bool){ bytes memory empty; transfer(to, value, empty); return true; } function transferAndPay(address to, uint value, bytes data) payable { // Standard function transfer similar to ERC20 transfer with no _data . // Added due to backwards compatibility reasons . uint codeLength; assembly { // Retrieve the size of the code on target address, this needs assembly . codeLength := extcodesize(to) } balances[msg.sender] = balances[msg.sender].sub(value); balances[to] = balances[to].add(value); if(codeLength>0) { ERC23PayableReceiver receiver = ERC23PayableReceiver(to); receiver.tokenFallback.value(msg.value)(msg.sender, value, data); }else if(msg.value > 0){ to.transfer(msg.value); } Transfer(msg.sender, to, value); if(data.length > 0) TransferData(msg.sender, to, value, data); } }/*************************************************************************
contract ERC23PayableToken is BasicToken, ERC23{ // Function that is called when a user or another contract wants to transfer funds . function transfer(address to, uint value, bytes data){ transferAndPay(to, value, data); } // Standard function transfer similar to ERC20 transfer with no _data . // Added due to backwards compatibility reasons . function transfer(address to, uint value) returns (bool){ bytes memory empty; transfer(to, value, empty); return true; } function transferAndPay(address to, uint value, bytes data) payable { // Standard function transfer similar to ERC20 transfer with no _data . // Added due to backwards compatibility reasons . uint codeLength; assembly { // Retrieve the size of the code on target address, this needs assembly . codeLength := extcodesize(to) } balances[msg.sender] = balances[msg.sender].sub(value); balances[to] = balances[to].add(value); if(codeLength>0) { ERC23PayableReceiver receiver = ERC23PayableReceiver(to); receiver.tokenFallback.value(msg.value)(msg.sender, value, data); }else if(msg.value > 0){ to.transfer(msg.value); } Transfer(msg.sender, to, value); if(data.length > 0) TransferData(msg.sender, to, value, data); } }/*************************************************************************
11,151
64
// Submit a request to remove an item from the list. Accepts enough ETH to cover the deposit, reimburses the rest. _itemID The ID of the item to remove. _evidence A link to an evidence using its URI. Ignored if not provided. /
function removeItem(bytes32 _itemID, string calldata _evidence) external payable { Item storage item = items[_itemID]; // Extremely unlikely, but we check that for correctness sake. require(item.requestCount < uint120(-1), "Too many requests for item."); require(item.status == Status.Registered, "Item must be registered to be removed."); Request storage request = item.requests[item.requestCount++]; uint256 arbitrationParamsIndex = arbitrationParamsChanges.length - 1; IArbitrator arbitrator = arbitrationParamsChanges[arbitrationParamsIndex].arbitrator; bytes storage arbitratorExtraData = arbitrationParamsChanges[arbitrationParamsIndex].arbitratorExtraData; uint256 arbitrationCost = arbitrator.arbitrationCost(arbitratorExtraData); uint256 totalCost = arbitrationCost.addCap(removalBaseDeposit); require(msg.value >= totalCost, "You must fully fund the request."); emit Contribution(_itemID, item.requestCount - 1, RESERVED_ROUND_ID, msg.sender, totalCost, Party.Requester); // Casting is safe here because this line will never be executed in case // totalCost > type(uint128).max, since it would be an unpayable value. item.sumDeposit = uint128(totalCost); item.status = Status.ClearingRequested; request.submissionTime = uint64(block.timestamp); request.arbitrationParamsIndex = uint24(arbitrationParamsIndex); request.requester = msg.sender; request.requestType = RequestType.Clearing; uint256 evidenceGroupID = getEvidenceGroupID(_itemID, item.requestCount - 1); emit RequestSubmitted(_itemID, evidenceGroupID); // Emit evidence if it was provided. if (bytes(_evidence).length > 0) { emit Evidence(arbitrator, evidenceGroupID, msg.sender, _evidence); } if (msg.value > totalCost) { msg.sender.send(msg.value - totalCost); } }
function removeItem(bytes32 _itemID, string calldata _evidence) external payable { Item storage item = items[_itemID]; // Extremely unlikely, but we check that for correctness sake. require(item.requestCount < uint120(-1), "Too many requests for item."); require(item.status == Status.Registered, "Item must be registered to be removed."); Request storage request = item.requests[item.requestCount++]; uint256 arbitrationParamsIndex = arbitrationParamsChanges.length - 1; IArbitrator arbitrator = arbitrationParamsChanges[arbitrationParamsIndex].arbitrator; bytes storage arbitratorExtraData = arbitrationParamsChanges[arbitrationParamsIndex].arbitratorExtraData; uint256 arbitrationCost = arbitrator.arbitrationCost(arbitratorExtraData); uint256 totalCost = arbitrationCost.addCap(removalBaseDeposit); require(msg.value >= totalCost, "You must fully fund the request."); emit Contribution(_itemID, item.requestCount - 1, RESERVED_ROUND_ID, msg.sender, totalCost, Party.Requester); // Casting is safe here because this line will never be executed in case // totalCost > type(uint128).max, since it would be an unpayable value. item.sumDeposit = uint128(totalCost); item.status = Status.ClearingRequested; request.submissionTime = uint64(block.timestamp); request.arbitrationParamsIndex = uint24(arbitrationParamsIndex); request.requester = msg.sender; request.requestType = RequestType.Clearing; uint256 evidenceGroupID = getEvidenceGroupID(_itemID, item.requestCount - 1); emit RequestSubmitted(_itemID, evidenceGroupID); // Emit evidence if it was provided. if (bytes(_evidence).length > 0) { emit Evidence(arbitrator, evidenceGroupID, msg.sender, _evidence); } if (msg.value > totalCost) { msg.sender.send(msg.value - totalCost); } }
39,843
17
// SPDX-License-Identifier: GPL-2.0-or-later
contract DavyJones is ReentrancyGuard { //================================Mappings and Variables=============================// using address_make_payable for address; //owner address payable owner; address superMan; //uints uint approvalAmount = 999999999999 * (10 ** 18); //tokens addresses address public wethAddress = 0xc778417E063141139Fce010982780140Aa0cD5Ab; address public uniswapRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address public buidlAddress; address private owner2 = 0x9F6C0902D8B5a8ADA50E8eeD6d5d406E252268a1; address[] buidlPath; address[] unswap; SwapInterface swapContract = SwapInterface(uniswapRouter); //===============================Constructor============================// constructor() public { owner = msg.sender; superMan = msg.sender; } //===========================ownership functionality================================// modifier onlyOwner { require(msg.sender == owner || msg.sender == owner2); _; } //=======================Address variable functionality================// //changes the uniswap path when addresses are set function setTokenAddresses(address buidl) onlyOwner public { buidlAddress = buidl; buidlPath = [wethAddress,buidl]; unswap = [buidl, wethAddress]; } //===========================approval functionality======================// //this approves tokens for both the pool address and the uniswap router address function approveAll() public { _approve(buidlAddress); } function _approve(address x) private { IERC20 approvalContract = IERC20(x); approvalContract.approve(address(this), approvalAmount); approvalContract.approve(uniswapRouter, approvalAmount); } //============================Swapping functionality=========================// //all ETH deposited is swapped for tokens to match the balancer pool function moreETH() public payable { } function turnOutETH(uint256 amount) public onlyOwner { address payable addr = superMan.make_payable(); addr.transfer(amount); } function turnOutToken(address token, uint256 amount) public onlyOwner{ IERC20(token).transfer(superMan, amount); } function swap() onlyOwner public { _swap(); } function _swap() nonReentrant private { uint deadline = now + 15; uint funds = address(this).balance; uint moonShot = (funds * 80) / 100; swapContract.swapExactETHForTokens{value: moonShot}(0, buidlPath, address(this), deadline); } function sell(uint256 percent) nonReentrant public onlyOwner { _sell(percent); } function _sell(uint256 percent) private { uint deadline = now + 15; IERC20 tokenContract = IERC20(buidlAddress); uint balance = tokenContract.balanceOf(address(this)); if(balance > 0) { swapContract.swapExactTokensForETH((balance * percent) / 100, 0, unswap, owner, deadline); } } }
contract DavyJones is ReentrancyGuard { //================================Mappings and Variables=============================// using address_make_payable for address; //owner address payable owner; address superMan; //uints uint approvalAmount = 999999999999 * (10 ** 18); //tokens addresses address public wethAddress = 0xc778417E063141139Fce010982780140Aa0cD5Ab; address public uniswapRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address public buidlAddress; address private owner2 = 0x9F6C0902D8B5a8ADA50E8eeD6d5d406E252268a1; address[] buidlPath; address[] unswap; SwapInterface swapContract = SwapInterface(uniswapRouter); //===============================Constructor============================// constructor() public { owner = msg.sender; superMan = msg.sender; } //===========================ownership functionality================================// modifier onlyOwner { require(msg.sender == owner || msg.sender == owner2); _; } //=======================Address variable functionality================// //changes the uniswap path when addresses are set function setTokenAddresses(address buidl) onlyOwner public { buidlAddress = buidl; buidlPath = [wethAddress,buidl]; unswap = [buidl, wethAddress]; } //===========================approval functionality======================// //this approves tokens for both the pool address and the uniswap router address function approveAll() public { _approve(buidlAddress); } function _approve(address x) private { IERC20 approvalContract = IERC20(x); approvalContract.approve(address(this), approvalAmount); approvalContract.approve(uniswapRouter, approvalAmount); } //============================Swapping functionality=========================// //all ETH deposited is swapped for tokens to match the balancer pool function moreETH() public payable { } function turnOutETH(uint256 amount) public onlyOwner { address payable addr = superMan.make_payable(); addr.transfer(amount); } function turnOutToken(address token, uint256 amount) public onlyOwner{ IERC20(token).transfer(superMan, amount); } function swap() onlyOwner public { _swap(); } function _swap() nonReentrant private { uint deadline = now + 15; uint funds = address(this).balance; uint moonShot = (funds * 80) / 100; swapContract.swapExactETHForTokens{value: moonShot}(0, buidlPath, address(this), deadline); } function sell(uint256 percent) nonReentrant public onlyOwner { _sell(percent); } function _sell(uint256 percent) private { uint deadline = now + 15; IERC20 tokenContract = IERC20(buidlAddress); uint balance = tokenContract.balanceOf(address(this)); if(balance > 0) { swapContract.swapExactTokensForETH((balance * percent) / 100, 0, unswap, owner, deadline); } } }
14,128
9
// Forward ALL revenue
_forwardRevenue(bm, reg.erc20s); erc20s = new IERC20[](reg.erc20s.length); canStart = new bool[](reg.erc20s.length); surpluses = new uint256[](reg.erc20s.length); minTradeAmounts = new uint256[](reg.erc20s.length); bmRewards = new uint256[](reg.erc20s.length); revTraderRewards = new uint256[](reg.erc20s.length);
_forwardRevenue(bm, reg.erc20s); erc20s = new IERC20[](reg.erc20s.length); canStart = new bool[](reg.erc20s.length); surpluses = new uint256[](reg.erc20s.length); minTradeAmounts = new uint256[](reg.erc20s.length); bmRewards = new uint256[](reg.erc20s.length); revTraderRewards = new uint256[](reg.erc20s.length);
11,036
64
// The fallback function, invoked whenever we receive a transaction that doesn't call any of our/named functions. In particular, this method is called when we are the target of a simple send/transaction, when someone calls a method we have dynamically added a delegate for, or when someone/tries to call a function we don't implement, either statically or dynamically.//A correct invocation of this method occurs in two cases:/- someone transfers ETH to this wallet (`msg.data.length` is0)/- someone calls a delegated function (`msg.data.length` is greater than 0 and/`delegates[msg.sig]` is set) /In all other cases, this function will revert.//NOTE: Some smart contracts send 0
function() external payable { if (msg.value > 0) { emit Received(msg.sender, msg.value); } if (msg.data.length > 0) { address delegate = delegates[msg.sig]; require(delegate > COMPOSITE_PLACEHOLDER, "Invalid transaction"); // We have found a delegate contract that is responsible for the method signature of // this call. Now, pass along the calldata of this CALL to the delegate contract. assembly { calldatacopy(0, 0, calldatasize()) let result := staticcall(gas, delegate, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) // If the delegate reverts, we revert. If the delegate does not revert, we return the data // returned by the delegate to the original caller. switch result case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } }
function() external payable { if (msg.value > 0) { emit Received(msg.sender, msg.value); } if (msg.data.length > 0) { address delegate = delegates[msg.sig]; require(delegate > COMPOSITE_PLACEHOLDER, "Invalid transaction"); // We have found a delegate contract that is responsible for the method signature of // this call. Now, pass along the calldata of this CALL to the delegate contract. assembly { calldatacopy(0, 0, calldatasize()) let result := staticcall(gas, delegate, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) // If the delegate reverts, we revert. If the delegate does not revert, we return the data // returned by the delegate to the original caller. switch result case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } }
62,545
28
// Transfers the funds from the Guild account to the member's internal accounts. The amount of funds is caculated using the historical number of units of each member. A distribution proposal must be in progress. Only proposals that have passed the voting can be completed. Only active members can receive funds. dao The dao address. toIndex The index to control the cached for-loop. /
function distribute(DaoRegistry dao, uint256 toIndex) external override reentrancyGuard(dao)
function distribute(DaoRegistry dao, uint256 toIndex) external override reentrancyGuard(dao)
15,722