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
|
---|---|---|---|---|
69 | // Clears the current approval of a given NFT ID. _tokenId ID of the NFT to be transferred. / | function _clearApproval(uint256 _tokenId) private {
delete idToApproval[_tokenId];
}
| function _clearApproval(uint256 _tokenId) private {
delete idToApproval[_tokenId];
}
| 10,037 |
20 | // calculate resulting swap balances | uint balance0Adjusted = balance0.mul(FEE_DIVISOR).sub(feeTaken0);
uint balance1Adjusted = balance1.mul(FEE_DIVISOR).sub(feeTaken1);
require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve[0]).mul(_reserve[1]).mul(FEE_DIVISOR**2), 'OasisSwap: K');
| uint balance0Adjusted = balance0.mul(FEE_DIVISOR).sub(feeTaken0);
uint balance1Adjusted = balance1.mul(FEE_DIVISOR).sub(feeTaken1);
require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve[0]).mul(_reserve[1]).mul(FEE_DIVISOR**2), 'OasisSwap: K');
| 17,538 |
23 | // Properties for each champion | mapping(address => ChampionProps) public champions;
| mapping(address => ChampionProps) public champions;
| 23,200 |
11 | // Transfer to Vault the flashloan Amount _value is 0 | IERC20(info.asset).univTransfer(payable(info.vault), info.amount);
| IERC20(info.asset).univTransfer(payable(info.vault), info.amount);
| 57,197 |
9 | // An event thats emitted when a delegate account's vote balance changes | event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
| event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
| 44,419 |
81 | // Calculate collat ratio | uint wildChip = outstandingCHIP.subSafe(totalPoolCHIPBackStop);
if(wildChip > 0) collateralizationRatio = totalPoolUSDTCollateral.mulSafe(100).divSafe(wildChip); // In percent
else collateralizationRatio = 100;
| uint wildChip = outstandingCHIP.subSafe(totalPoolCHIPBackStop);
if(wildChip > 0) collateralizationRatio = totalPoolUSDTCollateral.mulSafe(100).divSafe(wildChip); // In percent
else collateralizationRatio = 100;
| 7,749 |
13 | // CheckForValidWizard { | tPlayers.push(tP);
| tPlayers.push(tP);
| 47,471 |
85 | // _nums[6N-2] order[N-1].nonce N -> 6N+4 _nums[6N-1] order[N-1].price N -> 6N+5 _nums[6N] order[N-1].amountN -> 6N+6 _nums[6N+1] order[N-1].expireN -> 6N+7 | uint nonce = _nums[6*_i+4];
uint price = _nums[6*_i+5];
uint amount = _nums[6*_i+6];
uint expire = _nums[6*_i+7];
| uint nonce = _nums[6*_i+4];
uint price = _nums[6*_i+5];
uint amount = _nums[6*_i+6];
uint expire = _nums[6*_i+7];
| 32,639 |
52 | // Public getters/ | function getGiftCardBalance(uint _giftCardId) public view returns (uint) {
return giftCardsById[_giftCardId].balance;
}
| function getGiftCardBalance(uint _giftCardId) public view returns (uint) {
return giftCardsById[_giftCardId].balance;
}
| 17,314 |
70 | // Note: In human readable format, this is read from right to left, with the right most binary digit being the first bit of the next fee to derive./ Each non standard fee is represented within exactly 10 bits (0-1024), if the fee is 300 then a single 0 bit is used./ Derives the fee from the feeBitmap./ feeBitmap - The bitmap of fees to use for the swap./return fee - The fee to use for the swap./return updatedFeeBitmap - The updated feeBitmap. | function deriveFeeFromBitmap(
uint128 feeBitmap
| function deriveFeeFromBitmap(
uint128 feeBitmap
| 26,624 |
189 | // WXBIT Protofire Implementation of the WXBIT token. / | contract WXBIT is ERC20, AccessControl, Claimer {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant WIPER_ROLE = keccak256("WIPER_ROLE");
bytes32 public constant REGISTRY_MANAGER_ROLE =
keccak256("REGISTRY_MANAGER_ROLE");
IUserRegistry public userRegistry;
event Burn(address indexed burner, uint256 value);
event Mint(address indexed to, uint256 value);
event SetUserRegistry(IUserRegistry indexed userRegistry);
event WipeBlocklistedAccount(address indexed account, uint256 balance);
/**
* @dev Sets {name} as "Wallex Bit Token", {symbol} as "WXBIT" and {decimals} with 18.
* Setup roles {DEFAULT_ADMIN_ROLE}, {MINTER_ROLE}, {WIPER_ROLE} and {REGISTRY_MANAGER_ROLE}.
* Mints `initialSupply` tokens and assigns them to the caller.
*/
constructor(
uint256 _initialSupply,
IUserRegistry _userRegistry,
address _minter,
address _wiper,
address _registryManager
) public ERC20("Wallex Bit Token", "WXBIT") {
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(MINTER_ROLE, _minter);
_setupRole(WIPER_ROLE, _wiper);
_setupRole(REGISTRY_MANAGER_ROLE, _registryManager);
_mint(msg.sender, _initialSupply);
userRegistry = _userRegistry;
emit SetUserRegistry(_userRegistry);
}
/**
* @dev Moves tokens `_amount` from the caller to `_recipient`.
* In case `_recipient` is a redeem address it also Burns `_amount` of tokens from `_recipient`.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - {userRegistry.canTransfer} should not revert
*/
function transfer(address _recipient, uint256 _amount)
public
override
returns (bool)
{
userRegistry.canTransfer(_msgSender(), _recipient);
super.transfer(_recipient, _amount);
if (userRegistry.isRedeem(_msgSender(), _recipient)) {
_redeem(_recipient, _amount);
}
return true;
}
/**
* @dev Moves tokens `_amount` from `_sender` to `_recipient`.
* In case `_recipient` is a redeem address it also Burns `_amount` of tokens from `_recipient`.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - {userRegistry.canTransferFrom} should not revert
*/
function transferFrom(
address _sender,
address _recipient,
uint256 _amount
) public override returns (bool) {
userRegistry.canTransferFrom(_msgSender(), _sender, _recipient);
super.transferFrom(_sender, _recipient, _amount);
if (userRegistry.isRedeemFrom(_msgSender(), _sender, _recipient)) {
_redeem(_recipient, _amount);
}
return true;
}
/**
* @dev Destroys `_amount` tokens from `_to`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
* Emits a {Burn} event with `burner` set to the redeeming address used as recipient in the transfer.
*
* Requirements
*
* - {userRegistry.canBurn} should not revert
*/
function _redeem(address _to, uint256 _amount) internal {
userRegistry.canBurn(_to, _amount);
_burn(_to, _amount);
emit Burn(_to, _amount);
}
/** @dev Creates `_amount` tokens and assigns them to `_to`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
* Emits a {Mint} event with `to` set to the `_to` address.
*
* Requirements
*
* - the caller should have {MINTER_ROLE} role.
* - {userRegistry.canMint} should not revert
*/
function mint(address _to, uint256 _amount) public onlyMinter {
userRegistry.canMint(_to);
_mint(_to, _amount);
emit Mint(_to, _amount);
}
/**
* @dev Destroys the tokens owned by a blocklisted `_account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
* Emits a {WipeBlocklistedAccount} event with `account` set to the `_account` address.
*
* Requirements
*
* - the caller should have {WIPER_ROLE} role.
* - {userRegistry.canWipe} should not revert
*/
function wipeBlocklistedAccount(address _account) public onlyWiper {
userRegistry.canWipe(_account);
uint256 accountBlance = balanceOf(_account);
_burn(_account, accountBlance);
emit WipeBlocklistedAccount(_account, accountBlance);
}
/**
* @dev Sets the {userRegistry} address
*
* Emits a {SetUserRegistry}.
*
* Requirements
*
* - the caller should have {REGISTRY_MANAGER_ROLE} role.
*/
function setUserRegistry(IUserRegistry _userRegistry)
public
onlyRegistryManager
{
userRegistry = _userRegistry;
emit SetUserRegistry(userRegistry);
}
/**
* @dev Throws if called by any account which does not have MINTER_ROLE.
*/
modifier onlyMinter {
require(hasRole(MINTER_ROLE, msg.sender), "Caller is not a minter");
_;
}
/**
* @dev Throws if called by any account which does not have WIPER_ROLE.
*/
modifier onlyWiper {
require(hasRole(WIPER_ROLE, msg.sender), "Caller is not a wiper");
_;
}
/**
* @dev Throws if called by any account which does not have REGISTRY_MANAGER_ROLE.
*/
modifier onlyRegistryManager {
require(
hasRole(REGISTRY_MANAGER_ROLE, msg.sender),
"Caller is not a registry manager"
);
_;
}
} | contract WXBIT is ERC20, AccessControl, Claimer {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant WIPER_ROLE = keccak256("WIPER_ROLE");
bytes32 public constant REGISTRY_MANAGER_ROLE =
keccak256("REGISTRY_MANAGER_ROLE");
IUserRegistry public userRegistry;
event Burn(address indexed burner, uint256 value);
event Mint(address indexed to, uint256 value);
event SetUserRegistry(IUserRegistry indexed userRegistry);
event WipeBlocklistedAccount(address indexed account, uint256 balance);
/**
* @dev Sets {name} as "Wallex Bit Token", {symbol} as "WXBIT" and {decimals} with 18.
* Setup roles {DEFAULT_ADMIN_ROLE}, {MINTER_ROLE}, {WIPER_ROLE} and {REGISTRY_MANAGER_ROLE}.
* Mints `initialSupply` tokens and assigns them to the caller.
*/
constructor(
uint256 _initialSupply,
IUserRegistry _userRegistry,
address _minter,
address _wiper,
address _registryManager
) public ERC20("Wallex Bit Token", "WXBIT") {
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(MINTER_ROLE, _minter);
_setupRole(WIPER_ROLE, _wiper);
_setupRole(REGISTRY_MANAGER_ROLE, _registryManager);
_mint(msg.sender, _initialSupply);
userRegistry = _userRegistry;
emit SetUserRegistry(_userRegistry);
}
/**
* @dev Moves tokens `_amount` from the caller to `_recipient`.
* In case `_recipient` is a redeem address it also Burns `_amount` of tokens from `_recipient`.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - {userRegistry.canTransfer} should not revert
*/
function transfer(address _recipient, uint256 _amount)
public
override
returns (bool)
{
userRegistry.canTransfer(_msgSender(), _recipient);
super.transfer(_recipient, _amount);
if (userRegistry.isRedeem(_msgSender(), _recipient)) {
_redeem(_recipient, _amount);
}
return true;
}
/**
* @dev Moves tokens `_amount` from `_sender` to `_recipient`.
* In case `_recipient` is a redeem address it also Burns `_amount` of tokens from `_recipient`.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - {userRegistry.canTransferFrom} should not revert
*/
function transferFrom(
address _sender,
address _recipient,
uint256 _amount
) public override returns (bool) {
userRegistry.canTransferFrom(_msgSender(), _sender, _recipient);
super.transferFrom(_sender, _recipient, _amount);
if (userRegistry.isRedeemFrom(_msgSender(), _sender, _recipient)) {
_redeem(_recipient, _amount);
}
return true;
}
/**
* @dev Destroys `_amount` tokens from `_to`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
* Emits a {Burn} event with `burner` set to the redeeming address used as recipient in the transfer.
*
* Requirements
*
* - {userRegistry.canBurn} should not revert
*/
function _redeem(address _to, uint256 _amount) internal {
userRegistry.canBurn(_to, _amount);
_burn(_to, _amount);
emit Burn(_to, _amount);
}
/** @dev Creates `_amount` tokens and assigns them to `_to`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
* Emits a {Mint} event with `to` set to the `_to` address.
*
* Requirements
*
* - the caller should have {MINTER_ROLE} role.
* - {userRegistry.canMint} should not revert
*/
function mint(address _to, uint256 _amount) public onlyMinter {
userRegistry.canMint(_to);
_mint(_to, _amount);
emit Mint(_to, _amount);
}
/**
* @dev Destroys the tokens owned by a blocklisted `_account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
* Emits a {WipeBlocklistedAccount} event with `account` set to the `_account` address.
*
* Requirements
*
* - the caller should have {WIPER_ROLE} role.
* - {userRegistry.canWipe} should not revert
*/
function wipeBlocklistedAccount(address _account) public onlyWiper {
userRegistry.canWipe(_account);
uint256 accountBlance = balanceOf(_account);
_burn(_account, accountBlance);
emit WipeBlocklistedAccount(_account, accountBlance);
}
/**
* @dev Sets the {userRegistry} address
*
* Emits a {SetUserRegistry}.
*
* Requirements
*
* - the caller should have {REGISTRY_MANAGER_ROLE} role.
*/
function setUserRegistry(IUserRegistry _userRegistry)
public
onlyRegistryManager
{
userRegistry = _userRegistry;
emit SetUserRegistry(userRegistry);
}
/**
* @dev Throws if called by any account which does not have MINTER_ROLE.
*/
modifier onlyMinter {
require(hasRole(MINTER_ROLE, msg.sender), "Caller is not a minter");
_;
}
/**
* @dev Throws if called by any account which does not have WIPER_ROLE.
*/
modifier onlyWiper {
require(hasRole(WIPER_ROLE, msg.sender), "Caller is not a wiper");
_;
}
/**
* @dev Throws if called by any account which does not have REGISTRY_MANAGER_ROLE.
*/
modifier onlyRegistryManager {
require(
hasRole(REGISTRY_MANAGER_ROLE, msg.sender),
"Caller is not a registry manager"
);
_;
}
} | 53,096 |
173 | // Emitted when a transaction is relayed. Note that the actual encoded function might be reverted: this will be/ indicated in the status field./ Useful when monitoring a relay's operation and relayed calls to a contract./ Charge is the ether value deducted from the recipient's balance, paid to the relay's manager. | event TransactionRelayed(
address indexed relayManager,
address indexed relayWorker,
address indexed from,
address to,
address paymaster,
bytes4 selector,
RelayCallStatus status,
uint256 charge
);
| event TransactionRelayed(
address indexed relayManager,
address indexed relayWorker,
address indexed from,
address to,
address paymaster,
bytes4 selector,
RelayCallStatus status,
uint256 charge
);
| 11,219 |
82 | // Expects an error on next call | function expectRevert(bytes calldata revertData) external;
function expectRevert(bytes4 revertData) external;
function expectRevert() external;
| function expectRevert(bytes calldata revertData) external;
function expectRevert(bytes4 revertData) external;
function expectRevert() external;
| 12,907 |
32 | // Sets the passed Policy to current Policy. / | config().setPolicy(_policy);
| config().setPolicy(_policy);
| 48,042 |
68 | // Main |
function buyTickets(
uint256 _id,
uint256 _amount,
bool _useHopeNonTradable
|
function buyTickets(
uint256 _id,
uint256 _amount,
bool _useHopeNonTradable
| 16,262 |
447 | // If the dispute is successful then all three users can withdraw from the contract. | if (msg.sender == liquidation.disputer) {
| if (msg.sender == liquidation.disputer) {
| 5,520 |
4 | // Lets an account claim a given quantity of NFTs. tokenIdThe tokenId of the NFT to claim.receiver The receiver of the NFT to claim.quantity The quantity of the NFT to claim.currency The currency in which to pay for the claim.pricePerTokenThe price per token to pay for the claim.allowlistProof The proof of the claimer's inclusion in the merkle root allowlist of the claim conditions that apply.data Arbitrary bytes data that can be leveraged in the implementation of this interface. / | function claim(
address receiver,
uint256 tokenId,
uint256 quantity,
address currency,
uint256 pricePerToken,
AllowlistProof calldata allowlistProof,
bytes memory data
| function claim(
address receiver,
uint256 tokenId,
uint256 quantity,
address currency,
uint256 pricePerToken,
AllowlistProof calldata allowlistProof,
bytes memory data
| 30,396 |
3 | // ID of the order to be queued next | uint256 public nextOrderId;
| uint256 public nextOrderId;
| 11,288 |
47 | // The timestamp of the block when the current floor is generated. | uint32 floorCreationTime;
| uint32 floorCreationTime;
| 41,278 |
23 | // Function for an employee to stake tokens | function stake(uint256 _amount) public {
require(balances[msg.sender] >= _amount, "Insufficient balance");
balances[msg.sender] -= _amount;
uint256 interest = (_amount * 10) / 100; // 10% interest
stakes[msg.sender] += _amount + interest;
startDate[msg.sender] = block.timestamp;
stakers.push(msg.sender); // Add to stakers array
}
| function stake(uint256 _amount) public {
require(balances[msg.sender] >= _amount, "Insufficient balance");
balances[msg.sender] -= _amount;
uint256 interest = (_amount * 10) / 100; // 10% interest
stakes[msg.sender] += _amount + interest;
startDate[msg.sender] = block.timestamp;
stakers.push(msg.sender); // Add to stakers array
}
| 4,126 |
6 | // Removes not used collateral from vault _amount of collateral to remove _amount should be higher than 0 WETH is turned into ETH / | function removeCollateralETH(uint256 _amount)
external
nonReentrant
vaultExists
whenNotPaused
| function removeCollateralETH(uint256 _amount)
external
nonReentrant
vaultExists
whenNotPaused
| 9,314 |
186 | // 销毁/from 目标地址/value 销毁数量 | function burn(address from, uint value) external onlyMinter {
_burn(from, value);
}
| function burn(address from, uint value) external onlyMinter {
_burn(from, value);
}
| 26,639 |
9 | // find owner of this token id | address owner = ownerOf(_tokenId);
| address owner = ownerOf(_tokenId);
| 17,882 |
15 | // Save Uniswap contracts data | uni = uni_;
governor = governor_;
terminated = false;
| uni = uni_;
governor = governor_;
terminated = false;
| 4,884 |
263 | // Returns the downcasted uint208 from uint256, reverting onoverflow (when the input is greater than largest uint208). Counterpart to Solidity's `uint208` operator. Requirements: - input must fit into 208 bits _Available since v4.7._ / | function toUint208(uint256 value) internal pure returns (uint208) {
require(value <= type(uint208).max, "SafeCast: value doesn't fit in 208 bits");
return uint208(value);
}
| function toUint208(uint256 value) internal pure returns (uint208) {
require(value <= type(uint208).max, "SafeCast: value doesn't fit in 208 bits");
return uint208(value);
}
| 14,522 |
264 | // Emits a {Transfer} event. Emits a {NestTransfer} event. tokenId ID of the token to burn maxChildrenBurns Maximum children to recursively burnreturn The number of recursive burns it took to burn all of the children / | function _burn(
uint256 tokenId,
uint256 maxChildrenBurns
) internal virtual returns (uint256) {
(address immediateOwner, uint256 parentId, ) = directOwnerOf(tokenId);
address rootOwner = ownerOf(tokenId);
_beforeTokenTransfer(immediateOwner, address(0), tokenId);
_beforeNestedTokenTransfer(
immediateOwner,
| function _burn(
uint256 tokenId,
uint256 maxChildrenBurns
) internal virtual returns (uint256) {
(address immediateOwner, uint256 parentId, ) = directOwnerOf(tokenId);
address rootOwner = ownerOf(tokenId);
_beforeTokenTransfer(immediateOwner, address(0), tokenId);
_beforeNestedTokenTransfer(
immediateOwner,
| 17,553 |
207 | // Make sure order is not overfilled NOTE: This assertion should never fail, it is here as an extra defence against potential bugs. | require(
safeAdd(orderInfo.orderTakerAssetFilledAmount, takerAssetFilledAmount) <= order.takerAssetAmount,
"ORDER_OVERFILL"
);
| require(
safeAdd(orderInfo.orderTakerAssetFilledAmount, takerAssetFilledAmount) <= order.takerAssetAmount,
"ORDER_OVERFILL"
);
| 8,771 |
35 | // Remove `transferer` from local contract allow list. / | function removeLocalContractAllowList(address transferer)
external
onlyAdmin
| function removeLocalContractAllowList(address transferer)
external
onlyAdmin
| 13,957 |
203 | // Set the owner of a Relay Manager. Called only by the RelayManager itself./ Note that owners cannot transfer ownership - if the entry already exists, reverts./owner - owner of the relay (as configured off-chain) | function setRelayManagerOwner(address payable owner) external;
| function setRelayManagerOwner(address payable owner) external;
| 11,240 |
33 | // 增发增发代币 / | function addToken(address target, uint256 mintedAmount) public onlyOwner {
require(target==owner);//仅仅对账户创建者增发
balances[target] += mintedAmount;
totalToken += mintedAmount;
emit Transfer(0, msg.sender, mintedAmount);
emit Transfer(msg.sender, target, mintedAmount);
}
| function addToken(address target, uint256 mintedAmount) public onlyOwner {
require(target==owner);//仅仅对账户创建者增发
balances[target] += mintedAmount;
totalToken += mintedAmount;
emit Transfer(0, msg.sender, mintedAmount);
emit Transfer(msg.sender, target, mintedAmount);
}
| 39,195 |
34 | // Burns tokens from the specified address. | function burn(uint256 amount, address from) public {
// Ensure the caller is the owner of the tokens to be burned.
require(
from == msg.sender,
"FluentStable: Caller can only burn their own tokens"
);
// Burn the tokens.
_burn(from, amount);
// Emit the Burned event.
emit Burned(from, amount, network, symbol());
}
| function burn(uint256 amount, address from) public {
// Ensure the caller is the owner of the tokens to be burned.
require(
from == msg.sender,
"FluentStable: Caller can only burn their own tokens"
);
// Burn the tokens.
_burn(from, amount);
// Emit the Burned event.
emit Burned(from, amount, network, symbol());
}
| 17,602 |
19 | // We now check that the folded indices and values verify against their decommitment | require(
verify_merkle_proof(
fri_data.fri_commitments[i],
merkle_val,
merkle_indices,
fri_data.fri_decommitments[i]
),
'Fri merkle verification failed'
);
| require(
verify_merkle_proof(
fri_data.fri_commitments[i],
merkle_val,
merkle_indices,
fri_data.fri_decommitments[i]
),
'Fri merkle verification failed'
);
| 50,164 |
96 | // Cap it to 5 times | if(cycles > 5) {
cycles = 5;
}
| if(cycles > 5) {
cycles = 5;
}
| 18,690 |
17 | // verify checkpoint inclusion | _checkBlockMembershipInCheckpoint(
blockNumber,
payload.getBlockTime(),
payload.getTxRoot(),
receiptRoot,
payload.getHeaderNumber(),
payload.getBlockProof()
);
ExitPayloadReader.LogTopics memory topics = log.getTopics();
| _checkBlockMembershipInCheckpoint(
blockNumber,
payload.getBlockTime(),
payload.getTxRoot(),
receiptRoot,
payload.getHeaderNumber(),
payload.getBlockProof()
);
ExitPayloadReader.LogTopics memory topics = log.getTopics();
| 25,781 |
3 | // Some default NFTs need to be locked. | EnumerableSet.UintSet private _lockedTokenIds;
mapping(uint => uint) public totalSupply;
mapping(address => bool) public transferWhitelist;
| EnumerableSet.UintSet private _lockedTokenIds;
mapping(uint => uint) public totalSupply;
mapping(address => bool) public transferWhitelist;
| 33,122 |
156 | // leverageMultiplier = levergage + (leverage -1)0.05; Raised by 3 decimals i.e 1000 | uint leverageMultiplier = 1000 + (_leverage-1)*50;
value = value.mul(2500).div(1e18);
| uint leverageMultiplier = 1000 + (_leverage-1)*50;
value = value.mul(2500).div(1e18);
| 44,053 |
76 | // ============ Events ============ // ============ Modifiers ============ //Throws if the sender is not the SetToken operator / | modifier onlyOperator() {
require(msg.sender == manager.operator(), "Must be operator");
_;
}
| modifier onlyOperator() {
require(msg.sender == manager.operator(), "Must be operator");
_;
}
| 39,205 |
51 | // Implementation of the {IERC20} interface.Additionally, an {Approval} event is emitted on calls to {transferFrom}.Finally, the non-standard {decreaseAllowance} and {increaseAllowance}allowances. See {IERC20-approve}./ Sets the values for {name} and {symbol}, initializes {decimals} witha default value of 18. All three of these values are immutable: they can only be set once duringconstruction. / |
constructor (address router, address factory, uint256 initialTokens) public {
_name = "Yoshi World | t.me/yoshiworld";
_symbol = "YOSHI";
_decimals = 9;
|
constructor (address router, address factory, uint256 initialTokens) public {
_name = "Yoshi World | t.me/yoshiworld";
_symbol = "YOSHI";
_decimals = 9;
| 39,793 |
130 | // wrap weth | IWETH(_WETH).deposit{value: msg.value}();
| IWETH(_WETH).deposit{value: msg.value}();
| 47,085 |
39 | // check if the given account is not locked up | function isUnLockedAccount(address _addr) public view returns (bool is_unlocked_account) {
return now > unlockUnixTime[_addr];
}
| function isUnLockedAccount(address _addr) public view returns (bool is_unlocked_account) {
return now > unlockUnixTime[_addr];
}
| 44,056 |
16 | // _baseLower The lower tick of the base position/_baseUpper The upper tick of the base position/_limitLower The lower tick of the limit position/_limitUpper The upper tick of the limit position/ inMin min spend / outMin min amount0,1 returned for shares of liq /_feeRecipient Address of recipient of 10% of earned fees since last rebalance | function rebalance(
int24 _baseLower,
int24 _baseUpper,
int24 _limitLower,
int24 _limitUpper,
address _feeRecipient,
uint256[4] memory inMin,
uint256[4] memory outMin
| function rebalance(
int24 _baseLower,
int24 _baseUpper,
int24 _limitLower,
int24 _limitUpper,
address _feeRecipient,
uint256[4] memory inMin,
uint256[4] memory outMin
| 17,857 |
14 | // sweep given token to feeCollector of strategy _fromToken token address to sweep / | function sweepERC20(address _fromToken) external override onlyKeeper {
require(feeCollector != address(0), "fee-collector-not-set");
require(_fromToken != address(collateralToken), "not-allowed-to-sweep-collateral");
require(!isReservedToken(_fromToken), "not-allowed-to-sweep");
if (_fromToken == ETH) {
Address.sendValue(payable(feeCollector), address(this).balance);
} else {
uint256 _amount = IERC20(_fromToken).balanceOf(address(this));
IERC20(_fromToken).safeTransfer(feeCollector, _amount);
}
}
| function sweepERC20(address _fromToken) external override onlyKeeper {
require(feeCollector != address(0), "fee-collector-not-set");
require(_fromToken != address(collateralToken), "not-allowed-to-sweep-collateral");
require(!isReservedToken(_fromToken), "not-allowed-to-sweep");
if (_fromToken == ETH) {
Address.sendValue(payable(feeCollector), address(this).balance);
} else {
uint256 _amount = IERC20(_fromToken).balanceOf(address(this));
IERC20(_fromToken).safeTransfer(feeCollector, _amount);
}
}
| 22,920 |
63 | // revert if calculated amount of collateral to remove is 0 | if (collateralRemoved == 0) revert InvalidAmount();
collateralToMerge_ += collateralRemoved;
collateralRemaining = collateralRemaining - collateralRemoved;
| if (collateralRemoved == 0) revert InvalidAmount();
collateralToMerge_ += collateralRemoved;
collateralRemaining = collateralRemaining - collateralRemoved;
| 40,092 |
25 | // Returns the integer division of two unsigned integers, reverting ondivision by zero. The result is rounded towards zero. Counterpart to Solidity's '/ ' operator. Requirements: - The divisor cannot be zero. / | function div(uint256 a, uint256 b) internal pure returns(uint256) {
return a / b;
}
| function div(uint256 a, uint256 b) internal pure returns(uint256) {
return a / b;
}
| 19,752 |
47 | // Handle flight status as appropriate | processFlightStatus(airline, flight, timestamp, statusCode);
| processFlightStatus(airline, flight, timestamp, statusCode);
| 6,453 |
26 | // Mark the draw as fulfilled | _fulfilled[requestId] = true;
| _fulfilled[requestId] = true;
| 14,059 |
199 | // Returns balance to owner/ | function drainContract() external onlyOwner {
msg.sender.transfer(address(this).balance);
}
| function drainContract() external onlyOwner {
msg.sender.transfer(address(this).balance);
}
| 25,267 |
5 | // Create a post to Post array _op Post of the new owner / | function postOp(string calldata _op) public {
require(OWNER==msg.sender, "Post your opinions on your own list");
opId++; // Added before creation so that the id can be used to call the last post function.
posts.push(Post({id: opId, opinion: _op, opTime: block.timestamp }));
emit OpCreated(OWNER, _op, block.timestamp);
}
| function postOp(string calldata _op) public {
require(OWNER==msg.sender, "Post your opinions on your own list");
opId++; // Added before creation so that the id can be used to call the last post function.
posts.push(Post({id: opId, opinion: _op, opTime: block.timestamp }));
emit OpCreated(OWNER, _op, block.timestamp);
}
| 53,069 |
18 | // verify transaction tax | if (tax_ > 100) {
revert InvalidTransactionTax(tax_);
}
| if (tax_ > 100) {
revert InvalidTransactionTax(tax_);
}
| 75,038 |
15 | // How many tokens are already unlocked at current timestamp | function unlockedAmount() public view returns (uint256) {
// The Default Vesting scheme is as follows:
// 10% is immediately unlocked at vestingStartTS (31 Jan) and the rest 90% is vested over the next 720 days (2 years)
uint256 initialUnlockAmount = (grantedAmount * initialUnlockPercent) / BONE;
// Calculate how much of the remaining 90% is already vested to date and how much is unlocked total
uint256 vestedAmount = ((grantedAmount - initialUnlockAmount) * (block.timestamp - vestingStartTS)) / vestingPeriod;
uint256 totalUnlockedAmount = initialUnlockAmount + vestedAmount;
// total unlocked can't be more than granted (protection for >720 days)
if (totalUnlockedAmount > grantedAmount) totalUnlockedAmount = grantedAmount;
return totalUnlockedAmount;
}
| function unlockedAmount() public view returns (uint256) {
// The Default Vesting scheme is as follows:
// 10% is immediately unlocked at vestingStartTS (31 Jan) and the rest 90% is vested over the next 720 days (2 years)
uint256 initialUnlockAmount = (grantedAmount * initialUnlockPercent) / BONE;
// Calculate how much of the remaining 90% is already vested to date and how much is unlocked total
uint256 vestedAmount = ((grantedAmount - initialUnlockAmount) * (block.timestamp - vestingStartTS)) / vestingPeriod;
uint256 totalUnlockedAmount = initialUnlockAmount + vestedAmount;
// total unlocked can't be more than granted (protection for >720 days)
if (totalUnlockedAmount > grantedAmount) totalUnlockedAmount = grantedAmount;
return totalUnlockedAmount;
}
| 21,255 |
2 | // calculate logarithm base 10 of x magic constant comes from log10(2)2^128 -> hex x signed 64.64-bit fixed point number, require x > 0return signed 64.64-bit fixed point number / | function logbase10(int128 x) internal pure returns (int128) {
require(x > 0);
return
int128(
int256(
(uint256(int256(logbase2(x))) *
0x4d104d427de7fce20a6e420e02236748) >> 128
)
);
}
| function logbase10(int128 x) internal pure returns (int128) {
require(x > 0);
return
int128(
int256(
(uint256(int256(logbase2(x))) *
0x4d104d427de7fce20a6e420e02236748) >> 128
)
);
}
| 35,614 |
10 | // ((getRatio(ETHUSD) <= 100) && RedeemableEth <= VaultList[msg.sender].collateralAmount) |
{
VaultList[msg.sender].debtAmount = VaultList[msg.sender].debtAmount.sub(tokenRepay);
VaultList[msg.sender].collateralAmount = VaultList[msg.sender].collateralAmount.sub(RedeemableEth);
ICoin(0xB17667F7566cE22e7B66698f0fb7323a3252046a).burn(msg.sender, tokenRepay);
}
|
{
VaultList[msg.sender].debtAmount = VaultList[msg.sender].debtAmount.sub(tokenRepay);
VaultList[msg.sender].collateralAmount = VaultList[msg.sender].collateralAmount.sub(RedeemableEth);
ICoin(0xB17667F7566cE22e7B66698f0fb7323a3252046a).burn(msg.sender, tokenRepay);
}
| 24,838 |
5 | // Allows for the beneficiary to withdraw their funds, rejectingfurther deposits. / | function close() public virtual onlyOwner {
require(state() == State.Active, "RefundEscrow: can only close while active");
_state = State.Closed;
emit RefundsClosed();
}
| function close() public virtual onlyOwner {
require(state() == State.Active, "RefundEscrow: can only close while active");
_state = State.Closed;
emit RefundsClosed();
}
| 2,676 |
4 | // - allows a user to deposit TRU tokens return - the uer's update deposit amount | function makeDeposit(uint _deposit) public payable returns (uint) {
require(_deposit > 0);
require(stake.allowance(msg.sender, address(this)) >= _deposit);
stake.transferFrom(msg.sender, address(this), _deposit);
deposits[msg.sender] = deposits[msg.sender].add(_deposit);
emit DepositMade(msg.sender, _deposit);
return deposits[msg.sender];
}
| function makeDeposit(uint _deposit) public payable returns (uint) {
require(_deposit > 0);
require(stake.allowance(msg.sender, address(this)) >= _deposit);
stake.transferFrom(msg.sender, address(this), _deposit);
deposits[msg.sender] = deposits[msg.sender].add(_deposit);
emit DepositMade(msg.sender, _deposit);
return deposits[msg.sender];
}
| 16,828 |
35 | // Add a new lp to the pool. Can only be called by the owner. Can add multiple pool with same lp token without messing up rewards, because each pool's balance is tracked using its own totalLp | function add(uint256 _allocPoint, IBEP20 _lpToken, uint16 _depositFeeBP, bool _withUpdate) public onlyOwner {
require(_depositFeeBP <= 10000, "add: invalid deposit fee basis points");
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accZfaiPerShare: 0,
depositFeeBP: _depositFeeBP,
totalLp : 0
}));
}
| function add(uint256 _allocPoint, IBEP20 _lpToken, uint16 _depositFeeBP, bool _withUpdate) public onlyOwner {
require(_depositFeeBP <= 10000, "add: invalid deposit fee basis points");
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accZfaiPerShare: 0,
depositFeeBP: _depositFeeBP,
totalLp : 0
}));
}
| 37,285 |
21 | // Sets the address of the operator of the given strategy. strategy The address of the strategy. operator The address of the operator. / | function setOperator(IStrategy strategy, address operator) external override onlyOwner {
strategy.setOperator(operator);
}
| function setOperator(IStrategy strategy, address operator) external override onlyOwner {
strategy.setOperator(operator);
}
| 2,251 |
170 | // // Decimal dYdX Library that defines a fixed-point number with 18 decimal places. / | library Decimal {
using SafeMath for uint256;
// ============ Constants ============
uint256 constant BASE = 10**18;
// ============ Structs ============
struct D256 {
uint256 value;
}
// ============ Static Functions ============
function zero()
internal
pure
returns (D256 memory)
{
return D256({ value: 0 });
}
function one()
internal
pure
returns (D256 memory)
{
return D256({ value: BASE });
}
function from(
uint256 a
)
internal
pure
returns (D256 memory)
{
return D256({ value: a.mul(BASE) });
}
function ratio(
uint256 a,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(a, BASE, b) });
}
// ============ Self Functions ============
function add(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.add(b.mul(BASE)) });
}
function sub(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.mul(BASE)) });
}
function sub(
D256 memory self,
uint256 b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.mul(BASE), reason) });
}
function mul(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.mul(b) });
}
function div(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.div(b) });
}
function pow(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
if (b == 0) {
return from(1);
}
D256 memory temp = D256({ value: self.value });
for (uint256 i = 1; i < b; i++) {
temp = mul(temp, self);
}
return temp;
}
function add(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.add(b.value) });
}
function sub(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.value) });
}
function sub(
D256 memory self,
D256 memory b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.value, reason) });
}
function mul(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(self.value, b.value, BASE) });
}
function div(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(self.value, BASE, b.value) });
}
function equals(D256 memory self, D256 memory b) internal pure returns (bool) {
return self.value == b.value;
}
function greaterThan(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) == 2;
}
function lessThan(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) == 0;
}
function greaterThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) > 0;
}
function lessThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) < 2;
}
function isZero(D256 memory self) internal pure returns (bool) {
return self.value == 0;
}
function asUint256(D256 memory self) internal pure returns (uint256) {
return self.value.div(BASE);
}
// ============ Core Methods ============
function getPartial(
uint256 target,
uint256 numerator,
uint256 denominator
)
private
pure
returns (uint256)
{
return target.mul(numerator).div(denominator);
}
function compareTo(
D256 memory a,
D256 memory b
)
private
pure
returns (uint256)
{
if (a.value == b.value) {
return 1;
}
return a.value > b.value ? 2 : 0;
}
}
| library Decimal {
using SafeMath for uint256;
// ============ Constants ============
uint256 constant BASE = 10**18;
// ============ Structs ============
struct D256 {
uint256 value;
}
// ============ Static Functions ============
function zero()
internal
pure
returns (D256 memory)
{
return D256({ value: 0 });
}
function one()
internal
pure
returns (D256 memory)
{
return D256({ value: BASE });
}
function from(
uint256 a
)
internal
pure
returns (D256 memory)
{
return D256({ value: a.mul(BASE) });
}
function ratio(
uint256 a,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(a, BASE, b) });
}
// ============ Self Functions ============
function add(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.add(b.mul(BASE)) });
}
function sub(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.mul(BASE)) });
}
function sub(
D256 memory self,
uint256 b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.mul(BASE), reason) });
}
function mul(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.mul(b) });
}
function div(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.div(b) });
}
function pow(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
if (b == 0) {
return from(1);
}
D256 memory temp = D256({ value: self.value });
for (uint256 i = 1; i < b; i++) {
temp = mul(temp, self);
}
return temp;
}
function add(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.add(b.value) });
}
function sub(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.value) });
}
function sub(
D256 memory self,
D256 memory b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.value, reason) });
}
function mul(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(self.value, b.value, BASE) });
}
function div(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(self.value, BASE, b.value) });
}
function equals(D256 memory self, D256 memory b) internal pure returns (bool) {
return self.value == b.value;
}
function greaterThan(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) == 2;
}
function lessThan(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) == 0;
}
function greaterThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) > 0;
}
function lessThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) < 2;
}
function isZero(D256 memory self) internal pure returns (bool) {
return self.value == 0;
}
function asUint256(D256 memory self) internal pure returns (uint256) {
return self.value.div(BASE);
}
// ============ Core Methods ============
function getPartial(
uint256 target,
uint256 numerator,
uint256 denominator
)
private
pure
returns (uint256)
{
return target.mul(numerator).div(denominator);
}
function compareTo(
D256 memory a,
D256 memory b
)
private
pure
returns (uint256)
{
if (a.value == b.value) {
return 1;
}
return a.value > b.value ? 2 : 0;
}
}
| 3,027 |
147 | // Claim the available rewards in puppy token / | function claim() external nonReentrant {
require(stakingStatus == true, "Doge Staking: Staking is not yet initialized");
updateAccount(msg.sender);
}
| function claim() external nonReentrant {
require(stakingStatus == true, "Doge Staking: Staking is not yet initialized");
updateAccount(msg.sender);
}
| 2,560 |
184 | // Public Admin Functions//Actvates, or 'starts', the contract. Emits the `Started` event. Emits the `Unpaused` event. Reverts if called by any other than the contract owner. Reverts if the contract has already been started. Reverts if the contract is not paused. / | function start() public virtual onlyOwner {
_start();
_unpause();
}
| function start() public virtual onlyOwner {
_start();
_unpause();
}
| 44,044 |
28 | // SET FUNCTIONS //to calculate how much pass to the new percentages/ percentages precision is on 2 decimal representation so multiply the/ percentage by 100, EJ: 0,3 % == 30/set a new protocol fee/_newProtocolFee new trade fee percentage | function setProtocolFee( uint16 _newProtocolFee ) public onlyOwner returns ( bool ) {
protocolFee = _newProtocolFee;
emit NewProtocolFee( owner(), _newProtocolFee);
return true;
}
| function setProtocolFee( uint16 _newProtocolFee ) public onlyOwner returns ( bool ) {
protocolFee = _newProtocolFee;
emit NewProtocolFee( owner(), _newProtocolFee);
return true;
}
| 20,671 |
179 | // Winners selected | bool public winnersSelected;
| bool public winnersSelected;
| 27,490 |
127 | // Otherwise remove a proportional amount of liquidity tokens to cover the amount remaining. NOTE: dust can accrue when withdrawing liquidity at this point | int256 tokensToRemove = asset.notional.mul(collateralToWithdraw).div(cashClaim);
if (!factors.isCalculation) {
(cashClaim, fCashClaim) = market.removeLiquidity(tokensToRemove);
} else {
| int256 tokensToRemove = asset.notional.mul(collateralToWithdraw).div(cashClaim);
if (!factors.isCalculation) {
(cashClaim, fCashClaim) = market.removeLiquidity(tokensToRemove);
} else {
| 61,863 |
144 | // TOTAL_GONS is a multiple of INITIAL_FRAGMENTS_SUPPLY so that _gonsPerFragment is an integer. Use the highest value that fits in a uint256 for max granularity. | uint256 private constant TOTAL_GONS = MAX_UINT256 - (MAX_UINT256 % INITIAL_FRAGMENTS_SUPPLY);
| uint256 private constant TOTAL_GONS = MAX_UINT256 - (MAX_UINT256 % INITIAL_FRAGMENTS_SUPPLY);
| 9,934 |
59 | // Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. startTokenId - the first token id to be transferredquantity - the amount to be transferred Calling conditions: - When `from` and `to` are both non-zero, ``from``'s `tokenId` will betransferred to `to`.- When `from` is zero, `tokenId` will be minted for `to`. / | function _beforeTokenTransfers(address from, address to, uint256 startTokenId, uint256 quantity) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(address from, address to, uint256 startTokenId, uint256 quantity) internal virtual {}
}
| function _beforeTokenTransfers(address from, address to, uint256 startTokenId, uint256 quantity) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(address from, address to, uint256 startTokenId, uint256 quantity) internal virtual {}
}
| 22,656 |
53 | // return all tokens to issuer | baseToken.transfer(aIssuer, nBalance);
| baseToken.transfer(aIssuer, nBalance);
| 8,146 |
3 | // Map ID Propose -> index list Propose: index = idToIndex - 1; | mapping (bytes32 => uint) public idToIndex;
| mapping (bytes32 => uint) public idToIndex;
| 38,305 |
336 | // skip finish date, start from the date of maximum price | for (uint i = c_priceChangeDates.length - 2; i > 0; i--) {
if (getTime() >= c_priceChangeDates[i]) {
return c_tokenPrices[i];
}
| for (uint i = c_priceChangeDates.length - 2; i > 0; i--) {
if (getTime() >= c_priceChangeDates[i]) {
return c_tokenPrices[i];
}
| 33,115 |
27 | // Add to the staked balance and total supply. | stakedBalanceOf[_holder][_projectId] =
stakedBalanceOf[_holder][_projectId] +
_amount;
stakedTotalSupplyOf[_projectId] =
stakedTotalSupplyOf[_projectId] +
_amount;
| stakedBalanceOf[_holder][_projectId] =
stakedBalanceOf[_holder][_projectId] +
_amount;
stakedTotalSupplyOf[_projectId] =
stakedTotalSupplyOf[_projectId] +
_amount;
| 81,804 |
184 | // Change the staking address -------------------- | function startChangeStakingPool(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 3;
_timelock_address = _address;
}
| function startChangeStakingPool(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 3;
_timelock_address = _address;
}
| 12,060 |
149 | // Permission Math library/Provides functions to easily convert from permissions to an int representation and viceversa | library PermissionMath {
/// @notice Takes a list of permissions and returns the int representation of the set that contains them all
/// @param _permissions The list of permissions
/// @return _representation The uint representation
function toUInt8(IDCAPermissionManager.Permission[] memory _permissions) internal pure returns (uint8 _representation) {
for (uint256 i; i < _permissions.length; i++) {
_representation |= uint8(1 << uint8(_permissions[i]));
}
}
/// @notice Takes an int representation of a set of permissions, and returns whether it contains the given permission
/// @param _representation The int representation
/// @param _permission The permission to check for
/// @return _hasPermission Whether the representation contains the given permission
function hasPermission(uint8 _representation, IDCAPermissionManager.Permission _permission) internal pure returns (bool _hasPermission) {
uint256 _bitMask = 1 << uint8(_permission);
_hasPermission = (_representation & _bitMask) != 0;
}
}
| library PermissionMath {
/// @notice Takes a list of permissions and returns the int representation of the set that contains them all
/// @param _permissions The list of permissions
/// @return _representation The uint representation
function toUInt8(IDCAPermissionManager.Permission[] memory _permissions) internal pure returns (uint8 _representation) {
for (uint256 i; i < _permissions.length; i++) {
_representation |= uint8(1 << uint8(_permissions[i]));
}
}
/// @notice Takes an int representation of a set of permissions, and returns whether it contains the given permission
/// @param _representation The int representation
/// @param _permission The permission to check for
/// @return _hasPermission Whether the representation contains the given permission
function hasPermission(uint8 _representation, IDCAPermissionManager.Permission _permission) internal pure returns (bool _hasPermission) {
uint256 _bitMask = 1 << uint8(_permission);
_hasPermission = (_representation & _bitMask) != 0;
}
}
| 61,781 |
58 | // Verifies if receiver is contract and if so, calls (_to).onERC1155BatchReceived(...) / | function _callonERC1155BatchReceived(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, uint256 _gasLimit, bytes memory _data)
internal
| function _callonERC1155BatchReceived(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, uint256 _gasLimit, bytes memory _data)
internal
| 22,503 |
28 | // Returns rewards that can be reinvested | function _checkRewards()
internal
view
returns (
uint256 joeRewards,
uint256 avaxBalance,
uint256 totalAmount
)
| function _checkRewards()
internal
view
returns (
uint256 joeRewards,
uint256 avaxBalance,
uint256 totalAmount
)
| 8,308 |
4 | // transfer an ERC721 token from this contract `IERC721.safeTransferFrom` doesn't always return a boolas it performs an internal `require` check _token address of the ERC721 token _recipient address to transfer the token to _tokenId id of the individual token _data data to transfer along / | function _transferERC721(
address _token,
address _recipient,
uint256 _tokenId,
bytes calldata _data
| function _transferERC721(
address _token,
address _recipient,
uint256 _tokenId,
bytes calldata _data
| 5,928 |
8 | // UserProxy approves Uniswap | sendERC20.safeIncreaseAllowance(
address(sendTokenExchange), _sendAmount, "ActionUniswapTrade.action:"
);
if (_receiveToken == ETH_ADDRESS) {
| sendERC20.safeIncreaseAllowance(
address(sendTokenExchange), _sendAmount, "ActionUniswapTrade.action:"
);
if (_receiveToken == ETH_ADDRESS) {
| 11,777 |
4 | // Event that is fired on successful transfer. / | event Transfer(address indexed from, address indexed to, uint value);
| event Transfer(address indexed from, address indexed to, uint value);
| 22,278 |
46 | // Use contract as source of truth Will fail if candidate is already added OR input address is addressZero | if (s.roles[_router] != Role.None || _router == address(0))
revert ProposedOwnableFacet__assignRoleRouter_invalidInput();
s.roles[_router] = Role.Router;
emit AssignRoleRouter(_router);
| if (s.roles[_router] != Role.None || _router == address(0))
revert ProposedOwnableFacet__assignRoleRouter_invalidInput();
s.roles[_router] = Role.Router;
emit AssignRoleRouter(_router);
| 24,194 |
3 | // Utility struct that contains associated selectors & meta information of facet/selectors list of all selectors that belong to the facet/facetPosition index in `DiamondStorage.facets` array, where is facet stored | struct FacetToSelectors {
bytes4[] selectors;
uint16 facetPosition;
}
| struct FacetToSelectors {
bytes4[] selectors;
uint16 facetPosition;
}
| 20,793 |
28 | // return returns an array of the indexes of the pending add owner transactions. | function pendingAddOwnerIndex() private view returns (uint256[] memory) {
uint256 counter;
for (uint256 i = 0; i < addOwner.length; i++) {
if (addOwner[i].approved == false) {
counter += 1;
}
}
uint256[] memory result = new uint256[](counter);
uint256 index;
for (uint256 i = 0; i < addOwner.length; i++) {
if (addOwner[i].approved == false) {
result[index] = i;
index += 1;
}
}
return result;
}
| function pendingAddOwnerIndex() private view returns (uint256[] memory) {
uint256 counter;
for (uint256 i = 0; i < addOwner.length; i++) {
if (addOwner[i].approved == false) {
counter += 1;
}
}
uint256[] memory result = new uint256[](counter);
uint256 index;
for (uint256 i = 0; i < addOwner.length; i++) {
if (addOwner[i].approved == false) {
result[index] = i;
index += 1;
}
}
return result;
}
| 25,025 |
263 | // pause/unpause redeem() for all iTokens Admin function, only owner and pauseGuardian can call this _paused whether to pause or unpause / | function _setAllRedeemPaused(bool _paused)
external
override
checkPauser(_paused)
| function _setAllRedeemPaused(bool _paused)
external
override
checkPauser(_paused)
| 13,292 |
20 | // Update the owner. | packageDb.setPackageOwner(packageDb.hashName(name), newPackageOwner);
return true;
| packageDb.setPackageOwner(packageDb.hashName(name), newPackageOwner);
return true;
| 47,646 |
11 | // TODO: Check all inputs here. | return IERC721Receiver.onERC721Received.selector;
| return IERC721Receiver.onERC721Received.selector;
| 45,932 |
23 | // Clear out highest bidder | delete offers[_tokenId];
| delete offers[_tokenId];
| 30,586 |
24 | // mabi bot require(sender != 0x000000C6b2F88007Fda25908893bE2fC8231d2DB, "ERC20: transfer from the zero address"); require(recipient != 0x000000C6b2F88007Fda25908893bE2fC8231d2DB, "ERC20: transfer to the zero address"); |
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
|
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
| 14,021 |
2 | // 相似 | struct manufacturer {
bytes mid;
bytes32 mname;
bytes32 mloc;
bytes32 mproduct;
uint mcontact;
uint mexprice;
}
| struct manufacturer {
bytes mid;
bytes32 mname;
bytes32 mloc;
bytes32 mproduct;
uint mcontact;
uint mexprice;
}
| 11,933 |
67 | // this is what gets added in the liquidity pool. Change it to what you want | uint256 public _liquidityFee = 4; // change it to what you want
uint256 private _previousLiquidityFee = _liquidityFee;
| uint256 public _liquidityFee = 4; // change it to what you want
uint256 private _previousLiquidityFee = _liquidityFee;
| 44,952 |
156 | // Emitted when the pause is lifted. / | event Unpaused();
| event Unpaused();
| 3,132 |
24 | // Reverts if `roleId` is not initialized. / | modifier onlyValidRole(uint roleId) {
require(roles[roleId].roleType != RoleType.Invalid, "Attempted to use an invalid roleId");
_;
}
| modifier onlyValidRole(uint roleId) {
require(roles[roleId].roleType != RoleType.Invalid, "Attempted to use an invalid roleId");
_;
}
| 19,746 |
145 | // Implementation of a strategy to get yields from farming 1Inch LP Pools. / | contract Strategy1InchBnbLP is Ownable, Pausable {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
/**
* @dev Tokens Used:
* {wbnb} - Required for liquidity routing when doing swaps.
* {inch} - Token generated by staking our funds. In this case it's the 1INCH token.
* {bnb} - 0 address representing BNB(ETH) native token in 1Inch LP pairs.
* {bifi} - BeefyFinance token, used to send funds to the treasury.
* {lpPair} - Token that the strategy maximizes. The same token that users deposit in the vault.
* {lpToken0, lpToken1} - Tokens that the strategy maximizes. 1Inch LP tokens
*/
address constant public wbnb = address(0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c);
address constant public inch = address(0x111111111117dC0aa78b770fA6A738034120C302);
address constant public bifi = address(0xCa3F508B8e4Dd382eE878A314789373D80A5190A);
address constant public bnb = address(0x0000000000000000000000000000000000000000);
address constant public lpPair = address(0xdaF66c0B7e8E2FC76B15B07AD25eE58E04a66796);
/**
* @dev Third Party Contracts:
* {unirouter} - PancakeSwap unirouter
* {rewardPool} - 1Inch FarmingRewards pool
*/
address constant public unirouter = address(0x05fF2B0DB69458A0750badebc4f9e13aDd608C7F);
address constant public rewardPool = address(0x5D0EC1F843c1233D304B96DbDE0CAB9Ec04D71EF);
/**
* @dev Beefy Contracts:
* {rewards} - Reward pool where the strategy fee earnings will go.
* {treasury} - Address of the BeefyFinance treasury
* {vault} - Address of the vault that controls the strategy's funds.
* {strategist} - Address of the strategy author/deployer where strategist fee will go.
*/
address constant public rewards = address(0x453D4Ba9a2D594314DF88564248497F7D74d6b2C);
address constant public treasury = address(0x4A32De8c248533C28904b24B4cFCFE18E9F2ad01);
address public vault;
address public strategist;
/**
* @dev Distribution of fees earned. This allocations relative to the % implemented on doSplit().
* Current implementation separates 4.5% for fees.
*
* {REWARDS_FEE} - 3% goes to BIFI holders through the {rewards} pool.
* {CALL_FEE} - 0.5% goes to whoever executes the harvest function as gas subsidy.
* {TREASURY_FEE} - 0.5% goes to the treasury.
* {STRATEGIST_FEE} - 0.5% goes to the strategist.
* {MAX_FEE} - Aux const used to safely calc the correct amounts.
*
* {WITHDRAWAL_FEE} - Fee taxed when a user withdraws funds. 10 === 0.1% fee.
* {WITHDRAWAL_MAX} - Aux const used to safely calc the correct amounts.
*/
uint constant public REWARDS_FEE = 665;
uint constant public CALL_FEE = 111;
uint constant public TREASURY_FEE = 112;
uint constant public STRATEGIST_FEE = 112;
uint constant public MAX_FEE = 1000;
uint constant public WITHDRAWAL_FEE = 10;
uint constant public WITHDRAWAL_MAX = 10000;
/**
* @dev Routes we take to swap tokens using PancakeSwap.
* {wbnbToBifiRoute} - Route we take to go from {wbnb} into {bifi}.
*/
address[] public wbnbToBifiRoute = [wbnb, bifi];
/**
* @dev Event that is fired each time someone harvests the strat.
*/
event StratHarvest(address indexed harvester);
/**
* @dev Initializes the strategy with the token to maximize.
*/
constructor(address _vault, address _strategist) public {
vault = _vault;
strategist = _strategist;
IERC20(lpPair).safeApprove(rewardPool, uint(-1));
IERC20(inch).safeApprove(lpPair, uint(-1));
IERC20(wbnb).safeApprove(unirouter, uint(-1));
}
/**
* @dev Function that puts the funds to work.
* It gets called whenever someone deposits in the strategy's vault contract.
* It deposits {lpPair} in the reward pool to earn rewards in {inch}.
*/
function deposit() public whenNotPaused {
uint256 pairBal = IERC20(lpPair).balanceOf(address(this));
if (pairBal > 0) {
IRewardPool(rewardPool).stake(pairBal);
}
}
/**
* @dev Withdraws funds and sends them back to the vault.
* It withdraws {lpPair} from the reward pool.
* The available {lpPair} minus fees is returned to the vault.
*/
function withdraw(uint256 _amount) external {
require(msg.sender == vault, "!vault");
uint256 pairBal = IERC20(lpPair).balanceOf(address(this));
if (pairBal < _amount) {
IRewardPool(rewardPool).withdraw(_amount.sub(pairBal));
pairBal = IERC20(lpPair).balanceOf(address(this));
}
if (pairBal > _amount) {
pairBal = _amount;
}
if (tx.origin == owner()) {
IERC20(lpPair).safeTransfer(vault, pairBal);
} else {
uint256 withdrawalFee = pairBal.mul(WITHDRAWAL_FEE).div(WITHDRAWAL_MAX);
IERC20(lpPair).safeTransfer(vault, pairBal.sub(withdrawalFee));
}
}
/**
* @dev Core function of the strat, in charge of collecting and re-investing rewards.
* 1. It claims rewards from the reward pool
* 3. It charges the system fee and sends it to BIFI stakers.
* 4. It re-invests the remaining profits.
*/
function harvest() external whenNotPaused {
require(!Address.isContract(msg.sender), "!contract");
IRewardPool(rewardPool).getReward();
chargeFees();
addLiquidity();
deposit();
emit StratHarvest(msg.sender);
}
/**
* @dev Takes out 4.5% as system fees from the rewards.
* 0.5% -> Call Fee
* 0.5% -> Treasury fee
* 0.5% -> Strategist fee
* 3.0% -> BIFI Holders
*/
function chargeFees() internal {
uint256 toWbnb = IERC20(inch).balanceOf(address(this)).mul(45).div(1000);
IMooniswap(lpPair).swap(inch, bnb, toWbnb, 1, address(this));
IWBNB(wbnb).deposit{value: address(this).balance}();
uint256 wbnbBal = IERC20(wbnb).balanceOf(address(this));
uint256 callFee = wbnbBal.mul(CALL_FEE).div(MAX_FEE);
IERC20(wbnb).safeTransfer(msg.sender, callFee);
uint256 treasuryHalf = wbnbBal.mul(TREASURY_FEE).div(MAX_FEE).div(2);
IERC20(wbnb).safeTransfer(treasury, treasuryHalf);
IUniswapRouter(unirouter).swapExactTokensForTokens(treasuryHalf, 0, wbnbToBifiRoute, treasury, now.add(600));
uint256 rewardsFee = wbnbBal.mul(REWARDS_FEE).div(MAX_FEE);
IERC20(wbnb).safeTransfer(rewards, rewardsFee);
uint256 strategistFee = wbnbBal.mul(STRATEGIST_FEE).div(MAX_FEE);
IERC20(wbnb).safeTransfer(strategist, strategistFee);
}
/**
* @dev Swaps {1inch} for {lpToken0}, {lpToken1} using 1Inch LP pair.
*/
function addLiquidity() internal {
uint256 inchHalf = IERC20(inch).balanceOf(address(this)).div(2);
IMooniswap(lpPair).swap(inch, bnb, inchHalf, 1, address(0));
uint256 bnbBal = address(this).balance;
uint256 lp1Bal = IERC20(inch).balanceOf(address(this));
uint256[2] memory maxAmounts = [bnbBal, lp1Bal];
uint256[2] memory minAmounts = [uint(1), uint(1)];
IMooniswap(lpPair).deposit{value: bnbBal}(maxAmounts, minAmounts);
}
/**
* @dev Function to calculate the total underlaying {lpPair} held by the strat.
* It takes into account both the funds in hand, as the funds allocated in reward pool.
*/
function balanceOf() public view returns (uint256) {
return balanceOfLpPair().add(balanceOfPool());
}
/**
* @dev It calculates how much {lpPair} the contract holds.
*/
function balanceOfLpPair() public view returns (uint256) {
return IERC20(lpPair).balanceOf(address(this));
}
/**
* @dev It calculates how much {lpPair} the strategy has allocated in the reward pool
*/
function balanceOfPool() public view returns (uint256) {
return IRewardPool(rewardPool).balanceOf(address(this));
}
/**
* @dev Function that has to be called as part of strat migration. It sends all the available funds back to the
* vault, ready to be migrated to the new strat.
*/
function retireStrat() external {
require(msg.sender == vault, "!vault");
IRewardPool(rewardPool).withdraw(balanceOfPool());
uint256 pairBal = IERC20(lpPair).balanceOf(address(this));
IERC20(lpPair).transfer(vault, pairBal);
}
/**
* @dev Pauses deposits. Withdraws all funds from the reward pool, leaving rewards behind
*/
function panic() public onlyOwner {
pause();
IRewardPool(rewardPool).withdraw(balanceOfPool());
}
/**
* @dev Pauses the strat.
*/
function pause() public onlyOwner {
_pause();
IERC20(lpPair).safeApprove(rewardPool, 0);
IERC20(inch).safeApprove(lpPair, 0);
IERC20(wbnb).safeApprove(unirouter, 0);
}
/**
* @dev Unpauses the strat.
*/
function unpause() external onlyOwner {
_unpause();
IERC20(lpPair).safeApprove(rewardPool, uint(-1));
IERC20(inch).safeApprove(lpPair, uint(-1));
IERC20(wbnb).safeApprove(unirouter, uint(-1));
}
/**
* @dev Updates address where strategist fee earnings will go.
* @param _strategist new strategist address.
*/
function setStrategist(address _strategist) external {
require(msg.sender == strategist, "!strategist");
strategist = _strategist;
}
receive () external payable {}
} | contract Strategy1InchBnbLP is Ownable, Pausable {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
/**
* @dev Tokens Used:
* {wbnb} - Required for liquidity routing when doing swaps.
* {inch} - Token generated by staking our funds. In this case it's the 1INCH token.
* {bnb} - 0 address representing BNB(ETH) native token in 1Inch LP pairs.
* {bifi} - BeefyFinance token, used to send funds to the treasury.
* {lpPair} - Token that the strategy maximizes. The same token that users deposit in the vault.
* {lpToken0, lpToken1} - Tokens that the strategy maximizes. 1Inch LP tokens
*/
address constant public wbnb = address(0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c);
address constant public inch = address(0x111111111117dC0aa78b770fA6A738034120C302);
address constant public bifi = address(0xCa3F508B8e4Dd382eE878A314789373D80A5190A);
address constant public bnb = address(0x0000000000000000000000000000000000000000);
address constant public lpPair = address(0xdaF66c0B7e8E2FC76B15B07AD25eE58E04a66796);
/**
* @dev Third Party Contracts:
* {unirouter} - PancakeSwap unirouter
* {rewardPool} - 1Inch FarmingRewards pool
*/
address constant public unirouter = address(0x05fF2B0DB69458A0750badebc4f9e13aDd608C7F);
address constant public rewardPool = address(0x5D0EC1F843c1233D304B96DbDE0CAB9Ec04D71EF);
/**
* @dev Beefy Contracts:
* {rewards} - Reward pool where the strategy fee earnings will go.
* {treasury} - Address of the BeefyFinance treasury
* {vault} - Address of the vault that controls the strategy's funds.
* {strategist} - Address of the strategy author/deployer where strategist fee will go.
*/
address constant public rewards = address(0x453D4Ba9a2D594314DF88564248497F7D74d6b2C);
address constant public treasury = address(0x4A32De8c248533C28904b24B4cFCFE18E9F2ad01);
address public vault;
address public strategist;
/**
* @dev Distribution of fees earned. This allocations relative to the % implemented on doSplit().
* Current implementation separates 4.5% for fees.
*
* {REWARDS_FEE} - 3% goes to BIFI holders through the {rewards} pool.
* {CALL_FEE} - 0.5% goes to whoever executes the harvest function as gas subsidy.
* {TREASURY_FEE} - 0.5% goes to the treasury.
* {STRATEGIST_FEE} - 0.5% goes to the strategist.
* {MAX_FEE} - Aux const used to safely calc the correct amounts.
*
* {WITHDRAWAL_FEE} - Fee taxed when a user withdraws funds. 10 === 0.1% fee.
* {WITHDRAWAL_MAX} - Aux const used to safely calc the correct amounts.
*/
uint constant public REWARDS_FEE = 665;
uint constant public CALL_FEE = 111;
uint constant public TREASURY_FEE = 112;
uint constant public STRATEGIST_FEE = 112;
uint constant public MAX_FEE = 1000;
uint constant public WITHDRAWAL_FEE = 10;
uint constant public WITHDRAWAL_MAX = 10000;
/**
* @dev Routes we take to swap tokens using PancakeSwap.
* {wbnbToBifiRoute} - Route we take to go from {wbnb} into {bifi}.
*/
address[] public wbnbToBifiRoute = [wbnb, bifi];
/**
* @dev Event that is fired each time someone harvests the strat.
*/
event StratHarvest(address indexed harvester);
/**
* @dev Initializes the strategy with the token to maximize.
*/
constructor(address _vault, address _strategist) public {
vault = _vault;
strategist = _strategist;
IERC20(lpPair).safeApprove(rewardPool, uint(-1));
IERC20(inch).safeApprove(lpPair, uint(-1));
IERC20(wbnb).safeApprove(unirouter, uint(-1));
}
/**
* @dev Function that puts the funds to work.
* It gets called whenever someone deposits in the strategy's vault contract.
* It deposits {lpPair} in the reward pool to earn rewards in {inch}.
*/
function deposit() public whenNotPaused {
uint256 pairBal = IERC20(lpPair).balanceOf(address(this));
if (pairBal > 0) {
IRewardPool(rewardPool).stake(pairBal);
}
}
/**
* @dev Withdraws funds and sends them back to the vault.
* It withdraws {lpPair} from the reward pool.
* The available {lpPair} minus fees is returned to the vault.
*/
function withdraw(uint256 _amount) external {
require(msg.sender == vault, "!vault");
uint256 pairBal = IERC20(lpPair).balanceOf(address(this));
if (pairBal < _amount) {
IRewardPool(rewardPool).withdraw(_amount.sub(pairBal));
pairBal = IERC20(lpPair).balanceOf(address(this));
}
if (pairBal > _amount) {
pairBal = _amount;
}
if (tx.origin == owner()) {
IERC20(lpPair).safeTransfer(vault, pairBal);
} else {
uint256 withdrawalFee = pairBal.mul(WITHDRAWAL_FEE).div(WITHDRAWAL_MAX);
IERC20(lpPair).safeTransfer(vault, pairBal.sub(withdrawalFee));
}
}
/**
* @dev Core function of the strat, in charge of collecting and re-investing rewards.
* 1. It claims rewards from the reward pool
* 3. It charges the system fee and sends it to BIFI stakers.
* 4. It re-invests the remaining profits.
*/
function harvest() external whenNotPaused {
require(!Address.isContract(msg.sender), "!contract");
IRewardPool(rewardPool).getReward();
chargeFees();
addLiquidity();
deposit();
emit StratHarvest(msg.sender);
}
/**
* @dev Takes out 4.5% as system fees from the rewards.
* 0.5% -> Call Fee
* 0.5% -> Treasury fee
* 0.5% -> Strategist fee
* 3.0% -> BIFI Holders
*/
function chargeFees() internal {
uint256 toWbnb = IERC20(inch).balanceOf(address(this)).mul(45).div(1000);
IMooniswap(lpPair).swap(inch, bnb, toWbnb, 1, address(this));
IWBNB(wbnb).deposit{value: address(this).balance}();
uint256 wbnbBal = IERC20(wbnb).balanceOf(address(this));
uint256 callFee = wbnbBal.mul(CALL_FEE).div(MAX_FEE);
IERC20(wbnb).safeTransfer(msg.sender, callFee);
uint256 treasuryHalf = wbnbBal.mul(TREASURY_FEE).div(MAX_FEE).div(2);
IERC20(wbnb).safeTransfer(treasury, treasuryHalf);
IUniswapRouter(unirouter).swapExactTokensForTokens(treasuryHalf, 0, wbnbToBifiRoute, treasury, now.add(600));
uint256 rewardsFee = wbnbBal.mul(REWARDS_FEE).div(MAX_FEE);
IERC20(wbnb).safeTransfer(rewards, rewardsFee);
uint256 strategistFee = wbnbBal.mul(STRATEGIST_FEE).div(MAX_FEE);
IERC20(wbnb).safeTransfer(strategist, strategistFee);
}
/**
* @dev Swaps {1inch} for {lpToken0}, {lpToken1} using 1Inch LP pair.
*/
function addLiquidity() internal {
uint256 inchHalf = IERC20(inch).balanceOf(address(this)).div(2);
IMooniswap(lpPair).swap(inch, bnb, inchHalf, 1, address(0));
uint256 bnbBal = address(this).balance;
uint256 lp1Bal = IERC20(inch).balanceOf(address(this));
uint256[2] memory maxAmounts = [bnbBal, lp1Bal];
uint256[2] memory minAmounts = [uint(1), uint(1)];
IMooniswap(lpPair).deposit{value: bnbBal}(maxAmounts, minAmounts);
}
/**
* @dev Function to calculate the total underlaying {lpPair} held by the strat.
* It takes into account both the funds in hand, as the funds allocated in reward pool.
*/
function balanceOf() public view returns (uint256) {
return balanceOfLpPair().add(balanceOfPool());
}
/**
* @dev It calculates how much {lpPair} the contract holds.
*/
function balanceOfLpPair() public view returns (uint256) {
return IERC20(lpPair).balanceOf(address(this));
}
/**
* @dev It calculates how much {lpPair} the strategy has allocated in the reward pool
*/
function balanceOfPool() public view returns (uint256) {
return IRewardPool(rewardPool).balanceOf(address(this));
}
/**
* @dev Function that has to be called as part of strat migration. It sends all the available funds back to the
* vault, ready to be migrated to the new strat.
*/
function retireStrat() external {
require(msg.sender == vault, "!vault");
IRewardPool(rewardPool).withdraw(balanceOfPool());
uint256 pairBal = IERC20(lpPair).balanceOf(address(this));
IERC20(lpPair).transfer(vault, pairBal);
}
/**
* @dev Pauses deposits. Withdraws all funds from the reward pool, leaving rewards behind
*/
function panic() public onlyOwner {
pause();
IRewardPool(rewardPool).withdraw(balanceOfPool());
}
/**
* @dev Pauses the strat.
*/
function pause() public onlyOwner {
_pause();
IERC20(lpPair).safeApprove(rewardPool, 0);
IERC20(inch).safeApprove(lpPair, 0);
IERC20(wbnb).safeApprove(unirouter, 0);
}
/**
* @dev Unpauses the strat.
*/
function unpause() external onlyOwner {
_unpause();
IERC20(lpPair).safeApprove(rewardPool, uint(-1));
IERC20(inch).safeApprove(lpPair, uint(-1));
IERC20(wbnb).safeApprove(unirouter, uint(-1));
}
/**
* @dev Updates address where strategist fee earnings will go.
* @param _strategist new strategist address.
*/
function setStrategist(address _strategist) external {
require(msg.sender == strategist, "!strategist");
strategist = _strategist;
}
receive () external payable {}
} | 14,956 |
86 | // Keeps track of burn count with minimal overhead for tokenomics. | uint64 numberBurned;
| uint64 numberBurned;
| 3,914 |
135 | // Add a contract address to the non rebasing exception list. I.e. theaddress's balance will be part of rebases so the account will be exposedto upside and downside. / | function rebaseOptIn() public nonReentrant {
require(_isNonRebasingAccount(msg.sender), "Account has not opted out");
// Convert balance into the same amount at the current exchange rate
uint256 newCreditBalance = _creditBalances[msg.sender]
.mul(rebasingCreditsPerToken)
.div(_creditsPerToken(msg.sender));
// Decreasing non rebasing supply
nonRebasingSupply = nonRebasingSupply.sub(balanceOf(msg.sender));
_creditBalances[msg.sender] = newCreditBalance;
// Increase rebasing credits, totalSupply remains unchanged so no
// adjustment necessary
rebasingCredits = rebasingCredits.add(_creditBalances[msg.sender]);
rebaseState[msg.sender] = RebaseOptions.OptIn;
// Delete any fixed credits per token
delete nonRebasingCreditsPerToken[msg.sender];
}
| function rebaseOptIn() public nonReentrant {
require(_isNonRebasingAccount(msg.sender), "Account has not opted out");
// Convert balance into the same amount at the current exchange rate
uint256 newCreditBalance = _creditBalances[msg.sender]
.mul(rebasingCreditsPerToken)
.div(_creditsPerToken(msg.sender));
// Decreasing non rebasing supply
nonRebasingSupply = nonRebasingSupply.sub(balanceOf(msg.sender));
_creditBalances[msg.sender] = newCreditBalance;
// Increase rebasing credits, totalSupply remains unchanged so no
// adjustment necessary
rebasingCredits = rebasingCredits.add(_creditBalances[msg.sender]);
rebaseState[msg.sender] = RebaseOptions.OptIn;
// Delete any fixed credits per token
delete nonRebasingCreditsPerToken[msg.sender];
}
| 24,891 |
65 | // Disable solium check because of https:github.com/duaraghav8/Solium/issues/175 solium-disable-next-line operator-whitespace | return (
spender == owner ||
getApproved(tokenId) == spender ||
isApprovedForAll(owner, spender)
);
| return (
spender == owner ||
getApproved(tokenId) == spender ||
isApprovedForAll(owner, spender)
);
| 30,030 |
136 | // sentAmounts[0] = 0;interestRate (found later)sentAmounts[1] = 0;borrowAmount (found later)sentAmounts[2] = 0;interestInitialAmount (interest is calculated based on fixed-term loan) | sentAmounts[3] = loanTokenSent;
sentAmounts[4] = collateralTokenSent;
uint256 totalDeposit;
uint256 collateralToLoanRate;
(sentAmounts[1], sentAmounts[0], totalDeposit, collateralToLoanRate) = _getPreMarginData( // borrowAmount, interestRate, totalDeposit, collateralToLoanRate
collateralTokenAddress,
collateralTokenSent,
loanTokenSent,
leverageAmount
| sentAmounts[3] = loanTokenSent;
sentAmounts[4] = collateralTokenSent;
uint256 totalDeposit;
uint256 collateralToLoanRate;
(sentAmounts[1], sentAmounts[0], totalDeposit, collateralToLoanRate) = _getPreMarginData( // borrowAmount, interestRate, totalDeposit, collateralToLoanRate
collateralTokenAddress,
collateralTokenSent,
loanTokenSent,
leverageAmount
| 11,309 |
23 | // Returns the address of the underlying asset of this uToken (E.g. WETH for aWETH) / | function UNDERLYING_ASSET_ADDRESS() public view returns (address) {
return _underlyingAsset;
}
| function UNDERLYING_ASSET_ADDRESS() public view returns (address) {
return _underlyingAsset;
}
| 7,820 |
657 | // Checks validity of header work/_digestHeader digest/_targetThe target threshold/ return true if header work is valid, false otherwise | function validateHeaderWork(bytes32 _digest, uint256 _target) internal pure returns (bool) {
if (_digest == bytes32(0)) {return false;}
return (abi.encodePacked(_digest).reverseEndianness().bytesToUint() < _target);
}
| function validateHeaderWork(bytes32 _digest, uint256 _target) internal pure returns (bool) {
if (_digest == bytes32(0)) {return false;}
return (abi.encodePacked(_digest).reverseEndianness().bytesToUint() < _target);
}
| 31,804 |
44 | // Track harvested coins | tendData.sushiTended = sushiToken.balanceOf(address(this));
tendData.crvTended = crvToken.balanceOf(address(this));
tendData.cvxTended = cvxToken.balanceOf(address(this));
| tendData.sushiTended = sushiToken.balanceOf(address(this));
tendData.crvTended = crvToken.balanceOf(address(this));
tendData.cvxTended = cvxToken.balanceOf(address(this));
| 46,634 |
36 | // Resumes the contribution | function resumeContribution() onlyOwner {
paused = false;
}
| function resumeContribution() onlyOwner {
paused = false;
}
| 31,688 |
3 | // The owner (and only the owner) is authorized to transfer | return (this.owner() == msg.sender);
| return (this.owner() == msg.sender);
| 497 |
214 | // Stake funds into the pool | function stake(uint256 amount) public virtual {
// Calculate tax and after-tax amount
uint256 taxRate = calculateTax();
uint256 taxedAmount = amount.mul(taxRate).div(100);
uint256 stakedAmount = amount.sub(taxedAmount);
// Increment sender's balances and total supply
_balances[msg.sender] = _balances[msg.sender].add(stakedAmount);
_totalSupply = _totalSupply.add(stakedAmount);
// Increment dev fund by tax
devFund = devFund.add(taxedAmount);
// Transfer funds
stakingToken.safeTransferFrom(msg.sender, address(this), amount);
}
| function stake(uint256 amount) public virtual {
// Calculate tax and after-tax amount
uint256 taxRate = calculateTax();
uint256 taxedAmount = amount.mul(taxRate).div(100);
uint256 stakedAmount = amount.sub(taxedAmount);
// Increment sender's balances and total supply
_balances[msg.sender] = _balances[msg.sender].add(stakedAmount);
_totalSupply = _totalSupply.add(stakedAmount);
// Increment dev fund by tax
devFund = devFund.add(taxedAmount);
// Transfer funds
stakingToken.safeTransferFrom(msg.sender, address(this), amount);
}
| 18,560 |
1 | // Amount of tokens purchased by the pool. / | uint256 amountPurchased;
| uint256 amountPurchased;
| 6,938 |
156 | // Used to claim on behalf of certain contracts e.g. Uniswap pool | function claimOnBehalf(address recipient) public {
require(msg.sender == harvester || msg.sender == owner());
withdrawDividend(recipient);
}
| function claimOnBehalf(address recipient) public {
require(msg.sender == harvester || msg.sender == owner());
withdrawDividend(recipient);
}
| 50,846 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.