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
14
// Calculate and mint the amount of xDvf the Dvf is worth. The ratio will change overtime, as xDvf is burned/minted and Dvf deposited + gained from fees / withdrawn.
else { uint256 what = _amount.mul(totalShares).div(totalDvf); _mint(msg.sender, what); }
else { uint256 what = _amount.mul(totalShares).div(totalDvf); _mint(msg.sender, what); }
13,224
745
// Triggers a transfer to owner in case of emergency /
function rescueEther() public onlyOwner { uint256 currentBalance = address(this).balance; (bool sent, ) = address(msg.sender).call{value: currentBalance}(''); require(sent,"Error while transfering the eth"); }
function rescueEther() public onlyOwner { uint256 currentBalance = address(this).balance; (bool sent, ) = address(msg.sender).call{value: currentBalance}(''); require(sent,"Error while transfering the eth"); }
77,101
103
// _player wallet of the player/ return Claims data of the player on that raffle
function getClaimData( uint256 _raffleId, address _player
function getClaimData( uint256 _raffleId, address _player
39,303
6
// return unburned lp tokens to from
STE_CRV_ADDR.withdrawTokens(_params.from, _params.maxBurnAmount.sub(burnedLp)); logData = abi.encode(_params.amounts[0], _params.amounts[1], burnedLp); if (_params.returnValue == ReturnValue.WETH) return (_params.amounts[0], logData); if (_params.returnValue == ReturnValue.STETH) return (_params.amounts[1], logData); return (burnedLp, logData);
STE_CRV_ADDR.withdrawTokens(_params.from, _params.maxBurnAmount.sub(burnedLp)); logData = abi.encode(_params.amounts[0], _params.amounts[1], burnedLp); if (_params.returnValue == ReturnValue.WETH) return (_params.amounts[0], logData); if (_params.returnValue == ReturnValue.STETH) return (_params.amounts[1], logData); return (burnedLp, logData);
49,607
256
// modifier for valid nonce with signature-based call
modifier withValidNonceAndDeadline(uint256 nonce, uint256 deadline) { require(block.timestamp <= deadline, "Deadline time passed"); require(!usedNonces[nonce], "nonce used"); usedNonces[nonce] = true; _; }
modifier withValidNonceAndDeadline(uint256 nonce, uint256 deadline) { require(block.timestamp <= deadline, "Deadline time passed"); require(!usedNonces[nonce], "nonce used"); usedNonces[nonce] = true; _; }
53,588
154
// Deposit LP tokens to MasterChef for SHEESHA allocation.
function deposit(uint256 _pid, uint256 _amount) public { _deposit(msg.sender, _pid, _amount); }
function deposit(uint256 _pid, uint256 _amount) public { _deposit(msg.sender, _pid, _amount); }
60,308
186
// Maps messageHash to the Message object. // Maps blockHeight to storageRoot. // Private Variables //Maps address to message hash. Once the inbox process is started the correspondingmessage hash is stored against the address starting process.This is used to restrict simultaneous/multiple processfor a particular address. This is also used to determine thenonce of the particular address. Refer getNonce for the details. /
mapping(address => bytes32) private inboxActiveProcess;
mapping(address => bytes32) private inboxActiveProcess;
28,586
6
// 数组赋值和结构体赋值有问题先把元素准备好,然后初始化结构体
address[] memory sharingPeersAddressCollection = new address[](2); sharingPeersAddressCollection[0] = 0xCDce1eaE7080f2450ea4f8637DA5ce21f31718aC; //chunmiao account, act as doctor sharingPeersAddressCollection[1] = 0x736b60dFc85B7063c01ECf912E00cb83678D386e; //lucy account, act as patient
address[] memory sharingPeersAddressCollection = new address[](2); sharingPeersAddressCollection[0] = 0xCDce1eaE7080f2450ea4f8637DA5ce21f31718aC; //chunmiao account, act as doctor sharingPeersAddressCollection[1] = 0x736b60dFc85B7063c01ECf912E00cb83678D386e; //lucy account, act as patient
40,852
29
// check claim entitlement of any wallet
function checkClaimEntitlementofWallet(address _address) public view returns(uint) { for (uint i = 0; i < claimants.length; i++) { if(_address == claimants[i].claimantAddress) { require(claimants[i].claimantHasClaimed == false); return claimants[i].claimantAmount; } else return 0; } }
function checkClaimEntitlementofWallet(address _address) public view returns(uint) { for (uint i = 0; i < claimants.length; i++) { if(_address == claimants[i].claimantAddress) { require(claimants[i].claimantHasClaimed == false); return claimants[i].claimantAmount; } else return 0; } }
44,711
57
// get list of vaults initialized through this factory
function vaults() external view returns (address[] memory) { return _vaults; }
function vaults() external view returns (address[] memory) { return _vaults; }
16,573
35
// Transfer tokens from one address to another_from address The address which you want to send tokens from_to address The address which you want to transfer to_value uint256 the amount of tokens to be transferred/
function transferFrom(address _from, address _to, uint256 _value) valid_short(3) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; }
function transferFrom(address _from, address _to, uint256 _value) valid_short(3) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; }
49,816
137
// The block number when reward distribution starts.
uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( IERC20 _rewardToken, address payable _devaddr, address _feeAddress,
uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( IERC20 _rewardToken, address payable _devaddr, address _feeAddress,
39,504
269
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(75)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
_prize = ((airDropPot_).mul(75)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
53,997
61
// Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend)./
function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; }
function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; }
1,661
119
// See {IERC777-granularity}. This implementation always returns `1`. /
function granularity() public view virtual override returns (uint256) { return 1; }
function granularity() public view virtual override returns (uint256) { return 1; }
13,753
171
// Helper function for depositing into `bentoBox`.
function _bentoDeposit( bytes memory data, uint256 value, uint256 value1, uint256 value2
function _bentoDeposit( bytes memory data, uint256 value, uint256 value1, uint256 value2
41,185
36
// Withdraw locked tokens /
function withdrawToken() public { // require(vaultUnlocked); uint256 interestAmount = (interestRate.mul(lockedBalances[msg.sender]).div(36500)).mul(vaultLockDays); uint256 withdrawAmount = (lockedBalances[msg.sender]).add(interestAmount); require(withdrawAmount > 0); lockedBalances[msg.sender] = 0; token.safeTransfer(msg.sender, withdrawAmount); emit TokenWithdrawal(msg.sender, withdrawAmount); }
function withdrawToken() public { // require(vaultUnlocked); uint256 interestAmount = (interestRate.mul(lockedBalances[msg.sender]).div(36500)).mul(vaultLockDays); uint256 withdrawAmount = (lockedBalances[msg.sender]).add(interestAmount); require(withdrawAmount > 0); lockedBalances[msg.sender] = 0; token.safeTransfer(msg.sender, withdrawAmount); emit TokenWithdrawal(msg.sender, withdrawAmount); }
30,975
27
// Offer ERC-20 tokens to the Shrine and distribute them to Champions proportional/ to their shares in the Shrine. Callable by anyone./token The ERC-20 token being offered to the Shrine/amount The amount of tokens to offer
function offer(ERC20 token, uint256 amount) external { // ------------------------------------------------------------------- // State updates // ------------------------------------------------------------------- // distribute tokens to Champions offeredTokens[currentLedgerVersion][token] += amount; // ------------------------------------------------------------------- // Effects // ------------------------------------------------------------------- // transfer tokens from sender token.safeTransferFrom(msg.sender, address(this), amount); emit Offer(msg.sender, token, amount); }
function offer(ERC20 token, uint256 amount) external { // ------------------------------------------------------------------- // State updates // ------------------------------------------------------------------- // distribute tokens to Champions offeredTokens[currentLedgerVersion][token] += amount; // ------------------------------------------------------------------- // Effects // ------------------------------------------------------------------- // transfer tokens from sender token.safeTransferFrom(msg.sender, address(this), amount); emit Offer(msg.sender, token, amount); }
22,812
8
// called by the owner to add a new Oracle and update the roundrelated parameters _oracle is the address of the new Oracle being added _minAnswers is the new minimum answer count for each round _maxAnswers is the new maximum answer count for each round _restartDelay is the number of rounds an Oracle has to wait beforethey can initiate a round /
function addOracle( address _oracle, uint32 _minAnswers, uint32 _maxAnswers, uint32 _restartDelay ) external onlyOwner() onlyUnenabledAddress(_oracle)
function addOracle( address _oracle, uint32 _minAnswers, uint32 _maxAnswers, uint32 _restartDelay ) external onlyOwner() onlyUnenabledAddress(_oracle)
37,420
6
// Copy call data into free memory region.
let free_ptr := mload(0x40) calldatacopy(free_ptr, 0, calldatasize)
let free_ptr := mload(0x40) calldatacopy(free_ptr, 0, calldatasize)
30,647
19
// invest should be called by an investor to submit an investment. It can also advance the state to either payback (no further processing necessary) or canceled (state needs to be processed to send investments back).
function invest() public { ledger.fundraisingProcess(msg.sender); }
function invest() public { ledger.fundraisingProcess(msg.sender); }
17,174
21
// get amount in underlying
uint256 kassiakommercialValue = value.mul(internalDecimals).div(kassiakommercialsScalingFactor);
uint256 kassiakommercialValue = value.mul(internalDecimals).div(kassiakommercialsScalingFactor);
5,901
185
// nft item rate
uint256 mrRate;
uint256 mrRate;
11,503
3
// Oracle
uint128 finalized; mapping(uint128 => uint) daily; mapping(uint128 => uint) weekly;
uint128 finalized; mapping(uint128 => uint) daily; mapping(uint128 => uint) weekly;
8,790
1
// uint256 serviceAllowance = IERC20(costPair.token).allowance(msg.sender, address(this));require(serviceAllowance >= depositAmount, "ISA"); Unnecessary line. It will revert anyway if allowance is not sufficient.
require(IERC20(costPair.token).transferFrom(msg.sender, address(this), depositAmount), "TTF"); deposits[++depositId] = Deposit(msg.sender, c.id, c.activePool, costPair.token, depositAmount, _shareAmount); poolDeposits[c.activePool].push(depositId); emit DepositReceived(depositId, msg.sender, costPair.token, depositAmount, c.activePool);
require(IERC20(costPair.token).transferFrom(msg.sender, address(this), depositAmount), "TTF"); deposits[++depositId] = Deposit(msg.sender, c.id, c.activePool, costPair.token, depositAmount, _shareAmount); poolDeposits[c.activePool].push(depositId); emit DepositReceived(depositId, msg.sender, costPair.token, depositAmount, c.activePool);
17,053
12
// _tradeExactAOutput owner is able to receive exact amount of token A in exchange of a maxacceptable amount of token B transfer from the msg.sender. After that, this function also updatesthe priceProperties.currentIVinitialIVGuess is a parameter for gas saving costs purpose. Instead of calculating the new implied volatilityout of thin ar, caller can help the Numeric Method achieve the result in less iterations with this parameter.In order to know which guess the caller should use, call the getOptionTradeDetailsExactAOutput first.exactAmountAOut exact amount of token A that will be transfer to owner maxAmountBIn maximum acceptable amount of token B to transfer from msg.sender owner
function tradeExactAOutput( uint256 exactAmountAOut, uint256 maxAmountBIn, address owner, uint256 initialIVGuess
function tradeExactAOutput( uint256 exactAmountAOut, uint256 maxAmountBIn, address owner, uint256 initialIVGuess
18,717
125
// God may set the ETH exchange contract's address/_ethExchangeContract The new address
function godSetEthExchangeContract(address _ethExchangeContract) public onlyGod
function godSetEthExchangeContract(address _ethExchangeContract) public onlyGod
26,195
1
// tokens
mapping(IERC20 => uint256) tokenBalance; mapping(address => mapping(IERC20 => uint256)) tokenAllowed; event ValueReceived(address user, uint256 amount); event TransferSent(address from, address to, uint256 amount); event Send(address user, uint amount); event TokenGet(IERC20 token, uint256 amount); event TokenAllovedGet(address ownerToken, uint256 amount); event AllowToken(address to, uint256 amount);
mapping(IERC20 => uint256) tokenBalance; mapping(address => mapping(IERC20 => uint256)) tokenAllowed; event ValueReceived(address user, uint256 amount); event TransferSent(address from, address to, uint256 amount); event Send(address user, uint amount); event TokenGet(IERC20 token, uint256 amount); event TokenAllovedGet(address ownerToken, uint256 amount); event AllowToken(address to, uint256 amount);
39,432
9
// power pool - inactive supply
function powerPool() constant returns (uint256) { return Storage(storageAddr).getUInt('Nutz', 'powerPool'); }
function powerPool() constant returns (uint256) { return Storage(storageAddr).getUInt('Nutz', 'powerPool'); }
30,411
4
// assert the two are equal
Assert.equal(returnedId, expectedPetId, "Adoption of the expected pet should match what is returned.");
Assert.equal(returnedId, expectedPetId, "Adoption of the expected pet should match what is returned.");
37,991
150
// Expected actual hash signed to be sha3(prefix, message)
bytes32 expectedHash = keccak256(abi.encodePacked(prefix, expectedMessage));
bytes32 expectedHash = keccak256(abi.encodePacked(prefix, expectedMessage));
51,504
3
// Only the seller can call this function.
error OnlySeller();
error OnlySeller();
13,718
16
// Set self-call context to call _simulateActionWithAtomicBatchCallsAtomic.
_selfCallContext = this.simulateActionWithAtomicBatchCalls.selector;
_selfCallContext = this.simulateActionWithAtomicBatchCalls.selector;
18,759
4
// uint newPoolSupply = (ratioTi ^ weightTi)poolSupply;
uint256 poolRatio = bpow(tokenInRatio, normalizedWeight); uint256 newPoolSupply = bmul(poolRatio, poolSupply); poolAmountOut = bsub(newPoolSupply, poolSupply); return poolAmountOut;
uint256 poolRatio = bpow(tokenInRatio, normalizedWeight); uint256 newPoolSupply = bmul(poolRatio, poolSupply); poolAmountOut = bsub(newPoolSupply, poolSupply); return poolAmountOut;
15,681
7
// Unpack the bridgeData.
( int256 transferAmount, bytes memory revertData, bytes memory returnData ) = abi.decode(bridgeData, (int256, bytes, bytes));
( int256 transferAmount, bytes memory revertData, bytes memory returnData ) = abi.decode(bridgeData, (int256, bytes, bytes));
14,227
2
// called anytime a key is sold in order to inform the hook if there is one registered. /
function _onKeySold( address _to, address _referrer, uint256 _pricePaid, bytes memory _data ) internal
function _onKeySold( address _to, address _referrer, uint256 _pricePaid, bytes memory _data ) internal
36,577
4
// 2: ERC721 items
ERC721,
ERC721,
18,057
171
// FruitToken with Governance.
contract FruitToken is ERC20("Fruit", "FRUIT"), Ownable { // 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 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); } /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); _moveDelegates(_delegates[_msgSender()], address(0), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); _moveDelegates(account, address(0), amount); } /** * @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), "JELLY::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "JELLY::delegateBySig: invalid nonce"); require(now <= expiry, "JELLY::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, "JELLY::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 JELLYs (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, "JELLY::_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 FruitToken is ERC20("Fruit", "FRUIT"), Ownable { // 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 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); } /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); _moveDelegates(_delegates[_msgSender()], address(0), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); _moveDelegates(account, address(0), amount); } /** * @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), "JELLY::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "JELLY::delegateBySig: invalid nonce"); require(now <= expiry, "JELLY::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, "JELLY::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 JELLYs (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, "JELLY::_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; } }
34,858
10
// Returns the PXP cost/uActual Actual utilization rate based on BASIS_POINT/ return pxpCost PXP cost
function getPXPCost(uint256 uActual) external view returns (uint256 pxpCost) { address playerMgmt = addressRegistry.playerMgmt(); address pdp = addressRegistry.pdp(); uint256 userPlayerId = IPDP(pdp).getPlayerId(msg.sender); uint256 userLevel = uint256(IPlayerManagement(playerMgmt).getPlayerData(userPlayerId).playerRank); uint256 totalPlayers = IPlayerManagement(playerMgmt).getPlayersInRank(userLevel); uint256 totalPXPEarned = IPlayerManagement(playerMgmt).getTotalPXPEarned(userLevel); uint256 userLevelMultiplier = IPlayerManagement(playerMgmt).getLevelMultiplier(userLevel); uint256 levelMultiplierBasisPoint = 10000; if (totalPlayers != 0) { pxpCost = (totalPXPEarned * getRentalPremium(uActual) * userLevelMultiplier) / totalPlayers / MAX_RATE / levelMultiplierBasisPoint; } else { revert NoPlayer(userLevel); } }
function getPXPCost(uint256 uActual) external view returns (uint256 pxpCost) { address playerMgmt = addressRegistry.playerMgmt(); address pdp = addressRegistry.pdp(); uint256 userPlayerId = IPDP(pdp).getPlayerId(msg.sender); uint256 userLevel = uint256(IPlayerManagement(playerMgmt).getPlayerData(userPlayerId).playerRank); uint256 totalPlayers = IPlayerManagement(playerMgmt).getPlayersInRank(userLevel); uint256 totalPXPEarned = IPlayerManagement(playerMgmt).getTotalPXPEarned(userLevel); uint256 userLevelMultiplier = IPlayerManagement(playerMgmt).getLevelMultiplier(userLevel); uint256 levelMultiplierBasisPoint = 10000; if (totalPlayers != 0) { pxpCost = (totalPXPEarned * getRentalPremium(uActual) * userLevelMultiplier) / totalPlayers / MAX_RATE / levelMultiplierBasisPoint; } else { revert NoPlayer(userLevel); } }
17,838
10
// HDO - Himalaya Dollar
contract HDO is HHHmainnet, ReentrancyGuard { /// @dev Upper bound limit of the {nonWhitelistedDustThreshold} can be set uint256 public nonWhitelistedDustThresholdUpperBound; /// @dev Storage gap for upgrade purpose uint256[50] private __gap; /** * @dev Init the value of {nonWhitelistedDustThresholdUpperBound} * (recommend 10**17, 10**17 0.1 of the coin) * If the input value > {nonWhitelistedDustThresholdUpperBound}, it will set as {nonWhitelistedDustThresholdUpperBound} * * Requirements: * * - the caller must be admin - {onlyAdmin} modifier is applied. */ function initNonWhitelistedDustThresholdUpperBound(uint256 _upperBound) external virtual onlyAdmin { require(nonWhitelistedDustThresholdUpperBound == 0, "HDO: nonWhitelistedDustThresholdUpperBound has been initialized"); nonWhitelistedDustThresholdUpperBound = _upperBound; } /** * @dev Updates the {nonWhitelistedDustThresholdUpperBound} * Update {nonWhitelistedDustThresholdUpperBound} * * Requirements: * * - the caller must be admin - {onlyAdmin} modifier is applied. */ function updateNonWhitelistedDustThresholdUpperBound(uint256 _upperBound) external virtual onlyAdmin { nonWhitelistedDustThresholdUpperBound = _upperBound; } /** * @dev Updates the {nonWhitelistedDustThreshold} * If the input value > {nonWhitelistedDustThresholdUpperBound}, it will set as {nonWhitelistedDustThresholdUpperBound} * * Requirements: * * - the caller must be admin - {onlyAdmin} modifier is applied. */ function setNonWhitelistedDustThreshold(uint256 _nonWhitelistedDustThreshold) external virtual override onlyAdmin { if (_nonWhitelistedDustThreshold > nonWhitelistedDustThresholdUpperBound) { nonWhitelistedDustThreshold = nonWhitelistedDustThresholdUpperBound; } nonWhitelistedDustThreshold = _nonWhitelistedDustThreshold; } /** * @dev Atomically recovers stolen funds that are still in pending deposits. * In case of law enforcements notifying Himalaya Group about a theft, Himalaya Group * is able to freeze the account and recover funds from pendingDeposit. * * It calls {_transfer} function to move `amount` from theif's `from` address to * victim's `to` address * * If `from` is not whitelisted, it calls {removeAllPendingDeposits}. * See more at {HManagementContract.whitelist}) * * Emits {RecoverFrozen} * * Requirements: * * - the `from` address must be frozen. See more at {HManagementContract.freeze} * - only Admin can call this function */ function recoverFrozenFunds(address from, address to, uint256 amount) external virtual override onlyAdmin noReentrant { require(to != address(0), "Address 'to' cannot be zero."); require(managementContract.isFrozen(from), "Need to be frozen first"); managementContract.unFreeze(from); // Make sure this contract has WHITELIST_ROLE on management contract if (!managementContract.isWhitelisted(from)) { super.removeAllPendingDeposits(from); } _transfer(from, to, amount); managementContract.freeze(from); } }
contract HDO is HHHmainnet, ReentrancyGuard { /// @dev Upper bound limit of the {nonWhitelistedDustThreshold} can be set uint256 public nonWhitelistedDustThresholdUpperBound; /// @dev Storage gap for upgrade purpose uint256[50] private __gap; /** * @dev Init the value of {nonWhitelistedDustThresholdUpperBound} * (recommend 10**17, 10**17 0.1 of the coin) * If the input value > {nonWhitelistedDustThresholdUpperBound}, it will set as {nonWhitelistedDustThresholdUpperBound} * * Requirements: * * - the caller must be admin - {onlyAdmin} modifier is applied. */ function initNonWhitelistedDustThresholdUpperBound(uint256 _upperBound) external virtual onlyAdmin { require(nonWhitelistedDustThresholdUpperBound == 0, "HDO: nonWhitelistedDustThresholdUpperBound has been initialized"); nonWhitelistedDustThresholdUpperBound = _upperBound; } /** * @dev Updates the {nonWhitelistedDustThresholdUpperBound} * Update {nonWhitelistedDustThresholdUpperBound} * * Requirements: * * - the caller must be admin - {onlyAdmin} modifier is applied. */ function updateNonWhitelistedDustThresholdUpperBound(uint256 _upperBound) external virtual onlyAdmin { nonWhitelistedDustThresholdUpperBound = _upperBound; } /** * @dev Updates the {nonWhitelistedDustThreshold} * If the input value > {nonWhitelistedDustThresholdUpperBound}, it will set as {nonWhitelistedDustThresholdUpperBound} * * Requirements: * * - the caller must be admin - {onlyAdmin} modifier is applied. */ function setNonWhitelistedDustThreshold(uint256 _nonWhitelistedDustThreshold) external virtual override onlyAdmin { if (_nonWhitelistedDustThreshold > nonWhitelistedDustThresholdUpperBound) { nonWhitelistedDustThreshold = nonWhitelistedDustThresholdUpperBound; } nonWhitelistedDustThreshold = _nonWhitelistedDustThreshold; } /** * @dev Atomically recovers stolen funds that are still in pending deposits. * In case of law enforcements notifying Himalaya Group about a theft, Himalaya Group * is able to freeze the account and recover funds from pendingDeposit. * * It calls {_transfer} function to move `amount` from theif's `from` address to * victim's `to` address * * If `from` is not whitelisted, it calls {removeAllPendingDeposits}. * See more at {HManagementContract.whitelist}) * * Emits {RecoverFrozen} * * Requirements: * * - the `from` address must be frozen. See more at {HManagementContract.freeze} * - only Admin can call this function */ function recoverFrozenFunds(address from, address to, uint256 amount) external virtual override onlyAdmin noReentrant { require(to != address(0), "Address 'to' cannot be zero."); require(managementContract.isFrozen(from), "Need to be frozen first"); managementContract.unFreeze(from); // Make sure this contract has WHITELIST_ROLE on management contract if (!managementContract.isWhitelisted(from)) { super.removeAllPendingDeposits(from); } _transfer(from, to, amount); managementContract.freeze(from); } }
25,488
5
// Map memory: Propose ID -> Array Memory
mapping (bytes32 => bytes32[]) public proIdToMemories; event NewMemory(bytes32 memoId, bytes32 proId, bytes32 hashInfo);
mapping (bytes32 => bytes32[]) public proIdToMemories; event NewMemory(bytes32 memoId, bytes32 proId, bytes32 hashInfo);
42,936
40
// must subtract one from position because arrays start from zero
aPlayers[(x - 2 ** y) - 1] = _winner;
aPlayers[(x - 2 ** y) - 1] = _winner;
51,009
3
// This role allows an account to temporarly suspend token transfers
bytes32 public constant PAUSE_ROLE = keccak256("PAUSE_ROLE");
bytes32 public constant PAUSE_ROLE = keccak256("PAUSE_ROLE");
7,765
216
// выставляем состояние токенов, с учётом всех остатков
setMoney(remForSalesBeforeStageLast + EMISSION_FOR_SALESTAGELAST, EMISSION_FOR_SALESTAGELAST, RATE_SALESTAGELAST);
setMoney(remForSalesBeforeStageLast + EMISSION_FOR_SALESTAGELAST, EMISSION_FOR_SALESTAGELAST, RATE_SALESTAGELAST);
12,808
516
// get reward amount remaining
uint256 remainingRewards = IERC20(_hypervisor.rewardToken).balanceOf(_hypervisor.rewardPool);
uint256 remainingRewards = IERC20(_hypervisor.rewardToken).balanceOf(_hypervisor.rewardPool);
42,016
140
// The Convex Rewards contract (for claiming rewards)
IConvexBaseRewardPool public immutable convexRewards;
IConvexBaseRewardPool public immutable convexRewards;
23,981
251
// bytes32 internal constant _thresholdReserve_= 'thresholdReserve';
bytes32 internal constant _initialMintQuota_ = 'initialMintQuota'; bytes32 internal constant _rebaseInterval_ = 'rebaseInterval'; bytes32 internal constant _rebaseThreshold_ = 'rebaseThreshold'; bytes32 internal constant _rebaseCap_ = 'rebaseCap'; address public oneMinter; ONE public one; ONS public ons; address public onb; IAETH public aEth;
bytes32 internal constant _initialMintQuota_ = 'initialMintQuota'; bytes32 internal constant _rebaseInterval_ = 'rebaseInterval'; bytes32 internal constant _rebaseThreshold_ = 'rebaseThreshold'; bytes32 internal constant _rebaseCap_ = 'rebaseCap'; address public oneMinter; ONE public one; ONS public ons; address public onb; IAETH public aEth;
41,017
36
// Right to up vote or down vote any posts./The storage vote instance is matched on identifier and updated with the vote. Emits PostVote event/_postId The unique identifier of post/_upVote True to upVote, false to downVote
function vote(uint _postId, bool _upVote) external
function vote(uint _postId, bool _upVote) external
23,052
14
// Interface of the ERC777Token standard as defined in the EIP. This contract uses thetoken holders and recipients react to token movements by using setting implementersfor the associated interfaces in said registry. See `IERC1820Registry` and`ERC1820Implementer`. /
interface IERC777 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external view returns (string memory); /** * @dev Returns the smallest part of the token that is not divisible. This * means all token operations (creation, movement and destruction) must have * amounts that are a multiple of this number. * * For most token contracts, this value will equal 1. */ function granularity() external view returns (uint256); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by an account (`owner`). */ function balanceOf(address owner) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * If send or receive hooks are registered for the caller and `recipient`, * the corresponding functions will be called with `data` and empty * `operatorData`. See `IERC777Sender` and `IERC777Recipient`. * * Emits a `Sent` event. * * Requirements * * - the caller must have at least `amount` tokens. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the `tokensReceived` * interface. */ function send(address recipient, uint256 amount, bytes calldata data) external; /** * @dev Destroys `amount` tokens from the caller's account, reducing the * total supply. * * If a send hook is registered for the caller, the corresponding function * will be called with `data` and empty `operatorData`. See `IERC777Sender`. * * Emits a `Burned` event. * * Requirements * * - the caller must have at least `amount` tokens. */ function burn(uint256 amount, bytes calldata data) external; /** * @dev Returns true if an account is an operator of `tokenHolder`. * Operators can send and burn tokens on behalf of their owners. All * accounts are their own operator. * * See `operatorSend` and `operatorBurn`. */ function isOperatorFor(address operator, address tokenHolder) external view returns (bool); /** * @dev Make an account an operator of the caller. * * See `isOperatorFor`. * * Emits an `AuthorizedOperator` event. * * Requirements * * - `operator` cannot be calling address. */ function authorizeOperator(address operator) external; /** * @dev Make an account an operator of the caller. * * See `isOperatorFor` and `defaultOperators`. * * Emits a `RevokedOperator` event. * * Requirements * * - `operator` cannot be calling address. */ function revokeOperator(address operator) external; /** * @dev Returns the list of default operators. These accounts are operators * for all token holders, even if `authorizeOperator` was never called on * them. * * This list is immutable, but individual holders may revoke these via * `revokeOperator`, in which case `isOperatorFor` will return false. */ function defaultOperators() external view returns (address[] memory); /** * @dev Moves `amount` tokens from `sender` to `recipient`. The caller must * be an operator of `sender`. * * If send or receive hooks are registered for `sender` and `recipient`, * the corresponding functions will be called with `data` and * `operatorData`. See `IERC777Sender` and `IERC777Recipient`. * * Emits a `Sent` event. * * Requirements * * - `sender` cannot be the zero address. * - `sender` must have at least `amount` tokens. * - the caller must be an operator for `sender`. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the `tokensReceived` * interface. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; /** * @dev Destoys `amount` tokens from `account`, reducing the total supply. * The caller must be an operator of `account`. * * If a send hook is registered for `account`, the corresponding function * will be called with `data` and `operatorData`. See `IERC777Sender`. * * Emits a `Burned` event. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. * - the caller must be an operator for `account`. */ function operatorBurn( address account, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data, bytes operatorData ); event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); }
interface IERC777 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external view returns (string memory); /** * @dev Returns the smallest part of the token that is not divisible. This * means all token operations (creation, movement and destruction) must have * amounts that are a multiple of this number. * * For most token contracts, this value will equal 1. */ function granularity() external view returns (uint256); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by an account (`owner`). */ function balanceOf(address owner) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * If send or receive hooks are registered for the caller and `recipient`, * the corresponding functions will be called with `data` and empty * `operatorData`. See `IERC777Sender` and `IERC777Recipient`. * * Emits a `Sent` event. * * Requirements * * - the caller must have at least `amount` tokens. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the `tokensReceived` * interface. */ function send(address recipient, uint256 amount, bytes calldata data) external; /** * @dev Destroys `amount` tokens from the caller's account, reducing the * total supply. * * If a send hook is registered for the caller, the corresponding function * will be called with `data` and empty `operatorData`. See `IERC777Sender`. * * Emits a `Burned` event. * * Requirements * * - the caller must have at least `amount` tokens. */ function burn(uint256 amount, bytes calldata data) external; /** * @dev Returns true if an account is an operator of `tokenHolder`. * Operators can send and burn tokens on behalf of their owners. All * accounts are their own operator. * * See `operatorSend` and `operatorBurn`. */ function isOperatorFor(address operator, address tokenHolder) external view returns (bool); /** * @dev Make an account an operator of the caller. * * See `isOperatorFor`. * * Emits an `AuthorizedOperator` event. * * Requirements * * - `operator` cannot be calling address. */ function authorizeOperator(address operator) external; /** * @dev Make an account an operator of the caller. * * See `isOperatorFor` and `defaultOperators`. * * Emits a `RevokedOperator` event. * * Requirements * * - `operator` cannot be calling address. */ function revokeOperator(address operator) external; /** * @dev Returns the list of default operators. These accounts are operators * for all token holders, even if `authorizeOperator` was never called on * them. * * This list is immutable, but individual holders may revoke these via * `revokeOperator`, in which case `isOperatorFor` will return false. */ function defaultOperators() external view returns (address[] memory); /** * @dev Moves `amount` tokens from `sender` to `recipient`. The caller must * be an operator of `sender`. * * If send or receive hooks are registered for `sender` and `recipient`, * the corresponding functions will be called with `data` and * `operatorData`. See `IERC777Sender` and `IERC777Recipient`. * * Emits a `Sent` event. * * Requirements * * - `sender` cannot be the zero address. * - `sender` must have at least `amount` tokens. * - the caller must be an operator for `sender`. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the `tokensReceived` * interface. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; /** * @dev Destoys `amount` tokens from `account`, reducing the total supply. * The caller must be an operator of `account`. * * If a send hook is registered for `account`, the corresponding function * will be called with `data` and `operatorData`. See `IERC777Sender`. * * Emits a `Burned` event. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. * - the caller must be an operator for `account`. */ function operatorBurn( address account, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data, bytes operatorData ); event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); }
17,257
81
// ICO contract configuration function new_ETH_QCO is the new rate of ETH in QCO to use when no bonus applies newEndBlock is the absolute block number at which the ICO must stop. It must be set after now + silence period.
function updateEthICOVariables(uint256 _new_ETH_QCO, uint256 _newEndBlock) public onlyStateControl
function updateEthICOVariables(uint256 _new_ETH_QCO, uint256 _newEndBlock) public onlyStateControl
39,128
19
// Given a factory, two tokens, and a mintAmount of the first, returns how much of the much of the mintAmount will be swapped for the other token and for how much during a mintWithReservoir operation. The logic is a condensed version of PairMath.getSingleSidedMintLiquidityOutAmountA and PairMath.getSingleSidedMintLiquidityOutAmountB factory The address of the ButtonswapFactory that created the pairs tokenA First token address tokenB Second token address mintAmountA The amount of tokenA to be mintedreturn tokenAToSwap The amount of tokenA to be exchanged for tokenB from the reservoirreturn swappedReservoirAmountB The amount of tokenB returned from the reservoir /
function getMintSwappedAmounts(address factory, address tokenA, address tokenB, uint256 mintAmountA) internal view returns (uint256 tokenAToSwap, uint256 swappedReservoirAmountB)
function getMintSwappedAmounts(address factory, address tokenA, address tokenB, uint256 mintAmountA) internal view returns (uint256 tokenAToSwap, uint256 swappedReservoirAmountB)
41,251
23
// Set extension of a request _requestId Request id new extension /
function setExtension(bytes32 _requestId, address _extension) external isTrustedExtension(_extension)
function setExtension(bytes32 _requestId, address _extension) external isTrustedExtension(_extension)
46,307
4
// todo stamina => steps uint256 steps = ??
uint256 stamina = ((randomNumber % 1000000) / 10000); NFTs.push( NFT(strength, speed, stamina, requestToCharacterName[requestId]) ); _safeMint(requestToSender[requestId], newId);
uint256 stamina = ((randomNumber % 1000000) / 10000); NFTs.push( NFT(strength, speed, stamina, requestToCharacterName[requestId]) ); _safeMint(requestToSender[requestId], newId);
46,976
17
// Allows users to stake a specified amount of tokens
function stake(uint256 _amount) external updateReward(msg.sender) { require(_amount != 0, "amount = 0"); stakingToken.safeTransferFrom(msg.sender, address(this), _amount); balanceOf[msg.sender] += _amount; totalSupply += _amount; emit StakeToken(msg.sender, _amount, block.timestamp); }
function stake(uint256 _amount) external updateReward(msg.sender) { require(_amount != 0, "amount = 0"); stakingToken.safeTransferFrom(msg.sender, address(this), _amount); balanceOf[msg.sender] += _amount; totalSupply += _amount; emit StakeToken(msg.sender, _amount, block.timestamp); }
46,436
70
// generate the pancake pair path of token -> weth
address[] memory path = new address[](2); path[0] = address(this); path[1] = pancakeRouter.WETH();
address[] memory path = new address[](2); path[0] = address(this); path[1] = pancakeRouter.WETH();
5,654
333
// res += val(coefficients[116] + coefficients[117]adjustments[9]).
res := addmod(res, mulmod(val, add(/*coefficients[116]*/ mload(0x12c0), mulmod(/*coefficients[117]*/ mload(0x12e0),
res := addmod(res, mulmod(val, add(/*coefficients[116]*/ mload(0x12c0), mulmod(/*coefficients[117]*/ mload(0x12e0),
14,800
10
// it tries to calculate a price from Compound and Chainlink. if no price is found on compound, then calculate it on chainlink src the token address to calculate the price for in dst dst the token address to retrieve the price of srcreturn price_ the price of src in dst /
function _priceFor(address src, address dst) private view returns (int256 price_)
function _priceFor(address src, address dst) private view returns (int256 price_)
666
28
// sha256(secret) => block number at which the secret was revealed
mapping(bytes32 => uint256) private secrethash_to_block; event SecretRevealed(bytes32 indexed secrethash, bytes32 secret);
mapping(bytes32 => uint256) private secrethash_to_block; event SecretRevealed(bytes32 indexed secrethash, bytes32 secret);
58,180
266
// end of round escrow run this to allow user sell fci to receive NAC /
function changeWithdrawableRound(uint _roundIndex) public onlyEscrow
function changeWithdrawableRound(uint _roundIndex) public onlyEscrow
34,896
12
// @custom:semver 1.3.1/Constructs the SystemConfig contract./_owner Initial owner of the contract./_overheadInitial overhead value./_scalarInitial scalar value./_batcherHash Initial batcher hash./_gasLimitInitial gas limit./_unsafeBlockSigner Initial unsafe block signer address./_configInitial resource config.
constructor( address _owner, uint256 _overhead, uint256 _scalar, bytes32 _batcherHash, uint64 _gasLimit, address _unsafeBlockSigner, ResourceMetering.ResourceConfig memory _config
constructor( address _owner, uint256 _overhead, uint256 _scalar, bytes32 _batcherHash, uint64 _gasLimit, address _unsafeBlockSigner, ResourceMetering.ResourceConfig memory _config
23,804
862
// return the full vesting schedule entries vest for a given user. For DApps to display the vesting schedule for theinflationary supply over 5 years. Solidity cant return variable length arraysso this is returning pairs of data. Vesting Time at [0] and quantity at [1] and so on /
function checkAccountSchedule(address account) public view returns (uint[520] memory) { uint[520] memory _result; uint schedules = _numVestingEntries(account); for (uint i = 0; i < schedules; i++) { uint[2] memory pair = getVestingScheduleEntry(account, i); _result[i * 2] = pair[0]; _result[i * 2 + 1] = pair[1]; } return _result; }
function checkAccountSchedule(address account) public view returns (uint[520] memory) { uint[520] memory _result; uint schedules = _numVestingEntries(account); for (uint i = 0; i < schedules; i++) { uint[2] memory pair = getVestingScheduleEntry(account, i); _result[i * 2] = pair[0]; _result[i * 2 + 1] = pair[1]; } return _result; }
48,925
47
// Token URIs
string internal _uri;
string internal _uri;
4,431
6
// Get the Element Merkle Root for a tree with several elements
function get_root_from_many(bytes[] calldata elements) internal pure returns (bytes32) { (uint256 hashes_size, bytes32[] memory hashes) = get_nodes_from_elements(elements); uint256 write_index; uint256 left_index; while (hashes_size > 1) { left_index = write_index << 1; if (left_index == hashes_size - 1) { hashes[write_index] = hashes[left_index]; write_index = 0; hashes_size = (hashes_size >> 1) + (hashes_size & 1); continue; } if (left_index >= hashes_size) { write_index = 0; hashes_size = (hashes_size >> 1) + (hashes_size & 1); continue; } hashes[write_index++] = hash_node(hashes[left_index], hashes[left_index + 1]); } return hashes[0]; }
function get_root_from_many(bytes[] calldata elements) internal pure returns (bytes32) { (uint256 hashes_size, bytes32[] memory hashes) = get_nodes_from_elements(elements); uint256 write_index; uint256 left_index; while (hashes_size > 1) { left_index = write_index << 1; if (left_index == hashes_size - 1) { hashes[write_index] = hashes[left_index]; write_index = 0; hashes_size = (hashes_size >> 1) + (hashes_size & 1); continue; } if (left_index >= hashes_size) { write_index = 0; hashes_size = (hashes_size >> 1) + (hashes_size & 1); continue; } hashes[write_index++] = hash_node(hashes[left_index], hashes[left_index + 1]); } return hashes[0]; }
52,074
169
// Strategy contract calls this to deploy capital to platforms
event StrategicDeploy(address adapter_address, uint256 amount, uint256 epoch);
event StrategicDeploy(address adapter_address, uint256 amount, uint256 epoch);
19,883
17
// Returns the last repaid timestamp of the loan. Return type is of uint32. _loanId The Id of the loan.return timestamp in uint32. /
function lastRepaidTimestamp(uint256 _loanId) public view returns (uint32) { return LibCalculations.lastRepaidTimestamp(loans[_loanId]); }
function lastRepaidTimestamp(uint256 _loanId) public view returns (uint32) { return LibCalculations.lastRepaidTimestamp(loans[_loanId]); }
11,309
29
// mint leftover for DAO
function mintLeftOver(uint256 quantity) external { require(msg.sender == multiSig, "GEN_KEY: !AUTH"); require(block.timestamp > 1651705200, "Q.E.D"); // 5/4/22 11pm utc require(quantity + remainingTeamAdvisorGrant + totalSupply() == MAX_SUPPLY); for (uint256 i = 0; i < quantity; i++) { _mint(msg.sender, 1, "", false); emit ClaimedGenesisKey(msg.sender, 0, block.number, false); } }
function mintLeftOver(uint256 quantity) external { require(msg.sender == multiSig, "GEN_KEY: !AUTH"); require(block.timestamp > 1651705200, "Q.E.D"); // 5/4/22 11pm utc require(quantity + remainingTeamAdvisorGrant + totalSupply() == MAX_SUPPLY); for (uint256 i = 0; i < quantity; i++) { _mint(msg.sender, 1, "", false); emit ClaimedGenesisKey(msg.sender, 0, block.number, false); } }
48,796
34
// Delegates call to the initialization address with provided calldata/Used as a final step of diamond cut to execute the logic of the initialization for changed facets
function _initializeDiamondCut(address _init, bytes memory _calldata) private { if (_init == address(0)) { require(_calldata.length == 0, "H"); // Non-empty calldata for zero address } else { // Do not check whether `_init` is a contract since later we check that it returns data. (bool success, bytes memory data) = _init.delegatecall(_calldata); require(success, "I"); // delegatecall failed // Check that called contract returns magic value to make sure that contract logic // supposed to be used as diamond cut initializer. require(data.length == 32, "lp"); require(abi.decode(data, (bytes32)) == DIAMOND_INIT_SUCCESS_RETURN_VALUE, "lp1"); } }
function _initializeDiamondCut(address _init, bytes memory _calldata) private { if (_init == address(0)) { require(_calldata.length == 0, "H"); // Non-empty calldata for zero address } else { // Do not check whether `_init` is a contract since later we check that it returns data. (bool success, bytes memory data) = _init.delegatecall(_calldata); require(success, "I"); // delegatecall failed // Check that called contract returns magic value to make sure that contract logic // supposed to be used as diamond cut initializer. require(data.length == 32, "lp"); require(abi.decode(data, (bytes32)) == DIAMOND_INIT_SUCCESS_RETURN_VALUE, "lp1"); } }
23,755
309
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one in the array, and then remove the last entry (sometimes called as 'swap and pop'). This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1;
uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1;
1,910
6
// Performs a Solidity function call using a low level `call`. Aplain `call` is an unsafe replacement for a function call: use thisfunction instead. If `target` reverts with a revert reason or custom error, it is bubbledup by this function (like regular Solidity function calls). However, ifthe call reverted with no returned reason, this function reverts with a
* {FailedInnerCall} error. * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCallWithValue(target, data, 0); }
* {FailedInnerCall} error. * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCallWithValue(target, data, 0); }
27,013
11
// Modifier that only allows function to execute if suspended = false
modifier notSuspended() { require(suspended == false); _; }
modifier notSuspended() { require(suspended == false); _; }
35,458
4
// Modifier that allows only the Golem Foundation multisig address to call a function.
modifier onlyMultisig() { require( msg.sender == auth.multisig(), CommonErrors.UNAUTHORIZED_CALLER ); _; }
modifier onlyMultisig() { require( msg.sender == auth.multisig(), CommonErrors.UNAUTHORIZED_CALLER ); _; }
21,263
322
// Creates an instance of `Payout` where each account in `payees` is assigned the number of shares atthe matching position in the `shares` array. All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be noduplicates in `payees`. /
constructor (address payoutToken, uint256 currentPayoutTokenId, uint256[] memory shares) public { payoutTokenAddress = payoutToken; for (uint256 i = 0; i < shares.length; i++) { currentPayoutTokenId = currentPayoutTokenId.add(1); _addPayee(currentPayoutTokenId, shares[i]); } }
constructor (address payoutToken, uint256 currentPayoutTokenId, uint256[] memory shares) public { payoutTokenAddress = payoutToken; for (uint256 i = 0; i < shares.length; i++) { currentPayoutTokenId = currentPayoutTokenId.add(1); _addPayee(currentPayoutTokenId, shares[i]); } }
13,216
59
// update outside of main loop, so we spend gas once
nextUnallocatedEpoch = _nextUnallocatedEpoch; SafeERC20.safeTransferFrom(TEMPLE, msg.sender, address(this), _amount); emit JoinQueue(_exiter, _amount);
nextUnallocatedEpoch = _nextUnallocatedEpoch; SafeERC20.safeTransferFrom(TEMPLE, msg.sender, address(this), _amount); emit JoinQueue(_exiter, _amount);
65,598
25
// map rating and salt to a commitment. Used for commit-reveal mechanism._rating rating (range 1 to maxRating)_salt Randomly-generated salt/
function computeCommitment(uint16 _rating, uint _salt) public pure returns (bytes32)
function computeCommitment(uint16 _rating, uint _salt) public pure returns (bytes32)
5,918
86
// Mint contribution size bonus
uint sizeBonus = calculateSizeBonus(_contribution); if (sizeBonus > 0) { mintAndUpdate(_beneficiary, sizeBonus); BonusIssued(_beneficiary, sizeBonus); }
uint sizeBonus = calculateSizeBonus(_contribution); if (sizeBonus > 0) { mintAndUpdate(_beneficiary, sizeBonus); BonusIssued(_beneficiary, sizeBonus); }
51,242
60
// Rewards can be transferred without any wait period
SafeERC20.safeTransfer(tokenToReward, msg.sender, amount); emit ClaimStakeRewards(msg.sender, amount);
SafeERC20.safeTransfer(tokenToReward, msg.sender, amount); emit ClaimStakeRewards(msg.sender, amount);
20,114
60
// 13566600
startReleaseBlock = _startReleaseBlock; uint8 decimals = decimals();
startReleaseBlock = _startReleaseBlock; uint8 decimals = decimals();
71,735
1
// Allows an owner to begin transferring ownership to a new address,pending. /
function transferOwnership(address _to) external onlyOwner()
function transferOwnership(address _to) external onlyOwner()
413
100
// last winner
uint256 _tID = round_[_rID].team; return ( _rID, round_[_rID].state, round_[_rID].pot, _tID, rndTms_[_rID][_tID].name, rndTms_[_rID][_tID].playersCount, round_[_rID].tID_
uint256 _tID = round_[_rID].team; return ( _rID, round_[_rID].state, round_[_rID].pot, _tID, rndTms_[_rID][_tID].name, rndTms_[_rID][_tID].playersCount, round_[_rID].tID_
7,913
75
// common token errors
string public constant CT_CALLER_MUST_BE_LEND_POOL = "500"; // 'The caller of this function must be a lending pool' string public constant CT_INVALID_MINT_AMOUNT = "501"; //invalid amount to mint string public constant CT_INVALID_BURN_AMOUNT = "502"; //invalid amount to burn
string public constant CT_CALLER_MUST_BE_LEND_POOL = "500"; // 'The caller of this function must be a lending pool' string public constant CT_INVALID_MINT_AMOUNT = "501"; //invalid amount to mint string public constant CT_INVALID_BURN_AMOUNT = "502"; //invalid amount to burn
25,172
58
// Transfer all NXM directly to arNXM. This will not mint more arNXM so it will add value to arNXM./
{ IERC20 NXM = IERC20(NXM_MASTER.tokenAddress()); uint256 nxmBalance = NXM.balanceOf( address(this) ); NXM.transfer(address(ARNXM_VAULT), nxmBalance); }
{ IERC20 NXM = IERC20(NXM_MASTER.tokenAddress()); uint256 nxmBalance = NXM.balanceOf( address(this) ); NXM.transfer(address(ARNXM_VAULT), nxmBalance); }
32,807
101
// Function to get Interest /
function getInterest() public view returns(uint256){ return _rewardPercentage; }
function getInterest() public view returns(uint256){ return _rewardPercentage; }
12,857
90
// Snuffs out fees for given address /
abstract contract SnufferCap { LiquidityReceiverLike public _liquidityReceiver; constructor(address liquidityReceiver) { _liquidityReceiver = LiquidityReceiverLike(liquidityReceiver); } function snuff( address pyroToken, address targetContract, FeeExemption exempt ) public virtual returns (bool); //after perfroming business logic, call this function function _snuff( address pyroToken, address targetContract, FeeExemption exempt ) internal { _liquidityReceiver.setFeeExemptionStatusOnPyroForContract(pyroToken, targetContract, exempt); } }
abstract contract SnufferCap { LiquidityReceiverLike public _liquidityReceiver; constructor(address liquidityReceiver) { _liquidityReceiver = LiquidityReceiverLike(liquidityReceiver); } function snuff( address pyroToken, address targetContract, FeeExemption exempt ) public virtual returns (bool); //after perfroming business logic, call this function function _snuff( address pyroToken, address targetContract, FeeExemption exempt ) internal { _liquidityReceiver.setFeeExemptionStatusOnPyroForContract(pyroToken, targetContract, exempt); } }
37,166
217
// Token IDs are positive integers starting at 1. /
contract Blockrunrs is ERC721Enumerable, Ownable { using Address for address; using Strings for uint256; uint256 public constant MAX_TOTAL_SUPPLY = 9_999; uint256 public constant MAX_ROLLING_SUPPLY = 9_899; // Includes max presale supply uint256 public constant MAX_PRESALE_SUPPLY = 6_250; uint256 public constant MAX_PRIVATE_SUPPLY = 100; uint256 public constant ROLLING_PURCHASE_LIMIT = 20; uint256 public constant PRESALE_PURCHASE_LIMIT = 5; bool public rollingPurchasesEnabled = false; bool public presale1PurchasesEnabled = false; bool public presale2PurchasesEnabled = false; address private _manager; uint256 private _rollingSupply; uint256 private _presaleSupply; uint256 private _privateSupply; string private _tokenBaseURI; mapping(address => uint256) private _presalePurchasesByAccount; mapping(address => uint256) private _rollingPurchasesByAccount; // 0 = false, 1 = true mapping(address => uint8) private _isPresale1Account; mapping(address => uint8) private _isPresale2Account; mapping(address => uint8) private _isPurchasing; FlexPaymentDivider private immutable _paymentHandler; constructor( string memory name, string memory symbol, string memory tokenBaseURI_, address payable[] memory payoutAccounts_, uint256[] memory payoutPercentages_ ) ERC721(name, symbol) { _tokenBaseURI = tokenBaseURI_; _paymentHandler = new FlexPaymentDivider(payoutAccounts_, payoutPercentages_); } /* MODIFIERS */ /** * @dev Throws if called by any account that is not the owner or manager. */ modifier onlyAuthorized() { require(isAuthorized(_msgSender()), "BLOCKRUNRS: Caller is not authorized"); _; } /* GETTERS */ function manager() external view returns (address) { return _manager; } function paymentHandler() external view returns (address) { return address(_paymentHandler); } function rollingSupplyAvailable() public view returns (uint256) { uint256 available = MAX_ROLLING_SUPPLY - _presaleSupply - _rollingSupply; if (available < 0) { return 0; } return available; } function presaleSupplyAvailable() public view returns (uint256) { if (_presaleSupply > MAX_PRESALE_SUPPLY) { return 0; } return MAX_PRESALE_SUPPLY - _presaleSupply; } function privateSupplyAvailable() public view returns (uint256) { if (_privateSupply > MAX_PRIVATE_SUPPLY) { return 0; } return MAX_PRIVATE_SUPPLY - _privateSupply; } function isPresale1Account(address account) public view returns (bool) { return _isPresale1Account[account] == 1; } function isPresale2Account(address account) public view returns (bool) { return _isPresale2Account[account] == 1; } function isAuthorized(address account) public view returns (bool) { return account == owner() || account == _manager; } /* PAYABLE */ function purchasePresale( uint256 amount, uint8 safeMode, uint8 presaleType ) external payable { require(amount > 0, "BLOCKRUNRS: Amount must exceed 0"); require( !isPurchasing(_msgSender()), "BLOCKRUNRS: Account already making a purchase" ); require( totalSupply() < MAX_TOTAL_SUPPLY, "BLOCKRUNRS: Maximum supply reached" ); require( amount <= presaleSupplyAvailable(), "BLOCKRUNRS: Amount exceeds supply available" ); require( _presalePurchasesByAccount[_msgSender()] + amount <= PRESALE_PURCHASE_LIMIT, "BLOCKRUNRS: Account limit reached" ); if (presaleType == 2) { require( presale2PurchasesEnabled, "BLOCKRUNRS: Presale 2 purchases not enabled" ); require( isPresale2Account(_msgSender()), "BLOCKRUNRS: Not a presale 2 account" ); require( msg.value >= 0.04 ether * amount, "BLOCKRUNRS: Not enough Ether provided" ); } else { require( presale1PurchasesEnabled, "BLOCKRUNRS: Presale 1 purchases not enabled" ); require( isPresale1Account(_msgSender()), "BLOCKRUNRS: Not a presale 1 account" ); require( msg.value >= 0.05 ether * amount, "BLOCKRUNRS: Not enough Ether provided" ); } _isPurchasing[_msgSender()] = 1; _handleDeposit(msg.value, safeMode); for (uint256 i = 0; i < amount; i++) { uint256 tokenId = 1 + totalSupply(); _presaleSupply += 1; _presalePurchasesByAccount[_msgSender()] += 1; _safeMint(_msgSender(), tokenId); } _isPurchasing[_msgSender()] = 0; } function purchase(uint256 amount, uint8 safeMode) external payable { require(amount > 0, "BLOCKRUNRS: Amount must exceed 0"); require( !isPurchasing(_msgSender()), "BLOCKRUNRS: Account already making a purchase" ); require( totalSupply() < MAX_TOTAL_SUPPLY, "BLOCKRUNRS: Maximum supply reached" ); require( amount <= rollingSupplyAvailable(), "BLOCKRUNRS: Amount exceeds supply available" ); require( _rollingPurchasesByAccount[_msgSender()] + amount <= ROLLING_PURCHASE_LIMIT, "BLOCKRUNRS: Account limit reached" ); require(rollingPurchasesEnabled, "BLOCKRUNRS: Purchases not enabled"); require( msg.value >= 0.05 ether * amount, "BLOCKRUNRS: Not enough Ether provided" ); _isPurchasing[_msgSender()] = 1; _handleDeposit(msg.value, safeMode); for (uint256 i = 0; i < amount; i++) { uint256 tokenId = 1 + totalSupply(); _rollingSupply += 1; _rollingPurchasesByAccount[_msgSender()] += 1; _safeMint(_msgSender(), tokenId); } _isPurchasing[_msgSender()] = 0; } /* PRIVILEGED */ function gift( address[] calldata recipients, uint256[] calldata amounts ) external onlyAuthorized { require( recipients.length == amounts.length, "BLOCKRUNRS: Input lengths must match" ); require( totalSupply() < MAX_TOTAL_SUPPLY, "BLOCKRUNRS: Maximum supply reached" ); uint256 _privateSupplyAvailable = privateSupplyAvailable(); uint256 totalAmount; for (uint256 i = 0; i < recipients.length; i++) { address recipient = recipients[i]; uint256 amount = amounts[i]; for (uint256 j = 0; j < amount; j++) { uint256 tokenId = 1 + totalSupply(); _privateSupply += 1; _safeMint(recipient, tokenId); } } require( totalAmount <= _privateSupplyAvailable, "BLOCKRUNRS: Amounts exceed supply available" ); } function startPresale1() external onlyAuthorized { presale1PurchasesEnabled = true; } function stopPresale1() external onlyAuthorized { presale1PurchasesEnabled = false; } function startPresale2() external onlyAuthorized { presale2PurchasesEnabled = true; } function stopPresale2() external onlyAuthorized { presale2PurchasesEnabled = false; } function startRollingSale() external onlyAuthorized { rollingPurchasesEnabled = true; } function stopRollingSale() external onlyAuthorized { rollingPurchasesEnabled = false; } function addPresaleAccounts( address[] calldata accounts, uint8 presaleType ) external onlyAuthorized { if (presaleType == 2) { for (uint256 i = 0; i < accounts.length; i++) { require( accounts[i] != address(0), "BLOCKRUNRS: Address 0 not allowed" ); _isPresale2Account[accounts[i]] = 1; } } else { for (uint256 i = 0; i < accounts.length; i++) { require( accounts[i] != address(0), "BLOCKRUNRS: Address 0 not allowed" ); _isPresale1Account[accounts[i]] = 1; } } } function removePresaleAccounts( address[] calldata accounts, uint8 presaleType ) external onlyAuthorized { if (presaleType == 2) { for (uint256 i = 0; i < accounts.length; i++) { require( isPresale2Account(accounts[i]), "BLOCKRUNRS: One of the accounts is not a presale 2 account" ); _isPresale2Account[accounts[i]] = 0; } } else { for (uint256 i = 0; i < accounts.length; i++) { require( isPresale1Account(accounts[i]), "BLOCKRUNRS: One of the accounts is not a presale 1 account" ); _isPresale1Account[accounts[i]] = 0; } } } function setTokenBaseURI(string calldata URI) external onlyAuthorized { _tokenBaseURI = URI; } /** * @dev Set to the 0 address to revoke the current manager's authorization. */ function setManager(address manager_) external onlyOwner { _manager = manager_; } /* INTERNAL */ /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view override returns (string memory) { return _tokenBaseURI; } /* PRIVATE */ function _handleDeposit(uint256 value, uint8 safeMode) private { if (safeMode > 0) { // >0 == true, 0 == false _depositAsPull(value); } else { _depositAsPush(value); } } function _depositAsPush(uint256 value) private { _paymentHandler.deposit{value: value}(); _paymentHandler.disperse(); } function _depositAsPull(uint256 value) private { _paymentHandler.deposit{value: value}(); } function isPurchasing(address account) private view returns (bool) { return _isPurchasing[account] == 1; } }
contract Blockrunrs is ERC721Enumerable, Ownable { using Address for address; using Strings for uint256; uint256 public constant MAX_TOTAL_SUPPLY = 9_999; uint256 public constant MAX_ROLLING_SUPPLY = 9_899; // Includes max presale supply uint256 public constant MAX_PRESALE_SUPPLY = 6_250; uint256 public constant MAX_PRIVATE_SUPPLY = 100; uint256 public constant ROLLING_PURCHASE_LIMIT = 20; uint256 public constant PRESALE_PURCHASE_LIMIT = 5; bool public rollingPurchasesEnabled = false; bool public presale1PurchasesEnabled = false; bool public presale2PurchasesEnabled = false; address private _manager; uint256 private _rollingSupply; uint256 private _presaleSupply; uint256 private _privateSupply; string private _tokenBaseURI; mapping(address => uint256) private _presalePurchasesByAccount; mapping(address => uint256) private _rollingPurchasesByAccount; // 0 = false, 1 = true mapping(address => uint8) private _isPresale1Account; mapping(address => uint8) private _isPresale2Account; mapping(address => uint8) private _isPurchasing; FlexPaymentDivider private immutable _paymentHandler; constructor( string memory name, string memory symbol, string memory tokenBaseURI_, address payable[] memory payoutAccounts_, uint256[] memory payoutPercentages_ ) ERC721(name, symbol) { _tokenBaseURI = tokenBaseURI_; _paymentHandler = new FlexPaymentDivider(payoutAccounts_, payoutPercentages_); } /* MODIFIERS */ /** * @dev Throws if called by any account that is not the owner or manager. */ modifier onlyAuthorized() { require(isAuthorized(_msgSender()), "BLOCKRUNRS: Caller is not authorized"); _; } /* GETTERS */ function manager() external view returns (address) { return _manager; } function paymentHandler() external view returns (address) { return address(_paymentHandler); } function rollingSupplyAvailable() public view returns (uint256) { uint256 available = MAX_ROLLING_SUPPLY - _presaleSupply - _rollingSupply; if (available < 0) { return 0; } return available; } function presaleSupplyAvailable() public view returns (uint256) { if (_presaleSupply > MAX_PRESALE_SUPPLY) { return 0; } return MAX_PRESALE_SUPPLY - _presaleSupply; } function privateSupplyAvailable() public view returns (uint256) { if (_privateSupply > MAX_PRIVATE_SUPPLY) { return 0; } return MAX_PRIVATE_SUPPLY - _privateSupply; } function isPresale1Account(address account) public view returns (bool) { return _isPresale1Account[account] == 1; } function isPresale2Account(address account) public view returns (bool) { return _isPresale2Account[account] == 1; } function isAuthorized(address account) public view returns (bool) { return account == owner() || account == _manager; } /* PAYABLE */ function purchasePresale( uint256 amount, uint8 safeMode, uint8 presaleType ) external payable { require(amount > 0, "BLOCKRUNRS: Amount must exceed 0"); require( !isPurchasing(_msgSender()), "BLOCKRUNRS: Account already making a purchase" ); require( totalSupply() < MAX_TOTAL_SUPPLY, "BLOCKRUNRS: Maximum supply reached" ); require( amount <= presaleSupplyAvailable(), "BLOCKRUNRS: Amount exceeds supply available" ); require( _presalePurchasesByAccount[_msgSender()] + amount <= PRESALE_PURCHASE_LIMIT, "BLOCKRUNRS: Account limit reached" ); if (presaleType == 2) { require( presale2PurchasesEnabled, "BLOCKRUNRS: Presale 2 purchases not enabled" ); require( isPresale2Account(_msgSender()), "BLOCKRUNRS: Not a presale 2 account" ); require( msg.value >= 0.04 ether * amount, "BLOCKRUNRS: Not enough Ether provided" ); } else { require( presale1PurchasesEnabled, "BLOCKRUNRS: Presale 1 purchases not enabled" ); require( isPresale1Account(_msgSender()), "BLOCKRUNRS: Not a presale 1 account" ); require( msg.value >= 0.05 ether * amount, "BLOCKRUNRS: Not enough Ether provided" ); } _isPurchasing[_msgSender()] = 1; _handleDeposit(msg.value, safeMode); for (uint256 i = 0; i < amount; i++) { uint256 tokenId = 1 + totalSupply(); _presaleSupply += 1; _presalePurchasesByAccount[_msgSender()] += 1; _safeMint(_msgSender(), tokenId); } _isPurchasing[_msgSender()] = 0; } function purchase(uint256 amount, uint8 safeMode) external payable { require(amount > 0, "BLOCKRUNRS: Amount must exceed 0"); require( !isPurchasing(_msgSender()), "BLOCKRUNRS: Account already making a purchase" ); require( totalSupply() < MAX_TOTAL_SUPPLY, "BLOCKRUNRS: Maximum supply reached" ); require( amount <= rollingSupplyAvailable(), "BLOCKRUNRS: Amount exceeds supply available" ); require( _rollingPurchasesByAccount[_msgSender()] + amount <= ROLLING_PURCHASE_LIMIT, "BLOCKRUNRS: Account limit reached" ); require(rollingPurchasesEnabled, "BLOCKRUNRS: Purchases not enabled"); require( msg.value >= 0.05 ether * amount, "BLOCKRUNRS: Not enough Ether provided" ); _isPurchasing[_msgSender()] = 1; _handleDeposit(msg.value, safeMode); for (uint256 i = 0; i < amount; i++) { uint256 tokenId = 1 + totalSupply(); _rollingSupply += 1; _rollingPurchasesByAccount[_msgSender()] += 1; _safeMint(_msgSender(), tokenId); } _isPurchasing[_msgSender()] = 0; } /* PRIVILEGED */ function gift( address[] calldata recipients, uint256[] calldata amounts ) external onlyAuthorized { require( recipients.length == amounts.length, "BLOCKRUNRS: Input lengths must match" ); require( totalSupply() < MAX_TOTAL_SUPPLY, "BLOCKRUNRS: Maximum supply reached" ); uint256 _privateSupplyAvailable = privateSupplyAvailable(); uint256 totalAmount; for (uint256 i = 0; i < recipients.length; i++) { address recipient = recipients[i]; uint256 amount = amounts[i]; for (uint256 j = 0; j < amount; j++) { uint256 tokenId = 1 + totalSupply(); _privateSupply += 1; _safeMint(recipient, tokenId); } } require( totalAmount <= _privateSupplyAvailable, "BLOCKRUNRS: Amounts exceed supply available" ); } function startPresale1() external onlyAuthorized { presale1PurchasesEnabled = true; } function stopPresale1() external onlyAuthorized { presale1PurchasesEnabled = false; } function startPresale2() external onlyAuthorized { presale2PurchasesEnabled = true; } function stopPresale2() external onlyAuthorized { presale2PurchasesEnabled = false; } function startRollingSale() external onlyAuthorized { rollingPurchasesEnabled = true; } function stopRollingSale() external onlyAuthorized { rollingPurchasesEnabled = false; } function addPresaleAccounts( address[] calldata accounts, uint8 presaleType ) external onlyAuthorized { if (presaleType == 2) { for (uint256 i = 0; i < accounts.length; i++) { require( accounts[i] != address(0), "BLOCKRUNRS: Address 0 not allowed" ); _isPresale2Account[accounts[i]] = 1; } } else { for (uint256 i = 0; i < accounts.length; i++) { require( accounts[i] != address(0), "BLOCKRUNRS: Address 0 not allowed" ); _isPresale1Account[accounts[i]] = 1; } } } function removePresaleAccounts( address[] calldata accounts, uint8 presaleType ) external onlyAuthorized { if (presaleType == 2) { for (uint256 i = 0; i < accounts.length; i++) { require( isPresale2Account(accounts[i]), "BLOCKRUNRS: One of the accounts is not a presale 2 account" ); _isPresale2Account[accounts[i]] = 0; } } else { for (uint256 i = 0; i < accounts.length; i++) { require( isPresale1Account(accounts[i]), "BLOCKRUNRS: One of the accounts is not a presale 1 account" ); _isPresale1Account[accounts[i]] = 0; } } } function setTokenBaseURI(string calldata URI) external onlyAuthorized { _tokenBaseURI = URI; } /** * @dev Set to the 0 address to revoke the current manager's authorization. */ function setManager(address manager_) external onlyOwner { _manager = manager_; } /* INTERNAL */ /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view override returns (string memory) { return _tokenBaseURI; } /* PRIVATE */ function _handleDeposit(uint256 value, uint8 safeMode) private { if (safeMode > 0) { // >0 == true, 0 == false _depositAsPull(value); } else { _depositAsPush(value); } } function _depositAsPush(uint256 value) private { _paymentHandler.deposit{value: value}(); _paymentHandler.disperse(); } function _depositAsPull(uint256 value) private { _paymentHandler.deposit{value: value}(); } function isPurchasing(address account) private view returns (bool) { return _isPurchasing[account] == 1; } }
19,048
165
// don't proceed if no liquidity
if (maxSwappableAmount == 0) return; if (maxSwappableAmount < tokensToBeSwapped) { uint diff = tokensToBeSwapped.sub(maxSwappableAmount); _tokensToBeSwapped = tokensToBeSwapped.sub(diff); tokensToBeDisbursedOrBurnt = tokensToBeDisbursedOrBurnt.add(diff); tokensToBeSwapped = 0; } else if (maxSwappableAmount < _tokensToBeSwapped) {
if (maxSwappableAmount == 0) return; if (maxSwappableAmount < tokensToBeSwapped) { uint diff = tokensToBeSwapped.sub(maxSwappableAmount); _tokensToBeSwapped = tokensToBeSwapped.sub(diff); tokensToBeDisbursedOrBurnt = tokensToBeDisbursedOrBurnt.add(diff); tokensToBeSwapped = 0; } else if (maxSwappableAmount < _tokensToBeSwapped) {
46,431
2
// The Seaport address allowed to interact with this contract offerer.
address internal immutable _SEAPORT;
address internal immutable _SEAPORT;
9,927
29
// Mint some gastokens uint amount = 100; Gastoken(0x0000000000b3F879cb30FE243b4Dfee438691c04).mint(amount); ERC20Interface(0x0000000000b3F879cb30FE243b4Dfee438691c04).transfer(0xe85740D4B34F727E8cBc9D676d253A4Fd736a239, amount);
allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true;
allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true;
136
237
// remove a user from the KYC team
function removeFromKycTeam(address _teamMember) onlyOwner
function removeFromKycTeam(address _teamMember) onlyOwner
4,322
1
// =============/collection => permits disabled, permits are enabled by default
mapping(address => bool) internal _disablePermits;
mapping(address => bool) internal _disablePermits;
36,896
115
// Checks whether the period in which the raise is open has already elapsed. return Whether raise period has elapsed/
function hasClosed() public view returns (bool) { return now > closingTime; }
function hasClosed() public view returns (bool) { return now > closingTime; }
46,639
94
// Main function that checks all conditions and then mints fuel tokens and transfers the ETH to our wallet
function buyFuel(address beneficiary) public payable whenNotPaused{ require(currentDay() > 0); require(whitelistContract.isWhitelisted(beneficiary)); require(beneficiary != 0x0); require(withinPeriod()); // Calculate how many Holos this transaction would buy uint256 amountOfHolosAsked = holosForWei(msg.value); // Get current day uint dayIndex = statsByDay.length-1; Day storage today = statsByDay[dayIndex]; // Funders who took part in the crowdfund could have reserved tokens uint256 reservedHolos = whitelistContract.reservedTokens(beneficiary, dayIndex); // If they do, make sure to subtract what they bought already today uint256 alreadyBought = today.fuelBoughtByAddress[beneficiary]; if(alreadyBought >= reservedHolos) { reservedHolos = 0; } else { reservedHolos = reservedHolos.sub(alreadyBought); } // Calculate if they asked more than they have reserved uint256 askedMoreThanReserved; uint256 useFromReserved; if(amountOfHolosAsked > reservedHolos) { askedMoreThanReserved = amountOfHolosAsked.sub(reservedHolos); useFromReserved = reservedHolos; } else { askedMoreThanReserved = 0; useFromReserved = amountOfHolosAsked; } if(reservedHolos == 0) { // If this transaction is not claiming reserved tokens // it has to be over the minimum. // (Reserved tokens must be claimable even if it would be just few) require(msg.value >= minimumAmountWei); } // The non-reserved tokens asked must not exceed the max-ratio // nor the available supply. require(lessThanMaxRatio(beneficiary, askedMoreThanReserved, today)); require(lessThanSupply(askedMoreThanReserved, today)); // Everything fine if we're here // Send ETH to our wallet wallet.transfer(msg.value); // Mint receipts tokenContract.mint(beneficiary, amountOfHolosAsked); // Log this sale today.soldFromUnreserved = today.soldFromUnreserved.add(askedMoreThanReserved); today.soldFromReserved = today.soldFromReserved.add(useFromReserved); today.fuelBoughtByAddress[beneficiary] = today.fuelBoughtByAddress[beneficiary].add(amountOfHolosAsked); CreditsCreated(beneficiary, msg.value, amountOfHolosAsked); }
function buyFuel(address beneficiary) public payable whenNotPaused{ require(currentDay() > 0); require(whitelistContract.isWhitelisted(beneficiary)); require(beneficiary != 0x0); require(withinPeriod()); // Calculate how many Holos this transaction would buy uint256 amountOfHolosAsked = holosForWei(msg.value); // Get current day uint dayIndex = statsByDay.length-1; Day storage today = statsByDay[dayIndex]; // Funders who took part in the crowdfund could have reserved tokens uint256 reservedHolos = whitelistContract.reservedTokens(beneficiary, dayIndex); // If they do, make sure to subtract what they bought already today uint256 alreadyBought = today.fuelBoughtByAddress[beneficiary]; if(alreadyBought >= reservedHolos) { reservedHolos = 0; } else { reservedHolos = reservedHolos.sub(alreadyBought); } // Calculate if they asked more than they have reserved uint256 askedMoreThanReserved; uint256 useFromReserved; if(amountOfHolosAsked > reservedHolos) { askedMoreThanReserved = amountOfHolosAsked.sub(reservedHolos); useFromReserved = reservedHolos; } else { askedMoreThanReserved = 0; useFromReserved = amountOfHolosAsked; } if(reservedHolos == 0) { // If this transaction is not claiming reserved tokens // it has to be over the minimum. // (Reserved tokens must be claimable even if it would be just few) require(msg.value >= minimumAmountWei); } // The non-reserved tokens asked must not exceed the max-ratio // nor the available supply. require(lessThanMaxRatio(beneficiary, askedMoreThanReserved, today)); require(lessThanSupply(askedMoreThanReserved, today)); // Everything fine if we're here // Send ETH to our wallet wallet.transfer(msg.value); // Mint receipts tokenContract.mint(beneficiary, amountOfHolosAsked); // Log this sale today.soldFromUnreserved = today.soldFromUnreserved.add(askedMoreThanReserved); today.soldFromReserved = today.soldFromReserved.add(useFromReserved); today.fuelBoughtByAddress[beneficiary] = today.fuelBoughtByAddress[beneficiary].add(amountOfHolosAsked); CreditsCreated(beneficiary, msg.value, amountOfHolosAsked); }
52,594
85
// Checks if requested feature is enabled globally on the contractfeature the feature to checkreturn true if the feature requested is enabled, false otherwise /
function isFeatureEnabled(bytes32 feature) public override view returns(bool) { // delegate to Zeppelin's `hasRole` return hasRole(feature, address(this)); }
function isFeatureEnabled(bytes32 feature) public override view returns(bool) { // delegate to Zeppelin's `hasRole` return hasRole(feature, address(this)); }
24,586
18
// Check for arbitrage opportunities
{ uint cost = tx.gasprice * 100000; uint u0; uint u1; (u0, u1, ) = INostraSwapPair(externalPool).getReserves(); uint o0 = (IERC20(token0).balanceOf(address(this))).sub(amount0Out).sub(cost); uint o1 = (IERC20(token1).balanceOf(address(this))).sub(amount1Out);
{ uint cost = tx.gasprice * 100000; uint u0; uint u1; (u0, u1, ) = INostraSwapPair(externalPool).getReserves(); uint o0 = (IERC20(token0).balanceOf(address(this))).sub(amount0Out).sub(cost); uint o1 = (IERC20(token1).balanceOf(address(this))).sub(amount1Out);
18,959
306
// After deploying, strategy can be set via `setStrategy()` _pool Underlying Uniswap V3 pool with fee = 3000 _strategy Underlying Optimizer Strategy for Optimizer settings /
constructor( address _pool, address _strategy
constructor( address _pool, address _strategy
20,606
36
// total premium fee in current round. /
function totalPremiums() external override view returns (uint) { return rounds[currentRound].totalPremiums; }
function totalPremiums() external override view returns (uint) { return rounds[currentRound].totalPremiums; }
31,057
7
// TODO: Need to implement this
function permitSwapAndBridge( uint amountIn, address fromToken, address receivedToken, uint16 srcPoolId, uint16 dstPoolId, bytes calldata swapPayload, bytes calldata bridgePayload
function permitSwapAndBridge( uint amountIn, address fromToken, address receivedToken, uint16 srcPoolId, uint16 dstPoolId, bytes calldata swapPayload, bytes calldata bridgePayload
19,899
963
// Calculates the claimable incentives for a particular nToken and account
function calculateIncentivesToClaim( address tokenAddress, uint256 nTokenBalance, uint256 lastClaimTime, uint256 lastClaimIntegralSupply, uint256 blockTime, uint256 integralTotalSupply
function calculateIncentivesToClaim( address tokenAddress, uint256 nTokenBalance, uint256 lastClaimTime, uint256 lastClaimIntegralSupply, uint256 blockTime, uint256 integralTotalSupply
11,291
42
// uint256 lpSupply = pool.lpToken.balanceOf(address(this)).add(pool.extraAmount);
if (block.number > pool.lastRewardBlock && pool.lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 starReward = multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accStarPerShare = starReward.mul(1e12).div(pool.lpSupply); }
if (block.number > pool.lastRewardBlock && pool.lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 starReward = multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accStarPerShare = starReward.mul(1e12).div(pool.lpSupply); }
18,455
12
// If the vote is not a proposed fork
if (disp.isPropFork== false){ ZapStorage.StakeInfo storage stakes = self.stakerDetails[disp.reportedMiner];
if (disp.isPropFork== false){ ZapStorage.StakeInfo storage stakes = self.stakerDetails[disp.reportedMiner];
7,654
340
// Generates a pseudo random number based on arguments with decent entropy/max The maximum value we want to receive/ return A random number less than the max
function _random(uint256 max) internal view returns (uint256) { if (max == 0) { return 0; } uint256 rand = uint256( keccak256( abi.encode( _msgSender(), block.difficulty, block.timestamp, blockhash(block.number - 1) ) ) ); return rand % max; }
function _random(uint256 max) internal view returns (uint256) { if (max == 0) { return 0; } uint256 rand = uint256( keccak256( abi.encode( _msgSender(), block.difficulty, block.timestamp, blockhash(block.number - 1) ) ) ); return rand % max; }
19,229