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
89
// Set the address of HysiBatchZapper to allow the zapper to deposit and claim for user zapper_ Address of the HysiBatchZapper This should only be called once after deployment to mitigate the risk of changing this to a malicious contract /
function setZapper(address zapper_) external onlyOwner { require(zapper == address(0), "zapper already set"); zapper = zapper_; }
function setZapper(address zapper_) external onlyOwner { require(zapper == address(0), "zapper already set"); zapper = zapper_; }
12,275
408
// ========== Controller Only ========== //Deposits reserve into savingsAccount./It is part of Vault's interface./amount Value to be deposited.
function deposit(uint256 amount) external onlyController { require(amount > 0, 'Cannot deposit 0'); // Transfer mUSD from sender to this contract IERC20(musd).safeTransferFrom(msg.sender, address(this), amount); // Send to savings account IMStable(savingsContract).depositSavings(amount); }
function deposit(uint256 amount) external onlyController { require(amount > 0, 'Cannot deposit 0'); // Transfer mUSD from sender to this contract IERC20(musd).safeTransferFrom(msg.sender, address(this), amount); // Send to savings account IMStable(savingsContract).depositSavings(amount); }
74,047
256
// returns player info based on address.if no address is given, it will use msg.sender _roundId roundId _addr address of the player you want to lookup return general vault/
function getBoomShare(address _addr, uint256 _roundId) public view returns(uint256)
function getBoomShare(address _addr, uint256 _roundId) public view returns(uint256)
33,917
122
// if timePassed less than one second, rewards will be 0
return (0, 0, timePassed);
return (0, 0, timePassed);
38,288
2
// Check the total underyling token balance to see if we should earn();
function balance() public view returns (uint256) { return token.balanceOf(address(this)).add( IStrategy(strategy).balanceOf() ); }
function balance() public view returns (uint256) { return token.balanceOf(address(this)).add( IStrategy(strategy).balanceOf() ); }
34,543
79
// ./contracts/refs/ICoreRef.sol/ pragma solidity ^0.6.0; // pragma experimental ABIEncoderV2; // import "../core/ICore.sol"; //CoreRef interface/Fei Protocol
interface ICoreRef { // ----------- Events ----------- event CoreUpdate(address indexed _core); // ----------- Governor only state changing api ----------- function setCore(address core) external; function pause() external; function unpause() external; // ----------- Getters ----------- function core() external view returns (ICore); function fei() external view returns (IFei); function tribe() external view returns (IERC20_5); function feiBalance() external view returns (uint256); function tribeBalance() external view returns (uint256); }
interface ICoreRef { // ----------- Events ----------- event CoreUpdate(address indexed _core); // ----------- Governor only state changing api ----------- function setCore(address core) external; function pause() external; function unpause() external; // ----------- Getters ----------- function core() external view returns (ICore); function fei() external view returns (IFei); function tribe() external view returns (IERC20_5); function feiBalance() external view returns (uint256); function tribeBalance() external view returns (uint256); }
16,942
68
// The config which is passed to constructor.
Lottery.LotteryConfig internal cfg;
Lottery.LotteryConfig internal cfg;
4,593
243
// Used to store the total profit accrued by the strategies.
uint256 totalProfitAccrued;
uint256 totalProfitAccrued;
55,475
21
// Story Contract/upgradeable, inheritable abstract contract implementing the Story Contract interface/transientlabs.xyz/ @custom:version 4.0.2
abstract contract StoryContractUpgradeable is Initializable, IStory, ERC165Upgradeable { /*////////////////////////////////////////////////////////////////////////// State Variables //////////////////////////////////////////////////////////////////////////*/ bool public storyEnabled; /*////////////////////////////////////////////////////////////////////////// Modifiers //////////////////////////////////////////////////////////////////////////*/ modifier storyMustBeEnabled() { if (!storyEnabled) revert StoryNotEnabled(); _; } /*////////////////////////////////////////////////////////////////////////// Initializer //////////////////////////////////////////////////////////////////////////*/ /// @param enabled - a bool to enable or disable Story addition function __StoryContractUpgradeable_init(bool enabled) internal { __StoryContractUpgradeable_init_unchained(enabled); } /// @param enabled - a bool to enable or disable Story addition function __StoryContractUpgradeable_init_unchained(bool enabled) internal { storyEnabled = enabled; } /*////////////////////////////////////////////////////////////////////////// Story Functions //////////////////////////////////////////////////////////////////////////*/ /// @dev function to set story enabled/disabled /// @dev requires story admin /// @param enabled - a boolean setting to enable or disable Story additions function setStoryEnabled(bool enabled) external { if (!_isStoryAdmin(msg.sender)) revert NotStoryAdmin(); storyEnabled = enabled; } /// @inheritdoc IStory function addCreatorStory(uint256 tokenId, string calldata creatorName, string calldata story) external storyMustBeEnabled { if (!_tokenExists(tokenId)) revert TokenDoesNotExist(); if (!_isCreator(msg.sender, tokenId)) revert NotTokenCreator(); emit CreatorStory(tokenId, msg.sender, creatorName, story); } /// @inheritdoc IStory function addStory(uint256 tokenId, string calldata collectorName, string calldata story) external storyMustBeEnabled { if (!_tokenExists(tokenId)) revert TokenDoesNotExist(); if (!_isTokenOwner(msg.sender, tokenId)) revert NotTokenOwner(); emit Story(tokenId, msg.sender, collectorName, story); } /*////////////////////////////////////////////////////////////////////////// Hooks //////////////////////////////////////////////////////////////////////////*/ /// @dev function to allow access to enabling/disabling story /// @param potentialAdmin - the address to check for admin priviledges function _isStoryAdmin(address potentialAdmin) internal view virtual returns (bool); /// @dev function to check if a token exists on the token contract /// @param tokenId - the token id to check for existence function _tokenExists(uint256 tokenId) internal view virtual returns (bool); /// @dev function to check ownership of a token /// @param potentialOwner - the address to check for ownership of `tokenId` /// @param tokenId - the token id to check ownership against function _isTokenOwner(address potentialOwner, uint256 tokenId) internal view virtual returns (bool); /// @dev function to check creatorship of a token /// @param potentialCreator - the address to check creatorship of `tokenId` /// @param tokenId - the token id to check creatorship against function _isCreator(address potentialCreator, uint256 tokenId) internal view virtual returns (bool); /*////////////////////////////////////////////////////////////////////////// Overrides //////////////////////////////////////////////////////////////////////////*/ /// @inheritdoc ERC165Upgradeable function supportsInterface(bytes4 interfaceId) public view virtual override (ERC165Upgradeable) returns (bool) { return interfaceId == type(IStory).interfaceId || ERC165Upgradeable.supportsInterface(interfaceId); } /*////////////////////////////////////////////////////////////////////////// Upgradeability Gap //////////////////////////////////////////////////////////////////////////*/ /// @dev gap variable - see https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps uint256[50] private _gap; }
abstract contract StoryContractUpgradeable is Initializable, IStory, ERC165Upgradeable { /*////////////////////////////////////////////////////////////////////////// State Variables //////////////////////////////////////////////////////////////////////////*/ bool public storyEnabled; /*////////////////////////////////////////////////////////////////////////// Modifiers //////////////////////////////////////////////////////////////////////////*/ modifier storyMustBeEnabled() { if (!storyEnabled) revert StoryNotEnabled(); _; } /*////////////////////////////////////////////////////////////////////////// Initializer //////////////////////////////////////////////////////////////////////////*/ /// @param enabled - a bool to enable or disable Story addition function __StoryContractUpgradeable_init(bool enabled) internal { __StoryContractUpgradeable_init_unchained(enabled); } /// @param enabled - a bool to enable or disable Story addition function __StoryContractUpgradeable_init_unchained(bool enabled) internal { storyEnabled = enabled; } /*////////////////////////////////////////////////////////////////////////// Story Functions //////////////////////////////////////////////////////////////////////////*/ /// @dev function to set story enabled/disabled /// @dev requires story admin /// @param enabled - a boolean setting to enable or disable Story additions function setStoryEnabled(bool enabled) external { if (!_isStoryAdmin(msg.sender)) revert NotStoryAdmin(); storyEnabled = enabled; } /// @inheritdoc IStory function addCreatorStory(uint256 tokenId, string calldata creatorName, string calldata story) external storyMustBeEnabled { if (!_tokenExists(tokenId)) revert TokenDoesNotExist(); if (!_isCreator(msg.sender, tokenId)) revert NotTokenCreator(); emit CreatorStory(tokenId, msg.sender, creatorName, story); } /// @inheritdoc IStory function addStory(uint256 tokenId, string calldata collectorName, string calldata story) external storyMustBeEnabled { if (!_tokenExists(tokenId)) revert TokenDoesNotExist(); if (!_isTokenOwner(msg.sender, tokenId)) revert NotTokenOwner(); emit Story(tokenId, msg.sender, collectorName, story); } /*////////////////////////////////////////////////////////////////////////// Hooks //////////////////////////////////////////////////////////////////////////*/ /// @dev function to allow access to enabling/disabling story /// @param potentialAdmin - the address to check for admin priviledges function _isStoryAdmin(address potentialAdmin) internal view virtual returns (bool); /// @dev function to check if a token exists on the token contract /// @param tokenId - the token id to check for existence function _tokenExists(uint256 tokenId) internal view virtual returns (bool); /// @dev function to check ownership of a token /// @param potentialOwner - the address to check for ownership of `tokenId` /// @param tokenId - the token id to check ownership against function _isTokenOwner(address potentialOwner, uint256 tokenId) internal view virtual returns (bool); /// @dev function to check creatorship of a token /// @param potentialCreator - the address to check creatorship of `tokenId` /// @param tokenId - the token id to check creatorship against function _isCreator(address potentialCreator, uint256 tokenId) internal view virtual returns (bool); /*////////////////////////////////////////////////////////////////////////// Overrides //////////////////////////////////////////////////////////////////////////*/ /// @inheritdoc ERC165Upgradeable function supportsInterface(bytes4 interfaceId) public view virtual override (ERC165Upgradeable) returns (bool) { return interfaceId == type(IStory).interfaceId || ERC165Upgradeable.supportsInterface(interfaceId); } /*////////////////////////////////////////////////////////////////////////// Upgradeability Gap //////////////////////////////////////////////////////////////////////////*/ /// @dev gap variable - see https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps uint256[50] private _gap; }
36,724
23
// Decimal multiplier representing the difference between `CASH` decimals In `collateral` token decimals
uint256 public immutable decimalsMultiplier;
uint256 public immutable decimalsMultiplier;
1,574
160
// uint256 lpSupply = pool.lpToken.balanceOf(address(this));
uint256 lpSupply = pool.amount; if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(tokenId, pool.lastRewardBlock, block.number); uint256 tokenReward = multiplier.mul(pool.allocPoint).div(totalAllocPoint[tokenId]); accPerShare = accPerShare.add(tokenReward.mul(1e12).div(lpSupply)); }
uint256 lpSupply = pool.amount; if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(tokenId, pool.lastRewardBlock, block.number); uint256 tokenReward = multiplier.mul(pool.allocPoint).div(totalAllocPoint[tokenId]); accPerShare = accPerShare.add(tokenReward.mul(1e12).div(lpSupply)); }
2,375
5
// Curation registry managed by Art Blocks
address public artblocksCurationRegistryAddress;
address public artblocksCurationRegistryAddress;
33,271
4
// Set the API address to be requested
request.add("get", "https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=USD");
request.add("get", "https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=USD");
1,108
167
// HotdogFiClub with Governance.
contract HotdogFiClub is ERC20("Hotdogfi.club", "HOTC"), Ownable { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _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 /// @notice 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), "HOTC::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "HOTC::delegateBySig: invalid nonce"); require(now <= expiry, "HOTC::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, "HOTC::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 HOTCs (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, "HOTC::_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 HotdogFiClub is ERC20("Hotdogfi.club", "HOTC"), Ownable { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _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 /// @notice 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), "HOTC::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "HOTC::delegateBySig: invalid nonce"); require(now <= expiry, "HOTC::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, "HOTC::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 HOTCs (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, "HOTC::_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; } }
41,344
28
// May emit a {RoleGranted} event. /
function _grantRole(uint8 role, address account) internal virtual { if (!hasRole(role, account)) { roles[account] = role;
function _grantRole(uint8 role, address account) internal virtual { if (!hasRole(role, account)) { roles[account] = role;
20,141
14
// Just Business
function Order_Board(address _Business_Address,uint _Bussiness_ID,address _Scientist_Address,uint _Scientist_ID,uint _Instance_Count,string memory _Area,string memory _Description,uint Token_Pay)public payable
function Order_Board(address _Business_Address,uint _Bussiness_ID,address _Scientist_Address,uint _Scientist_ID,uint _Instance_Count,string memory _Area,string memory _Description,uint Token_Pay)public payable
22,030
124
// Returns current HID balance of this contract/
function getBalance() public view returns (uint256) { return hidToken.balanceOf(address(this)); }
function getBalance() public view returns (uint256) { return hidToken.balanceOf(address(this)); }
16,358
25
// Unwrap a wrapped NFT to retrieve underlying ERC1155, ERC721, ERC20 tokens.
function unwrap(uint256 _tokenId, address _recipient) external nonReentrant onlyRoleWithSwitch(UNWRAP_ROLE) { require(_tokenId < nextTokenIdToMint, "wrapped NFT DNE."); require(_isApprovedOrOwner(_msgSender(), _tokenId), "caller not approved for unwrapping."); _burn(_tokenId); _releaseTokens(_recipient, _tokenId); emit TokensUnwrapped(_msgSender(), _recipient, _tokenId); }
function unwrap(uint256 _tokenId, address _recipient) external nonReentrant onlyRoleWithSwitch(UNWRAP_ROLE) { require(_tokenId < nextTokenIdToMint, "wrapped NFT DNE."); require(_isApprovedOrOwner(_msgSender(), _tokenId), "caller not approved for unwrapping."); _burn(_tokenId); _releaseTokens(_recipient, _tokenId); emit TokensUnwrapped(_msgSender(), _recipient, _tokenId); }
30,546
298
// Records each value and the latest block number. /
setStorageCumulativeGlobalRewards(_nextRewards); setStorageLastSameRewardsAmountAndBlock(_amount, block.number);
setStorageCumulativeGlobalRewards(_nextRewards); setStorageLastSameRewardsAmountAndBlock(_amount, block.number);
52,074
14
// Get the balance of SnowBank token.
uint256 SnowBankBalance = IERC20Joe(SNOWBANK_TOKEN).balanceOf(address(this)); IERC20Joe(SNOWBANK_TOKEN).approve(address(this), uint256(-1)); IERC20Joe(SNOWBANK_TOKEN).approve(SNOWBANK_STAKING_HELPER, uint256(-1)); IERC20Joe(SNOWBANK_TOKEN).approve(SNOWBANK_STAKING, uint256(-1)); IStaking(SNOWBANK_STAKING_HELPER).stake(SnowBankBalance, address(this));
uint256 SnowBankBalance = IERC20Joe(SNOWBANK_TOKEN).balanceOf(address(this)); IERC20Joe(SNOWBANK_TOKEN).approve(address(this), uint256(-1)); IERC20Joe(SNOWBANK_TOKEN).approve(SNOWBANK_STAKING_HELPER, uint256(-1)); IERC20Joe(SNOWBANK_TOKEN).approve(SNOWBANK_STAKING, uint256(-1)); IStaking(SNOWBANK_STAKING_HELPER).stake(SnowBankBalance, address(this));
5,963
319
// if values are not the same (the removed bit was 1) set action to deposit
if (slippageAction != slippage) { isDeposit = true; }
if (slippageAction != slippage) { isDeposit = true; }
1,359
61
// require that time has elapsed
require(now > stakeBalances[msg.sender].initialStakeTime);
require(now > stakeBalances[msg.sender].initialStakeTime);
14,977
10
// start index greater than or equal to the sale's start token index, so ensure it starts after the sale's start token index + the number of PLOTs minted
if (_startTokenIndex <= saleStartTokenIndex + saleMintedPLOTs - 1) { return false; }
if (_startTokenIndex <= saleStartTokenIndex + saleMintedPLOTs - 1) { return false; }
72,687
54
// Шаблон для токена, который можно сжечь/
contract BurnableToken is StandardToken, Ownable, ValidationUtil { using SafeMath for uint; address public tokenOwnerBurner; /** Событие, сколько токенов мы сожгли */ event Burned(address burner, uint burnedAmount); function setOwnerBurner(address _tokenOwnerBurner) public onlyOwner invalidOwnerBurner{ // Проверка, что адрес не пустой requireNotEmptyAddress(_tokenOwnerBurner); tokenOwnerBurner = _tokenOwnerBurner; } /** * Сжигаем токены на балансе владельца токенов, вызвать может только tokenOwnerBurner */ function burnOwnerTokens(uint burnAmount) public onlyTokenOwnerBurner validOwnerBurner{ burnTokens(tokenOwnerBurner, burnAmount); } /** * Сжигаем токены на балансе адреса токенов, вызвать может только tokenOwnerBurner */ function burnTokens(address _address, uint burnAmount) public onlyTokenOwnerBurner validOwnerBurner{ balances[_address] = balances[_address].sub(burnAmount); // Вызываем событие Burned(_address, burnAmount); } /** * Сжигаем все токены на балансе владельца */ function burnAllOwnerTokens() public onlyTokenOwnerBurner validOwnerBurner{ uint burnAmount = balances[tokenOwnerBurner]; burnTokens(tokenOwnerBurner, burnAmount); } /** Модификаторы */ modifier onlyTokenOwnerBurner() { require(msg.sender == tokenOwnerBurner); _; } modifier validOwnerBurner() { // Проверка, что адрес не пустой requireNotEmptyAddress(tokenOwnerBurner); _; } modifier invalidOwnerBurner() { // Проверка, что адрес не пустой require(!isAddressValid(tokenOwnerBurner)); _; } }
contract BurnableToken is StandardToken, Ownable, ValidationUtil { using SafeMath for uint; address public tokenOwnerBurner; /** Событие, сколько токенов мы сожгли */ event Burned(address burner, uint burnedAmount); function setOwnerBurner(address _tokenOwnerBurner) public onlyOwner invalidOwnerBurner{ // Проверка, что адрес не пустой requireNotEmptyAddress(_tokenOwnerBurner); tokenOwnerBurner = _tokenOwnerBurner; } /** * Сжигаем токены на балансе владельца токенов, вызвать может только tokenOwnerBurner */ function burnOwnerTokens(uint burnAmount) public onlyTokenOwnerBurner validOwnerBurner{ burnTokens(tokenOwnerBurner, burnAmount); } /** * Сжигаем токены на балансе адреса токенов, вызвать может только tokenOwnerBurner */ function burnTokens(address _address, uint burnAmount) public onlyTokenOwnerBurner validOwnerBurner{ balances[_address] = balances[_address].sub(burnAmount); // Вызываем событие Burned(_address, burnAmount); } /** * Сжигаем все токены на балансе владельца */ function burnAllOwnerTokens() public onlyTokenOwnerBurner validOwnerBurner{ uint burnAmount = balances[tokenOwnerBurner]; burnTokens(tokenOwnerBurner, burnAmount); } /** Модификаторы */ modifier onlyTokenOwnerBurner() { require(msg.sender == tokenOwnerBurner); _; } modifier validOwnerBurner() { // Проверка, что адрес не пустой requireNotEmptyAddress(tokenOwnerBurner); _; } modifier invalidOwnerBurner() { // Проверка, что адрес не пустой require(!isAddressValid(tokenOwnerBurner)); _; } }
36,156
4
// get region admin _region region's id /
function getRegionAdmin(uint256 _region) public view returns(address) { return regionAdmin[_region]; }
function getRegionAdmin(uint256 _region) public view returns(address) { return regionAdmin[_region]; }
25,173
140
// Sets royalties percentage value _royaltiesPerMillion - The royalties amount, from 0 to 999,999 /
function setRoyaltiesPerMillion(uint256 _royaltiesPerMillion) external;
function setRoyaltiesPerMillion(uint256 _royaltiesPerMillion) external;
37,788
4
// owner -> balance mapping.
mapping(address => uint256) public balanceOf;
mapping(address => uint256) public balanceOf;
15,077
16
// return of interest on the deposit
function collectPercent() isIssetUser timePayment internal { //if the user received 200% or more of his contribution, delete the user if ((userDeposit[msg.sender].mul(2)) <= percentWithdrawnPure[msg.sender]) { _delete(msg.sender); //User has withdrawn more than x2 } else { uint payout = payoutAmount(msg.sender); _payout(msg.sender, payout); } }
function collectPercent() isIssetUser timePayment internal { //if the user received 200% or more of his contribution, delete the user if ((userDeposit[msg.sender].mul(2)) <= percentWithdrawnPure[msg.sender]) { _delete(msg.sender); //User has withdrawn more than x2 } else { uint payout = payoutAmount(msg.sender); _payout(msg.sender, payout); } }
14,421
1
// Implementation address for this contract /
address public implementation;
address public implementation;
29,227
289
// 5. Check the spender has enough pynths to make the repayment
_checkPynthBalance(repayer, loan.currency, payment);
_checkPynthBalance(repayer, loan.currency, payment);
39,268
20
// PROPOSAL PASSED
if (didPass && !proposal.aborted) { proposal.didPass = true;
if (didPass && !proposal.aborted) { proposal.didPass = true;
20,342
121
// tracks last job performed for a keeper
mapping(address => uint) public lastJob;
mapping(address => uint) public lastJob;
26,320
3
// surface the erc721 token contract address /
function tokenAddress() external view returns (address);
function tokenAddress() external view returns (address);
17,775
32
// Event for crowdsale finalization (forwarding) /
event Finalized();
event Finalized();
25,926
398
// DefaultReserveInterestRateStrategy contract - implements the calculation of the interest rates depending on the reserve parameters. if there is need to update the calculation of the interest rates for a specific reserve, a new version of this contract will be deployed. - This contract was cloned from Populous and modified to work with the Populous World eco-system./
contract DefaultReserveInterestRateStrategy is IReserveInterestRateStrategy { using WadRayMath for uint256; using SafeMath for uint256; /** * @dev this constant represents the utilization rate at which the pool aims to obtain most competitive borrow rates * expressed in ray **/ uint256 public constant OPTIMAL_UTILIZATION_RATE = 0.8 * 1e27; /** * @dev this constant represents the excess utilization rate above the optimal. It's always equal to * 1-optimal utilization rate. Added as a constant here for gas optimizations * expressed in ray **/ uint256 public constant EXCESS_UTILIZATION_RATE = 0.2 * 1e27; LendingPoolAddressesProvider public addressesProvider; //base variable borrow rate when Utilization rate = 0. Expressed in ray uint256 public baseVariableBorrowRate; //slope of the variable interest curve when utilization rate > 0 and <= OPTIMAL_UTILIZATION_RATE. Expressed in ray uint256 public variableRateSlope1; //slope of the variable interest curve when utilization rate > OPTIMAL_UTILIZATION_RATE. Expressed in ray uint256 public variableRateSlope2; //slope of the stable interest curve when utilization rate > 0 and <= OPTIMAL_UTILIZATION_RATE. Expressed in ray uint256 public stableRateSlope1; //slope of the stable interest curve when utilization rate > OPTIMAL_UTILIZATION_RATE. Expressed in ray uint256 public stableRateSlope2; address public reserve; constructor( address _reserve, LendingPoolAddressesProvider _provider, uint256 _baseVariableBorrowRate, uint256 _variableRateSlope1, uint256 _variableRateSlope2, uint256 _stableRateSlope1, uint256 _stableRateSlope2 ) public { addressesProvider = _provider; baseVariableBorrowRate = _baseVariableBorrowRate; variableRateSlope1 = _variableRateSlope1; variableRateSlope2 = _variableRateSlope2; stableRateSlope1 = _stableRateSlope1; stableRateSlope2 = _stableRateSlope2; reserve = _reserve; } /** @dev accessors */ function getBaseVariableBorrowRate() external view returns (uint256) { return baseVariableBorrowRate; } function getVariableRateSlope1() external view returns (uint256) { return variableRateSlope1; } function getVariableRateSlope2() external view returns (uint256) { return variableRateSlope2; } function getStableRateSlope1() external view returns (uint256) { return stableRateSlope1; } function getStableRateSlope2() external view returns (uint256) { return stableRateSlope2; } /** * @dev calculates the interest rates depending on the available liquidity and the total borrowed. * @param _reserve the address of the reserve * @param _availableLiquidity the liquidity available in the reserve * @param _totalBorrowsStable the total borrowed from the reserve a stable rate * @param _totalBorrowsVariable the total borrowed from the reserve at a variable rate * @param _averageStableBorrowRate the weighted average of all the stable rate borrows * @return the liquidity rate, stable borrow rate and variable borrow rate calculated from the input parameters **/ function calculateInterestRates( address _reserve, uint256 _availableLiquidity, uint256 _totalBorrowsStable, uint256 _totalBorrowsVariable, uint256 _averageStableBorrowRate ) external view returns ( uint256 currentLiquidityRate, uint256 currentStableBorrowRate, uint256 currentVariableBorrowRate ) { uint256 totalBorrows = _totalBorrowsStable.add(_totalBorrowsVariable); uint256 utilizationRate = (totalBorrows == 0 && _availableLiquidity == 0) ? 0 : totalBorrows.rayDiv(_availableLiquidity.add(totalBorrows)); currentStableBorrowRate = ILendingRateOracle(addressesProvider.getLendingRateOracle()) .getMarketBorrowRate(_reserve); if (utilizationRate > OPTIMAL_UTILIZATION_RATE) { uint256 excessUtilizationRateRatio = utilizationRate .sub(OPTIMAL_UTILIZATION_RATE) .rayDiv(EXCESS_UTILIZATION_RATE); currentStableBorrowRate = currentStableBorrowRate.add(stableRateSlope1).add( stableRateSlope2.rayMul(excessUtilizationRateRatio) ); currentVariableBorrowRate = baseVariableBorrowRate.add(variableRateSlope1).add( variableRateSlope2.rayMul(excessUtilizationRateRatio) ); } else { currentStableBorrowRate = currentStableBorrowRate.add( stableRateSlope1.rayMul( utilizationRate.rayDiv( OPTIMAL_UTILIZATION_RATE ) ) ); currentVariableBorrowRate = baseVariableBorrowRate.add( utilizationRate.rayDiv(OPTIMAL_UTILIZATION_RATE).rayMul(variableRateSlope1) ); } currentLiquidityRate = getOverallBorrowRateInternal( _totalBorrowsStable, _totalBorrowsVariable, currentVariableBorrowRate, _averageStableBorrowRate ) .rayMul(utilizationRate); } /** * @dev calculates the overall borrow rate as the weighted average between the total variable borrows and total stable borrows. * @param _totalBorrowsStable the total borrowed from the reserve a stable rate * @param _totalBorrowsVariable the total borrowed from the reserve at a variable rate * @param _currentVariableBorrowRate the current variable borrow rate * @param _currentAverageStableBorrowRate the weighted average of all the stable rate borrows * @return the weighted averaged borrow rate **/ function getOverallBorrowRateInternal( uint256 _totalBorrowsStable, uint256 _totalBorrowsVariable, uint256 _currentVariableBorrowRate, uint256 _currentAverageStableBorrowRate ) internal pure returns (uint256) { uint256 totalBorrows = _totalBorrowsStable.add(_totalBorrowsVariable); if (totalBorrows == 0) return 0; uint256 weightedVariableRate = _totalBorrowsVariable.wadToRay().rayMul( _currentVariableBorrowRate ); uint256 weightedStableRate = _totalBorrowsStable.wadToRay().rayMul( _currentAverageStableBorrowRate ); uint256 overallBorrowRate = weightedVariableRate.add(weightedStableRate).rayDiv( totalBorrows.wadToRay() ); return overallBorrowRate; } }
contract DefaultReserveInterestRateStrategy is IReserveInterestRateStrategy { using WadRayMath for uint256; using SafeMath for uint256; /** * @dev this constant represents the utilization rate at which the pool aims to obtain most competitive borrow rates * expressed in ray **/ uint256 public constant OPTIMAL_UTILIZATION_RATE = 0.8 * 1e27; /** * @dev this constant represents the excess utilization rate above the optimal. It's always equal to * 1-optimal utilization rate. Added as a constant here for gas optimizations * expressed in ray **/ uint256 public constant EXCESS_UTILIZATION_RATE = 0.2 * 1e27; LendingPoolAddressesProvider public addressesProvider; //base variable borrow rate when Utilization rate = 0. Expressed in ray uint256 public baseVariableBorrowRate; //slope of the variable interest curve when utilization rate > 0 and <= OPTIMAL_UTILIZATION_RATE. Expressed in ray uint256 public variableRateSlope1; //slope of the variable interest curve when utilization rate > OPTIMAL_UTILIZATION_RATE. Expressed in ray uint256 public variableRateSlope2; //slope of the stable interest curve when utilization rate > 0 and <= OPTIMAL_UTILIZATION_RATE. Expressed in ray uint256 public stableRateSlope1; //slope of the stable interest curve when utilization rate > OPTIMAL_UTILIZATION_RATE. Expressed in ray uint256 public stableRateSlope2; address public reserve; constructor( address _reserve, LendingPoolAddressesProvider _provider, uint256 _baseVariableBorrowRate, uint256 _variableRateSlope1, uint256 _variableRateSlope2, uint256 _stableRateSlope1, uint256 _stableRateSlope2 ) public { addressesProvider = _provider; baseVariableBorrowRate = _baseVariableBorrowRate; variableRateSlope1 = _variableRateSlope1; variableRateSlope2 = _variableRateSlope2; stableRateSlope1 = _stableRateSlope1; stableRateSlope2 = _stableRateSlope2; reserve = _reserve; } /** @dev accessors */ function getBaseVariableBorrowRate() external view returns (uint256) { return baseVariableBorrowRate; } function getVariableRateSlope1() external view returns (uint256) { return variableRateSlope1; } function getVariableRateSlope2() external view returns (uint256) { return variableRateSlope2; } function getStableRateSlope1() external view returns (uint256) { return stableRateSlope1; } function getStableRateSlope2() external view returns (uint256) { return stableRateSlope2; } /** * @dev calculates the interest rates depending on the available liquidity and the total borrowed. * @param _reserve the address of the reserve * @param _availableLiquidity the liquidity available in the reserve * @param _totalBorrowsStable the total borrowed from the reserve a stable rate * @param _totalBorrowsVariable the total borrowed from the reserve at a variable rate * @param _averageStableBorrowRate the weighted average of all the stable rate borrows * @return the liquidity rate, stable borrow rate and variable borrow rate calculated from the input parameters **/ function calculateInterestRates( address _reserve, uint256 _availableLiquidity, uint256 _totalBorrowsStable, uint256 _totalBorrowsVariable, uint256 _averageStableBorrowRate ) external view returns ( uint256 currentLiquidityRate, uint256 currentStableBorrowRate, uint256 currentVariableBorrowRate ) { uint256 totalBorrows = _totalBorrowsStable.add(_totalBorrowsVariable); uint256 utilizationRate = (totalBorrows == 0 && _availableLiquidity == 0) ? 0 : totalBorrows.rayDiv(_availableLiquidity.add(totalBorrows)); currentStableBorrowRate = ILendingRateOracle(addressesProvider.getLendingRateOracle()) .getMarketBorrowRate(_reserve); if (utilizationRate > OPTIMAL_UTILIZATION_RATE) { uint256 excessUtilizationRateRatio = utilizationRate .sub(OPTIMAL_UTILIZATION_RATE) .rayDiv(EXCESS_UTILIZATION_RATE); currentStableBorrowRate = currentStableBorrowRate.add(stableRateSlope1).add( stableRateSlope2.rayMul(excessUtilizationRateRatio) ); currentVariableBorrowRate = baseVariableBorrowRate.add(variableRateSlope1).add( variableRateSlope2.rayMul(excessUtilizationRateRatio) ); } else { currentStableBorrowRate = currentStableBorrowRate.add( stableRateSlope1.rayMul( utilizationRate.rayDiv( OPTIMAL_UTILIZATION_RATE ) ) ); currentVariableBorrowRate = baseVariableBorrowRate.add( utilizationRate.rayDiv(OPTIMAL_UTILIZATION_RATE).rayMul(variableRateSlope1) ); } currentLiquidityRate = getOverallBorrowRateInternal( _totalBorrowsStable, _totalBorrowsVariable, currentVariableBorrowRate, _averageStableBorrowRate ) .rayMul(utilizationRate); } /** * @dev calculates the overall borrow rate as the weighted average between the total variable borrows and total stable borrows. * @param _totalBorrowsStable the total borrowed from the reserve a stable rate * @param _totalBorrowsVariable the total borrowed from the reserve at a variable rate * @param _currentVariableBorrowRate the current variable borrow rate * @param _currentAverageStableBorrowRate the weighted average of all the stable rate borrows * @return the weighted averaged borrow rate **/ function getOverallBorrowRateInternal( uint256 _totalBorrowsStable, uint256 _totalBorrowsVariable, uint256 _currentVariableBorrowRate, uint256 _currentAverageStableBorrowRate ) internal pure returns (uint256) { uint256 totalBorrows = _totalBorrowsStable.add(_totalBorrowsVariable); if (totalBorrows == 0) return 0; uint256 weightedVariableRate = _totalBorrowsVariable.wadToRay().rayMul( _currentVariableBorrowRate ); uint256 weightedStableRate = _totalBorrowsStable.wadToRay().rayMul( _currentAverageStableBorrowRate ); uint256 overallBorrowRate = weightedVariableRate.add(weightedStableRate).rayDiv( totalBorrows.wadToRay() ); return overallBorrowRate; } }
31,054
43
// Transfers some tokens to an external address or a smart contractIERC20 `function transfer(address recipient, uint256 amount) external returns (bool)`Called by token owner (an address which has a positive token balance tracked by this smart contract) Throws on any error likeinsufficient token balance orincorrect `_to` address:zero address orself address orsmart contract which doesn't support ERC20_to an address to transfer tokens to, must be either an external address or a smart contract, compliant with the ERC20 standard _value amount of tokens to be transferred, must be greater than zeroreturn success true on success, throws otherwise /
function transfer(address _to, uint256 _value) external override returns (bool) { // just delegate call to `transferFrom`, // `FEATURE_TRANSFERS` is verified inside it return transferFrom(msg.sender, _to, _value); }
function transfer(address _to, uint256 _value) external override returns (bool) { // just delegate call to `transferFrom`, // `FEATURE_TRANSFERS` is verified inside it return transferFrom(msg.sender, _to, _value); }
1,709
9
// IPFS hidden Meta
function setHiddenUri(string memory _hiddenMetadataUri) external onlyOwner{ hiddenMetadataUri = _hiddenMetadataUri; }
function setHiddenUri(string memory _hiddenMetadataUri) external onlyOwner{ hiddenMetadataUri = _hiddenMetadataUri; }
15,483
205
// Callback for IUniswapV3PoolActionsmint/Any contract that calls IUniswapV3PoolActionsmint must implement this interface
interface IUniswapV3MintCallback { /// @notice Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint. /// @dev In the implementation you must pay the pool tokens owed for the minted liquidity. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// @param amount0Owed The amount of token0 due to the pool for the minted liquidity /// @param amount1Owed The amount of token1 due to the pool for the minted liquidity /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#mint call function uniswapV3MintCallback( uint256 amount0Owed, uint256 amount1Owed, bytes calldata data ) external; }
interface IUniswapV3MintCallback { /// @notice Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint. /// @dev In the implementation you must pay the pool tokens owed for the minted liquidity. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// @param amount0Owed The amount of token0 due to the pool for the minted liquidity /// @param amount1Owed The amount of token1 due to the pool for the minted liquidity /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#mint call function uniswapV3MintCallback( uint256 amount0Owed, uint256 amount1Owed, bytes calldata data ) external; }
6,042
261
// Set the price of summoning a hero with Eth.
function setEthPrice(uint256 _value) onlyOwner public
function setEthPrice(uint256 _value) onlyOwner public
9,408
5
// Add the collection to the global collections mapping
collections[uint256(collectionId)] = collection; no_of_collections++;
collections[uint256(collectionId)] = collection; no_of_collections++;
15,747
251
// stage number
uint8 internal stageIndex_;
uint8 internal stageIndex_;
29,589
69
// Deploys the `FeeManager` contract for a pair stablecoin/collateral/_poolManager `PoolManager` contract handling the collateral/The `_poolManager` address is used to grant the correct role. It does not need to be stored by the/ contract/There is no need to do a zero address check on the `_poolManager` as if the zero address is passed/ the function will revert when trying to fetch the `StableMaster`
constructor(IPoolManager _poolManager) { stableMaster = IStableMaster(_poolManager.stableMaster()); // Once a `FeeManager` contract has been initialized with a `PoolManager` contract, this // reference cannot be modified _setupRole(POOLMANAGER_ROLE, address(_poolManager)); _setRoleAdmin(POOLMANAGER_ROLE, POOLMANAGER_ROLE); _setRoleAdmin(GUARDIAN_ROLE, POOLMANAGER_ROLE); }
constructor(IPoolManager _poolManager) { stableMaster = IStableMaster(_poolManager.stableMaster()); // Once a `FeeManager` contract has been initialized with a `PoolManager` contract, this // reference cannot be modified _setupRole(POOLMANAGER_ROLE, address(_poolManager)); _setRoleAdmin(POOLMANAGER_ROLE, POOLMANAGER_ROLE); _setRoleAdmin(GUARDIAN_ROLE, POOLMANAGER_ROLE); }
53,264
7
// set the owner and data for position operator is msg.sender
deposits[tokenId] = Deposit({ owner: owner, liquidity: liquidity, token0: token0, token1: token1 });
deposits[tokenId] = Deposit({ owner: owner, liquidity: liquidity, token0: token0, token1: token1 });
22,953
8
// Function that tries to update switch executors addressThis function is allowed only for switch owner_executor New executor address No return, reverts on error /
function updateSwitchExecutor(address _executor) external payable;
function updateSwitchExecutor(address _executor) external payable;
18,123
22
// Available amount for an account account uint256 index uint256 /
function available(address account, uint256 index) public view returns (uint256)
function available(address account, uint256 index) public view returns (uint256)
11,521
21
// feet
rarities[6] = [ 243, 189, 133, 133, 57, 95, 152, 135, 133,
rarities[6] = [ 243, 189, 133, 133, 57, 95, 152, 135, 133,
10,746
24
// address of token0
address token0,
address token0,
10,230
64
// Change the maximum number of accepted RC subscribers. New value shall be at least equal to the currentnumber of subscribers. _maxSubscribers The maximum number of subscribers /
function setMaxSubscribers(uint256 _maxSubscribers) external onlyOwner beforeEnd whenReserving { require(_maxSubscribers > 0 && _maxSubscribers >= subscribers.length, "invalid _maxSubscribers"); maxSubscribers = _maxSubscribers; emit LogMaxSubscribersChanged(maxSubscribers); }
function setMaxSubscribers(uint256 _maxSubscribers) external onlyOwner beforeEnd whenReserving { require(_maxSubscribers > 0 && _maxSubscribers >= subscribers.length, "invalid _maxSubscribers"); maxSubscribers = _maxSubscribers; emit LogMaxSubscribersChanged(maxSubscribers); }
33,896
18
// Change fee
depositFee = _depositFee; withdrawFee = _withdrawFee; nftFee = _nftFee;
depositFee = _depositFee; withdrawFee = _withdrawFee; nftFee = _nftFee;
21,167
55
// Withdraw staked tokens + reward from vault.
function unstake(address vault) external { Stake memory s = staking[vault][msg.sender]; Setting memory set = settings[vault]; uint256 amount; uint256 balance = balances[vault][msg.sender]; if (set.period == 0) { require(balance != 0, "No reimbursement"); amount = balance; } else { require(s.amount != 0, "No stake"); uint256 interval = block.timestamp - s.startTime; amount = s.amount * 100 * interval / (set.period * set.reimbursementRatio); } delete staking[vault][msg.sender]; // remove staking record. if (amount > balance) amount = balance; balance -= amount; balances[vault][msg.sender] = balance; if (balance == 0) { vaults[msg.sender].remove(vault); // remove vault from vaults list where user has reimbursement tokens } if (set.isMintable) { totalReserved[vault] -= s.amount; TokenVault(vault).transferToken(msg.sender, s.amount); // withdraw staked amount IBEP20(set.token).mint(msg.sender, amount); // mint reimbursement token amount += s.amount; // total amount: rewards + staking } else { amount += s.amount; // total amount: rewards + staking totalReserved[vault] -= amount; TokenVault(vault).transferToken(msg.sender, amount); // withdraw staked amount + rewards } emit UnstakeToken(vault, msg.sender, block.timestamp, amount); }
function unstake(address vault) external { Stake memory s = staking[vault][msg.sender]; Setting memory set = settings[vault]; uint256 amount; uint256 balance = balances[vault][msg.sender]; if (set.period == 0) { require(balance != 0, "No reimbursement"); amount = balance; } else { require(s.amount != 0, "No stake"); uint256 interval = block.timestamp - s.startTime; amount = s.amount * 100 * interval / (set.period * set.reimbursementRatio); } delete staking[vault][msg.sender]; // remove staking record. if (amount > balance) amount = balance; balance -= amount; balances[vault][msg.sender] = balance; if (balance == 0) { vaults[msg.sender].remove(vault); // remove vault from vaults list where user has reimbursement tokens } if (set.isMintable) { totalReserved[vault] -= s.amount; TokenVault(vault).transferToken(msg.sender, s.amount); // withdraw staked amount IBEP20(set.token).mint(msg.sender, amount); // mint reimbursement token amount += s.amount; // total amount: rewards + staking } else { amount += s.amount; // total amount: rewards + staking totalReserved[vault] -= amount; TokenVault(vault).transferToken(msg.sender, amount); // withdraw staked amount + rewards } emit UnstakeToken(vault, msg.sender, block.timestamp, amount); }
50,546
4
// Getting the campaign we want to donate to
Campaign storage campaign = campaigns[_id]; campaign.donators.push(msg.sender); campaign.donations.push(amount);
Campaign storage campaign = campaigns[_id]; campaign.donators.push(msg.sender); campaign.donations.push(amount);
13,878
87
// Deposit LP tokens to MasterChef for pizza allocation.
function deposit(uint256 _pid, uint256 _amount) public checkStart { require(isUserExists(msg.sender), "user don't exists"); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid,msg.sender); if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.pid = _pid; pool.totalPool = pool.totalPool.add(_amount); address _referrer = users[msg.sender].referrer; for(uint256 i = 0;i<2;i++){ if(_referrer!= address(0) && isUserExists(_referrer)){ users[_referrer].referAmount[i] = _amount.add(users[_referrer].referAmount[i]); _referrer = users[_referrer].referrer; }else break; } } emit Deposit(msg.sender, _pid, _amount); }
function deposit(uint256 _pid, uint256 _amount) public checkStart { require(isUserExists(msg.sender), "user don't exists"); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid,msg.sender); if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.pid = _pid; pool.totalPool = pool.totalPool.add(_amount); address _referrer = users[msg.sender].referrer; for(uint256 i = 0;i<2;i++){ if(_referrer!= address(0) && isUserExists(_referrer)){ users[_referrer].referAmount[i] = _amount.add(users[_referrer].referAmount[i]); _referrer = users[_referrer].referrer; }else break; } } emit Deposit(msg.sender, _pid, _amount); }
27,090
36
// This contract can be paid transaction fees, e.g., from OpenSea/The contractURI specifies itself as the recipient of transaction fees
receive() external payable { } }
receive() external payable { } }
69,645
25
// Get the current Jar balance
uint balance = this.balance;
uint balance = this.balance;
16,972
1
// Handle the receipt of KIP-7 token The KIP-7 smart contract calls this function on the recipient after a `safeTransfer`. This function MAY throw to revert and reject the transfer. Return of other than the magic value MUST result in the transaction being reverted. Note: the contract address is always the message sender. _operator The address which called `safeTransferFrom` function _from The address which previously owned the token _amount The token amount which is being transferred. _data Additional data with no specified formatreturn `bytes4(keccak256("onKIP7Received(address,address,uint256,bytes)"))` unless throwing /
function onKIP7Received(address _operator, address _from, uint256 _amount, bytes memory _data) public returns (bytes4);
function onKIP7Received(address _operator, address _from, uint256 _amount, bytes memory _data) public returns (bytes4);
33,393
153
// Maps a value of `string` type to a given key.Only the owner can execute this function. /
function setString(bytes32 _key, string calldata _value) external onlyCurrentOwner
function setString(bytes32 _key, string calldata _value) external onlyCurrentOwner
30,074
111
// Provide a signal to the keeper that `tend()` should be called. The keeper will provide the estimated gas cost that they would pay to call `tend()`, and this function should use that estimate to make a determination if calling it is "worth it" for the keeper. This is not the only consideration into issuing this trigger, for example if the position would be negatively affected if `tend()` is not called shortly, then this can return `true` even if the keeper might be "at a loss" (keepers are always reimbursed by Yearn). `callCost` must be priced in terms of `want`.This call
function tendTrigger(uint256 callCost) public virtual view returns (bool) { // We usually don't need tend, but if there are positions that need // active maintainence, overriding this function is how you would // signal for that. return false; }
function tendTrigger(uint256 callCost) public virtual view returns (bool) { // We usually don't need tend, but if there are positions that need // active maintainence, overriding this function is how you would // signal for that. return false; }
2,260
0
// Adds priceFeed for a given token. /
function _addOracle( address _tokenAddress, IPriceFeed _priceFeedAddress, address[] memory _underlyingFeedTokens ) internal
function _addOracle( address _tokenAddress, IPriceFeed _priceFeedAddress, address[] memory _underlyingFeedTokens ) internal
37,673
10
// Status of the official sale
bool private saleIsActive = false;
bool private saleIsActive = false;
76,139
198
// Hook that is called after any token transfer. This includes minting and burning. If {ERC721Consecutive} isused, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1. Calling conditions: - When `from` and `to` are both non-zero, ``from``'s tokens were transferred to `to`.- When `from` is zero, the tokens were minted for `to`.- When `to` is zero, ``from``'s tokens were burned.- `from` and `to` are never both zero.- `batchSize` is non-zero. To learn more about hooks, head to xref:ROOT:extending-contracts.adocusing-hooks[Using Hooks]. /
function _afterTokenTransfer( address from, address to, uint256 firstTokenId, uint256 batchSize
function _afterTokenTransfer( address from, address to, uint256 firstTokenId, uint256 batchSize
313
7
// Withdraw unexpected tokens sent to the Simp Vault /
function inCaseTokensGetStuck(address _token) external onlyOwner { simpVault.inCaseTokensGetStuck(_token); uint256 amount = IERC20(_token).balanceOf(address(this)); IERC20(_token).safeTransfer(msg.sender, amount); }
function inCaseTokensGetStuck(address _token) external onlyOwner { simpVault.inCaseTokensGetStuck(_token); uint256 amount = IERC20(_token).balanceOf(address(this)); IERC20(_token).safeTransfer(msg.sender, amount); }
33,142
14
// See `IERC777.isOperatorFor`. /
function isOperatorFor( address operator, address tokenHolder ) public view returns (bool)
function isOperatorFor( address operator, address tokenHolder ) public view returns (bool)
7,922
28
// callback that provider will call after Dispatch.query() call/id request id/response bytes32 array
function callback(uint256 id, bytes32[] response) external;
function callback(uint256 id, bytes32[] response) external;
4,917
32
// allow owner to finalize and withdraw leftoverTokens
function finalize() public onlyOwner { require(!isFinalized); emit Finalized(); uint256 leftoverTokens = token.balanceOf(address(this)); token.transfer(address(this),leftoverTokens); isFinalized = true; }
function finalize() public onlyOwner { require(!isFinalized); emit Finalized(); uint256 leftoverTokens = token.balanceOf(address(this)); token.transfer(address(this),leftoverTokens); isFinalized = true; }
25,817
12
// Integer division of two numbers truncating the quotient, reverts on division by zero./
function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath div 0"); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; }
function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath div 0"); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; }
5,831
0
// @custom:oz-upgrades-unsafe-allow constructor
constructor() { _disableInitializers(); }
constructor() { _disableInitializers(); }
23,529
46
// result ptr, jump over length
let resultPtr := add(result, 32)
let resultPtr := add(result, 32)
2,218
3
// called by the owner on end of emergency, returns to normal state
function unhalt() external onlyOwner onlyInEmergency { halted = false; }
function unhalt() external onlyOwner onlyInEmergency { halted = false; }
17,939
157
// poolShares = totalSupplytokenWeight / totalWeight
uint poolShares = BalancerSafeMath.bdiv(BalancerSafeMath.bmul(totalSupply, bPool.getDenormalizedWeight(token)), bPool.getTotalDenormalizedWeight());
uint poolShares = BalancerSafeMath.bdiv(BalancerSafeMath.bmul(totalSupply, bPool.getDenormalizedWeight(token)), bPool.getTotalDenormalizedWeight());
6,663
298
// batch airdrop
function airdrop_batch(address[] calldata _recipients, uint[] calldata _mintAmounts) external onlyOwner { for (uint i = 0; i < _recipients.length; i++) { require(totalSupply() + _mintAmounts[i] <= maxSupply, "Too many"); _safeMint(_recipients[i], _mintAmounts[i]); } }
function airdrop_batch(address[] calldata _recipients, uint[] calldata _mintAmounts) external onlyOwner { for (uint i = 0; i < _recipients.length; i++) { require(totalSupply() + _mintAmounts[i] <= maxSupply, "Too many"); _safeMint(_recipients[i], _mintAmounts[i]); } }
38,524
24
// amount sent cannot exceed balance
require(balances[msg.sender] >= _amount);
require(balances[msg.sender] >= _amount);
2,737
145
// Return data is optional
require( abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed" );
require( abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed" );
4,517
33
// @inheritdoc AggregatorV3Interface
function getRoundData(uint80 _roundId) public view override checkAccess returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt,
function getRoundData(uint80 _roundId) public view override checkAccess returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt,
38,470
24
// 時間超過時,重設每天的限制
if (today() > m_lastDay) { DailySpent = 0; m_lastDay = today(); }
if (today() > m_lastDay) { DailySpent = 0; m_lastDay = today(); }
25,488
0
// Intermediary token to new LP token mapping./Used to prevent subsequent calls to masterchef's migrate function with the same PID.
mapping(address => address) public migrated; IBentoBoxMinimal public immutable bento; IMasterDeployer public immutable masterDeployer; IPoolFactory public immutable constantProductPoolFactory; address public immutable masterChef; constructor( IBentoBoxMinimal _bento, IMasterDeployer _masterDeployer,
mapping(address => address) public migrated; IBentoBoxMinimal public immutable bento; IMasterDeployer public immutable masterDeployer; IPoolFactory public immutable constantProductPoolFactory; address public immutable masterChef; constructor( IBentoBoxMinimal _bento, IMasterDeployer _masterDeployer,
38,456
122
// Returns true if the given role id is assigned to a member./_memberAddress Address of member/_roleId Checks member's authenticity with the roleId./ i.e. Returns true if this roleId is assigned to member
function checkRole(address _memberAddress, uint _roleId) public view returns(bool);
function checkRole(address _memberAddress, uint _roleId) public view returns(bool);
33,269
21
// A mapping from owner address to count of tokens that address owns.Used internally inside balanceOf() to resolve ownership count.
mapping(address => uint) private ownershipTokenCount;
mapping(address => uint) private ownershipTokenCount;
25,241
25
// check price
function test_price() view public { _contract.PRICE() == 0.07 ether; }
function test_price() view public { _contract.PRICE() == 0.07 ether; }
18,012
190
// Logs a change of senior rate model contract/oldModel Address of the old model/newModel Address of the new model
event SetSeniorRateModel(address oldModel, address newModel);
event SetSeniorRateModel(address oldModel, address newModel);
45,005
157
// Set the public drop data.
_publicDrops[msg.sender] = publicDrop;
_publicDrops[msg.sender] = publicDrop;
30,261
161
// Function which will be used to get depositGas
function getdepositGas() public view onlyOwner returns(uint gas)
function getdepositGas() public view onlyOwner returns(uint gas)
18,562
20
// Mint them a DAO Voting Token
DAOToken.safeMint(msg.sender);
DAOToken.safeMint(msg.sender);
8,477
0
// It is not actually an interface regarding solidity because interfaces can only have external functions
abstract contract DepositLockerInterface { function slash(address _depositorToBeSlashed) public virtual; }
abstract contract DepositLockerInterface { function slash(address _depositorToBeSlashed) public virtual; }
30,917
4
// A mix-in contract to decode different signed KYC payloads.This should be a library, but for the complexity and toolchain fragility risks involving of linking library inside library, we currently use this as a helper method mix-in. /
contract KYCPayloadDeserializer { using BytesDeserializer for bytes; // @notice this struct describes what kind of data we include in the payload, we do not use this directly // The bytes payload set on the server side // total 56 bytes struct KYCPayload { /** Customer whitelisted address where the deposit can come from */ address whitelistedAddress; // 20 bytes /** Customer id, UUID v4 */ uint128 customerId; // 16 bytes /** * Min amount this customer needs to invest in ETH. Set zero if no minimum. Expressed as parts of 10000. 1 ETH = 10000. * @notice Decided to use 32-bit words to make the copy-pasted Data field for the ICO transaction less lenghty. */ uint32 minETH; // 4 bytes /** Max amount this customer can to invest in ETH. Set zero if no maximum. Expressed as parts of 10000. 1 ETH = 10000. */ uint32 maxETH; // 4 bytes /** * Information about the price promised for this participant. It can be pricing tier id or directly one token price in weis. * @notice This is a later addition and not supported in all scenarios yet. */ uint256 pricingInfo; } /** * Same as above, but with pricing information included in the payload as the last integer. * * @notice In a long run, deprecate the legacy methods above and only use this payload. */ function getKYCPayload(bytes dataframe) public constant returns(address whitelistedAddress, uint128 customerId, uint32 minEth, uint32 maxEth, uint256 pricingInfo) { address _whitelistedAddress = dataframe.sliceAddress(0); uint128 _customerId = uint128(dataframe.slice16(20)); uint32 _minETH = uint32(dataframe.slice4(36)); uint32 _maxETH = uint32(dataframe.slice4(40)); uint256 _pricingInfo = uint256(dataframe.slice32(44)); return (_whitelistedAddress, _customerId, _minETH, _maxETH, _pricingInfo); } }
contract KYCPayloadDeserializer { using BytesDeserializer for bytes; // @notice this struct describes what kind of data we include in the payload, we do not use this directly // The bytes payload set on the server side // total 56 bytes struct KYCPayload { /** Customer whitelisted address where the deposit can come from */ address whitelistedAddress; // 20 bytes /** Customer id, UUID v4 */ uint128 customerId; // 16 bytes /** * Min amount this customer needs to invest in ETH. Set zero if no minimum. Expressed as parts of 10000. 1 ETH = 10000. * @notice Decided to use 32-bit words to make the copy-pasted Data field for the ICO transaction less lenghty. */ uint32 minETH; // 4 bytes /** Max amount this customer can to invest in ETH. Set zero if no maximum. Expressed as parts of 10000. 1 ETH = 10000. */ uint32 maxETH; // 4 bytes /** * Information about the price promised for this participant. It can be pricing tier id or directly one token price in weis. * @notice This is a later addition and not supported in all scenarios yet. */ uint256 pricingInfo; } /** * Same as above, but with pricing information included in the payload as the last integer. * * @notice In a long run, deprecate the legacy methods above and only use this payload. */ function getKYCPayload(bytes dataframe) public constant returns(address whitelistedAddress, uint128 customerId, uint32 minEth, uint32 maxEth, uint256 pricingInfo) { address _whitelistedAddress = dataframe.sliceAddress(0); uint128 _customerId = uint128(dataframe.slice16(20)); uint32 _minETH = uint32(dataframe.slice4(36)); uint32 _maxETH = uint32(dataframe.slice4(40)); uint256 _pricingInfo = uint256(dataframe.slice32(44)); return (_whitelistedAddress, _customerId, _minETH, _maxETH, _pricingInfo); } }
50,083
3
// Converts an `address` into `address payable`. Note that this issimply a type cast: the actual underlying value is not changed. _Available since v2.4.0._ /
function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); }
function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); }
2,907
19
// Ensures execution completed successfully, and reverts the created storage buffer back to the sender.
function commit() conditions(validState, none) internal pure { // Check value of storage buffer pointer - should be at least 0x180 bytes32 ptr = buffPtr(); require(ptr >= 0x180, "Invalid buffer pointer"); assembly { // Get the size of the buffer let size := mload(add(0x20, ptr)) mstore(ptr, 0x20) // Place dynamic data offset before buffer // Revert to storage revert(ptr, add(0x40, size)) } }
function commit() conditions(validState, none) internal pure { // Check value of storage buffer pointer - should be at least 0x180 bytes32 ptr = buffPtr(); require(ptr >= 0x180, "Invalid buffer pointer"); assembly { // Get the size of the buffer let size := mload(add(0x20, ptr)) mstore(ptr, 0x20) // Place dynamic data offset before buffer // Revert to storage revert(ptr, add(0x40, size)) } }
28,136
152
// product status enumerations
uint256 public constant PRODUCTSTATUS_ENABLED = 1; uint256 public constant PRODUCTSTATUS_DISABLED = 2;
uint256 public constant PRODUCTSTATUS_ENABLED = 1; uint256 public constant PRODUCTSTATUS_DISABLED = 2;
65,450
34
// Initiate flash borrow.
function simpleFlashSwap(address _tokenBorrow, uint _amount, address _tokenPay, address _balancerPool, uint _maxPrice) private { permissionedPairAddress = UniswapV2Factory.getPair(_tokenBorrow, _tokenPay); address pairAddress = permissionedPairAddress; require(pairAddress != address(0), "Requested pair is not available."); address token0 = IUniswapV2Pair(pairAddress).token0(); address token1 = IUniswapV2Pair(pairAddress).token1(); uint amount0Out = _tokenBorrow == token0 ? _amount : 0; uint amount1Out = _tokenBorrow == token1 ? _amount : 0; bytes memory data = abi.encode( _tokenBorrow, _amount, _tokenPay, _balancerPool, _maxPrice ); IUniswapV2Pair(pairAddress).swap(amount0Out, amount1Out, address(this), data); }
function simpleFlashSwap(address _tokenBorrow, uint _amount, address _tokenPay, address _balancerPool, uint _maxPrice) private { permissionedPairAddress = UniswapV2Factory.getPair(_tokenBorrow, _tokenPay); address pairAddress = permissionedPairAddress; require(pairAddress != address(0), "Requested pair is not available."); address token0 = IUniswapV2Pair(pairAddress).token0(); address token1 = IUniswapV2Pair(pairAddress).token1(); uint amount0Out = _tokenBorrow == token0 ? _amount : 0; uint amount1Out = _tokenBorrow == token1 ? _amount : 0; bytes memory data = abi.encode( _tokenBorrow, _amount, _tokenPay, _balancerPool, _maxPrice ); IUniswapV2Pair(pairAddress).swap(amount0Out, amount1Out, address(this), data); }
5,966
4
// Multiply two uint256 values, throw in case of overflow.a first value to multiply b second value to multiplyreturn ab /
function mul(uint256 a, uint256 b) internal returns (uint256) { if (a == 0 || b == 0) return 0; uint256 c = a * b; assert(c / a == b); return c; }
function mul(uint256 a, uint256 b) internal returns (uint256) { if (a == 0 || b == 0) return 0; uint256 c = a * b; assert(c / a == b); return c; }
50,292
24
// Compute `2 ^ exponent · (1 + fraction / 1024)`
int32 result = 0; if (exponent >= 0) { result = int32(((1 << uint256(exponent)) * 10000 * (uint256(significand) | 0x400)) >> 10); } else {
int32 result = 0; if (exponent >= 0) { result = int32(((1 << uint256(exponent)) * 10000 * (uint256(significand) | 0x400)) >> 10); } else {
6,665
278
// Note: function selector is the same for each dToken so just use dDai's.
_DDAI.redeemUnderlying.selector, balance ));
_DDAI.redeemUnderlying.selector, balance ));
9,842
2
// Gets the assetClosed indicator/
function getAssetClosed() external view returns (bool);
function getAssetClosed() external view returns (bool);
42,647
38
// Accommodation Coin STARTS HERE /
contract AccommodationCoin is owned, TokenERC20 { //Modify these variables uint256 _initialSupply=100000000; string _tokenName="Accommodation Coin"; string _tokenSymbol="ACC"; mapping (address => bool) public frozenAccount; /* This generates a public event on the blockchain that will notify clients */ event FrozenFunds(address target, bool frozen); /* Initializes contract with initial supply tokens to the creator of the contract */ function AccommodationCoin( ) TokenERC20(_initialSupply, _tokenName, _tokenSymbol) public {} /* Internal transfer, only can be called by this contract. */ function _transfer(address _from, address _to, uint _value) internal { require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead require(!frozenAccount[_from]); // Check if sender is frozen require(!frozenAccount[_to]); // Check if recipient is frozen balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient emit Transfer(_from, _to, _value); } /// function to create more coins and send it to `target` /// @param target Address to receive the tokens /// @param mintedAmount the amount of tokens it will receive function mintToken(address target, uint256 mintedAmount) onlyOwner public { balanceOf[target] = balanceOf[target].add(mintedAmount); totalSupply = totalSupply.add(mintedAmount); emit Transfer(0, this, mintedAmount); emit Transfer(this, target, mintedAmount); } function freezeAccount(address target, bool freeze) onlyOwner public { frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } }
contract AccommodationCoin is owned, TokenERC20 { //Modify these variables uint256 _initialSupply=100000000; string _tokenName="Accommodation Coin"; string _tokenSymbol="ACC"; mapping (address => bool) public frozenAccount; /* This generates a public event on the blockchain that will notify clients */ event FrozenFunds(address target, bool frozen); /* Initializes contract with initial supply tokens to the creator of the contract */ function AccommodationCoin( ) TokenERC20(_initialSupply, _tokenName, _tokenSymbol) public {} /* Internal transfer, only can be called by this contract. */ function _transfer(address _from, address _to, uint _value) internal { require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead require(!frozenAccount[_from]); // Check if sender is frozen require(!frozenAccount[_to]); // Check if recipient is frozen balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient emit Transfer(_from, _to, _value); } /// function to create more coins and send it to `target` /// @param target Address to receive the tokens /// @param mintedAmount the amount of tokens it will receive function mintToken(address target, uint256 mintedAmount) onlyOwner public { balanceOf[target] = balanceOf[target].add(mintedAmount); totalSupply = totalSupply.add(mintedAmount); emit Transfer(0, this, mintedAmount); emit Transfer(this, target, mintedAmount); } function freezeAccount(address target, bool freeze) onlyOwner public { frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } }
75,241
229
// issueId => trickyNumber => buyAmountSum
mapping (uint256 => mapping(uint64 => uint256)) public userBuyAmountSum;
mapping (uint256 => mapping(uint64 => uint256)) public userBuyAmountSum;
13,265
32
// false if our cache is invalid or if the resolver doesn't have the required address
if (resolver.getAddress(name) != addressCache[name] || addressCache[name] == address(0)) { return false; }
if (resolver.getAddress(name) != addressCache[name] || addressCache[name] == address(0)) { return false; }
30,323
3
// check If Member Already Exist /
function checkIfMemberAlreadyExist(address group_addr) external returns(bool);
function checkIfMemberAlreadyExist(address group_addr) external returns(bool);
11,563
171
// set the new leader bool to true
_eventData_.compressedData = _eventData_.compressedData + 100;
_eventData_.compressedData = _eventData_.compressedData + 100;
9,652
446
// Decreases the operator share for the given pool (i.e. increases pool rewards for members)./poolId Unique Id of pool./newOperatorShare The newly decreased percentage of any rewards owned by the operator.
function decreaseStakingPoolOperatorShare(bytes32 poolId, uint32 newOperatorShare) external;
function decreaseStakingPoolOperatorShare(bytes32 poolId, uint32 newOperatorShare) external;
12,359
80
// See `IERC777.operatorSend`. Emits `Sent` and `Transfer` events. /
function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external
function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external
26,173
13
// Moves `amount` tokens from the caller's account to `recipient`. Returns a boolean value indicating whether the operation succeeded.
* Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function decimals() external view returns (uint8); /** * Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
* Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function decimals() external view returns (uint8); /** * Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
42,030