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
2
// if char is -
if (char == 45) { continue; }
if (char == 45) { continue; }
8,203
37
// We must normalize the inputs to 18 point
_normalizeSortedArray(currentBalances); _normalizeSortedArray(maxAmountsIn);
_normalizeSortedArray(currentBalances); _normalizeSortedArray(maxAmountsIn);
23,513
139
// returns true if price is below the peg/counterintuitively checks if peg < price because price is reported as RUSD per X
function _isBelowPeg(Decimal.D256 memory peg) internal view returns (bool) { Decimal.D256 memory price = _getUniswapPrice(); return peg.lessThan(price); }
function _isBelowPeg(Decimal.D256 memory peg) internal view returns (bool) { Decimal.D256 memory price = _getUniswapPrice(); return peg.lessThan(price); }
39,101
246
// See {IRedeemBase-updateApprovedTokens} /
function updateApprovedTokens( address contract_, uint256[] memory tokenIds, bool[] memory approved ) public virtual override adminRequired { require( tokenIds.length == approved.length, "Redeem: Invalid input parameters" );
function updateApprovedTokens( address contract_, uint256[] memory tokenIds, bool[] memory approved ) public virtual override adminRequired { require( tokenIds.length == approved.length, "Redeem: Invalid input parameters" );
63,701
8
// Claim rewards for all staked Zombiez
function claimRewards(uint256[] calldata tokenIds) public whenNotPaused { uint256 reward; uint256 blockCur = Math.min(block.number, expiration); for (uint256 i; i < tokenIds.length; i++) { reward += calculateReward(msg.sender, tokenIds[i]); _lastClaimBlocks[msg.sender][tokenIds[i]] = blockCur; } if (reward > 0) { IERC20(fleshAddress).transfer(msg.sender, reward); } }
function claimRewards(uint256[] calldata tokenIds) public whenNotPaused { uint256 reward; uint256 blockCur = Math.min(block.number, expiration); for (uint256 i; i < tokenIds.length; i++) { reward += calculateReward(msg.sender, tokenIds[i]); _lastClaimBlocks[msg.sender][tokenIds[i]] = blockCur; } if (reward > 0) { IERC20(fleshAddress).transfer(msg.sender, reward); } }
34,077
87
// Called once after the initial deployment to set the Foundation treasury address. /
function _initializeFoundationTreasuryNode(address payable _treasury) internal initializer { require(_treasury.isContract(), "FoundationTreasuryNode: Address is not a contract"); treasury = _treasury; }
function _initializeFoundationTreasuryNode(address payable _treasury) internal initializer { require(_treasury.isContract(), "FoundationTreasuryNode: Address is not a contract"); treasury = _treasury; }
78,332
1
// https:etherscan.io/address/0xEd42a7D8559a463722Ca4beD50E0Cc05a386b0e1
address internal constant CROSS_CHAIN_CONTROLLER = 0xEd42a7D8559a463722Ca4beD50E0Cc05a386b0e1;
address internal constant CROSS_CHAIN_CONTROLLER = 0xEd42a7D8559a463722Ca4beD50E0Cc05a386b0e1;
15,940
0
// Verifies a merkle patricia proof. value The terminating value in the trie. encodedPath The path in the trie leading to value. rlpParentNodes The rlp encoded stack of nodes. root The root hash of the trie.return The boolean validity of the proof. /
function verify( bytes memory value, bytes memory encodedPath, bytes memory rlpParentNodes, bytes32 root ) internal pure returns (bool) { RLPReader.RLPItem memory item = RLPReader.toRlpItem(rlpParentNodes); RLPReader.RLPItem[] memory parentNodes = RLPReader.toList(item); bytes memory currentNode;
function verify( bytes memory value, bytes memory encodedPath, bytes memory rlpParentNodes, bytes32 root ) internal pure returns (bool) { RLPReader.RLPItem memory item = RLPReader.toRlpItem(rlpParentNodes); RLPReader.RLPItem[] memory parentNodes = RLPReader.toList(item); bytes memory currentNode;
24,743
106
// returns the full rewards since the last claim /
function _fullRewards( address provider, IDSToken poolToken, IReserveToken reserveToken, PoolRewards memory poolRewardsData, ProviderRewards memory providerRewards, PoolProgram memory program, ILiquidityProtectionStats lpStats
function _fullRewards( address provider, IDSToken poolToken, IReserveToken reserveToken, PoolRewards memory poolRewardsData, ProviderRewards memory providerRewards, PoolProgram memory program, ILiquidityProtectionStats lpStats
48,878
165
// Internal function for adding executed amount for some token. _token address of the token contract. _day day number, when tokens are processed. _value amount of bridge tokens. /
function addTotalExecutedPerDay( address _token, uint256 _day, uint256 _value
function addTotalExecutedPerDay( address _token, uint256 _day, uint256 _value
8,950
42
// Override isApprovedForAll to allowlist user's OpenSea proxy accounts to enable gas-less listings. //function isApprovedForAll(address owner, address operator)
{ // Get a reference to OpenSea's proxy registry contract by instantiating // the contract using the already existing address. ProxyRegistry proxyRegistry = ProxyRegistry( openSeaProxyRegistryAddress ); if ( isOpenSeaProxyActive && address(proxyRegistry.proxies(owner)) == operator ) { return true; } return super.isApprovedForAll(owner, operator); }*/
{ // Get a reference to OpenSea's proxy registry contract by instantiating // the contract using the already existing address. ProxyRegistry proxyRegistry = ProxyRegistry( openSeaProxyRegistryAddress ); if ( isOpenSeaProxyActive && address(proxyRegistry.proxies(owner)) == operator ) { return true; } return super.isApprovedForAll(owner, operator); }*/
25,561
5
// Transfers ERC20 tokens from `owner` to `to`. Only callable from within./token The token to spend./owner The owner of the tokens./to The recipient of the tokens./amount The amount of `token` to transfer.
function _spendERC20Tokens( IERC20TokenV06 token, address owner, address to, uint256 amount ) external override onlySelf
function _spendERC20Tokens( IERC20TokenV06 token, address owner, address to, uint256 amount ) external override onlySelf
46,888
67
// Information isn't considered verified until at least MIN_RESPONSES oracles respond with thesameinformation
emit OracleReport(airline, flight, timestamp, statusCode);
emit OracleReport(airline, flight, timestamp, statusCode);
15,667
13
// We never auction for less than starting price
if (nextPrice < GEN0_STARTING_PRICE) { nextPrice = GEN0_STARTING_PRICE; }
if (nextPrice < GEN0_STARTING_PRICE) { nextPrice = GEN0_STARTING_PRICE; }
5,875
16
// Return member address who holds the right to add/remove any member from specific role.
function authorized(uint _memberRoleId) internal view returns(address);
function authorized(uint _memberRoleId) internal view returns(address);
41,298
143
// paid
else { require(mintedQty + _mintQty <= TOTAL_MINT_MAX_QTY, "MAXL"); require(minterToTokenQty[msg.sender] + _mintQty <= MAX_QTY_PER_WALLET, "MAXP"); require(msg.value >= PRICE * _mintQty, "SETH"); }
else { require(mintedQty + _mintQty <= TOTAL_MINT_MAX_QTY, "MAXL"); require(minterToTokenQty[msg.sender] + _mintQty <= MAX_QTY_PER_WALLET, "MAXP"); require(msg.value >= PRICE * _mintQty, "SETH"); }
36,401
3
// Total number of tokens in circulation
uint public totalSupply = 100_000_000e18; // 100 million PUSH
uint public totalSupply = 100_000_000e18; // 100 million PUSH
9,489
108
// Market
address private market;
address private market;
14,568
90
// The owner can add new token(s) to existing list, by address./Attempting to add token addresses which are already in the list will cause revert./_listId ID of list to add new tokens./_tokens Array of token addresses to add.
function addTokens(uint256 _listId, address[] memory _tokens) public onlyOwner { require(_listId <= listCount, 'DXTokenRegistry : INVALID_LIST'); for (uint32 i = 0; i < _tokens.length; i++) { require( tcrs[_listId].status[_tokens[i]] != TokenStatus.ACTIVE, 'DXTokenRegistry : DUPLICATE_TOKEN' ); tcrs[_listId].tokens.push(_tokens[i]); tcrs[_listId].status[_tokens[i]] = TokenStatus.ACTIVE; tcrs[_listId].activeTokenCount++; emit AddToken(_listId, _tokens[i]); } }
function addTokens(uint256 _listId, address[] memory _tokens) public onlyOwner { require(_listId <= listCount, 'DXTokenRegistry : INVALID_LIST'); for (uint32 i = 0; i < _tokens.length; i++) { require( tcrs[_listId].status[_tokens[i]] != TokenStatus.ACTIVE, 'DXTokenRegistry : DUPLICATE_TOKEN' ); tcrs[_listId].tokens.push(_tokens[i]); tcrs[_listId].status[_tokens[i]] = TokenStatus.ACTIVE; tcrs[_listId].activeTokenCount++; emit AddToken(_listId, _tokens[i]); } }
8,451
0
// Initialize the smart contract wallet. /
function initialize(address _defaultAdmin, address _entrypoint) public initializer { if (_defaultAdmin == address(0) || _entrypoint == address(0)) { revert ZeroAddressNotAllowed(); }
function initialize(address _defaultAdmin, address _entrypoint) public initializer { if (_defaultAdmin == address(0) || _entrypoint == address(0)) { revert ZeroAddressNotAllowed(); }
16,048
413
// Function that burns the amount sent during an exchange in case the protection circuit is activatedfrom The address to move synth fromsourceCurrencyKey source currency from.sourceAmount The amount, specified in UNIT of source currency. return Boolean that indicates whether the transfer succeeded or failed./
function _internalLiquidation( address from, bytes4 sourceCurrencyKey, uint sourceAmount ) internal returns (bool)
function _internalLiquidation( address from, bytes4 sourceCurrencyKey, uint sourceAmount ) internal returns (bool)
25,568
104
// A Secondary contract can only be used by its primary account (the one that created it). /
contract Secondary is Context { address private _primary; /** * @dev Emitted when the primary contract changes. */ event PrimaryTransferred( address recipient ); /** * @dev Sets the primary account to the one that is creating the Secondary contract. */ constructor () internal { address msgSender = _msgSender(); _primary = msgSender; emit PrimaryTransferred(msgSender); } /** * @dev Reverts if called from any account other than the primary. */ modifier onlyPrimary() { require(_msgSender() == _primary, "Secondary: caller is not the primary account"); _; } /** * @return the address of the primary. */ function primary() public view returns (address) { return _primary; } /** * @dev Transfers contract to a new primary. * @param recipient The address of new primary. */ function transferPrimary(address recipient) public onlyPrimary { require(recipient != address(0), "Secondary: new primary is the zero address"); _primary = recipient; emit PrimaryTransferred(recipient); } }
contract Secondary is Context { address private _primary; /** * @dev Emitted when the primary contract changes. */ event PrimaryTransferred( address recipient ); /** * @dev Sets the primary account to the one that is creating the Secondary contract. */ constructor () internal { address msgSender = _msgSender(); _primary = msgSender; emit PrimaryTransferred(msgSender); } /** * @dev Reverts if called from any account other than the primary. */ modifier onlyPrimary() { require(_msgSender() == _primary, "Secondary: caller is not the primary account"); _; } /** * @return the address of the primary. */ function primary() public view returns (address) { return _primary; } /** * @dev Transfers contract to a new primary. * @param recipient The address of new primary. */ function transferPrimary(address recipient) public onlyPrimary { require(recipient != address(0), "Secondary: new primary is the zero address"); _primary = recipient; emit PrimaryTransferred(recipient); } }
37,163
198
// OPERATOR ONLY: Set methodology settings and check new settings are valid. Note: Need to pass in existing parameters if only changing a few settings. Must not bein a rebalance._newMethodologySettingsStruct containing methodology parameters /
function setMethodologySettings(MethodologySettings memory _newMethodologySettings) external onlyOperator noRebalanceInProgress { methodology = _newMethodologySettings; _validateSettings(methodology, execution, incentive); emit MethodologySettingsUpdated( methodology.targetLeverageRatio, methodology.minLeverageRatio, methodology.maxLeverageRatio, methodology.recenteringSpeed, methodology.rebalanceInterval ); }
function setMethodologySettings(MethodologySettings memory _newMethodologySettings) external onlyOperator noRebalanceInProgress { methodology = _newMethodologySettings; _validateSettings(methodology, execution, incentive); emit MethodologySettingsUpdated( methodology.targetLeverageRatio, methodology.minLeverageRatio, methodology.maxLeverageRatio, methodology.recenteringSpeed, methodology.rebalanceInterval ); }
15,080
60
// Returns the number of reveal skips made by the specified validator during the specified staking epoch./_stakingEpoch The number of staking epoch./_miningAddress The mining address of the validator.
function revealSkips(uint256 _stakingEpoch, address _miningAddress) public view returns(uint256) { address stakingAddress = validatorSetContract.stakingByMiningAddress(_miningAddress); return _revealSkips[_stakingEpoch][stakingAddress]; }
function revealSkips(uint256 _stakingEpoch, address _miningAddress) public view returns(uint256) { address stakingAddress = validatorSetContract.stakingByMiningAddress(_miningAddress); return _revealSkips[_stakingEpoch][stakingAddress]; }
7,414
11
// List of unique location keys
uint[] public locations;
uint[] public locations;
45,777
101
// Maximise precision by picking the largest possible sharesPerToken value It is crucial to pick a maxSupply value that will never be exceeded
_sharesPerToken = MAX_UINT256.div(maxExpectedSupply_); _maxExpectedSupply = maxExpectedSupply_; _totalSupply = initialSupply_; _totalShares = initialSupply_.mul(_sharesPerToken); _shareBalances[msg.sender] = _totalShares; downstreamCaller = new DownstreamCaller(); emit Transfer(address(0x0), msg.sender, _totalSupply);
_sharesPerToken = MAX_UINT256.div(maxExpectedSupply_); _maxExpectedSupply = maxExpectedSupply_; _totalSupply = initialSupply_; _totalShares = initialSupply_.mul(_sharesPerToken); _shareBalances[msg.sender] = _totalShares; downstreamCaller = new DownstreamCaller(); emit Transfer(address(0x0), msg.sender, _totalSupply);
48,808
28
// Returns whether the random number request has completed.return True if a random number request has completed, false otherwise. /
function isRngCompleted() external view returns (bool);
function isRngCompleted() external view returns (bool);
15,286
14
// The manager has control over options like fees and features
function setManager(address _manager) external; function mint( uint256[] calldata tokenIds, uint256[] calldata amounts /* ignored for ERC721 vaults */ ) external returns (uint256); function mintTo( uint256[] calldata tokenIds, uint256[] calldata amounts, /* ignored for ERC721 vaults */
function setManager(address _manager) external; function mint( uint256[] calldata tokenIds, uint256[] calldata amounts /* ignored for ERC721 vaults */ ) external returns (uint256); function mintTo( uint256[] calldata tokenIds, uint256[] calldata amounts, /* ignored for ERC721 vaults */
61,102
15
// Voter[] voterList;
bool isUnlocked;
bool isUnlocked;
31,190
3
// Raised when trying to transfer an NFT to a non ERC721Receiver /
error NotERC721Receiver();
error NotERC721Receiver();
40,299
1
// Public View Functions//Return the net asset value for the token.
function nav() external view returns (uint256);
function nav() external view returns (uint256);
7,755
59
// called by the owner to unpause, returns to normal state /
function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); }
function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); }
3,834
61
// Pool is not cancelled!
require(state == PoolState.CANCELLED); _;
require(state == PoolState.CANCELLED); _;
30,470
75
// Returns whether the token changer is currently paused or not. While being in the paused state the contract should revert the transaction instead of converting tokens return Whether the token changer is in the paused state /
function isPaused() public view returns (bool) { return paused; }
function isPaused() public view returns (bool) { return paused; }
26,235
18
// Returns the version of the contract.
function contractVersion() external pure returns (uint8) { return uint8(VERSION); }
function contractVersion() external pure returns (uint8) { return uint8(VERSION); }
40,610
65
// Internal function that burns an amount of the token of a givenaccount, deducting from the sender's allowance for said account. Uses theinternal burn function.Emits an Approval event (reflecting the reduced allowance). account The account whose tokens will be burnt. value The amount that will be burnt. /
function _burnFrom(address account, uint256 value) internal { _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value); _burn(account, value); emit Approval(account, msg.sender, _allowed[account][msg.sender]); }
function _burnFrom(address account, uint256 value) internal { _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value); _burn(account, value); emit Approval(account, msg.sender, _allowed[account][msg.sender]); }
8,836
14
// The ordered list of calldata to be passed to each call
bytes[] calldatas;
bytes[] calldatas;
40,576
10
// Gas-optimized contract to wrap NFT into BENTO.
contract Tamago { IBentoBridge constant bento = IBentoBridge(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966); // BENTO vault contract mapping(IERC20 => Tama) public tamas; struct Tama { IERC721Wrap nft; uint64 tokenId; uint64 ctrlSupply; uint128 totalSupply; }
contract Tamago { IBentoBridge constant bento = IBentoBridge(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966); // BENTO vault contract mapping(IERC20 => Tama) public tamas; struct Tama { IERC721Wrap nft; uint64 tokenId; uint64 ctrlSupply; uint128 totalSupply; }
11,377
9
// Platform address /
address public platform;
address public platform;
35,948
282
// Pick a random index
function randomIndex() internal returns (uint256) { uint256 totalSize = TOKEN_LIMIT - totalSupply(); uint256 index = uint(keccak256(abi.encodePacked(nonce, msg.sender, block.difficulty, block.timestamp))) % totalSize; uint256 value = 0; if (indices[index] != 0) { value = indices[index]; } else { value = index; } if (indices[totalSize - 1] == 0) { indices[index] = totalSize - 1; } else { indices[index] = indices[totalSize - 1]; } nonce++; return value.add(1); }
function randomIndex() internal returns (uint256) { uint256 totalSize = TOKEN_LIMIT - totalSupply(); uint256 index = uint(keccak256(abi.encodePacked(nonce, msg.sender, block.difficulty, block.timestamp))) % totalSize; uint256 value = 0; if (indices[index] != 0) { value = indices[index]; } else { value = index; } if (indices[totalSize - 1] == 0) { indices[index] = totalSize - 1; } else { indices[index] = indices[totalSize - 1]; } nonce++; return value.add(1); }
40,632
82
// BurnableCrowdsale BurnableCrowdsale is based on zeppelin's Crowdsale contract.The difference is that we're using BurnableToken instead of MintableToken. /
contract BurnableCrowdsale { using SafeMath for uint256; // The token being sold BurnableToken public token; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected address public wallet; // how many token units a buyer gets per wei uint256 public rate; // amount of raised money in wei uint256 public weiRaised; // address to the token to use in the crowdsale address public tokenAddress; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); function BurnableCrowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, address _tokenAddress) public { require(_startTime >= now); require(_endTime >= _startTime); require(_rate > 0); require(_wallet != address(0)); tokenAddress = _tokenAddress; token = createTokenContract(); startTime = _startTime; endTime = _endTime; rate = _rate; wallet = _wallet; } // creates the token to be sold. // override this method to have crowdsale of a specific mintable token. // Rubynor override: change type to BurnableToken function createTokenContract() internal returns (BurnableToken) { return new BurnableToken(); } // fallback function can be used to buy tokens function () external payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) public payable { // We implement/override this function in BullTokenCrowdsale.sol } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { // We implement/override this function in BullTokenCrowdsale.sol } // @return true if the transaction can buy tokens function validPurchase() internal view returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { return now > endTime; } }
contract BurnableCrowdsale { using SafeMath for uint256; // The token being sold BurnableToken public token; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected address public wallet; // how many token units a buyer gets per wei uint256 public rate; // amount of raised money in wei uint256 public weiRaised; // address to the token to use in the crowdsale address public tokenAddress; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); function BurnableCrowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, address _tokenAddress) public { require(_startTime >= now); require(_endTime >= _startTime); require(_rate > 0); require(_wallet != address(0)); tokenAddress = _tokenAddress; token = createTokenContract(); startTime = _startTime; endTime = _endTime; rate = _rate; wallet = _wallet; } // creates the token to be sold. // override this method to have crowdsale of a specific mintable token. // Rubynor override: change type to BurnableToken function createTokenContract() internal returns (BurnableToken) { return new BurnableToken(); } // fallback function can be used to buy tokens function () external payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) public payable { // We implement/override this function in BullTokenCrowdsale.sol } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { // We implement/override this function in BullTokenCrowdsale.sol } // @return true if the transaction can buy tokens function validPurchase() internal view returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { return now > endTime; } }
16,226
137
// Internal auth
auctionHouse.addAuthorization(address(liquidationEngine)); auctionHouse.addAuthorization(globalSettlement);
auctionHouse.addAuthorization(address(liquidationEngine)); auctionHouse.addAuthorization(globalSettlement);
22,056
125
// The multiplication in the next line is necessary because when slicing multiples of 32 bytes (lengthmod == 0) the following copy loop was copying the origin's length and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for {
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for {
3,622
3
// will return whitelist end (quantity or time) return - uint of either number of whitelist mints ora timestamp ERC165 datum IMAX721Whitelist => 0x22699a34
function whitelistEnd() external view returns (uint);
function whitelistEnd() external view returns (uint);
5,363
349
// Calculates and prices in the time value of the option amount Option size period The option period in seconds (1 days <= period <= 90 days)return fee The premium size to be paid /
{ return (amount * _priceModifier(amount, period, pool)) / PRICE_DECIMALS / PRICE_MODIFIER_DECIMALS; }
{ return (amount * _priceModifier(amount, period, pool)) / PRICE_DECIMALS / PRICE_MODIFIER_DECIMALS; }
7,212
51
// Check to make sure the address is not zero address toTest The Address to make sure it&39;s not zero address /
modifier onlyNonZeroAddress(address toTest) { require(toTest != address(0), "Address must be non zero address"); _; }
modifier onlyNonZeroAddress(address toTest) { require(toTest != address(0), "Address must be non zero address"); _; }
8,180
89
// set's liquidity fee percentage /
function setLiquidityFeePercent(uint256 Fee) external onlyOwner { liquidityFee = Fee; _totalFee = liquidityFee.add(marketingFee).add(developmentFee).add(maintainanceFee); }
function setLiquidityFeePercent(uint256 Fee) external onlyOwner { liquidityFee = Fee; _totalFee = liquidityFee.add(marketingFee).add(developmentFee).add(maintainanceFee); }
57,439
32
// функция продажи токенов
function sell(uint _amountToSell) external { require( _amountToSell > 0 && // нельзя продать 0 токенов token.balanceOf(msg.sender) >= _amountToSell, // у юзера >= токенов чем он хочет продать "Incorrect amount!" ); // проверяем разрешил ли владелец списывать этиденьги магазину BibaCity uint allowance = token.allowance(msg.sender, address(this)); require(allowance >= _amountToSell, "Check allowsnce!"); // переводим токены магазину // address(this) - адресс контракта BibaCity token.transferFrom(msg.sender, address(this), _amountToSell); // переводим деньги за токены, тому кто их продал // есть еще call и send payable(msg.sender).transfer(_amountToSell); // событие о продаже emit Sold(_amountToSell, msg.sender); }
function sell(uint _amountToSell) external { require( _amountToSell > 0 && // нельзя продать 0 токенов token.balanceOf(msg.sender) >= _amountToSell, // у юзера >= токенов чем он хочет продать "Incorrect amount!" ); // проверяем разрешил ли владелец списывать этиденьги магазину BibaCity uint allowance = token.allowance(msg.sender, address(this)); require(allowance >= _amountToSell, "Check allowsnce!"); // переводим токены магазину // address(this) - адресс контракта BibaCity token.transferFrom(msg.sender, address(this), _amountToSell); // переводим деньги за токены, тому кто их продал // есть еще call и send payable(msg.sender).transfer(_amountToSell); // событие о продаже emit Sold(_amountToSell, msg.sender); }
30,725
407
// Borrow Fei from the Turbo Fuse Pool and deposit it into an authorized Vault./vault The Vault to deposit the borrowed Fei into./feiAmount The amount of Fei to borrow and supply into the Vault.
function boost(ERC4626 vault, uint256 feiAmount) external nonReentrant requiresAuth { // Ensure the Vault accepts Fei asset. require(vault.asset() == fei, "NOT_FEI"); // Call the Master where it will do extra validation // and update it's total count of funds used for boosting. master.onSafeBoost(asset, vault, feiAmount); // Increase the boost total proportionately. totalFeiBoosted += feiAmount; // Update the total Fei deposited into the Vault proportionately. getTotalFeiBoostedForVault[vault] += feiAmount; emit VaultBoosted(msg.sender, vault, feiAmount); // Borrow the Fei amount from the Fei cToken in the Turbo Fuse Pool. require(feiTurboCToken.borrow(feiAmount) == 0, "BORROW_FAILED"); // Approve the borrowed Fei to the specified Vault. fei.safeApprove(address(vault), feiAmount); // Deposit the Fei into the specified Vault. vault.deposit(feiAmount, address(this)); }
function boost(ERC4626 vault, uint256 feiAmount) external nonReentrant requiresAuth { // Ensure the Vault accepts Fei asset. require(vault.asset() == fei, "NOT_FEI"); // Call the Master where it will do extra validation // and update it's total count of funds used for boosting. master.onSafeBoost(asset, vault, feiAmount); // Increase the boost total proportionately. totalFeiBoosted += feiAmount; // Update the total Fei deposited into the Vault proportionately. getTotalFeiBoostedForVault[vault] += feiAmount; emit VaultBoosted(msg.sender, vault, feiAmount); // Borrow the Fei amount from the Fei cToken in the Turbo Fuse Pool. require(feiTurboCToken.borrow(feiAmount) == 0, "BORROW_FAILED"); // Approve the borrowed Fei to the specified Vault. fei.safeApprove(address(vault), feiAmount); // Deposit the Fei into the specified Vault. vault.deposit(feiAmount, address(this)); }
61,651
5
// TokenID
uint256 private TOKEN_ID = 0;
uint256 private TOKEN_ID = 0;
48,343
22
// Sets pixel. Given canvas can't be yet finished./
function setPixel(uint32 _canvasId, uint32 _index, uint8 _color) external { Canvas storage _canvas = _getCanvas(_canvasId); _setPixelInternal(_canvas, _canvasId, _index, _color); _finishCanvasIfNeeded(_canvas, _canvasId); }
function setPixel(uint32 _canvasId, uint32 _index, uint8 _color) external { Canvas storage _canvas = _getCanvas(_canvasId); _setPixelInternal(_canvas, _canvasId, _index, _color); _finishCanvasIfNeeded(_canvas, _canvasId); }
36,370
338
// Verify market is listed
Market storage market = markets[address(cToken)]; if (!market.isListed) { return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS); }
Market storage market = markets[address(cToken)]; if (!market.isListed) { return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS); }
7,529
123
// Flag this darknode for registration
store.appendDarknode( _darknodeID, msg.sender, _bond, _publicKey, currentEpoch.blocknumber + minimumEpochInterval, 0 ); numDarknodesNextEpoch += 1;
store.appendDarknode( _darknodeID, msg.sender, _bond, _publicKey, currentEpoch.blocknumber + minimumEpochInterval, 0 ); numDarknodesNextEpoch += 1;
22,976
7
// Constructor of the collection
constructor(address[] memory _team, uint[] memory _teamShares) PaymentSplitter(_team, _teamShares) { _teamLength = _team.length; _communityPrices[Version.LightTracker] = 0.04 ether; _communityPrices[Version.CompleteTracker] = 0.1 ether; _communityPrices[Version.ToolsTracker] = 0.1 ether; _communityPrices[Version.Full] = 0.2 ether; _individualPrices[Version.LightTracker] = 0.01 ether; _individualPrices[Version.CompleteTracker] = 0.02 ether; _individualPrices[Version.Full] = 0.03 ether; }
constructor(address[] memory _team, uint[] memory _teamShares) PaymentSplitter(_team, _teamShares) { _teamLength = _team.length; _communityPrices[Version.LightTracker] = 0.04 ether; _communityPrices[Version.CompleteTracker] = 0.1 ether; _communityPrices[Version.ToolsTracker] = 0.1 ether; _communityPrices[Version.Full] = 0.2 ether; _individualPrices[Version.LightTracker] = 0.01 ether; _individualPrices[Version.CompleteTracker] = 0.02 ether; _individualPrices[Version.Full] = 0.03 ether; }
34,965
65
// Transfer
_unwrap(to); emit Trade(maturity, msg.sender, to, baseOut.i128(), -(fyTokenIn.i128()));
_unwrap(to); emit Trade(maturity, msg.sender, to, baseOut.i128(), -(fyTokenIn.i128()));
25,399
113
// Writes a bytes20 to the buffer. Resizes if doing so would exceed thecapacity of the buffer.buf The buffer to append to.off The offset to write at.data The data to append. return The original buffer, for chaining./
function writeBytes20(buffer memory buf, uint off, bytes20 data) internal pure returns (buffer memory) { return write(buf, off, bytes32(data), 20); }
function writeBytes20(buffer memory buf, uint off, bytes20 data) internal pure returns (buffer memory) { return write(buf, off, bytes32(data), 20); }
3,046
775
// INTERNAL VARIABLES AND STORAGE/
enum Roles { Owner, // Can set the proposer. Proposer // Address that can make proposals. }
enum Roles { Owner, // Can set the proposer. Proposer // Address that can make proposals. }
10,113
14
// 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, it is bubbled up by thisfunction (like regular Solidity function calls). Returns the raw returned data. To convert to the expected return value, Requirements: - `target` must be a contract.- calling `target` with `data` must not revert. _Available since v3.1._ /
function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); }
function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); }
78,427
19
// Sets `amount` as the allowance of `spender` over the `owner` s tokens. This internal function is equivalent to `approve`, and can be used toe.g. set automatic allowances for certain subsystems, etc. Emits an {Approval} event. /
function _approve(address owner, address spender, uint256 amount) internal virtual {
function _approve(address owner, address spender, uint256 amount) internal virtual {
55,459
145
// 1 starts a pixel
isRow = false; state = RendererState.PIXEL_COL;
isRow = false; state = RendererState.PIXEL_COL;
3,219
58
// initializes a new SmartToken instance_name token name_symbol token short symbol, minimum 1 character_decimals for display purposes only/
constructor(string memory _name, string memory _symbol, uint8 _decimals) public ERC20Token(_name, _symbol, _decimals, 0)
constructor(string memory _name, string memory _symbol, uint8 _decimals) public ERC20Token(_name, _symbol, _decimals, 0)
75,310
43
// Checks msg.sender can transfer a token, by being owner, approved, or operator _tokenId uint ID of the token to validate /
modifier canTransfer(uint _tokenId) { require(isApprovedOrOwner(msg.sender, _tokenId)); _; }
modifier canTransfer(uint _tokenId) { require(isApprovedOrOwner(msg.sender, _tokenId)); _; }
5,468
7
// See {IERC165-supportsInterface}. /
function getSupportedInterfaces( address account, bytes4[] memory interfaceIds ) internal view returns (bool[] memory) {
function getSupportedInterfaces( address account, bytes4[] memory interfaceIds ) internal view returns (bool[] memory) {
1,169
39
// Returns the owner of the given record. The owner could also be get by using the function getSSP but in that case all record attributes are returned.
function getOwner(address key) constant returns(address) { return records[key].owner; }
function getOwner(address key) constant returns(address) { return records[key].owner; }
27,310
99
// FulfillmentApplier 0age FulfillmentApplier contains logic related to applying fulfillments,both as part of order matching (where offer items are matched toconsideration items) as well as fulfilling available orders (whereorder items and consideration items are independently aggregated). /
contract FulfillmentApplier is FulfillmentApplicationErrors { /** * @dev Internal pure function to match offer items to consideration items * on a group of orders via a supplied fulfillment. * * @param advancedOrders The orders to match. * @param offerComponents An array designating offer components to * match to consideration components. * @param considerationComponents An array designating consideration * components to match to offer components. * Note that each consideration amount must * be zero in order for the match operation * to be valid. * * @return execution The transfer performed as a result of the fulfillment. */ function _applyFulfillment( AdvancedOrder[] memory advancedOrders, FulfillmentComponent[] calldata offerComponents, FulfillmentComponent[] calldata considerationComponents ) internal pure returns (Execution memory execution) { // Ensure 1+ of both offer and consideration components are supplied. if ( offerComponents.length == 0 || considerationComponents.length == 0 ) { revert OfferAndConsiderationRequiredOnFulfillment(); } // Declare a new Execution struct. Execution memory considerationExecution; // Validate & aggregate consideration items to new Execution object. _aggregateValidFulfillmentConsiderationItems( advancedOrders, considerationComponents, considerationExecution ); // Retrieve the consideration item from the execution struct. ReceivedItem memory considerationItem = considerationExecution.item; // Recipient does not need to be specified because it will always be set // to that of the consideration. // Validate & aggregate offer items to Execution object. _aggregateValidFulfillmentOfferItems( advancedOrders, offerComponents, execution ); // Ensure offer and consideration share types, tokens and identifiers. if ( execution.item.itemType != considerationItem.itemType || execution.item.token != considerationItem.token || execution.item.identifier != considerationItem.identifier ) { revert MismatchedFulfillmentOfferAndConsiderationComponents(); } // If total consideration amount exceeds the offer amount... if (considerationItem.amount > execution.item.amount) { // Retrieve the first consideration component from the fulfillment. FulfillmentComponent memory targetComponent = ( considerationComponents[0] ); // Skip underflow check as the conditional being true implies that // considerationItem.amount > execution.item.amount. unchecked { // Add excess consideration item amount to original order array. advancedOrders[targetComponent.orderIndex] .parameters .consideration[targetComponent.itemIndex] .startAmount = (considerationItem.amount - execution.item.amount); } // Reduce total consideration amount to equal the offer amount. considerationItem.amount = execution.item.amount; } else { // Retrieve the first offer component from the fulfillment. FulfillmentComponent memory targetComponent = offerComponents[0]; // Skip underflow check as the conditional being false implies that // execution.item.amount >= considerationItem.amount. unchecked { // Add excess offer item amount to the original array of orders. advancedOrders[targetComponent.orderIndex] .parameters .offer[targetComponent.itemIndex] .startAmount = (execution.item.amount - considerationItem.amount); } // Reduce total offer amount to equal the consideration amount. execution.item.amount = considerationItem.amount; } // Reuse consideration recipient. execution.item.recipient = considerationItem.recipient; // Return the final execution that will be triggered for relevant items. return execution; // Execution(considerationItem, offerer, conduitKey); } /** * @dev Internal view function to aggregate offer or consideration items * from a group of orders into a single execution via a supplied array * of fulfillment components. Items that are not available to aggregate * will not be included in the aggregated execution. * * @param advancedOrders The orders to aggregate. * @param side The side (i.e. offer or consideration). * @param fulfillmentComponents An array designating item components to * aggregate if part of an available order. * @param fulfillerConduitKey A bytes32 value indicating what conduit, if * any, to source the fulfiller's token * approvals from. The zero hash signifies that * no conduit should be used, with approvals * set directly on this contract. * @param recipient The intended recipient for all received * items. * * @return execution The transfer performed as a result of the fulfillment. */ function _aggregateAvailable( AdvancedOrder[] memory advancedOrders, Side side, FulfillmentComponent[] memory fulfillmentComponents, bytes32 fulfillerConduitKey, address recipient ) internal view returns (Execution memory execution) { // Skip overflow / underflow checks; conditions checked or unreachable. unchecked { // Retrieve fulfillment components array length and place on stack. // Ensure at least one fulfillment component has been supplied. if (fulfillmentComponents.length == 0) { revert MissingFulfillmentComponentOnAggregation(side); } // If the fulfillment components are offer components... if (side == Side.OFFER) { // Set the supplied recipient on the execution item. execution.item.recipient = payable(recipient); // Return execution for aggregated items provided by offerer. _aggregateValidFulfillmentOfferItems( advancedOrders, fulfillmentComponents, execution ); } else { // Otherwise, fulfillment components are consideration // components. Return execution for aggregated items provided by // the fulfiller. _aggregateValidFulfillmentConsiderationItems( advancedOrders, fulfillmentComponents, execution ); // Set the caller as the offerer on the execution. execution.offerer = msg.sender; // Set fulfiller conduit key as the conduit key on execution. execution.conduitKey = fulfillerConduitKey; } // Set the offerer and recipient to null address if execution // amount is zero. This will cause the execution item to be skipped. if (execution.item.amount == 0) { execution.offerer = address(0); execution.item.recipient = payable(0); } } } /** * @dev Internal pure function to aggregate a group of offer items using * supplied directives on which component items are candidates for * aggregation, skipping items on orders that are not available. * * @param advancedOrders The orders to aggregate offer items from. * @param offerComponents An array of FulfillmentComponent structs * indicating the order index and item index of each * candidate offer item for aggregation. * @param execution The execution to apply the aggregation to. */ function _aggregateValidFulfillmentOfferItems( AdvancedOrder[] memory advancedOrders, FulfillmentComponent[] memory offerComponents, Execution memory execution ) internal pure { assembly { // Declare function for reverts on invalid fulfillment data. function throwInvalidFulfillmentComponentData() { // Store the InvalidFulfillmentComponentData error signature. mstore(0, InvalidFulfillmentComponentData_error_signature) // Return, supplying InvalidFulfillmentComponentData signature. revert(0, InvalidFulfillmentComponentData_error_len) } // Declare function for reverts due to arithmetic overflows. function throwOverflow() { // Store the Panic error signature. mstore(0, Panic_error_signature) // Store the arithmetic (0x11) panic code as initial argument. mstore(Panic_error_offset, Panic_arithmetic) // Return, supplying Panic signature and arithmetic code. revert(0, Panic_error_length) } // Get position in offerComponents head. let fulfillmentHeadPtr := add(offerComponents, OneWord) // Retrieve the order index using the fulfillment pointer. let orderIndex := mload(mload(fulfillmentHeadPtr)) // Ensure that the order index is not out of range. if iszero(lt(orderIndex, mload(advancedOrders))) { throwInvalidFulfillmentComponentData() } // Read advancedOrders[orderIndex] pointer from its array head. let orderPtr := mload( // Calculate head position of advancedOrders[orderIndex]. add(add(advancedOrders, OneWord), mul(orderIndex, OneWord)) ) // Read the pointer to OrderParameters from the AdvancedOrder. let paramsPtr := mload(orderPtr) // Load the offer array pointer. let offerArrPtr := mload( add(paramsPtr, OrderParameters_offer_head_offset) ) // Retrieve item index using an offset of the fulfillment pointer. let itemIndex := mload( add(mload(fulfillmentHeadPtr), Fulfillment_itemIndex_offset) ) // Only continue if the fulfillment is not invalid. if iszero(lt(itemIndex, mload(offerArrPtr))) { throwInvalidFulfillmentComponentData() } // Retrieve consideration item pointer using the item index. let offerItemPtr := mload( add( // Get pointer to beginning of receivedItem. add(offerArrPtr, OneWord), // Calculate offset to pointer for desired order. mul(itemIndex, OneWord) ) ) // Declare a variable for the final aggregated item amount. let amount := 0 // Create variable to track errors encountered with amount. let errorBuffer := 0 // Only add offer amount to execution amount on a nonzero numerator. if mload(add(orderPtr, AdvancedOrder_numerator_offset)) { // Retrieve amount pointer using consideration item pointer. let amountPtr := add(offerItemPtr, Common_amount_offset) // Set the amount. amount := mload(amountPtr) // Zero out amount on item to indicate it is credited. mstore(amountPtr, 0) // Buffer indicating whether issues were found. errorBuffer := iszero(amount) } // Retrieve the received item pointer. let receivedItemPtr := mload(execution) // Set the item type on the received item. mstore(receivedItemPtr, mload(offerItemPtr)) // Set the token on the received item. mstore( add(receivedItemPtr, Common_token_offset), mload(add(offerItemPtr, Common_token_offset)) ) // Set the identifier on the received item. mstore( add(receivedItemPtr, Common_identifier_offset), mload(add(offerItemPtr, Common_identifier_offset)) ) // Set the offerer on returned execution using order pointer. mstore(add(execution, Execution_offerer_offset), mload(paramsPtr)) // Set conduitKey on returned execution via offset of order pointer. mstore( add(execution, Execution_conduit_offset), mload(add(paramsPtr, OrderParameters_conduit_offset)) ) // Calculate the hash of (itemType, token, identifier). let dataHash := keccak256( receivedItemPtr, ReceivedItem_CommonParams_size ) // Get position one word past last element in head of array. let endPtr := add( offerComponents, mul(mload(offerComponents), OneWord) ) // Iterate over remaining offer components. // prettier-ignore for {} lt(fulfillmentHeadPtr, endPtr) {} { // Increment the pointer to the fulfillment head by one word. fulfillmentHeadPtr := add(fulfillmentHeadPtr, OneWord) // Get the order index using the fulfillment pointer. orderIndex := mload(mload(fulfillmentHeadPtr)) // Ensure the order index is in range. if iszero(lt(orderIndex, mload(advancedOrders))) { throwInvalidFulfillmentComponentData() } // Get pointer to AdvancedOrder element. orderPtr := mload( add( add(advancedOrders, OneWord), mul(orderIndex, OneWord) ) ) // Only continue if numerator is not zero. if iszero(mload( add(orderPtr, AdvancedOrder_numerator_offset) )) { continue } // Read the pointer to OrderParameters from the AdvancedOrder. paramsPtr := mload(orderPtr) // Load offer array pointer. offerArrPtr := mload( add( paramsPtr, OrderParameters_offer_head_offset ) ) // Get the item index using the fulfillment pointer. itemIndex := mload(add(mload(fulfillmentHeadPtr), OneWord)) // Throw if itemIndex is out of the range of array. if iszero( lt(itemIndex, mload(offerArrPtr)) ) { throwInvalidFulfillmentComponentData() } // Retrieve offer item pointer using index. offerItemPtr := mload( add( // Get pointer to beginning of receivedItem. add(offerArrPtr, OneWord), // Use offset to pointer for desired order. mul(itemIndex, OneWord) ) ) // Retrieve amount pointer using offer item pointer. let amountPtr := add( offerItemPtr, Common_amount_offset ) // Add offer amount to execution amount. let newAmount := add(amount, mload(amountPtr)) // Update error buffer: 1 = zero amount, 2 = overflow, 3 = both. errorBuffer := or( errorBuffer, or( shl(1, lt(newAmount, amount)), iszero(mload(amountPtr)) ) ) // Update the amount to the new, summed amount. amount := newAmount // Zero out amount on original item to indicate it is credited. mstore(amountPtr, 0) // Ensure the indicated item matches original item. if iszero( and( and( // The offerer must match on both items. eq( mload(paramsPtr), mload( add(execution, Execution_offerer_offset) ) ), // The conduit key must match on both items. eq( mload( add( paramsPtr, OrderParameters_conduit_offset ) ), mload( add( execution, Execution_conduit_offset ) ) ) ), // The itemType, token, and identifier must match. eq( dataHash, keccak256( offerItemPtr, ReceivedItem_CommonParams_size ) ) ) ) { // Throw if any of the requirements are not met. throwInvalidFulfillmentComponentData() } } // Write final amount to execution. mstore(add(mload(execution), Common_amount_offset), amount) // Determine whether the error buffer contains a nonzero error code. if errorBuffer { // If errorBuffer is 1, an item had an amount of zero. if eq(errorBuffer, 1) { // Store the MissingItemAmount error signature. mstore(0, MissingItemAmount_error_signature) // Return, supplying MissingItemAmount signature. revert(0, MissingItemAmount_error_len) } // If errorBuffer is not 1 or 0, the sum overflowed. // Panic! throwOverflow() } } }
contract FulfillmentApplier is FulfillmentApplicationErrors { /** * @dev Internal pure function to match offer items to consideration items * on a group of orders via a supplied fulfillment. * * @param advancedOrders The orders to match. * @param offerComponents An array designating offer components to * match to consideration components. * @param considerationComponents An array designating consideration * components to match to offer components. * Note that each consideration amount must * be zero in order for the match operation * to be valid. * * @return execution The transfer performed as a result of the fulfillment. */ function _applyFulfillment( AdvancedOrder[] memory advancedOrders, FulfillmentComponent[] calldata offerComponents, FulfillmentComponent[] calldata considerationComponents ) internal pure returns (Execution memory execution) { // Ensure 1+ of both offer and consideration components are supplied. if ( offerComponents.length == 0 || considerationComponents.length == 0 ) { revert OfferAndConsiderationRequiredOnFulfillment(); } // Declare a new Execution struct. Execution memory considerationExecution; // Validate & aggregate consideration items to new Execution object. _aggregateValidFulfillmentConsiderationItems( advancedOrders, considerationComponents, considerationExecution ); // Retrieve the consideration item from the execution struct. ReceivedItem memory considerationItem = considerationExecution.item; // Recipient does not need to be specified because it will always be set // to that of the consideration. // Validate & aggregate offer items to Execution object. _aggregateValidFulfillmentOfferItems( advancedOrders, offerComponents, execution ); // Ensure offer and consideration share types, tokens and identifiers. if ( execution.item.itemType != considerationItem.itemType || execution.item.token != considerationItem.token || execution.item.identifier != considerationItem.identifier ) { revert MismatchedFulfillmentOfferAndConsiderationComponents(); } // If total consideration amount exceeds the offer amount... if (considerationItem.amount > execution.item.amount) { // Retrieve the first consideration component from the fulfillment. FulfillmentComponent memory targetComponent = ( considerationComponents[0] ); // Skip underflow check as the conditional being true implies that // considerationItem.amount > execution.item.amount. unchecked { // Add excess consideration item amount to original order array. advancedOrders[targetComponent.orderIndex] .parameters .consideration[targetComponent.itemIndex] .startAmount = (considerationItem.amount - execution.item.amount); } // Reduce total consideration amount to equal the offer amount. considerationItem.amount = execution.item.amount; } else { // Retrieve the first offer component from the fulfillment. FulfillmentComponent memory targetComponent = offerComponents[0]; // Skip underflow check as the conditional being false implies that // execution.item.amount >= considerationItem.amount. unchecked { // Add excess offer item amount to the original array of orders. advancedOrders[targetComponent.orderIndex] .parameters .offer[targetComponent.itemIndex] .startAmount = (execution.item.amount - considerationItem.amount); } // Reduce total offer amount to equal the consideration amount. execution.item.amount = considerationItem.amount; } // Reuse consideration recipient. execution.item.recipient = considerationItem.recipient; // Return the final execution that will be triggered for relevant items. return execution; // Execution(considerationItem, offerer, conduitKey); } /** * @dev Internal view function to aggregate offer or consideration items * from a group of orders into a single execution via a supplied array * of fulfillment components. Items that are not available to aggregate * will not be included in the aggregated execution. * * @param advancedOrders The orders to aggregate. * @param side The side (i.e. offer or consideration). * @param fulfillmentComponents An array designating item components to * aggregate if part of an available order. * @param fulfillerConduitKey A bytes32 value indicating what conduit, if * any, to source the fulfiller's token * approvals from. The zero hash signifies that * no conduit should be used, with approvals * set directly on this contract. * @param recipient The intended recipient for all received * items. * * @return execution The transfer performed as a result of the fulfillment. */ function _aggregateAvailable( AdvancedOrder[] memory advancedOrders, Side side, FulfillmentComponent[] memory fulfillmentComponents, bytes32 fulfillerConduitKey, address recipient ) internal view returns (Execution memory execution) { // Skip overflow / underflow checks; conditions checked or unreachable. unchecked { // Retrieve fulfillment components array length and place on stack. // Ensure at least one fulfillment component has been supplied. if (fulfillmentComponents.length == 0) { revert MissingFulfillmentComponentOnAggregation(side); } // If the fulfillment components are offer components... if (side == Side.OFFER) { // Set the supplied recipient on the execution item. execution.item.recipient = payable(recipient); // Return execution for aggregated items provided by offerer. _aggregateValidFulfillmentOfferItems( advancedOrders, fulfillmentComponents, execution ); } else { // Otherwise, fulfillment components are consideration // components. Return execution for aggregated items provided by // the fulfiller. _aggregateValidFulfillmentConsiderationItems( advancedOrders, fulfillmentComponents, execution ); // Set the caller as the offerer on the execution. execution.offerer = msg.sender; // Set fulfiller conduit key as the conduit key on execution. execution.conduitKey = fulfillerConduitKey; } // Set the offerer and recipient to null address if execution // amount is zero. This will cause the execution item to be skipped. if (execution.item.amount == 0) { execution.offerer = address(0); execution.item.recipient = payable(0); } } } /** * @dev Internal pure function to aggregate a group of offer items using * supplied directives on which component items are candidates for * aggregation, skipping items on orders that are not available. * * @param advancedOrders The orders to aggregate offer items from. * @param offerComponents An array of FulfillmentComponent structs * indicating the order index and item index of each * candidate offer item for aggregation. * @param execution The execution to apply the aggregation to. */ function _aggregateValidFulfillmentOfferItems( AdvancedOrder[] memory advancedOrders, FulfillmentComponent[] memory offerComponents, Execution memory execution ) internal pure { assembly { // Declare function for reverts on invalid fulfillment data. function throwInvalidFulfillmentComponentData() { // Store the InvalidFulfillmentComponentData error signature. mstore(0, InvalidFulfillmentComponentData_error_signature) // Return, supplying InvalidFulfillmentComponentData signature. revert(0, InvalidFulfillmentComponentData_error_len) } // Declare function for reverts due to arithmetic overflows. function throwOverflow() { // Store the Panic error signature. mstore(0, Panic_error_signature) // Store the arithmetic (0x11) panic code as initial argument. mstore(Panic_error_offset, Panic_arithmetic) // Return, supplying Panic signature and arithmetic code. revert(0, Panic_error_length) } // Get position in offerComponents head. let fulfillmentHeadPtr := add(offerComponents, OneWord) // Retrieve the order index using the fulfillment pointer. let orderIndex := mload(mload(fulfillmentHeadPtr)) // Ensure that the order index is not out of range. if iszero(lt(orderIndex, mload(advancedOrders))) { throwInvalidFulfillmentComponentData() } // Read advancedOrders[orderIndex] pointer from its array head. let orderPtr := mload( // Calculate head position of advancedOrders[orderIndex]. add(add(advancedOrders, OneWord), mul(orderIndex, OneWord)) ) // Read the pointer to OrderParameters from the AdvancedOrder. let paramsPtr := mload(orderPtr) // Load the offer array pointer. let offerArrPtr := mload( add(paramsPtr, OrderParameters_offer_head_offset) ) // Retrieve item index using an offset of the fulfillment pointer. let itemIndex := mload( add(mload(fulfillmentHeadPtr), Fulfillment_itemIndex_offset) ) // Only continue if the fulfillment is not invalid. if iszero(lt(itemIndex, mload(offerArrPtr))) { throwInvalidFulfillmentComponentData() } // Retrieve consideration item pointer using the item index. let offerItemPtr := mload( add( // Get pointer to beginning of receivedItem. add(offerArrPtr, OneWord), // Calculate offset to pointer for desired order. mul(itemIndex, OneWord) ) ) // Declare a variable for the final aggregated item amount. let amount := 0 // Create variable to track errors encountered with amount. let errorBuffer := 0 // Only add offer amount to execution amount on a nonzero numerator. if mload(add(orderPtr, AdvancedOrder_numerator_offset)) { // Retrieve amount pointer using consideration item pointer. let amountPtr := add(offerItemPtr, Common_amount_offset) // Set the amount. amount := mload(amountPtr) // Zero out amount on item to indicate it is credited. mstore(amountPtr, 0) // Buffer indicating whether issues were found. errorBuffer := iszero(amount) } // Retrieve the received item pointer. let receivedItemPtr := mload(execution) // Set the item type on the received item. mstore(receivedItemPtr, mload(offerItemPtr)) // Set the token on the received item. mstore( add(receivedItemPtr, Common_token_offset), mload(add(offerItemPtr, Common_token_offset)) ) // Set the identifier on the received item. mstore( add(receivedItemPtr, Common_identifier_offset), mload(add(offerItemPtr, Common_identifier_offset)) ) // Set the offerer on returned execution using order pointer. mstore(add(execution, Execution_offerer_offset), mload(paramsPtr)) // Set conduitKey on returned execution via offset of order pointer. mstore( add(execution, Execution_conduit_offset), mload(add(paramsPtr, OrderParameters_conduit_offset)) ) // Calculate the hash of (itemType, token, identifier). let dataHash := keccak256( receivedItemPtr, ReceivedItem_CommonParams_size ) // Get position one word past last element in head of array. let endPtr := add( offerComponents, mul(mload(offerComponents), OneWord) ) // Iterate over remaining offer components. // prettier-ignore for {} lt(fulfillmentHeadPtr, endPtr) {} { // Increment the pointer to the fulfillment head by one word. fulfillmentHeadPtr := add(fulfillmentHeadPtr, OneWord) // Get the order index using the fulfillment pointer. orderIndex := mload(mload(fulfillmentHeadPtr)) // Ensure the order index is in range. if iszero(lt(orderIndex, mload(advancedOrders))) { throwInvalidFulfillmentComponentData() } // Get pointer to AdvancedOrder element. orderPtr := mload( add( add(advancedOrders, OneWord), mul(orderIndex, OneWord) ) ) // Only continue if numerator is not zero. if iszero(mload( add(orderPtr, AdvancedOrder_numerator_offset) )) { continue } // Read the pointer to OrderParameters from the AdvancedOrder. paramsPtr := mload(orderPtr) // Load offer array pointer. offerArrPtr := mload( add( paramsPtr, OrderParameters_offer_head_offset ) ) // Get the item index using the fulfillment pointer. itemIndex := mload(add(mload(fulfillmentHeadPtr), OneWord)) // Throw if itemIndex is out of the range of array. if iszero( lt(itemIndex, mload(offerArrPtr)) ) { throwInvalidFulfillmentComponentData() } // Retrieve offer item pointer using index. offerItemPtr := mload( add( // Get pointer to beginning of receivedItem. add(offerArrPtr, OneWord), // Use offset to pointer for desired order. mul(itemIndex, OneWord) ) ) // Retrieve amount pointer using offer item pointer. let amountPtr := add( offerItemPtr, Common_amount_offset ) // Add offer amount to execution amount. let newAmount := add(amount, mload(amountPtr)) // Update error buffer: 1 = zero amount, 2 = overflow, 3 = both. errorBuffer := or( errorBuffer, or( shl(1, lt(newAmount, amount)), iszero(mload(amountPtr)) ) ) // Update the amount to the new, summed amount. amount := newAmount // Zero out amount on original item to indicate it is credited. mstore(amountPtr, 0) // Ensure the indicated item matches original item. if iszero( and( and( // The offerer must match on both items. eq( mload(paramsPtr), mload( add(execution, Execution_offerer_offset) ) ), // The conduit key must match on both items. eq( mload( add( paramsPtr, OrderParameters_conduit_offset ) ), mload( add( execution, Execution_conduit_offset ) ) ) ), // The itemType, token, and identifier must match. eq( dataHash, keccak256( offerItemPtr, ReceivedItem_CommonParams_size ) ) ) ) { // Throw if any of the requirements are not met. throwInvalidFulfillmentComponentData() } } // Write final amount to execution. mstore(add(mload(execution), Common_amount_offset), amount) // Determine whether the error buffer contains a nonzero error code. if errorBuffer { // If errorBuffer is 1, an item had an amount of zero. if eq(errorBuffer, 1) { // Store the MissingItemAmount error signature. mstore(0, MissingItemAmount_error_signature) // Return, supplying MissingItemAmount signature. revert(0, MissingItemAmount_error_len) } // If errorBuffer is not 1 or 0, the sum overflowed. // Panic! throwOverflow() } } }
14,368
10
// Assert that the given domain has a xApp Router registered and return its address _domain The domain of the chain for which to get the xApp Routerreturn _remote The address of the remote xApp Router on _domain /
function _mustHaveRemote(uint32 _domain) internal view returns (bytes32 _remote)
function _mustHaveRemote(uint32 _domain) internal view returns (bytes32 _remote)
14,587
177
// Used to track which version of `StrategyAPI` this Strategy implements. The Strategy's version must match the Vault's `API_VERSION`.return A string which holds the current API version of this contract. /
function apiVersion() public pure returns (string memory) { return "0.4.2"; }
function apiVersion() public pure returns (string memory) { return "0.4.2"; }
5,009
297
// users should stake treasury through transfer proxy to avoid setting allowance to this contract for staked tokens
function deposit(uint _tokenMoveAmount, uint _tokenMoveEthAmount) public { depositInternal(msg.sender, _tokenMoveAmount, _tokenMoveEthAmount, false); }
function deposit(uint _tokenMoveAmount, uint _tokenMoveEthAmount) public { depositInternal(msg.sender, _tokenMoveAmount, _tokenMoveEthAmount, false); }
76,474
154
// Burn receipt tokens from some user from Address of the user that gets the receipt tokens burn amount Amount of receipt tokens that will get burned /
function burn(address from, uint256 amount) public override onlySameChain onlyOwner { _burn(from, amount); }
function burn(address from, uint256 amount) public override onlySameChain onlyOwner { _burn(from, amount); }
41,581
182
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
5,254
9
// abi encoding offset
mstore(0x20, 0x20)
mstore(0x20, 0x20)
23,661
52
// Transfer tokens when not paused /
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); }
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); }
20,781
363
// startUpgradePoll(): open a poll on making _proposal the new ecliptic
function startUpgradePoll(address _proposal) external onlyOwner
function startUpgradePoll(address _proposal) external onlyOwner
51,985
50
// lowered due to lower initial liquidity amount.
maxTransactionAmount = _tTotal * 25 / 10000; // 0.25% maxTransactionAmountTxn minimumTokensBeforeSwap = _tTotal * 5 / 10000; // 0.05% swap tokens amount marketingAddress = payable(0x92CE6Bd83C8fd4F97cc14E3186D82E0b0271a48F); // Marketing Address _isExcludedFromFee[newOwner] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[marketingAddress] = true; excludeFromMaxTransaction(newOwner, true);
maxTransactionAmount = _tTotal * 25 / 10000; // 0.25% maxTransactionAmountTxn minimumTokensBeforeSwap = _tTotal * 5 / 10000; // 0.05% swap tokens amount marketingAddress = payable(0x92CE6Bd83C8fd4F97cc14E3186D82E0b0271a48F); // Marketing Address _isExcludedFromFee[newOwner] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[marketingAddress] = true; excludeFromMaxTransaction(newOwner, true);
21,421
138
// This contract provide core operations for Aave
abstract contract AaveCore { //solhint-disable-next-line const-name-snakecase StakedAave public constant stkAAVE = StakedAave(0x4da27a545c0c5B758a6BA100e3a049001de870f5); address public constant AAVE = 0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9; AaveLendingPoolAddressesProvider public aaveAddressesProvider = AaveLendingPoolAddressesProvider(0xB53C1a33016B2DC2fF3653530bfF1848a515c8c5); AaveLendingPool public aaveLendingPool; AaveProtocolDataProvider public aaveProtocolDataProvider; AToken internal immutable aToken; bytes32 private constant AAVE_PROVIDER_ID = 0x0100000000000000000000000000000000000000000000000000000000000000; event UpdatedAddressesProvider(address _previousProvider, address _newProvider); constructor(address _receiptToken) { require(_receiptToken != address(0), "aToken-address-is-zero"); aToken = AToken(_receiptToken); aaveLendingPool = AaveLendingPool(aaveAddressesProvider.getLendingPool()); aaveProtocolDataProvider = AaveProtocolDataProvider(aaveAddressesProvider.getAddress(AAVE_PROVIDER_ID)); } ///////////////////////// External access functions ///////////////////////// /** * @notice Initiate cooldown to unstake aave. * @dev We only want to call this function when cooldown is expired and * that's the reason we have 'if' condition. * @dev Child contract should expose this function as external and onlyKeeper */ function _startCooldown() internal returns (bool) { if (canStartCooldown()) { stkAAVE.cooldown(); return true; } return false; } /** * @notice Unstake Aave from stakedAave contract * @dev We want to unstake as soon as favorable condition exit * @dev No guarding condition thus this call can fail, if we can't unstake. * @dev Child contract should expose this function as external and onlyKeeper */ function _unstakeAave() internal { stkAAVE.redeem(address(this), type(uint256).max); } /** * @notice Update address of Aave LendingPoolAddressesProvider * @dev We will use new address to fetch lendingPool address and update that too. * @dev Child contract should expose this function as external and onlyGovernor */ function _updateAddressesProvider(address _newAddressesProvider) internal { require(_newAddressesProvider != address(0), "provider-address-is-zero"); require(address(aaveAddressesProvider) != _newAddressesProvider, "same-addresses-provider"); emit UpdatedAddressesProvider(address(aaveAddressesProvider), _newAddressesProvider); aaveAddressesProvider = AaveLendingPoolAddressesProvider(_newAddressesProvider); aaveLendingPool = AaveLendingPool(aaveAddressesProvider.getLendingPool()); aaveProtocolDataProvider = AaveProtocolDataProvider(aaveAddressesProvider.getAddress(AAVE_PROVIDER_ID)); } /////////////////////////////////////////////////////////////////////////// /// @notice Returns true if Aave can be unstaked function canUnstake() external view returns (bool) { (, uint256 _cooldownEnd, uint256 _unstakeEnd) = cooldownData(); return _canUnstake(_cooldownEnd, _unstakeEnd); } /// @notice Returns true if we should start cooldown function canStartCooldown() public view returns (bool) { (uint256 _cooldownStart, , uint256 _unstakeEnd) = cooldownData(); return _canStartCooldown(_cooldownStart, _unstakeEnd); } /// @notice Return cooldown related timestamps function cooldownData() public view returns ( uint256 _cooldownStart, uint256 _cooldownEnd, uint256 _unstakeEnd ) { _cooldownStart = stkAAVE.stakersCooldowns(address(this)); _cooldownEnd = _cooldownStart + stkAAVE.COOLDOWN_SECONDS(); _unstakeEnd = _cooldownEnd + stkAAVE.UNSTAKE_WINDOW(); } /** * @notice Claim Aave. Also unstake all Aave if favorable condition exits or start cooldown. * @dev If we unstake all Aave, we can't start cooldown because it requires StakedAave balance. * @dev DO NOT convert 'if else' to 2 'if's as we are reading cooldown state once to save gas. */ function _claimAave() internal returns (uint256) { (uint256 _cooldownStart, uint256 _cooldownEnd, uint256 _unstakeEnd) = cooldownData(); if (_cooldownStart == 0 || block.timestamp > _unstakeEnd) { // claim stkAave when its first rebalance or unstake period passed. address[] memory _assets = new address[](1); _assets[0] = address(aToken); IAaveIncentivesController(aToken.getIncentivesController()).claimRewards( _assets, type(uint256).max, address(this) ); } // Fetch and check again for next action. (_cooldownStart, _cooldownEnd, _unstakeEnd) = cooldownData(); if (_canUnstake(_cooldownEnd, _unstakeEnd)) { stkAAVE.redeem(address(this), type(uint256).max); } else if (_canStartCooldown(_cooldownStart, _unstakeEnd)) { stkAAVE.cooldown(); } stkAAVE.claimRewards(address(this), type(uint256).max); return IERC20(AAVE).balanceOf(address(this)); } /// @notice Deposit asset into Aave function _deposit(address _asset, uint256 _amount) internal { if (_amount != 0) { aaveLendingPool.deposit(_asset, _amount, address(this), 0); } } /** * @notice Safe withdraw will make sure to check asking amount against available amount. * @dev Check we have enough aToken and liquidity to support this withdraw * @param _asset Address of asset to withdraw * @param _to Address that will receive collateral token. * @param _amount Amount of collateral to withdraw. * @return Actual collateral withdrawn */ function _safeWithdraw( address _asset, address _to, uint256 _amount ) internal returns (uint256) { uint256 _aTokenBalance = aToken.balanceOf(address(this)); // If Vesper becomes large liquidity provider in Aave(This happened in past in vUSDC 1.0) // In this case we might have more aToken compare to available liquidity in Aave and any // withdraw asking more than available liquidity will fail. To do safe withdraw, check // _amount against available liquidity. (uint256 _availableLiquidity, , , , , , , , , ) = aaveProtocolDataProvider.getReserveData(_asset); // Get minimum of _amount, _aTokenBalance and _availableLiquidity return _withdraw(_asset, _to, _min(_amount, _min(_aTokenBalance, _availableLiquidity))); } /** * @notice Withdraw given amount of collateral from Aave to given address * @param _asset Address of asset to withdraw * @param _to Address that will receive collateral token. * @param _amount Amount of collateral to withdraw. * @return Actual collateral withdrawn */ function _withdraw( address _asset, address _to, uint256 _amount ) internal returns (uint256) { if (_amount != 0) { require(aaveLendingPool.withdraw(_asset, _amount, _to) == _amount, "withdrawn-amount-is-not-correct"); } return _amount; } /** * @dev Return true, only if we have StakedAave balance and either cooldown expired or cooldown is zero * @dev If we are in cooldown period we cannot unstake Aave. But our cooldown is still valid so we do * not want to reset/start cooldown. */ function _canStartCooldown(uint256 _cooldownStart, uint256 _unstakeEnd) internal view returns (bool) { return stkAAVE.balanceOf(address(this)) != 0 && (_cooldownStart == 0 || block.timestamp > _unstakeEnd); } /// @dev Return true, if cooldown is over and we are in unstake window. function _canUnstake(uint256 _cooldownEnd, uint256 _unstakeEnd) internal view returns (bool) { return block.timestamp > _cooldownEnd && block.timestamp <= _unstakeEnd; } /// @dev Check whether given token is reserved or not. Reserved tokens are not allowed to sweep. function _isReservedToken(address _token) internal view returns (bool) { return _token == address(aToken) || _token == AAVE || _token == address(stkAAVE); } /// @notice Returns minimum of 2 given numbers function _min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } }
abstract contract AaveCore { //solhint-disable-next-line const-name-snakecase StakedAave public constant stkAAVE = StakedAave(0x4da27a545c0c5B758a6BA100e3a049001de870f5); address public constant AAVE = 0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9; AaveLendingPoolAddressesProvider public aaveAddressesProvider = AaveLendingPoolAddressesProvider(0xB53C1a33016B2DC2fF3653530bfF1848a515c8c5); AaveLendingPool public aaveLendingPool; AaveProtocolDataProvider public aaveProtocolDataProvider; AToken internal immutable aToken; bytes32 private constant AAVE_PROVIDER_ID = 0x0100000000000000000000000000000000000000000000000000000000000000; event UpdatedAddressesProvider(address _previousProvider, address _newProvider); constructor(address _receiptToken) { require(_receiptToken != address(0), "aToken-address-is-zero"); aToken = AToken(_receiptToken); aaveLendingPool = AaveLendingPool(aaveAddressesProvider.getLendingPool()); aaveProtocolDataProvider = AaveProtocolDataProvider(aaveAddressesProvider.getAddress(AAVE_PROVIDER_ID)); } ///////////////////////// External access functions ///////////////////////// /** * @notice Initiate cooldown to unstake aave. * @dev We only want to call this function when cooldown is expired and * that's the reason we have 'if' condition. * @dev Child contract should expose this function as external and onlyKeeper */ function _startCooldown() internal returns (bool) { if (canStartCooldown()) { stkAAVE.cooldown(); return true; } return false; } /** * @notice Unstake Aave from stakedAave contract * @dev We want to unstake as soon as favorable condition exit * @dev No guarding condition thus this call can fail, if we can't unstake. * @dev Child contract should expose this function as external and onlyKeeper */ function _unstakeAave() internal { stkAAVE.redeem(address(this), type(uint256).max); } /** * @notice Update address of Aave LendingPoolAddressesProvider * @dev We will use new address to fetch lendingPool address and update that too. * @dev Child contract should expose this function as external and onlyGovernor */ function _updateAddressesProvider(address _newAddressesProvider) internal { require(_newAddressesProvider != address(0), "provider-address-is-zero"); require(address(aaveAddressesProvider) != _newAddressesProvider, "same-addresses-provider"); emit UpdatedAddressesProvider(address(aaveAddressesProvider), _newAddressesProvider); aaveAddressesProvider = AaveLendingPoolAddressesProvider(_newAddressesProvider); aaveLendingPool = AaveLendingPool(aaveAddressesProvider.getLendingPool()); aaveProtocolDataProvider = AaveProtocolDataProvider(aaveAddressesProvider.getAddress(AAVE_PROVIDER_ID)); } /////////////////////////////////////////////////////////////////////////// /// @notice Returns true if Aave can be unstaked function canUnstake() external view returns (bool) { (, uint256 _cooldownEnd, uint256 _unstakeEnd) = cooldownData(); return _canUnstake(_cooldownEnd, _unstakeEnd); } /// @notice Returns true if we should start cooldown function canStartCooldown() public view returns (bool) { (uint256 _cooldownStart, , uint256 _unstakeEnd) = cooldownData(); return _canStartCooldown(_cooldownStart, _unstakeEnd); } /// @notice Return cooldown related timestamps function cooldownData() public view returns ( uint256 _cooldownStart, uint256 _cooldownEnd, uint256 _unstakeEnd ) { _cooldownStart = stkAAVE.stakersCooldowns(address(this)); _cooldownEnd = _cooldownStart + stkAAVE.COOLDOWN_SECONDS(); _unstakeEnd = _cooldownEnd + stkAAVE.UNSTAKE_WINDOW(); } /** * @notice Claim Aave. Also unstake all Aave if favorable condition exits or start cooldown. * @dev If we unstake all Aave, we can't start cooldown because it requires StakedAave balance. * @dev DO NOT convert 'if else' to 2 'if's as we are reading cooldown state once to save gas. */ function _claimAave() internal returns (uint256) { (uint256 _cooldownStart, uint256 _cooldownEnd, uint256 _unstakeEnd) = cooldownData(); if (_cooldownStart == 0 || block.timestamp > _unstakeEnd) { // claim stkAave when its first rebalance or unstake period passed. address[] memory _assets = new address[](1); _assets[0] = address(aToken); IAaveIncentivesController(aToken.getIncentivesController()).claimRewards( _assets, type(uint256).max, address(this) ); } // Fetch and check again for next action. (_cooldownStart, _cooldownEnd, _unstakeEnd) = cooldownData(); if (_canUnstake(_cooldownEnd, _unstakeEnd)) { stkAAVE.redeem(address(this), type(uint256).max); } else if (_canStartCooldown(_cooldownStart, _unstakeEnd)) { stkAAVE.cooldown(); } stkAAVE.claimRewards(address(this), type(uint256).max); return IERC20(AAVE).balanceOf(address(this)); } /// @notice Deposit asset into Aave function _deposit(address _asset, uint256 _amount) internal { if (_amount != 0) { aaveLendingPool.deposit(_asset, _amount, address(this), 0); } } /** * @notice Safe withdraw will make sure to check asking amount against available amount. * @dev Check we have enough aToken and liquidity to support this withdraw * @param _asset Address of asset to withdraw * @param _to Address that will receive collateral token. * @param _amount Amount of collateral to withdraw. * @return Actual collateral withdrawn */ function _safeWithdraw( address _asset, address _to, uint256 _amount ) internal returns (uint256) { uint256 _aTokenBalance = aToken.balanceOf(address(this)); // If Vesper becomes large liquidity provider in Aave(This happened in past in vUSDC 1.0) // In this case we might have more aToken compare to available liquidity in Aave and any // withdraw asking more than available liquidity will fail. To do safe withdraw, check // _amount against available liquidity. (uint256 _availableLiquidity, , , , , , , , , ) = aaveProtocolDataProvider.getReserveData(_asset); // Get minimum of _amount, _aTokenBalance and _availableLiquidity return _withdraw(_asset, _to, _min(_amount, _min(_aTokenBalance, _availableLiquidity))); } /** * @notice Withdraw given amount of collateral from Aave to given address * @param _asset Address of asset to withdraw * @param _to Address that will receive collateral token. * @param _amount Amount of collateral to withdraw. * @return Actual collateral withdrawn */ function _withdraw( address _asset, address _to, uint256 _amount ) internal returns (uint256) { if (_amount != 0) { require(aaveLendingPool.withdraw(_asset, _amount, _to) == _amount, "withdrawn-amount-is-not-correct"); } return _amount; } /** * @dev Return true, only if we have StakedAave balance and either cooldown expired or cooldown is zero * @dev If we are in cooldown period we cannot unstake Aave. But our cooldown is still valid so we do * not want to reset/start cooldown. */ function _canStartCooldown(uint256 _cooldownStart, uint256 _unstakeEnd) internal view returns (bool) { return stkAAVE.balanceOf(address(this)) != 0 && (_cooldownStart == 0 || block.timestamp > _unstakeEnd); } /// @dev Return true, if cooldown is over and we are in unstake window. function _canUnstake(uint256 _cooldownEnd, uint256 _unstakeEnd) internal view returns (bool) { return block.timestamp > _cooldownEnd && block.timestamp <= _unstakeEnd; } /// @dev Check whether given token is reserved or not. Reserved tokens are not allowed to sweep. function _isReservedToken(address _token) internal view returns (bool) { return _token == address(aToken) || _token == AAVE || _token == address(stkAAVE); } /// @notice Returns minimum of 2 given numbers function _min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } }
61,484
51
// Withdraws any ERC20 tokens sent here by mistake/
function rescueTokens(address _token) external onlyOwner() { uint256 amount = IERC20(_token).balanceOf(address(this)); IERC20(_token).transfer(owner(), amount); }
function rescueTokens(address _token) external onlyOwner() { uint256 amount = IERC20(_token).balanceOf(address(this)); IERC20(_token).transfer(owner(), amount); }
10,906
22
// Ensure the provided reward amount is not more than the balance in the contract. This keeps the reward rate in the right range, preventing overflows due to very high values of rewardRate in the earned and rewardsPerToken functions; Reward + leftover must be less than 2^256 / 10^18 to avoid overflow.
uint balance = rewardsToken.balanceOf(address(this)); require(rewardRate <= balance.div(rewardsDuration), "Provided reward too high"); lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(rewardsDuration); emit RewardAdded(reward);
uint balance = rewardsToken.balanceOf(address(this)); require(rewardRate <= balance.div(rewardsDuration), "Provided reward too high"); lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(rewardsDuration); emit RewardAdded(reward);
19,960
4
// Used to stop deposits from contracts (avoid accidentally lost tokens)
require(!Address.isContract(msg.sender), "Account not EOA"); _;
require(!Address.isContract(msg.sender), "Account not EOA"); _;
20,157
189
// keep leftover ETH for buyback
(success,) = address(buyBackWallet).call{value: address(this).balance}("");
(success,) = address(buyBackWallet).call{value: address(this).balance}("");
19,392
3
// non-value-transfer getters
function getRewardDivisor() noEther constant returns (uint) { return rewardDivisor; }
function getRewardDivisor() noEther constant returns (uint) { return rewardDivisor; }
56,670
51
// Sum up cumulative power
cumulativePower = cumulativePower + _currentValset.powers[i];
cumulativePower = cumulativePower + _currentValset.powers[i];
56,854
6
// Verify that an account is in the winners list for a specific raffle/ using a merkle proof and the raffle's previous public commitments. This is/ a view-only function that does not record if a winner has already claimed/ their win; that is left up to the caller to handle./raffleId ID of the raffle to check against/leafHash Hash of the leaf value that represents the participant/proof Merkle subproof (hashes)/originalIndex Original leaf index in merkle tree, part of merkle proof/ return isWinner true if claiming account is indeed a winner/ return permutedIndex winning (shuffled) index
function verifyRaffleWinner( uint256 raffleId, bytes32 leafHash, bytes32[] calldata proof, uint256 originalIndex ) external view returns (bool isWinner, uint256 permutedIndex);
function verifyRaffleWinner( uint256 raffleId, bytes32 leafHash, bytes32[] calldata proof, uint256 originalIndex ) external view returns (bool isWinner, uint256 permutedIndex);
38,683
69
// if not the same then replace _selector with lastSelector
if (selectorPosition != lastSelectorPosition) { bytes4 lastSelector = ds.facetFunctionSelectors[_facetAddress].functionSelectors[ lastSelectorPosition ]; ds.facetFunctionSelectors[_facetAddress].functionSelectors[ selectorPosition ] = lastSelector; ds.selectorToFacetAndPosition[lastSelector] .functionSelectorPosition = uint16(selectorPosition);
if (selectorPosition != lastSelectorPosition) { bytes4 lastSelector = ds.facetFunctionSelectors[_facetAddress].functionSelectors[ lastSelectorPosition ]; ds.facetFunctionSelectors[_facetAddress].functionSelectors[ selectorPosition ] = lastSelector; ds.selectorToFacetAndPosition[lastSelector] .functionSelectorPosition = uint16(selectorPosition);
12,240
163
// the most significant bit of the sequence corresponds to the offset of the relevant bucket
uint256 msb; for (uint256 i = 128; i > 0; i >>= 1) { if (sequence >> i > 0) { msb += i; sequence >>= i; }
uint256 msb; for (uint256 i = 128; i > 0; i >>= 1) { if (sequence >> i > 0) { msb += i; sequence >>= i; }
48,312
43
// The random number from Oraclizes decides the game result.If Oraclize sends a message instead of the requested number, the bet is returned to the player./
function __callback(bytes32 myid, string result) { if (msg.sender != oraclize_cbAddress()) throw; if (players[myid]==0x0) throw; uint random = convertToInt(result); if(random==0){//result not a number, return bet if(!players[myid].send(bets[myid])) throw; gameResult(101,players[myid]); delete players[myid]; return; } uint range = 0; for(uint i = 0; i<probabilities.length; i++){ range+=probabilities[i]; if(random<=range){ if(!players[myid].send(bets[myid]/100*prizes[i])){ gameResult(100,players[myid]);//100 -> error throw; } gameResult(i, players[myid]); delete players[myid]; return; } } //else player loses everything gameResult(probabilities.length, players[myid]); delete players[myid]; }
function __callback(bytes32 myid, string result) { if (msg.sender != oraclize_cbAddress()) throw; if (players[myid]==0x0) throw; uint random = convertToInt(result); if(random==0){//result not a number, return bet if(!players[myid].send(bets[myid])) throw; gameResult(101,players[myid]); delete players[myid]; return; } uint range = 0; for(uint i = 0; i<probabilities.length; i++){ range+=probabilities[i]; if(random<=range){ if(!players[myid].send(bets[myid]/100*prizes[i])){ gameResult(100,players[myid]);//100 -> error throw; } gameResult(i, players[myid]); delete players[myid]; return; } } //else player loses everything gameResult(probabilities.length, players[myid]); delete players[myid]; }
29,504
73
// Determine if address is an administrator. _administrator Address of the administrator to be checked. /
function isAdministrator(address _administrator) public view returns (bool) { return hasRole(_administrator, ROLE_ADMINISTRATOR); }
function isAdministrator(address _administrator) public view returns (bool) { return hasRole(_administrator, ROLE_ADMINISTRATOR); }
56,961
35
// shortcut for blocks newer than the latest checkpoint == current balance
if (epochId >= checkpoints[max].epochId) { return getCheckpointEffectiveBalance(checkpoints[max]); }
if (epochId >= checkpoints[max].epochId) { return getCheckpointEffectiveBalance(checkpoints[max]); }
42,662
6
// Sends an arbitrary message from one domain to anothervia the safe bridge mechanism, which relies on the chain's native bridge. It is unnecessary during normal operations but essential only in case of challenge. It may require some ETH (or whichever native token) to pay for the bridging cost,depending on the underlying safe bridge._receiver The L1 contract address who will receive the calldata _calldata The receiving domain encoded message data. /
function sendSafe(address _receiver, bytes memory _calldata) external payable { // The safe bridge sends the encoded data to the FastBridgeReceiver // in order for the FastBridgeReceiver to resolve any potential // challenges and then forwards the message to the actual // intended recipient encoded in `data` // TODO: For this encodedData needs to be wrapped into an // IFastBridgeReceiver function. // TODO: add access checks for this on the FastBridgeReceiver. // TODO: how much ETH should be provided for bridging? add an ISafeBridge.bridgingCost() bytes memory encodedData = abi.encode(_receiver, _calldata); safebridge.sendSafe{value: msg.value}(address(fastBridgeReceiver), encodedData); }
function sendSafe(address _receiver, bytes memory _calldata) external payable { // The safe bridge sends the encoded data to the FastBridgeReceiver // in order for the FastBridgeReceiver to resolve any potential // challenges and then forwards the message to the actual // intended recipient encoded in `data` // TODO: For this encodedData needs to be wrapped into an // IFastBridgeReceiver function. // TODO: add access checks for this on the FastBridgeReceiver. // TODO: how much ETH should be provided for bridging? add an ISafeBridge.bridgingCost() bytes memory encodedData = abi.encode(_receiver, _calldata); safebridge.sendSafe{value: msg.value}(address(fastBridgeReceiver), encodedData); }
364
22
// Calculate amount by exchange rate/_keyId key id of the token id list/_tokenId id of the token to be added to the tokens list of the given key id/_amout amount
function _exchangedAmountOf( uint256 _keyId, uint256 _tokenId, uint256 _amout
function _exchangedAmountOf( uint256 _keyId, uint256 _tokenId, uint256 _amout
24,906
35
// Modifier to make a function callable only when the contract is paused. Requirements: - The contract must be paused. /
modifier whenPaused() { require(paused(), "Pausable: not paused"); _; }
modifier whenPaused() { require(paused(), "Pausable: not paused"); _; }
258
199
// The Awoo Studios account where fees are sent
address public awooStudiosAccount; address[2] private _admins; bool private _adminsSet;
address public awooStudiosAccount; address[2] private _admins; bool private _adminsSet;
39,652
164
// Assembly for more efficient computing: keccak256(abi.encodePacked( _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH, keccak256(bytes(name)), keccak256(bytes(version)), chainId, uint256(verifyingContract) ))
assembly {
assembly {
7,540
5
// mayoria de 2/3
} else if (_majority == 4) {
} else if (_majority == 4) {
21,802
4
// Want "initialize" so can use proxy
function initialize(string memory _name, string memory _symbol, uint256 _maxTokens, uint256 _tokenPrice, address _artistFundsAddress, uint256 _artistTokenRoyalty) public initializer { __ERC721_init(_name, _symbol); __ERC721Enumerable_init_unchained(); __Ownable_init(); __Pausable_init(); isArtCodeSealed = false; // Fixed, but can be adjusted for each proxy contract with setPlatformFields. sunflowerMintPercent = 29; sunflowerTokenRoyalty = 31; // Every 31th token, so 3.22%. Use a prime to reduce collisions. artistBalance = 0; tokenBaseURI = ""; // Use these methods so the checks of those methods will run. setArtistFields(_artistTokenRoyalty); setMaxTokens(_maxTokens); setTokenPrice(_tokenPrice); currentTokenID = 0; artistFundsAddress = payable(_artistFundsAddress); privilegedMinterAddress = address(0); artistAddress = owner(); // initialize to the deployer address, and don't let it be changed pauseNormalMinting(); }
function initialize(string memory _name, string memory _symbol, uint256 _maxTokens, uint256 _tokenPrice, address _artistFundsAddress, uint256 _artistTokenRoyalty) public initializer { __ERC721_init(_name, _symbol); __ERC721Enumerable_init_unchained(); __Ownable_init(); __Pausable_init(); isArtCodeSealed = false; // Fixed, but can be adjusted for each proxy contract with setPlatformFields. sunflowerMintPercent = 29; sunflowerTokenRoyalty = 31; // Every 31th token, so 3.22%. Use a prime to reduce collisions. artistBalance = 0; tokenBaseURI = ""; // Use these methods so the checks of those methods will run. setArtistFields(_artistTokenRoyalty); setMaxTokens(_maxTokens); setTokenPrice(_tokenPrice); currentTokenID = 0; artistFundsAddress = payable(_artistFundsAddress); privilegedMinterAddress = address(0); artistAddress = owner(); // initialize to the deployer address, and don't let it be changed pauseNormalMinting(); }
26,703
29
// Executes a buy order of a specific product.storeName the name of the storeproductIndex the id of the productquantity the quantity of products to purchase/
function buy(string storeName, uint256 productIndex, uint256 quantity) public stopInEmergency { require(storesByName[storeName] != address(0)); storesByName[storeName].sell(msg.sender, productIndex, quantity); }
function buy(string storeName, uint256 productIndex, uint256 quantity) public stopInEmergency { require(storesByName[storeName] != address(0)); storesByName[storeName].sell(msg.sender, productIndex, quantity); }
19,133
241
// Check that this tokenURI exists
require(blueprintExists[_tokenURI], "NFTManager: That token URI doesn't exist");
require(blueprintExists[_tokenURI], "NFTManager: That token URI doesn't exist");
1,106
1
// the base instance that minimal proxies are cloned from /
address private _splitterTemplate; address private _owner; function initialize(address owner_, address[] memory paymentTokens_) public
address private _splitterTemplate; address private _owner; function initialize(address owner_, address[] memory paymentTokens_) public
28,485
90
// generate the job hash. Used to reference the job in all future function calls/transactions.
bytes32 jobHash = getJobHash( _jobId, _hirer, _contractor, _value, _fee);
bytes32 jobHash = getJobHash( _jobId, _hirer, _contractor, _value, _fee);
28,076
108
// Block number when bonus WNRZ period ends.
uint256 public bonusEndBlock;
uint256 public bonusEndBlock;
5,096
40
// send datatoken to publisher
require( transfer(getPaymentCollector(), amount), "Failed to send DT to publisher" );
require( transfer(getPaymentCollector(), amount), "Failed to send DT to publisher" );
32,036