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
17
// Sanity check in case the contract does not do this
require(balance > 0); require(erc20.transfer(msg.sender, balance)); return true;
require(balance > 0); require(erc20.transfer(msg.sender, balance)); return true;
48,195
519
// unsuccess:
success := 0
success := 0
18,527
80
// Last time the pool distribute rewards to all stakeholders
uint256 internal _lastRewardDistributionOn; uint256 public _poolRewardHalvingAt = 0;
uint256 internal _lastRewardDistributionOn; uint256 public _poolRewardHalvingAt = 0;
7,322
163
// MIP39c2-SP2: Adding Risk Core Unit Hash: seth keccak -- "$(wget https:raw.githubusercontent.com/makerdao/mips/5c981b8b24c966d110f133c792d27e7728cc77ab/MIP39/MIP39c2-Subproposals/MIP39c2-SP2.md -q -O - 2>/dev/null)"
string constant public MIP39c2SP2 = "0xd1989672d982ca42dccbaf6d2682e68fd0ecc8c0b9537f2c970665af25c593c3";
string constant public MIP39c2SP2 = "0xd1989672d982ca42dccbaf6d2682e68fd0ecc8c0b9537f2c970665af25c593c3";
54,987
3
// Reentrant evil erc20
contract ReentrantERC20 { address state_gravityAddress; constructor(address _gravityAddress) public { state_gravityAddress = _gravityAddress; } function transfer(address _recipient, uint256 _amount) public returns (bool) { // _currentValidators, _currentPowers, _currentValsetNonce, _v, _r, _s, _args);( address[] memory addresses = new address[](0); bytes32[] memory bytes32s = new bytes32[](0); uint256[] memory uint256s = new uint256[](0); address blankAddress = address(0); bytes memory bytess = new bytes(0); uint256 zero = 0; LogicCallArgs memory args; ValsetArgs memory valset; { args = LogicCallArgs( uint256s, addresses, uint256s, addresses, address(0), bytess, zero, bytes32(0), zero ); } { valset = ValsetArgs(addresses, uint256s, zero, zero, blankAddress); } Gravity(state_gravityAddress).submitLogicCall( valset, new uint8[](0), bytes32s, bytes32s, args ); } }
contract ReentrantERC20 { address state_gravityAddress; constructor(address _gravityAddress) public { state_gravityAddress = _gravityAddress; } function transfer(address _recipient, uint256 _amount) public returns (bool) { // _currentValidators, _currentPowers, _currentValsetNonce, _v, _r, _s, _args);( address[] memory addresses = new address[](0); bytes32[] memory bytes32s = new bytes32[](0); uint256[] memory uint256s = new uint256[](0); address blankAddress = address(0); bytes memory bytess = new bytes(0); uint256 zero = 0; LogicCallArgs memory args; ValsetArgs memory valset; { args = LogicCallArgs( uint256s, addresses, uint256s, addresses, address(0), bytess, zero, bytes32(0), zero ); } { valset = ValsetArgs(addresses, uint256s, zero, zero, blankAddress); } Gravity(state_gravityAddress).submitLogicCall( valset, new uint8[](0), bytes32s, bytes32s, args ); } }
2,143
38
// Deposit LP tokens to MasterChef for FUZZ allocation.
function deposit(uint256 _pid, uint256 _amount) public { require (_pid != 0, 'deposit FUZZ by staking'); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); uint256 stakingRewards = 0; if(stakingRewardActive){ stakingRewards = pendingStakingRewards(_pid, msg.sender); } if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accFuzzPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeFuzzTransfer(msg.sender, pending.add(stakingRewards)); user.lastPendingFuzz = 0; } } if (_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accFuzzPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); }
function deposit(uint256 _pid, uint256 _amount) public { require (_pid != 0, 'deposit FUZZ by staking'); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); uint256 stakingRewards = 0; if(stakingRewardActive){ stakingRewards = pendingStakingRewards(_pid, msg.sender); } if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accFuzzPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeFuzzTransfer(msg.sender, pending.add(stakingRewards)); user.lastPendingFuzz = 0; } } if (_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accFuzzPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); }
16,554
22
// A function used by withdrawLiquidation function from SelfMintingPerpetualLiquidatableMultiParty contractto withdraw any proceeds after a successfull liquidation on a token sponsor position liquidation The liquidation for which proceeds will be withdrawn fetched from storage liquidatableData Data for the liquidation fetched from storage positionManagerData Data for specific position of a sponsor fetched from storage feePayerData Fees and distribution data fetched from storage liquidationId The id of the liquidation for which to withdraw proceeds sponsor The address of the token sponsor on which a liqudation was performed /
function withdrawLiquidation( SelfMintingPerpetualLiquidatableMultiParty.LiquidationData storage liquidation, SelfMintingPerpetualLiquidatableMultiParty.LiquidatableData storage liquidatableData, SelfMintingPerpetualPositionManagerMultiParty.PositionManagerData storage positionManagerData, FeePayerParty.FeePayerData storage feePayerData, uint256 liquidationId, address sponsor
function withdrawLiquidation( SelfMintingPerpetualLiquidatableMultiParty.LiquidationData storage liquidation, SelfMintingPerpetualLiquidatableMultiParty.LiquidatableData storage liquidatableData, SelfMintingPerpetualPositionManagerMultiParty.PositionManagerData storage positionManagerData, FeePayerParty.FeePayerData storage feePayerData, uint256 liquidationId, address sponsor
9,582
7
// Assigns a new address to act as the COO. Only available to the current CEO/_newCOO The address of the new COO
function setCOO(address _newCOO) public onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; }
function setCOO(address _newCOO) public onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; }
61,010
108
// sets affiliate fee with WEI_PERCENT_PRECISION/newValue affiliate fee percent
function setAffiliateFeePercent(uint256 newValue) external;
function setAffiliateFeePercent(uint256 newValue) external;
43,016
125
// (avgPriceoldBalance) + (currPricenewQty)) / totBalance
userAvgPrices[usr] = userAvgPrices[usr].mul(oldBalance).add(price.mul(newQty)).div(oldBalance.add(newQty));
userAvgPrices[usr] = userAvgPrices[usr].mul(oldBalance).add(price.mul(newQty)).div(oldBalance.add(newQty));
22,855
82
// this calls getPlayerId because it was almost a copy of it.
(bool out, ) = getPlayerId(_avatarId); return out;
(bool out, ) = getPlayerId(_avatarId); return out;
40,176
15
// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
uint immutable x = 1;
uint immutable x = 1;
37,780
194
// Changes the admin of the proxy.
* Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); }
* Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); }
17,995
107
// In case there are some issues discovered about the pool or underlying asset Governance can exit the pool properly The function is only used for emergency to exit the pool/
function emergencyExit() public onlyGovernance { rewardPool.exit(); pausedInvesting = true; }
function emergencyExit() public onlyGovernance { rewardPool.exit(); pausedInvesting = true; }
46,872
488
// Liquidate a loan if it is expired or under collateralized loanID The ID of the loan to be liquidated /
function liquidateLoan(uint256 loanID) external loanActive(loanID) isInitialized() whenNotPaused() whenLendingPoolNotPaused(address(lendingPool)) nonReentrant()
function liquidateLoan(uint256 loanID) external loanActive(loanID) isInitialized() whenNotPaused() whenLendingPoolNotPaused(address(lendingPool)) nonReentrant()
12,231
9
// Starts a proposal for fee /
function setProposal(Proposal memory VoteProposal) redeemRightToVot public { proposals.push( Proposal({ motivation: VoteProposal.motivation, value: VoteProposal.value, voteCount: 0 })); }
function setProposal(Proposal memory VoteProposal) redeemRightToVot public { proposals.push( Proposal({ motivation: VoteProposal.motivation, value: VoteProposal.value, voteCount: 0 })); }
37,700
48
// Mapping of actionIds to Actions. This data can be accessed through the `getAction` function.
mapping(uint256 actionId => Action) internal actions;
mapping(uint256 actionId => Action) internal actions;
33,712
3
// VaultCore.sol
function mint( address _asset, uint256 _amount, uint256 _minimumOusdAmount ) external; function mintMultiple( address[] calldata _assets, uint256[] calldata _amount, uint256 _minimumOusdAmount
function mint( address _asset, uint256 _amount, uint256 _minimumOusdAmount ) external; function mintMultiple( address[] calldata _assets, uint256[] calldata _amount, uint256 _minimumOusdAmount
33,898
111
// track amount allocated into pool
if ( amount < tokenInfo[ token ].deployed ) { tokenInfo[ token ].deployed = tokenInfo[ token ].deployed.sub( amount ); } else {
if ( amount < tokenInfo[ token ].deployed ) { tokenInfo[ token ].deployed = tokenInfo[ token ].deployed.sub( amount ); } else {
31,340
1
// Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to theaccount that deploys the contract. Token URIs will be autogenerated based on `baseURI` and their token IDs.See {ERC721-tokenURI}. /
constructor(string memory name, string memory symbol, string memory baseTokenURI, address royaltiesReceiver, uint96 royaltiesFeeNumerator, address eventContract) ERC721(name, symbol,eventContract) {
constructor(string memory name, string memory symbol, string memory baseTokenURI, address royaltiesReceiver, uint96 royaltiesFeeNumerator, address eventContract) ERC721(name, symbol,eventContract) {
21,163
99
// To display on website
function getGameInfo() external constant returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256[], bool[]){ uint256[] memory units = new uint256[](schema.currentNumberOfUnits()); bool[] memory upgrades = new bool[](schema.currentNumberOfUpgrades()); uint256 startId; uint256 endId; (startId, endId) = schema.productionUnitIdRange(); uint256 i; while (startId <= endId) { units[i] = unitsOwned[msg.sender][startId]; i++; startId++; } (startId, endId) = schema.battleUnitIdRange(); while (startId <= endId) { units[i] = unitsOwned[msg.sender][startId]; i++; startId++; } // Reset for upgrades i = 0; (startId, endId) = schema.upgradeIdRange(); while (startId <= endId) { upgrades[i] = upgradesOwned[msg.sender][startId]; i++; startId++; } return (block.timestamp, totalEtherGooResearchPool, totalGooProduction, totalGooDepositSnapshots[totalGooDepositSnapshots.length - 1], gooDepositSnapshots[msg.sender][totalGooDepositSnapshots.length - 1], nextSnapshotTime, balanceOf(msg.sender), ethBalance[msg.sender], getGooProduction(msg.sender), units, upgrades); }
function getGameInfo() external constant returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256[], bool[]){ uint256[] memory units = new uint256[](schema.currentNumberOfUnits()); bool[] memory upgrades = new bool[](schema.currentNumberOfUpgrades()); uint256 startId; uint256 endId; (startId, endId) = schema.productionUnitIdRange(); uint256 i; while (startId <= endId) { units[i] = unitsOwned[msg.sender][startId]; i++; startId++; } (startId, endId) = schema.battleUnitIdRange(); while (startId <= endId) { units[i] = unitsOwned[msg.sender][startId]; i++; startId++; } // Reset for upgrades i = 0; (startId, endId) = schema.upgradeIdRange(); while (startId <= endId) { upgrades[i] = upgradesOwned[msg.sender][startId]; i++; startId++; } return (block.timestamp, totalEtherGooResearchPool, totalGooProduction, totalGooDepositSnapshots[totalGooDepositSnapshots.length - 1], gooDepositSnapshots[msg.sender][totalGooDepositSnapshots.length - 1], nextSnapshotTime, balanceOf(msg.sender), ethBalance[msg.sender], getGooProduction(msg.sender), units, upgrades); }
62,020
2
// SHOPX Settings value percentage (using 2 decimals: 10000 = 100.00%, 0 = 0.00%) shopxFee value (between 0 and 10000)
address public shopxAddress; uint256 public shopxFee;
address public shopxAddress; uint256 public shopxFee;
20,195
166
// set locked amount
Staked[sender] = 0;
Staked[sender] = 0;
60,761
52
// Emitted when a previosly dead token is marked as alive tokenId Token ID /
event Resurrection(uint256 indexed tokenId);
event Resurrection(uint256 indexed tokenId);
80,005
16
// 从未上过架的上架 { preItemId: 上级授权的item id}
function uploadMarket( address nftContract, uint256 tokenId, uint256 preItemId, uint256 price ) public payable nonReentrant { require( price >= _marketFee, "Price must be larger than the mark fee of 0.0000001 ether" );
function uploadMarket( address nftContract, uint256 tokenId, uint256 preItemId, uint256 price ) public payable nonReentrant { require( price >= _marketFee, "Price must be larger than the mark fee of 0.0000001 ether" );
28,179
24
// ERC20 Token Info /
function name() external view override returns (string memory) { return _name; }
function name() external view override returns (string memory) { return _name; }
5,085
22
// 发行 Cat
function issueCat( string _genes
function issueCat( string _genes
43,778
15
// check if boost and boost allowed
if (_method == Method.Boost && !holder.boostEnabled) return (false, 0, "Boost not enabled");
if (_method == Method.Boost && !holder.boostEnabled) return (false, 0, "Boost not enabled");
12,744
61
// ensures instantiation only by sub-contracts/
constructor() internal {} // protects a function against reentrancy attacks modifier protected() { _protected(); locked = true; _; locked = false; }
constructor() internal {} // protects a function against reentrancy attacks modifier protected() { _protected(); locked = true; _; locked = false; }
1,549
24
// Lets an owner or approved operator burn NFTs of the given tokenIds. _ownerThe owner of the NFTs to burn._tokenIds The tokenIds of the NFTs to burn._amountsThe amounts of the NFTs to burn. /
function burnBatch( address _owner, uint256[] memory _tokenIds, uint256[] memory _amounts
function burnBatch( address _owner, uint256[] memory _tokenIds, uint256[] memory _amounts
26,397
19
// fill pot with c2d
if(info.roundNumber%bigPotFrequency == 0){
if(info.roundNumber%bigPotFrequency == 0){
43,099
221
// Pull aTokens from user
_pullAToken( collateralAsset, collateralReserveData.aTokenAddress, msg.sender, amounts[0], permitSignature );
_pullAToken( collateralAsset, collateralReserveData.aTokenAddress, msg.sender, amounts[0], permitSignature );
47,654
29
// -------------------------------------------------------------------------- Miner --------------------------------------------------------------------------
function getFreeMiner(address ref) public
function getFreeMiner(address ref) public
29,318
13
// Restore the zero slot.
mstore(0x60, 0)
mstore(0x60, 0)
21,265
44
// Call the contract, and revert if the call fails.
if iszero( call( gas(), // Gas remaining. c, // `contracts[i]`. 0, // `msg.value` of the call: 0 ETH. m, // Start of the copy of `bytes[i]` in memory. calldataload(o), // The length of the `bytes[i]`. 0x00, // Start of output. Not used. 0x00 // Size of output. Not used. )
if iszero( call( gas(), // Gas remaining. c, // `contracts[i]`. 0, // `msg.value` of the call: 0 ETH. m, // Start of the copy of `bytes[i]` in memory. calldataload(o), // The length of the `bytes[i]`. 0x00, // Start of output. Not used. 0x00 // Size of output. Not used. )
14,815
6
// FSA for the policy is a one step with a minimum approval count /
function challengeResponse(uint64 pendingActionId, uint64 challengeId, bool approval) external override { senderRequires(Role.ADMIN); validatePolicyInitialized(); validatePendingActionId(pendingActionId); validateChallengeId(challengeId); _actions.challengeResponse(pendingActionId, challengeId, approval); PendingAction memory action = _actions.getPending(pendingActionId); if(hasReachedApproval(action)){ _actions.authorize(pendingActionId); } else if(cannotReachApproval(action)) { _actions.deny(pendingActionId); } }
function challengeResponse(uint64 pendingActionId, uint64 challengeId, bool approval) external override { senderRequires(Role.ADMIN); validatePolicyInitialized(); validatePendingActionId(pendingActionId); validateChallengeId(challengeId); _actions.challengeResponse(pendingActionId, challengeId, approval); PendingAction memory action = _actions.getPending(pendingActionId); if(hasReachedApproval(action)){ _actions.authorize(pendingActionId); } else if(cannotReachApproval(action)) { _actions.deny(pendingActionId); } }
44,958
127
// SusafeToken with Governance.
contract SusafeToken is ERC20Capped("SusafeToken", "SUSAFE", 210000 ether), Ownable { address public dev = address(0); function setDev(address _dev) public onlyOwner { require(dev == address(0) && _dev != address(0), "DevFund contract can be set once only (to avoid of rug-pull)"); dev = _dev; } /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public { require(owner() == msg.sender || dev == msg.sender, "Ownable: caller is not the owner nor dev fund contract"); _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } /** * support to burn SUSAFE */ function burn(uint256 _amount) public { _burn(msg.sender, _amount); _moveDelegates(_delegates[msg.sender], address(0), _amount); } /** * See {ERC20-_burn} and {ERC20-allowance}. */ function burnFrom(address _account, uint256 _amount) public virtual { uint256 decreasedAllowance = allowance(_account, msg.sender).sub(_amount, "ERC20: burn amount exceeds allowance"); _approve(_account, msg.sender, decreasedAllowance); _burn(_account, _amount); _moveDelegates(_delegates[_account], address(0), _amount); } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @dev A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "SUSAFE::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "SUSAFE::delegateBySig: invalid nonce"); require(now <= expiry, "SUSAFE::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "SUSAFE::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying SUSAFEs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "SUSAFE::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
contract SusafeToken is ERC20Capped("SusafeToken", "SUSAFE", 210000 ether), Ownable { address public dev = address(0); function setDev(address _dev) public onlyOwner { require(dev == address(0) && _dev != address(0), "DevFund contract can be set once only (to avoid of rug-pull)"); dev = _dev; } /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public { require(owner() == msg.sender || dev == msg.sender, "Ownable: caller is not the owner nor dev fund contract"); _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } /** * support to burn SUSAFE */ function burn(uint256 _amount) public { _burn(msg.sender, _amount); _moveDelegates(_delegates[msg.sender], address(0), _amount); } /** * See {ERC20-_burn} and {ERC20-allowance}. */ function burnFrom(address _account, uint256 _amount) public virtual { uint256 decreasedAllowance = allowance(_account, msg.sender).sub(_amount, "ERC20: burn amount exceeds allowance"); _approve(_account, msg.sender, decreasedAllowance); _burn(_account, _amount); _moveDelegates(_delegates[_account], address(0), _amount); } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @dev A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "SUSAFE::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "SUSAFE::delegateBySig: invalid nonce"); require(now <= expiry, "SUSAFE::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "SUSAFE::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying SUSAFEs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "SUSAFE::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
66,085
31
// class => {armor | offhand | mainhand} => value => address
mapping(uint8 => mapping(uint8 => mapping(uint8 => mapping(uint8 => address)))) public traitSvgs; IDogewood public dogewood; string internal constant TABLE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
mapping(uint8 => mapping(uint8 => mapping(uint8 => mapping(uint8 => address)))) public traitSvgs; IDogewood public dogewood; string internal constant TABLE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
48,775
26
// Adjusting
error AdjustmentResultsInMinimumCollateralNotBeingMet(address thrower, OptionPosition position, uint spotPrice); error CannotClosePositionZero(address thrower); error CannotOpenZeroAmount(address thrower); error CannotAdjustInvalidPosition( address thrower, uint positionId, bool invalidPositionId, bool positionInactive, bool strikeMismatch, bool optionTypeMismatch
error AdjustmentResultsInMinimumCollateralNotBeingMet(address thrower, OptionPosition position, uint spotPrice); error CannotClosePositionZero(address thrower); error CannotOpenZeroAmount(address thrower); error CannotAdjustInvalidPosition( address thrower, uint positionId, bool invalidPositionId, bool positionInactive, bool strikeMismatch, bool optionTypeMismatch
15,731
67
// Redeem all Dharma Dai held by this account for Dai. /
function redeemAllDDai() external { _withdrawMaxFromDharmaToken(AssetType.DAI); }
function redeemAllDDai() external { _withdrawMaxFromDharmaToken(AssetType.DAI); }
43,503
353
// Ensure the Vault has not already been initialized.
require(!isInitialized, "ALREADY_INITIALIZED");
require(!isInitialized, "ALREADY_INITIALIZED");
40,367
15
// Twenty6Fifty2lileddie.eth / Enefte Studio/
contract Twenty6Fifty2 is ERC721A, EnefteOwnership { uint64 public MAX_SUPPLY = 2652; uint64 public TOKEN_PRICE = 0.01 ether; uint64 public SALE_OPENS = 0; uint64 public SALE_CLOSES = 999999999999; uint256 public EMISSIONS = 91000 ether; INinety1 NINETY_ONE; IFold FOLD; IFoldStaking foldStaking; mapping(uint => uint) handMultiplier; string public BASE_URI = "https://enefte.info/n1/?token_id="; bool LOCKED = false; modifier notLocked() { if(LOCKED){ revert("Contract Locked"); } _; } /** * @notice minting process for the main sale * * @param _numberOfTokens number of tokens to be minted */ function mint(uint64 _numberOfTokens) external payable { if(block.timestamp < SALE_OPENS || block.timestamp > SALE_CLOSES){ revert("Sale Closed"); } if(totalSupply() + _numberOfTokens > MAX_SUPPLY){ revert("Not Enough Tokens Left"); } if(TOKEN_PRICE * _numberOfTokens > msg.value){ revert("Not Enough Funds Sent"); } _safeMint(msg.sender, _numberOfTokens); FOLD.mint(EMISSIONS*_numberOfTokens); } function fold(uint _tokenId) external { if(ownerOf(_tokenId) != msg.sender){ revert("Not your token"); } NINETY_ONE.mint(msg.sender); FOLD.transfer(address(NINETY_ONE),EMISSIONS); _burn(_tokenId); } /* * Move to staking contract?? */ function setMultipliers(uint[] calldata _tokenIds, uint _tier) external onlyOwner notLocked { for (uint256 i = 0; i < _tokenIds.length; i++) { handMultiplier[_tokenIds[i]] = _tier; } } /** * @notice set the timestamp of when the main sale should begin * * @param _openTime the unix timestamp the sale opens * @param _closeTime the unix timestamp the sale closes */ function setSaleTimes(uint64 _openTime, uint64 _closeTime) external onlyOwner notLocked { SALE_OPENS = _openTime; SALE_CLOSES = _closeTime; } /** * @notice sets the URI of where metadata will be hosted, gets appended with the token id * * @param _uri the amount URI address */ function setBaseURI(string memory _uri) external onlyOwner notLocked { BASE_URI = _uri; } /** * @notice set the address for the smart contracts * */ function setContracts(address _address91, address _addressFold, address _addressStaking) external onlyOwner notLocked { NINETY_ONE = INinety1(_address91); FOLD = IFold(_addressFold); foldStaking = IFoldStaking(_addressStaking); } /** * @notice returns the URI that is used for the metadata */ function _baseURI() internal view override returns (string memory) { return BASE_URI; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, _toString(tokenId))) : ''; } /** * @notice withdraw the funds from the contract to a specificed address. */ function withdrawBalance() external onlyOwner { uint256 balance = address(this).balance; (bool sent, bytes memory data) = msg.sender.call{value: balance}(""); require(sent, "Failed to send Ether to Wallet"); } function calculateEmissions(uint256 _firstTokenId, uint256 _quantity) internal view returns (uint256 totalEmissions) { uint _emissions = 0; for(uint i = 0;i < _quantity;i++){ uint tokenId = _firstTokenId + i; uint multiplier = handMultiplier[tokenId]; _emissions += EMISSIONS * multiplier; } return _emissions; } function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual override { uint256 totalEmissions = calculateEmissions(startTokenId,quantity); if(from == address(0)){ foldStaking.deposit(totalEmissions,to); } else if(to == address(0)){ foldStaking.withdraw(totalEmissions,from); } else if(from == address(0)){ foldStaking.withdraw(totalEmissions,from); foldStaking.deposit(totalEmissions,to); } } function lockContract() external onlyOwner notLocked { LOCKED = true; } /** * @notice Start token IDs from this number */ function _startTokenId() internal override view virtual returns (uint256) { return 1; } constructor() ERC721A("Twenty6Fifty2", "2652") { setOwner(msg.sender); } }
contract Twenty6Fifty2 is ERC721A, EnefteOwnership { uint64 public MAX_SUPPLY = 2652; uint64 public TOKEN_PRICE = 0.01 ether; uint64 public SALE_OPENS = 0; uint64 public SALE_CLOSES = 999999999999; uint256 public EMISSIONS = 91000 ether; INinety1 NINETY_ONE; IFold FOLD; IFoldStaking foldStaking; mapping(uint => uint) handMultiplier; string public BASE_URI = "https://enefte.info/n1/?token_id="; bool LOCKED = false; modifier notLocked() { if(LOCKED){ revert("Contract Locked"); } _; } /** * @notice minting process for the main sale * * @param _numberOfTokens number of tokens to be minted */ function mint(uint64 _numberOfTokens) external payable { if(block.timestamp < SALE_OPENS || block.timestamp > SALE_CLOSES){ revert("Sale Closed"); } if(totalSupply() + _numberOfTokens > MAX_SUPPLY){ revert("Not Enough Tokens Left"); } if(TOKEN_PRICE * _numberOfTokens > msg.value){ revert("Not Enough Funds Sent"); } _safeMint(msg.sender, _numberOfTokens); FOLD.mint(EMISSIONS*_numberOfTokens); } function fold(uint _tokenId) external { if(ownerOf(_tokenId) != msg.sender){ revert("Not your token"); } NINETY_ONE.mint(msg.sender); FOLD.transfer(address(NINETY_ONE),EMISSIONS); _burn(_tokenId); } /* * Move to staking contract?? */ function setMultipliers(uint[] calldata _tokenIds, uint _tier) external onlyOwner notLocked { for (uint256 i = 0; i < _tokenIds.length; i++) { handMultiplier[_tokenIds[i]] = _tier; } } /** * @notice set the timestamp of when the main sale should begin * * @param _openTime the unix timestamp the sale opens * @param _closeTime the unix timestamp the sale closes */ function setSaleTimes(uint64 _openTime, uint64 _closeTime) external onlyOwner notLocked { SALE_OPENS = _openTime; SALE_CLOSES = _closeTime; } /** * @notice sets the URI of where metadata will be hosted, gets appended with the token id * * @param _uri the amount URI address */ function setBaseURI(string memory _uri) external onlyOwner notLocked { BASE_URI = _uri; } /** * @notice set the address for the smart contracts * */ function setContracts(address _address91, address _addressFold, address _addressStaking) external onlyOwner notLocked { NINETY_ONE = INinety1(_address91); FOLD = IFold(_addressFold); foldStaking = IFoldStaking(_addressStaking); } /** * @notice returns the URI that is used for the metadata */ function _baseURI() internal view override returns (string memory) { return BASE_URI; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, _toString(tokenId))) : ''; } /** * @notice withdraw the funds from the contract to a specificed address. */ function withdrawBalance() external onlyOwner { uint256 balance = address(this).balance; (bool sent, bytes memory data) = msg.sender.call{value: balance}(""); require(sent, "Failed to send Ether to Wallet"); } function calculateEmissions(uint256 _firstTokenId, uint256 _quantity) internal view returns (uint256 totalEmissions) { uint _emissions = 0; for(uint i = 0;i < _quantity;i++){ uint tokenId = _firstTokenId + i; uint multiplier = handMultiplier[tokenId]; _emissions += EMISSIONS * multiplier; } return _emissions; } function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual override { uint256 totalEmissions = calculateEmissions(startTokenId,quantity); if(from == address(0)){ foldStaking.deposit(totalEmissions,to); } else if(to == address(0)){ foldStaking.withdraw(totalEmissions,from); } else if(from == address(0)){ foldStaking.withdraw(totalEmissions,from); foldStaking.deposit(totalEmissions,to); } } function lockContract() external onlyOwner notLocked { LOCKED = true; } /** * @notice Start token IDs from this number */ function _startTokenId() internal override view virtual returns (uint256) { return 1; } constructor() ERC721A("Twenty6Fifty2", "2652") { setOwner(msg.sender); } }
747
15
// Prepare storage for first call.
if (_paidFees.firstContributionTime == 0) { _paidFees.firstContributionTime = now; _paidFees.ruling.push(0); _paidFees.stake.push(stake); _paidFees.totalValue.push(0); _paidFees.totalContributedPerSide.push([0, 0]); _paidFees.loserFullyFunded.push(false); _paidFees.contributions.length++; }
if (_paidFees.firstContributionTime == 0) { _paidFees.firstContributionTime = now; _paidFees.ruling.push(0); _paidFees.stake.push(stake); _paidFees.totalValue.push(0); _paidFees.totalContributedPerSide.push([0, 0]); _paidFees.loserFullyFunded.push(false); _paidFees.contributions.length++; }
1,482
316
// Per-market mapping of "accounts in this asset"
mapping(address => bool) accountMembership;
mapping(address => bool) accountMembership;
3,331
1
// Public functions //Creates a new ultimate Oracle contract/oracle Oracle address/collateralToken Collateral token address/spreadMultiplier Defines the spread as a multiple of the money bet on other outcomes/challengePeriod Time to challenge oracle outcome/challengeAmount Amount to challenge the outcome/frontRunnerPeriod Time to overbid the front-runner/ return ultimateOracle Oracle contract
function createUltimateOracle( Oracle oracle, Token collateralToken, uint8 spreadMultiplier, uint challengePeriod, uint challengeAmount, uint frontRunnerPeriod ) public returns (UltimateOracle ultimateOracle)
function createUltimateOracle( Oracle oracle, Token collateralToken, uint8 spreadMultiplier, uint challengePeriod, uint challengeAmount, uint frontRunnerPeriod ) public returns (UltimateOracle ultimateOracle)
13,131
36
// Function to Withdraw certain amountof funds in ETHER. This method is hereso the Owner can be able to withdraw fundsin case that there is a needof exchanging the amount of ETHER storedin this contract for some other Asset, Fiat or the Like. /
function withdrawSome(uint256 amount) external onlyOwner { require( address(this).balance >= amount, "MDST: No balance found for that amount" ); payable(msg.sender).transfer(amount); }
function withdrawSome(uint256 amount) external onlyOwner { require( address(this).balance >= amount, "MDST: No balance found for that amount" ); payable(msg.sender).transfer(amount); }
43,622
89
// amount sold from virtual trades
uint256 blockTimestampElapsed = blockTimestamp - longTermOrders.lastVirtualOrderTimestamp; uint256 token0SellAmount = orderPool0.currentSalesRate * blockTimestampElapsed / SELL_RATE_ADDITIONAL_PRECISION; uint256 token1SellAmount = orderPool1.currentSalesRate * blockTimestampElapsed / SELL_RATE_ADDITIONAL_PRECISION; (uint256 token0Out, uint256 token1Out) = executeVirtualTradesAndOrderExpiries(reserveResult, token0SellAmount, token1SellAmount); updateOrderPoolAfterExecution(longTermOrders, orderPool0, orderPool1, token0Out, token1Out, blockTimestamp);
uint256 blockTimestampElapsed = blockTimestamp - longTermOrders.lastVirtualOrderTimestamp; uint256 token0SellAmount = orderPool0.currentSalesRate * blockTimestampElapsed / SELL_RATE_ADDITIONAL_PRECISION; uint256 token1SellAmount = orderPool1.currentSalesRate * blockTimestampElapsed / SELL_RATE_ADDITIONAL_PRECISION; (uint256 token0Out, uint256 token1Out) = executeVirtualTradesAndOrderExpiries(reserveResult, token0SellAmount, token1SellAmount); updateOrderPoolAfterExecution(longTermOrders, orderPool0, orderPool1, token0Out, token1Out, blockTimestamp);
60,378
367
// Sets the quorum threshold. _domain The remote domain of the validator set. _threshold The new quorum threshold. /
function setThreshold(uint32 _domain, uint8 _threshold) public onlyOwner { require( _threshold > 0 && _threshold <= validatorCount(_domain), "!range" ); threshold[_domain] = _threshold; emit ThresholdSet(_domain, _threshold); _updateCommitment(_domain); }
function setThreshold(uint32 _domain, uint8 _threshold) public onlyOwner { require( _threshold > 0 && _threshold <= validatorCount(_domain), "!range" ); threshold[_domain] = _threshold; emit ThresholdSet(_domain, _threshold); _updateCommitment(_domain); }
19,167
107
// Once all allocations on queue have been claimed, reset user state
if (user.Amount == 0) {
if (user.Amount == 0) {
51,334
136
// Transfer enterToken even it's ETH or ERC20._to Offset to generate the random number _amount Random number to generate the other random number /
function _transferEnterToken(address _to, uint256 _amount) internal { if (_isEthPool()) { IWETH(controller.getWeth()).withdraw(_amount); (bool status, ) = payable(_to).call{value: _amount}(""); require(status, "ETH not transferred"); } else { enterToken.transfer(address(_to), _amount); } }
function _transferEnterToken(address _to, uint256 _amount) internal { if (_isEthPool()) { IWETH(controller.getWeth()).withdraw(_amount); (bool status, ) = payable(_to).call{value: _amount}(""); require(status, "ETH not transferred"); } else { enterToken.transfer(address(_to), _amount); } }
32,379
10
// Return the current second highest bid
function getSecondHighestBid() public view returns (uint256){ return runnerUpBid; }
function getSecondHighestBid() public view returns (uint256){ return runnerUpBid; }
7,846
13
// Checks if `str1` ends with `str2`/str1 Span to search within/str2 Span pointing to characters to look for/ return True if the span ends with the provided text, false otherwise
function endsWith(span memory str1, span memory str2) internal pure returns(bool) { if (str1.length < str2.length) { return false; } uint256 str1Ptr = str1.ptr; uint256 str2Ptr = str2.ptr; assembly { let len1 := mload(add(str1, 0x20)) let len2 := mload(add(str2, 0x20)) str1Ptr := sub(add(str1Ptr, len1), 1) str2Ptr := sub(add(str2Ptr, len2), 1) } for (uint256 i = 0; i < str2.length; i++) { bytes1 str1Char; bytes1 str2Char; assembly { str1Char := mload(str1Ptr) str2Char := mload(str2Ptr) str1Ptr := sub(str1Ptr, 1) str2Ptr := sub(str2Ptr, 1) } if (str1Char != str2Char) { return false; } } return true; }
function endsWith(span memory str1, span memory str2) internal pure returns(bool) { if (str1.length < str2.length) { return false; } uint256 str1Ptr = str1.ptr; uint256 str2Ptr = str2.ptr; assembly { let len1 := mload(add(str1, 0x20)) let len2 := mload(add(str2, 0x20)) str1Ptr := sub(add(str1Ptr, len1), 1) str2Ptr := sub(add(str2Ptr, len2), 1) } for (uint256 i = 0; i < str2.length; i++) { bytes1 str1Char; bytes1 str2Char; assembly { str1Char := mload(str1Ptr) str2Char := mload(str2Ptr) str1Ptr := sub(str1Ptr, 1) str2Ptr := sub(str2Ptr, 1) } if (str1Char != str2Char) { return false; } } return true; }
37,132
104
// Control and manage Cocos Use for owner setting operating income address, PayerInterface. /
contract WorldCupControl is WorldCupFactory { /// @dev Operating income address. address public cooAddress; function WorldCupControl() public { cooAddress = msg.sender; } /// @dev Assigns a new address to act as the COO. /// @param _newCOO The address of the new COO. function setCOO(address _newCOO) external onlyOwner { require(_newCOO != address(0)); cooAddress = _newCOO; } /// @dev Allows the CFO to capture the balance available to the contract. function withdrawBalance() external onlyOwner { uint balance = address(this).balance; cooAddress.send(balance); } }
contract WorldCupControl is WorldCupFactory { /// @dev Operating income address. address public cooAddress; function WorldCupControl() public { cooAddress = msg.sender; } /// @dev Assigns a new address to act as the COO. /// @param _newCOO The address of the new COO. function setCOO(address _newCOO) external onlyOwner { require(_newCOO != address(0)); cooAddress = _newCOO; } /// @dev Allows the CFO to capture the balance available to the contract. function withdrawBalance() external onlyOwner { uint balance = address(this).balance; cooAddress.send(balance); } }
46,572
77
// Claim ETH Overflow/Claim ETH Overflow from contract
function claimETHOverflow() external onlyOwner { require(address(this).balance > 0, "Ares Token: Cannot send more than contract balance"); uint256 amount = address(this).balance; (bool success,) = address(owner()).call{value : amount}(""); if (success){ emit ClaimETHOverflow(amount); } }
function claimETHOverflow() external onlyOwner { require(address(this).balance > 0, "Ares Token: Cannot send more than contract balance"); uint256 amount = address(this).balance; (bool success,) = address(owner()).call{value : amount}(""); if (success){ emit ClaimETHOverflow(amount); } }
10,851
24
// An event that's emitted when a new mint is accepted
event MintAccepted(uint256 indexed amount, address indexed recipient, uint256 oldSupply, uint256 newSupply);
event MintAccepted(uint256 indexed amount, address indexed recipient, uint256 oldSupply, uint256 newSupply);
9,075
77
// Wrappers over Solidity's arithmetic operations with added overflowchecks. Arithmetic operations in Solidity wrap on overflow. This can easily resultin bugs, because programmers usually assume that an overflow raises anerror, which is the standard behavior in high level programming languages.`SafeMath` restores this intuition by reverting the transaction when anoperation overflows. Using this library instead of the unchecked operations eliminates an entireclass of bugs, so it's recommended to use it always. This library is a version of Open Zeppelin's SafeMath, modified to supportunsigned 64 bit integers. /
library SafeMath64 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint64 a, uint64 b) internal pure returns (uint64) { uint64 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint64 a, uint64 b) internal pure returns (uint64) { require(b <= a, "SafeMath: subtraction overflow"); uint64 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint64 a, uint64 b) internal pure returns (uint64) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint64 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint64 a, uint64 b) internal pure returns (uint64) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint64 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint64 a, uint64 b) internal pure returns (uint64) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } }
library SafeMath64 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint64 a, uint64 b) internal pure returns (uint64) { uint64 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint64 a, uint64 b) internal pure returns (uint64) { require(b <= a, "SafeMath: subtraction overflow"); uint64 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint64 a, uint64 b) internal pure returns (uint64) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint64 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint64 a, uint64 b) internal pure returns (uint64) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint64 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint64 a, uint64 b) internal pure returns (uint64) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } }
1,484
193
// Returns the scaling factor for one of the Pool's tokens. Reverts if `token` is not a token registered by thePool. /
function _scalingFactor(bool token0) internal view returns (uint256) { return token0 ? _scalingFactor0 : _scalingFactor1; }
function _scalingFactor(bool token0) internal view returns (uint256) { return token0 ? _scalingFactor0 : _scalingFactor1; }
3,108
62
// If a vault is provided, it must be valid, otherwise throw rather than optimistically-minting with original `msg.sender`. Note, we do not check `checkDelegateForAll` as well, as it is known to be implicitly checked by calling `checkDelegateForContract`.
bool isValidDelegee = delegationRegistryContract .checkDelegateForContract( msg.sender, // delegate _vault, // vault genArt721CoreAddress // contract ); require(isValidDelegee, "Invalid delegate-vault pairing"); vault = _vault;
bool isValidDelegee = delegationRegistryContract .checkDelegateForContract( msg.sender, // delegate _vault, // vault genArt721CoreAddress // contract ); require(isValidDelegee, "Invalid delegate-vault pairing"); vault = _vault;
30,806
216
// Free up returns for Vault to pull
(profit, loss, debtPayment) = prepareReturn(vault.debtOutstanding());
(profit, loss, debtPayment) = prepareReturn(vault.debtOutstanding());
7,398
93
// recompute unless we're on a lower tick boundary (i.e. already transitioned ticks), and haven't moved
state.tick = TickMath.getTickAtSqrtRatio(state.sqrtPriceX96);
state.tick = TickMath.getTickAtSqrtRatio(state.sqrtPriceX96);
39,969
15
// if layer has traits to pick and no trait been picked yet then pick a trait and roll it.
if (pool[i].length > 0 && picks[i] == 0x0) { j = _uniform(a, pool[i].length); // roll a dice to choose starting pos uint256 count = 0; while (true) { if (count==pool[i].length) { break; }
if (pool[i].length > 0 && picks[i] == 0x0) { j = _uniform(a, pool[i].length); // roll a dice to choose starting pos uint256 count = 0; while (true) { if (count==pool[i].length) { break; }
27,948
153
// contracts/math/SafeMathUint.sol/ pragma solidity 0.6.11; /
library SafeMathUint { function toInt256Safe(uint256 a) internal pure returns (int256 b) { b = int256(a); require(b >= 0, "SMU:OOB"); } }
library SafeMathUint { function toInt256Safe(uint256 a) internal pure returns (int256 b) { b = int256(a); require(b >= 0, "SMU:OOB"); } }
20,846
4
// 向owner发送ether
result = owner.send(number); sendEvent(owner, number, result);
result = owner.send(number); sendEvent(owner, number, result);
14,986
0
// MOBOX FarmContract/
address public moboxFarm;
address public moboxFarm;
7,737
17
// : logic overview Redeem `amount` of underlying at the given `couponEpoch` Reverts if balance of underlying at `couponEpoch` is less than `amount`
function redeemCoupons(uint256 couponEpoch, uint256 amount) external { require(epoch().sub(couponEpoch) >= 2, "Market: Too early to redeem"); require(amount != 0, "Market: Amount too low"); decrementBalanceOfCouponUnderlying(msg.sender, couponEpoch, amount, "Market: Insufficient coupon underlying balance"); dollar().mint(msg.sender, amount); emit CouponRedemption(msg.sender, couponEpoch, amount, 0); }
function redeemCoupons(uint256 couponEpoch, uint256 amount) external { require(epoch().sub(couponEpoch) >= 2, "Market: Too early to redeem"); require(amount != 0, "Market: Amount too low"); decrementBalanceOfCouponUnderlying(msg.sender, couponEpoch, amount, "Market: Insufficient coupon underlying balance"); dollar().mint(msg.sender, amount); emit CouponRedemption(msg.sender, couponEpoch, amount, 0); }
52,028
163
// Pausable transferFrom function from The address from which tokens are sent to The recipient address value The amount of token to be transferred.return If the transaction was successful in bool. /
function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) { return super.transferFrom(from, to, value); }
function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) { return super.transferFrom(from, to, value); }
38,109
31
// Transfers ownership of the contract to a new account (`newOwner`). /
function _transferOwnership(address newOwner) internal { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; }
function _transferOwnership(address newOwner) internal { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; }
14,554
61
// 2^192 doesn't fit within the 192.64-bit format used internally in this function.
if (x >= 192e18) { revert PRBMathUD60x18__Exp2InputTooBig(x); }
if (x >= 192e18) { revert PRBMathUD60x18__Exp2InputTooBig(x); }
53,742
154
// |/ Burn _amount of tokens of a given token id _fromThe address to burn tokens from _idToken id to burn _amountThe amount to be burned /
function _burn(address _from, uint256 _id, uint256 _amount) internal
function _burn(address _from, uint256 _id, uint256 _amount) internal
8,324
41
// sorted lists of orders. one list for token to Eth, other for Eth to token. Each order is added in the correct position in the list to keep it sorted.
OrderListInterface public tokenToEthList; OrderListInterface public ethToTokenList;
OrderListInterface public tokenToEthList; OrderListInterface public ethToTokenList;
21,761
95
// Transfer tokens from other address Send `_value` tokens to `_to` in behalf of `_from`_from The address of the sender _to The address of the recipient _value the amount to send /
function transferFrom(address _from, address _to, uint256 _value) public onlyTranferable returns (bool success)
function transferFrom(address _from, address _to, uint256 _value) public onlyTranferable returns (bool success)
43,709
13
// Returns true if mainnet contracts and schain contracts are connected together for transferring messages. /
function hasSchain(string calldata schainName) external view override returns (bool connected) { uint length = _mainnetContracts.length(); connected = messageProxy.isConnectedChain(schainName); for (uint i = 0; connected && i < length; i++) { connected = connected && Twin(_mainnetContracts.at(i)).hasSchainContract(schainName); } }
function hasSchain(string calldata schainName) external view override returns (bool connected) { uint length = _mainnetContracts.length(); connected = messageProxy.isConnectedChain(schainName); for (uint i = 0; connected && i < length; i++) { connected = connected && Twin(_mainnetContracts.at(i)).hasSchainContract(schainName); } }
59,577
10
// Returns an array of all hashes./
{ return _allHashes.paginate(page, limit); }
{ return _allHashes.paginate(page, limit); }
1,922
3
// Template version
uint256 public constant VERSION = 1_01_00;
uint256 public constant VERSION = 1_01_00;
28,919
46
// Store the size
mstore(ptr, returndatasize())
mstore(ptr, returndatasize())
25,614
4
// ENG::Function that show SmarrtContract BalanceФункция которая отобразит Баланс СмартКонтракта
function getTotalBalance() public constant returns(uint) { return address(this).balance; }
function getTotalBalance() public constant returns(uint) { return address(this).balance; }
28,263
151
// Allow as many s as desired.
if (character >= 0x30 && character <= 0x39) {
if (character >= 0x30 && character <= 0x39) {
33,170
28
// https:docs.peri.finance/contracts/source/contracts/rewardsdistribution
contract RewardsDistribution is Owned, IRewardsDistribution { using SafeMath for uint; using SafeDecimalMath for uint; /** * @notice Authorised address able to call distributeRewards */ address public authority; /** * @notice Address of the PeriFinance ProxyERC20 */ address public periFinanceProxy; /** * @notice Address of the RewardEscrow contract */ address public rewardEscrow; /** * @notice Address of the FeePoolProxy */ address public feePoolProxy; /** * @notice An array of addresses and amounts to send */ DistributionData[] public distributions; /** * @dev _authority maybe the underlying periFinance contract. * Remember to set the authority on a periFinance upgrade */ constructor( address _owner, address _authority, address _periFinanceProxy, address _rewardEscrow, address _feePoolProxy ) public Owned(_owner) { authority = _authority; periFinanceProxy = _periFinanceProxy; rewardEscrow = _rewardEscrow; feePoolProxy = _feePoolProxy; } // ========== EXTERNAL SETTERS ========== function setPeriFinanceProxy(address _periFinanceProxy) external onlyOwner { periFinanceProxy = _periFinanceProxy; } function setRewardEscrow(address _rewardEscrow) external onlyOwner { rewardEscrow = _rewardEscrow; } function setFeePoolProxy(address _feePoolProxy) external onlyOwner { feePoolProxy = _feePoolProxy; } /** * @notice Set the address of the contract authorised to call distributeRewards() * @param _authority Address of the authorised calling contract. */ function setAuthority(address _authority) external onlyOwner { authority = _authority; } // ========== EXTERNAL FUNCTIONS ========== /** * @notice Adds a Rewards DistributionData struct to the distributions * array. Any entries here will be iterated and rewards distributed to * each address when tokens are sent to this contract and distributeRewards() * is called by the autority. * @param destination An address to send rewards tokens too * @param amount The amount of rewards tokens to send */ function addRewardDistribution(address destination, uint amount) external onlyOwner returns (bool) { require(destination != address(0), "Cant add a zero address"); require(amount != 0, "Cant add a zero amount"); DistributionData memory rewardsDistribution = DistributionData(destination, amount); distributions.push(rewardsDistribution); emit RewardDistributionAdded(distributions.length - 1, destination, amount); return true; } /** * @notice Deletes a RewardDistribution from the distributions * so it will no longer be included in the call to distributeRewards() * @param index The index of the DistributionData to delete */ function removeRewardDistribution(uint index) external onlyOwner { require(index <= distributions.length - 1, "index out of bounds"); // shift distributions indexes across for (uint i = index; i < distributions.length - 1; i++) { distributions[i] = distributions[i + 1]; } distributions.length--; // Since this function must shift all later entries down to fill the // gap from the one it removed, it could in principle consume an // unbounded amount of gas. However, the number of entries will // presumably always be very low. } /** * @notice Edits a RewardDistribution in the distributions array. * @param index The index of the DistributionData to edit * @param destination The destination address. Send the same address to keep or different address to change it. * @param amount The amount of tokens to edit. Send the same number to keep or change the amount of tokens to send. */ function editRewardDistribution( uint index, address destination, uint amount ) external onlyOwner returns (bool) { require(index <= distributions.length - 1, "index out of bounds"); distributions[index].destination = destination; distributions[index].amount = amount; return true; } function distributeRewards(uint amount) external returns (bool) { require(amount > 0, "Nothing to distribute"); require(msg.sender == authority, "Caller is not authorised"); require(rewardEscrow != address(0), "RewardEscrow is not set"); require(periFinanceProxy != address(0), "PeriFinanceProxy is not set"); require(feePoolProxy != address(0), "FeePoolProxy is not set"); require( IERC20(periFinanceProxy).balanceOf(address(this)) >= amount, "RewardsDistribution contract does not have enough tokens to distribute" ); uint remainder = amount; // Iterate the array of distributions sending the configured amounts for (uint i = 0; i < distributions.length; i++) { if (distributions[i].destination != address(0) || distributions[i].amount != 0) { remainder = remainder.sub(distributions[i].amount); // Transfer the PERI IERC20(periFinanceProxy).transfer(distributions[i].destination, distributions[i].amount); // If the contract implements RewardsDistributionRecipient.sol, inform it how many PERI its received. bytes memory payload = abi.encodeWithSignature("notifyRewardAmount(uint256)", distributions[i].amount); // solhint-disable avoid-low-level-calls (bool success, ) = distributions[i].destination.call(payload); if (!success) { // Note: we're ignoring the return value as it will fail for contracts that do not implement RewardsDistributionRecipient.sol } } } // After all ditributions have been sent, send the remainder to the RewardsEscrow contract IERC20(periFinanceProxy).transfer(rewardEscrow, remainder); // Tell the FeePool how much it has to distribute to the stakers IFeePool(feePoolProxy).setRewardsToDistribute(remainder); emit RewardsDistributed(amount); return true; } /* ========== VIEWS ========== */ /** * @notice Retrieve the length of the distributions array */ function distributionsLength() external view returns (uint) { return distributions.length; } /* ========== Events ========== */ event RewardDistributionAdded(uint index, address destination, uint amount); event RewardsDistributed(uint amount); }
contract RewardsDistribution is Owned, IRewardsDistribution { using SafeMath for uint; using SafeDecimalMath for uint; /** * @notice Authorised address able to call distributeRewards */ address public authority; /** * @notice Address of the PeriFinance ProxyERC20 */ address public periFinanceProxy; /** * @notice Address of the RewardEscrow contract */ address public rewardEscrow; /** * @notice Address of the FeePoolProxy */ address public feePoolProxy; /** * @notice An array of addresses and amounts to send */ DistributionData[] public distributions; /** * @dev _authority maybe the underlying periFinance contract. * Remember to set the authority on a periFinance upgrade */ constructor( address _owner, address _authority, address _periFinanceProxy, address _rewardEscrow, address _feePoolProxy ) public Owned(_owner) { authority = _authority; periFinanceProxy = _periFinanceProxy; rewardEscrow = _rewardEscrow; feePoolProxy = _feePoolProxy; } // ========== EXTERNAL SETTERS ========== function setPeriFinanceProxy(address _periFinanceProxy) external onlyOwner { periFinanceProxy = _periFinanceProxy; } function setRewardEscrow(address _rewardEscrow) external onlyOwner { rewardEscrow = _rewardEscrow; } function setFeePoolProxy(address _feePoolProxy) external onlyOwner { feePoolProxy = _feePoolProxy; } /** * @notice Set the address of the contract authorised to call distributeRewards() * @param _authority Address of the authorised calling contract. */ function setAuthority(address _authority) external onlyOwner { authority = _authority; } // ========== EXTERNAL FUNCTIONS ========== /** * @notice Adds a Rewards DistributionData struct to the distributions * array. Any entries here will be iterated and rewards distributed to * each address when tokens are sent to this contract and distributeRewards() * is called by the autority. * @param destination An address to send rewards tokens too * @param amount The amount of rewards tokens to send */ function addRewardDistribution(address destination, uint amount) external onlyOwner returns (bool) { require(destination != address(0), "Cant add a zero address"); require(amount != 0, "Cant add a zero amount"); DistributionData memory rewardsDistribution = DistributionData(destination, amount); distributions.push(rewardsDistribution); emit RewardDistributionAdded(distributions.length - 1, destination, amount); return true; } /** * @notice Deletes a RewardDistribution from the distributions * so it will no longer be included in the call to distributeRewards() * @param index The index of the DistributionData to delete */ function removeRewardDistribution(uint index) external onlyOwner { require(index <= distributions.length - 1, "index out of bounds"); // shift distributions indexes across for (uint i = index; i < distributions.length - 1; i++) { distributions[i] = distributions[i + 1]; } distributions.length--; // Since this function must shift all later entries down to fill the // gap from the one it removed, it could in principle consume an // unbounded amount of gas. However, the number of entries will // presumably always be very low. } /** * @notice Edits a RewardDistribution in the distributions array. * @param index The index of the DistributionData to edit * @param destination The destination address. Send the same address to keep or different address to change it. * @param amount The amount of tokens to edit. Send the same number to keep or change the amount of tokens to send. */ function editRewardDistribution( uint index, address destination, uint amount ) external onlyOwner returns (bool) { require(index <= distributions.length - 1, "index out of bounds"); distributions[index].destination = destination; distributions[index].amount = amount; return true; } function distributeRewards(uint amount) external returns (bool) { require(amount > 0, "Nothing to distribute"); require(msg.sender == authority, "Caller is not authorised"); require(rewardEscrow != address(0), "RewardEscrow is not set"); require(periFinanceProxy != address(0), "PeriFinanceProxy is not set"); require(feePoolProxy != address(0), "FeePoolProxy is not set"); require( IERC20(periFinanceProxy).balanceOf(address(this)) >= amount, "RewardsDistribution contract does not have enough tokens to distribute" ); uint remainder = amount; // Iterate the array of distributions sending the configured amounts for (uint i = 0; i < distributions.length; i++) { if (distributions[i].destination != address(0) || distributions[i].amount != 0) { remainder = remainder.sub(distributions[i].amount); // Transfer the PERI IERC20(periFinanceProxy).transfer(distributions[i].destination, distributions[i].amount); // If the contract implements RewardsDistributionRecipient.sol, inform it how many PERI its received. bytes memory payload = abi.encodeWithSignature("notifyRewardAmount(uint256)", distributions[i].amount); // solhint-disable avoid-low-level-calls (bool success, ) = distributions[i].destination.call(payload); if (!success) { // Note: we're ignoring the return value as it will fail for contracts that do not implement RewardsDistributionRecipient.sol } } } // After all ditributions have been sent, send the remainder to the RewardsEscrow contract IERC20(periFinanceProxy).transfer(rewardEscrow, remainder); // Tell the FeePool how much it has to distribute to the stakers IFeePool(feePoolProxy).setRewardsToDistribute(remainder); emit RewardsDistributed(amount); return true; } /* ========== VIEWS ========== */ /** * @notice Retrieve the length of the distributions array */ function distributionsLength() external view returns (uint) { return distributions.length; } /* ========== Events ========== */ event RewardDistributionAdded(uint index, address destination, uint amount); event RewardsDistributed(uint amount); }
18,313
59
// Add to balance so tokens don't get issued.
_terminal.addToBalanceOf{value: _payableValue}(_projectId, _amount, _token, _memo, _metadata);
_terminal.addToBalanceOf{value: _payableValue}(_projectId, _amount, _token, _memo, _metadata);
37,088
186
// Only used for local testing. payoutContractAddress = addresses[5];
_name = strings[0]; _symbol = strings[1]; _setSecondary(uints[0]); _setRoyalties(royaltiesAddrs, [uints[1], uints[2], uints[3], uints[4]]); if (uints[5] != 0) { timePerDecrement = uints[5]; }
_name = strings[0]; _symbol = strings[1]; _setSecondary(uints[0]); _setRoyalties(royaltiesAddrs, [uints[1], uints[2], uints[3], uints[4]]); if (uints[5] != 0) { timePerDecrement = uints[5]; }
33,583
72
// - `index` must be strictly less than {length}./
function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; }
function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; }
342
7
// ensure the msg.value is greather than the amount of ETH being sent
require(msg.value > amount, "Not enough ETH provided as msg.value");
require(msg.value > amount, "Not enough ETH provided as msg.value");
5,223
17
// Sets up the initial assets for the pool. Note: `tokenProvider` must have approved the pool to transfer thecorresponding `balances` of `tokens`.tokens Underlying tokens to initialize the pool with balances Initial balances to transfer denorms Initial denormalized weights for the tokens tokenProvider Address to transfer the balances from /
function initialize( address[] calldata tokens, uint256[] calldata balances, uint96[] calldata denorms, address tokenProvider ) external override _control_
function initialize( address[] calldata tokens, uint256[] calldata balances, uint96[] calldata denorms, address tokenProvider ) external override _control_
7,542
256
// returns the staked balance of a given reserve token_reserveTokenreserve token address return staked balance/
function reserveStakedBalance(IERC20Token _reserveToken) public view validReserve(_reserveToken) returns (uint256)
function reserveStakedBalance(IERC20Token _reserveToken) public view validReserve(_reserveToken) returns (uint256)
10,093
35
// counter starts in 1 as 0 is reserved for empty objects
counter.increment();
counter.increment();
22,133
236
// When the level of the sheet is less than 4, both the nest and the scale of the offer are doubled
if (level < uint(config.maxBiteNestedLevel)) {
if (level < uint(config.maxBiteNestedLevel)) {
37,338
1
// Add new migration data to the contract oldPoolAddress pool address to migrate from mData MigrationData struct that contains information of the old and new pools overwrite should overwrite existing migration data /
function addMigrationData( address oldPoolAddress, MigrationData memory mData, bool overwrite ) external onlyOwner {
function addMigrationData( address oldPoolAddress, MigrationData memory mData, bool overwrite ) external onlyOwner {
23,505
0
// Creates `_amount` token to `_to`. Must only be called by the owner.
function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); }
function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); }
23,575
537
// Implements logic for repay credit accounts//borrower Borrower address/to Address to transfer assets from credit account
function _repayCreditAccountImpl(address borrower, address to) internal returns (uint256)
function _repayCreditAccountImpl(address borrower, address to) internal returns (uint256)
28,849
7
// Generates a data key of keyType Mapping by hashing a string and concatenating it with an address:<bytes10(keccak256(firstWord))>:<bytes2(0)>:<bytes20(addr)> firstWord Used to generate a hash and its first 10 bytesare used for the first part of the data key of keyType Mapping addr used for the last part of the data key of keyType Mapping /
function generateMappingKey(string memory firstWord, address addr) internal pure returns (bytes32)
function generateMappingKey(string memory firstWord, address addr) internal pure returns (bytes32)
16,602
4
// owner of the contract
address contractOwner;
address contractOwner;
20,330
145
// Verifies that the caller is the Savings Manager contract /
modifier onlyVault() { require(vaultAddress == msg.sender, "Caller is not the Vault"); _; }
modifier onlyVault() { require(vaultAddress == msg.sender, "Caller is not the Vault"); _; }
11,571
83
// Constructs the Basis Bond ERC-20 contract. /
constructor() public ERC20('BBOND', 'BBOND') {} /** * @notice Operator mints basis bonds to a recipient * @param recipient_ The address of recipient * @param amount_ The amount of basis bonds to mint to * @return whether the process has been done */ function mint(address recipient_, uint256 amount_) public onlyOperator returns (bool) { uint256 balanceBefore = balanceOf(recipient_); _mint(recipient_, amount_); uint256 balanceAfter = balanceOf(recipient_); return balanceAfter > balanceBefore; }
constructor() public ERC20('BBOND', 'BBOND') {} /** * @notice Operator mints basis bonds to a recipient * @param recipient_ The address of recipient * @param amount_ The amount of basis bonds to mint to * @return whether the process has been done */ function mint(address recipient_, uint256 amount_) public onlyOperator returns (bool) { uint256 balanceBefore = balanceOf(recipient_); _mint(recipient_, amount_); uint256 balanceAfter = balanceOf(recipient_); return balanceAfter > balanceBefore; }
15,565
12
// wallet section: erc721
function receiveNft(ERC721 _nft, uint id) external { require(msg.sender == _nft.ownerOf(id),"just real owner"); // _nft.setApprovalForAll(address(this), true); // this is by sender from contract address.1- handly, 2- signature _nft.approve(address(this), id); _nft.transferFrom(msg.sender, address(this), id); nftOwner[covrage] = msg.sender; covrage += 1; }
function receiveNft(ERC721 _nft, uint id) external { require(msg.sender == _nft.ownerOf(id),"just real owner"); // _nft.setApprovalForAll(address(this), true); // this is by sender from contract address.1- handly, 2- signature _nft.approve(address(this), id); _nft.transferFrom(msg.sender, address(this), id); nftOwner[covrage] = msg.sender; covrage += 1; }
45,830
65
// in case of hack, funds can be transfered out to another addresses and transferred to the stake holders from there
if (payoutBlocked) if(!secondaryPayoutAddress.send(address(this).balance)) revert();
if (payoutBlocked) if(!secondaryPayoutAddress.send(address(this).balance)) revert();
22,114
39
// Ensures that the msg.sender is a provider for the passed EIN./ein The EIN to check.
modifier _isProviderFor(uint ein) { require(isProviderFor(ein, msg.sender), "The identity has not set the passed provider."); _; }
modifier _isProviderFor(uint ein) { require(isProviderFor(ein, msg.sender), "The identity has not set the passed provider."); _; }
30,212
8
// _registrar The initial registrar for the manager/_feeToken The module fee token contract to mint from upon module registration
constructor(address _registrar, address _feeToken) { require(_registrar != address(0), "ZMM::must set registrar to non-zero address"); registrar = _registrar; moduleFeeToken = ZoraProtocolFeeSettings(_feeToken); }
constructor(address _registrar, address _feeToken) { require(_registrar != address(0), "ZMM::must set registrar to non-zero address"); registrar = _registrar; moduleFeeToken = ZoraProtocolFeeSettings(_feeToken); }
4,903
109
// Claim ALX allocation
function claimALX() public onlyEOA { require(claimTimestamp <= block.timestamp, "cannot claim yet"); require(!claimed[msg.sender], "already claimed"); if(invested[msg.sender] > 0) { ERC20(ALX).transfer(msg.sender, invested[msg.sender]); } claimed[msg.sender] = true; }
function claimALX() public onlyEOA { require(claimTimestamp <= block.timestamp, "cannot claim yet"); require(!claimed[msg.sender], "already claimed"); if(invested[msg.sender] > 0) { ERC20(ALX).transfer(msg.sender, invested[msg.sender]); } claimed[msg.sender] = true; }
17,839
136
// info stored for each initialized individual tick
struct Info { // the total position liquidity that references this tick uint128 liquidityGross; // amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left), int128 liquidityNet; // fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick) // only has relative meaning, not absolute — the value depends on when the tick is initialized uint256 feeGrowthOutside0X128; uint256 feeGrowthOutside1X128; // the cumulative tick value on the other side of the tick int56 tickCumulativeOutside; // the seconds per unit of liquidity on the _other_ side of this tick (relative to the current tick) // only has relative meaning, not absolute — the value depends on when the tick is initialized uint160 secondsPerLiquidityOutsideX128; // the seconds spent on the other side of the tick (relative to the current tick) // only has relative meaning, not absolute — the value depends on when the tick is initialized uint32 secondsOutside; // true iff the tick is initialized, i.e. the value is exactly equivalent to the expression liquidityGross != 0 // these 8 bits are set to prevent fresh sstores when crossing newly initialized ticks bool initialized; }
struct Info { // the total position liquidity that references this tick uint128 liquidityGross; // amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left), int128 liquidityNet; // fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick) // only has relative meaning, not absolute — the value depends on when the tick is initialized uint256 feeGrowthOutside0X128; uint256 feeGrowthOutside1X128; // the cumulative tick value on the other side of the tick int56 tickCumulativeOutside; // the seconds per unit of liquidity on the _other_ side of this tick (relative to the current tick) // only has relative meaning, not absolute — the value depends on when the tick is initialized uint160 secondsPerLiquidityOutsideX128; // the seconds spent on the other side of the tick (relative to the current tick) // only has relative meaning, not absolute — the value depends on when the tick is initialized uint32 secondsOutside; // true iff the tick is initialized, i.e. the value is exactly equivalent to the expression liquidityGross != 0 // these 8 bits are set to prevent fresh sstores when crossing newly initialized ticks bool initialized; }
50,970
6
// ipfs:QmcM2pbvjXfTYQShMUWihZxNYdyE8roHHNBVi5r8mTytfj/hidden.json ipfs:QmdTQDFiNGySULUFXdqWBYFZAjzh74JWsikxzV68CZBT5m/
contract ERC721Metadata is ERC721Enumerable, Ownable { using Strings for uint256; // Base URI string private baseURI; string public baseExtension = ".json"; bool public revealed = false; string public notRevealedUri; uint256 private _maxNftSupply; constructor( string memory name_, string memory symbol_, string memory baseURI_, string memory notRevealedUri_, uint256 maxNftSupply_ ) ERC721(name_, symbol_) { setBaseURI(baseURI_); setNotRevealedURI(notRevealedUri_); _maxNftSupply = maxNftSupply_; } function setBaseURI(string memory baseURI_) private onlyOwner { require( keccak256(abi.encodePacked((baseURI))) != keccak256(abi.encodePacked((baseURI_))), "ERC721Metadata: existed baseURI" ); baseURI = baseURI_; } function reveal() external onlyOwner { revealed = true; } function setNotRevealedURI(string memory _notRevealedURI) private onlyOwner { notRevealedUri = _notRevealedURI; } function tokenURI(uint256 tokenId) public view override returns (string memory) { require( tokenId <= _maxNftSupply, "ERC721Metadata: URI query for nonexistent token" ); if (!_exists(tokenId) || !revealed) { return notRevealedUri; } return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString(), baseExtension)) : ""; } }
contract ERC721Metadata is ERC721Enumerable, Ownable { using Strings for uint256; // Base URI string private baseURI; string public baseExtension = ".json"; bool public revealed = false; string public notRevealedUri; uint256 private _maxNftSupply; constructor( string memory name_, string memory symbol_, string memory baseURI_, string memory notRevealedUri_, uint256 maxNftSupply_ ) ERC721(name_, symbol_) { setBaseURI(baseURI_); setNotRevealedURI(notRevealedUri_); _maxNftSupply = maxNftSupply_; } function setBaseURI(string memory baseURI_) private onlyOwner { require( keccak256(abi.encodePacked((baseURI))) != keccak256(abi.encodePacked((baseURI_))), "ERC721Metadata: existed baseURI" ); baseURI = baseURI_; } function reveal() external onlyOwner { revealed = true; } function setNotRevealedURI(string memory _notRevealedURI) private onlyOwner { notRevealedUri = _notRevealedURI; } function tokenURI(uint256 tokenId) public view override returns (string memory) { require( tokenId <= _maxNftSupply, "ERC721Metadata: URI query for nonexistent token" ); if (!_exists(tokenId) || !revealed) { return notRevealedUri; } return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString(), baseExtension)) : ""; } }
30,059