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 |
|---|---|---|---|---|
18 | // Modifier that requires that 'voterAddress' has not voted for 'airlineAddress'/ | modifier requireVoterNotVotedForAirline(address voterAddress, address airlineAddress) {
require(!alreadyVotedForAirline(voterAddress, airlineAddress), "Voter has voted for this airline already.");
_;
}
| modifier requireVoterNotVotedForAirline(address voterAddress, address airlineAddress) {
require(!alreadyVotedForAirline(voterAddress, airlineAddress), "Voter has voted for this airline already.");
_;
}
| 38,341 |
349 | // Withdraw shares Shares to withdrawreturn Withdrawn amount / | function _withdraw(uint128 shares, uint256[] memory) internal override returns(uint128) {
uint256 fTokensTotal = pool.balanceOf(address(this));
uint256 fWithdrawAmount = (fTokensTotal * shares) / strategies[self].totalShares;
// withdraw staked fTokens from pool
pool.withdraw(fWithdrawAmount);
// withdraw fTokens from vault
uint256 undelyingBefore = underlying.balanceOf(address(this));
vault.withdraw(fWithdrawAmount);
uint256 undelyingWithdrawn = underlying.balanceOf(address(this)) - undelyingBefore;
return SafeCast.toUint128(undelyingWithdrawn);
}
| function _withdraw(uint128 shares, uint256[] memory) internal override returns(uint128) {
uint256 fTokensTotal = pool.balanceOf(address(this));
uint256 fWithdrawAmount = (fTokensTotal * shares) / strategies[self].totalShares;
// withdraw staked fTokens from pool
pool.withdraw(fWithdrawAmount);
// withdraw fTokens from vault
uint256 undelyingBefore = underlying.balanceOf(address(this));
vault.withdraw(fWithdrawAmount);
uint256 undelyingWithdrawn = underlying.balanceOf(address(this)) - undelyingBefore;
return SafeCast.toUint128(undelyingWithdrawn);
}
| 1,384 |
189 | // Represents a transcoder's current state | struct Transcoder {
uint256 lastRewardRound; // Last round that the transcoder called reward
uint256 rewardCut; // % of reward paid to transcoder by a delegator
uint256 feeShare; // % of fees paid to delegators by transcoder
uint256 pricePerSegmentDEPRECATED; // DEPRECATED - DO NOT USE
uint256 pendingRewardCutDEPRECATED; // DEPRECATED - DO NOT USE
uint256 pendingFeeShareDEPRECATED; // DEPRECATED - DO NOT USE
uint256 pendingPricePerSegmentDEPRECATED; // DEPRECATED - DO NOT USE
mapping (uint256 => EarningsPool.Data) earningsPoolPerRound; // Mapping of round => earnings pool for the round
uint256 lastActiveStakeUpdateRound; // Round for which the stake was last updated while the transcoder is active
uint256 activationRound; // Round in which the transcoder became active - 0 if inactive
uint256 deactivationRound; // Round in which the transcoder will become inactive
}
| struct Transcoder {
uint256 lastRewardRound; // Last round that the transcoder called reward
uint256 rewardCut; // % of reward paid to transcoder by a delegator
uint256 feeShare; // % of fees paid to delegators by transcoder
uint256 pricePerSegmentDEPRECATED; // DEPRECATED - DO NOT USE
uint256 pendingRewardCutDEPRECATED; // DEPRECATED - DO NOT USE
uint256 pendingFeeShareDEPRECATED; // DEPRECATED - DO NOT USE
uint256 pendingPricePerSegmentDEPRECATED; // DEPRECATED - DO NOT USE
mapping (uint256 => EarningsPool.Data) earningsPoolPerRound; // Mapping of round => earnings pool for the round
uint256 lastActiveStakeUpdateRound; // Round for which the stake was last updated while the transcoder is active
uint256 activationRound; // Round in which the transcoder became active - 0 if inactive
uint256 deactivationRound; // Round in which the transcoder will become inactive
}
| 12,316 |
3 | // Set maximum mintable tokens | function _setMaxMintable(uint256 _maxMint) public onlyOwner {
maxMint = _maxMint;
}
| function _setMaxMintable(uint256 _maxMint) public onlyOwner {
maxMint = _maxMint;
}
| 56,927 |
267 | // If tokens are already locked, then functions extendLock or increaseLockAmount should be used to make any changes | _lock(msg.sender, _reason, _amount, _time);
return true;
| _lock(msg.sender, _reason, _amount, _time);
return true;
| 22,272 |
45 | // CHECK VALUES | assert(totalIRCAllocated <= totalSupply);
assert(totalIRCAllocated > 0);
assert(balanceSafe > 0);
assert(totalWEIInvested > 0);
assert(contributedSafe > 0);
| assert(totalIRCAllocated <= totalSupply);
assert(totalIRCAllocated > 0);
assert(balanceSafe > 0);
assert(totalWEIInvested > 0);
assert(contributedSafe > 0);
| 33,918 |
137 | // Set storage | Bet storage newBet = bets[queryId];
newBet.player = player;
props = amount;
props = props << 64;
| Bet storage newBet = bets[queryId];
newBet.player = player;
props = amount;
props = props << 64;
| 47,857 |
9 | // The creater of the smart contract | constructor () public payable {
address_A = msg.sender;
}
| constructor () public payable {
address_A = msg.sender;
}
| 12,151 |
27 | // Buy NFT listedOnly if the signature and sell order are verified, NFT must be transferred. In case of Dutch auction, _startPricePerItem will be higher than _endPricerPerItem._listItem Sell order listed _signature EIP-712 based signature / | function buyItem(ListItem memory _listItem, bytes memory _signature) external nonReentrant {
// validate order
_validateList(_listItem, _signature);
// mark nonce
require(!isUsedNonce[_listItem.owner][_listItem.nonce], "Used nonce");
isUsedNonce[_listItem.owner][_listItem.nonce] = true;
// execute order
_buyItem(_listItem);
emit BuyItem(
_listItem.owner,
msg.sender,
_listItem.nftAddress,
_listItem.tokenId,
_listItem.payToken,
_listItem.startTime,
_listItem.startPricePerItem,
_listItem.quantity,
_listItem.endTime,
_listItem.endPricePerItem
);
}
| function buyItem(ListItem memory _listItem, bytes memory _signature) external nonReentrant {
// validate order
_validateList(_listItem, _signature);
// mark nonce
require(!isUsedNonce[_listItem.owner][_listItem.nonce], "Used nonce");
isUsedNonce[_listItem.owner][_listItem.nonce] = true;
// execute order
_buyItem(_listItem);
emit BuyItem(
_listItem.owner,
msg.sender,
_listItem.nftAddress,
_listItem.tokenId,
_listItem.payToken,
_listItem.startTime,
_listItem.startPricePerItem,
_listItem.quantity,
_listItem.endTime,
_listItem.endPricePerItem
);
}
| 17,130 |
130 | // Internal function to invoke {IERC1363Receiver-onApprovalReceived} on a target address. The call is not executed if the target address is not a contract. spender address The address which will spend the funds amount uint256 The amount of tokens to be spent data bytes Optional data to send along with the callreturn whether the call correctly returned the expected magic value / | function _checkOnApprovalReceived(
address spender,
uint256 amount,
bytes memory data
) internal virtual returns (bool) {
if (!spender.isContract()) {
revert("ERC1363: approve a non contract address");
}
| function _checkOnApprovalReceived(
address spender,
uint256 amount,
bytes memory data
) internal virtual returns (bool) {
if (!spender.isContract()) {
revert("ERC1363: approve a non contract address");
}
| 31,832 |
6 | // Fee owner takes on each sale, measured in basis points (1/100 of a percent). Values 0-10,000 map to 0%-100% | uint256 internal saleFee;
| uint256 internal saleFee;
| 34,394 |
16 | // {SaleEnv-competitionContract}) is stored within the Bundle itself: this allows upgrading thecompetition contract address without affecting the existing bundles; when the contract address is amended,only new bundles will be affected by the change. data Array of arrayfied bundle data; each bundle consists of 9 array elements; the input orderis consistent to {setupBundle}. / | function setupBundleMulti(
uint256[9][] calldata data,
address competitionContract
) external onlyRole(METAWIN_ROLE) {
uint256 count = data.length;
for(uint i; i<count;){
_setupBundle_kxU(
data[i][0], // Bundle Id
data[i][1], // Token Id
data[i][2], // Price
| function setupBundleMulti(
uint256[9][] calldata data,
address competitionContract
) external onlyRole(METAWIN_ROLE) {
uint256 count = data.length;
for(uint i; i<count;){
_setupBundle_kxU(
data[i][0], // Bundle Id
data[i][1], // Token Id
data[i][2], // Price
| 17,900 |
16 | // Curve main registry | address public constant MAIN_REGISTRY = address(0x90E00ACe148ca3b23Ac1bC8C240C2a7Dd9c2d7f5);
| address public constant MAIN_REGISTRY = address(0x90E00ACe148ca3b23Ac1bC8C240C2a7Dd9c2d7f5);
| 82,562 |
14 | // return True iff multiplying x and y would not overflow. / | function mulIsSafe(uint x, uint y)
pure
internal
returns (bool)
| function mulIsSafe(uint x, uint y)
pure
internal
returns (bool)
| 15,033 |
6 | // Contract module which provides access control mechanism, wherethere is an account (an owner) that can be granted exclusive access tospecific functions. By default, the owner account will be the one that deploys the contract. This | * can later be changed with {transferOwnership} and {acceptOwnership}.
*
* This module is used through inheritance. It will make available all functions
* from parent (Ownable).
*/
abstract contract Ownable2Step is Ownable {
address private s_pendingOwner;
/**
* @dev Emits in transferOwnership (start of the transfer)
* @param _previousOwner address of the previous owner
* @param _newOwner address of the new owner
*/
event OwnershipTransferStarted(address indexed _previousOwner, address indexed _newOwner);
/**
* @dev Returns the address of the pending owner.
*/
function pendingOwner() public view virtual returns (address) {
return s_pendingOwner;
}
/**
* @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual override onlyOwner {
s_pendingOwner = newOwner;
emit OwnershipTransferStarted(owner(), newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual override {
delete s_pendingOwner;
super._transferOwnership(newOwner);
}
/**
* @dev The new owner accepts the ownership transfer.
*/
function acceptOwnership() external {
address sender = _msgSender();
if (pendingOwner() != sender) {
revert Ownable2Step__CallerNotNewOwner();
}
_transferOwnership(sender);
}
}
| * can later be changed with {transferOwnership} and {acceptOwnership}.
*
* This module is used through inheritance. It will make available all functions
* from parent (Ownable).
*/
abstract contract Ownable2Step is Ownable {
address private s_pendingOwner;
/**
* @dev Emits in transferOwnership (start of the transfer)
* @param _previousOwner address of the previous owner
* @param _newOwner address of the new owner
*/
event OwnershipTransferStarted(address indexed _previousOwner, address indexed _newOwner);
/**
* @dev Returns the address of the pending owner.
*/
function pendingOwner() public view virtual returns (address) {
return s_pendingOwner;
}
/**
* @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual override onlyOwner {
s_pendingOwner = newOwner;
emit OwnershipTransferStarted(owner(), newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual override {
delete s_pendingOwner;
super._transferOwnership(newOwner);
}
/**
* @dev The new owner accepts the ownership transfer.
*/
function acceptOwnership() external {
address sender = _msgSender();
if (pendingOwner() != sender) {
revert Ownable2Step__CallerNotNewOwner();
}
_transferOwnership(sender);
}
}
| 5,951 |
787 | // Sender must first invoke requestWithdrawal in a previous cycle/This function will burn the fAsset and transfers underlying asset back to sender/Will execute a partial withdrawal if either available liquidity or previously requested amount is insufficient/amount Amount of fTokens to redeem, value can be in excess of available tokens, operation will be reduced to maximum permissible | function withdraw(uint256 amount, bool asEth) external;
| function withdraw(uint256 amount, bool asEth) external;
| 47,619 |
102 | // Lender Utility Functions /// | function loanSanityChecks(IMapleGlobals globals, address liquidityAsset, address collateralAsset, uint256[5] calldata specs) external view {
require(globals.isValidLiquidityAsset(liquidityAsset), "L:INVALID_LIQ_ASSET");
require(globals.isValidCollateralAsset(collateralAsset), "L:INVALID_COL_ASSET");
require(specs[2] != uint256(0), "L:ZERO_PID");
require(specs[1].mod(specs[2]) == uint256(0), "L:INVALID_TERM_DAYS");
require(specs[3] > uint256(0), "L:ZERO_REQUEST_AMT");
}
| function loanSanityChecks(IMapleGlobals globals, address liquidityAsset, address collateralAsset, uint256[5] calldata specs) external view {
require(globals.isValidLiquidityAsset(liquidityAsset), "L:INVALID_LIQ_ASSET");
require(globals.isValidCollateralAsset(collateralAsset), "L:INVALID_COL_ASSET");
require(specs[2] != uint256(0), "L:ZERO_PID");
require(specs[1].mod(specs[2]) == uint256(0), "L:INVALID_TERM_DAYS");
require(specs[3] > uint256(0), "L:ZERO_REQUEST_AMT");
}
| 14,710 |
214 | // Allow spending tokens from addresses with balance Note that this still allows listings and marketplaces with escrow to transfer tokens if transferred from an EOA. | if (from == msg.sender) {
_;
return;
}
| if (from == msg.sender) {
_;
return;
}
| 1,237 |
9 | // VVV These parameters will be governable by the DAO VVV Percentages are multipl1ied by 1,000,000. | uint256 public minApr = 2500000; // 2.5%
uint256 public maxApr = 75000000; // 75%
uint256 public stakeTarget = 10e6 ether; // 10M API3
| uint256 public minApr = 2500000; // 2.5%
uint256 public maxApr = 75000000; // 75%
uint256 public stakeTarget = 10e6 ether; // 10M API3
| 26,062 |
1 | // Limit withdrawal amount and time | require(withdraw_amount <= 100000000000000000);
| require(withdraw_amount <= 100000000000000000);
| 31,004 |
57 | // Domain-separation tag for the hash used as the final VRF output. Corresponds to vrfRandomOutputHashPrefix in vrf.go | uint256 internal constant VRF_RANDOM_OUTPUT_HASH_PREFIX = 3;
| uint256 internal constant VRF_RANDOM_OUTPUT_HASH_PREFIX = 3;
| 1,818 |
25 | // Allows an owner to submit and confirm a transaction./destination Transaction target address./value Transaction ether value./data Transaction data payload./ return Returns transaction ID. | function submitTransaction(address destination, uint value, bytes data)
public
returns (uint transactionId)
| function submitTransaction(address destination, uint value, bytes data)
public
returns (uint transactionId)
| 37,672 |
16 | // See {IERC1155MetadataUpgradeable-uri}. / | function uri(uint256 id) external view override returns (string memory) {
if (!_editionExists(id)) return "";
return _editionURI[id];
}
| function uri(uint256 id) external view override returns (string memory) {
if (!_editionExists(id)) return "";
return _editionURI[id];
}
| 28,422 |
11 | // add total OUT staking token | _totalStakes[stakingToken_].totalOutStake = _totalStakes[stakingToken_]
.totalOutStake
.add(amountStakingToken_);
| _totalStakes[stakingToken_].totalOutStake = _totalStakes[stakingToken_]
.totalOutStake
.add(amountStakingToken_);
| 12,857 |
75 | // Pays task completer and updates escrow balances | function rewardTaskCompletion(uint uuid, address user) public onlyVoteController {
communityAccount.transferTokensOut(address(nativeTokenInstance), user, communityAccount.escrowedTaskBalances(uuid));
communityAccount.setTotalTaskEscrow(SafeMath.sub(communityAccount.totalTaskEscrow(), communityAccount.escrowedTaskBalances(uuid)));
communityAccount.setEscrowedTaskBalances(uuid, 0);
logger.emitGenericLog("rewardTaskCompletion", "");
}
| function rewardTaskCompletion(uint uuid, address user) public onlyVoteController {
communityAccount.transferTokensOut(address(nativeTokenInstance), user, communityAccount.escrowedTaskBalances(uuid));
communityAccount.setTotalTaskEscrow(SafeMath.sub(communityAccount.totalTaskEscrow(), communityAccount.escrowedTaskBalances(uuid)));
communityAccount.setEscrowedTaskBalances(uuid, 0);
logger.emitGenericLog("rewardTaskCompletion", "");
}
| 42,734 |
0 | // Mapping from consensus address => weight | mapping(address => uint256) internal _consensusWeight;
| mapping(address => uint256) internal _consensusWeight;
| 23,984 |
155 | // Collect ether from completed Shotgun.Called by Shard Registry after burning caller's Shards.For counterclaimants, returns both the proportional worth of theiralternative: OpenZeppelin PaymentSplitter/ | function collectEtherProceeds(uint balance, address payable caller) external {
require(
msg.sender == address(_shardRegistry),
"[collectEtherProceeds] Caller not authorized"
);
if (_claimWinner == ClaimWinner.Claimant && caller != _initialClaimantAddress) {
uint weiProceeds = (_pricePerShardInWei.mul(balance)).div(10**18);
weiProceeds = weiProceeds.add(_counterclaimContribs[caller]);
_counterclaimContribs[caller] = 0;
(bool success, ) = address(caller).call.value(weiProceeds)("");
require(success, "[collectEtherProceeds] Transfer failed.");
emit EtherCollected(caller, weiProceeds);
} else if (_claimWinner == ClaimWinner.Counterclaimant && caller == _initialClaimantAddress) {
uint amount = (_pricePerShardInWei.mul(_initialClaimantBalance)).div(10**18);
amount = amount.add(_initialOfferInWei);
_initialClaimantBalance = 0;
(bool success, ) = address(caller).call.value(amount)("");
require(success, "[collectEtherProceeds] Transfer failed.");
emit EtherCollected(caller, amount);
}
}
| function collectEtherProceeds(uint balance, address payable caller) external {
require(
msg.sender == address(_shardRegistry),
"[collectEtherProceeds] Caller not authorized"
);
if (_claimWinner == ClaimWinner.Claimant && caller != _initialClaimantAddress) {
uint weiProceeds = (_pricePerShardInWei.mul(balance)).div(10**18);
weiProceeds = weiProceeds.add(_counterclaimContribs[caller]);
_counterclaimContribs[caller] = 0;
(bool success, ) = address(caller).call.value(weiProceeds)("");
require(success, "[collectEtherProceeds] Transfer failed.");
emit EtherCollected(caller, weiProceeds);
} else if (_claimWinner == ClaimWinner.Counterclaimant && caller == _initialClaimantAddress) {
uint amount = (_pricePerShardInWei.mul(_initialClaimantBalance)).div(10**18);
amount = amount.add(_initialOfferInWei);
_initialClaimantBalance = 0;
(bool success, ) = address(caller).call.value(amount)("");
require(success, "[collectEtherProceeds] Transfer failed.");
emit EtherCollected(caller, amount);
}
}
| 40,502 |
45 | // -------------------------------------------------------------------------- // owners // -------------------------------------------------------------------------- / | function clearStuckBalance() external onlyOwner {
(bool success,) = payable(msg.sender).call{value: address(this).balance}("");
require(success);
}
| function clearStuckBalance() external onlyOwner {
(bool success,) = payable(msg.sender).call{value: address(this).balance}("");
require(success);
}
| 19,319 |
29 | // Reward is normal ERC20 token, and is send from `rewardSender` | contract RewardMasterChef is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool.
uint256 lastRewardBlock; // Last block number that REWARDs distribution occurs.
uint256 accRewardPerShare; // Accumulated REWARDs per share, times 'accRewardMultiplier'.
}
// mutiplier make accumulated REWARDs per share more accurate
uint256 public accRewardMultiplier = 1e12;
// The REWARD TOKEN!
IERC20 public rewardToken;
// REWARD sending from this address
address public rewardSender;
// REWARD tokens created per block.
uint256 public rewardPerBlock;
// reduce reward cycle (of block numbers)
uint256 public reduceCycle;
uint256 public reducePercent;
uint256 public lastReduceBlock;
// Info of each pool.
PoolInfo[] public poolInfo;
mapping (address => uint256) public poolIndex;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when REWARD mining starts.
uint256 public startBlock;
// The block number when REWARD mining ends.
uint256 public endBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
IERC20 _rewardToken,
uint256 _startBlock,
uint256 _rewardPerBlock
) public {
rewardToken = _rewardToken;
startBlock = _startBlock > 0 ? _startBlock : block.number;
rewardPerBlock = _rewardPerBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
function _getCurRewardBlock() internal view returns (uint256) {
return (block.number > endBlock && endBlock > 0) ? endBlock : block.number;
}
function setEndBlock(uint256 _endBlock) public onlyOwner {
require(_endBlock >= startBlock && _endBlock >= block.number, "end block is too low");
endBlock = _endBlock;
}
function setRewardPerBlock(uint256 _rewardPerBlock, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
rewardPerBlock = _rewardPerBlock;
}
function setReduce(uint256 _start, uint256 _reduceCycle, uint256 _reducePercent) public onlyOwner {
require(block.number < _start.add(_reduceCycle), "passed cycle");
lastReduceBlock = _start;
reduceCycle = _reduceCycle;
reducePercent = _reducePercent;
}
// Add a new lp to the pool. Can only be called by the owner.
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
require(poolIndex[address(_lpToken)] == 0, "exist");
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accRewardPerShare: 0
}));
poolIndex[address(_lpToken)] = poolInfo.length;
}
// Update the given pool's REWARD allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// View function to see pending REWARDs on frontend.
function pendingReward(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accRewardPerShare = pool.accRewardPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
uint256 curRewardBlock = _getCurRewardBlock();
if (curRewardBlock > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = curRewardBlock.sub(pool.lastRewardBlock);
uint256 tokenReward = multiplier.mul(rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accRewardPerShare = accRewardPerShare.add(tokenReward.mul(accRewardMultiplier).div(lpSupply));
}
return user.amount.mul(accRewardPerShare).div(accRewardMultiplier).sub(user.rewardDebt);
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reduce cycle
function updateReduce() public {
if (reduceCycle == 0 || reducePercent == 100) {
return;
}
while (block.number >= lastReduceBlock.add(reduceCycle)) {
lastReduceBlock = lastReduceBlock.add(reduceCycle);
rewardPerBlock = rewardPerBlock.mul(reducePercent).div(100);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
updateReduce();
PoolInfo storage pool = poolInfo[_pid];
uint256 curRewardBlock = _getCurRewardBlock();
if (curRewardBlock <= pool.lastRewardBlock) {
if (rewardPerBlock > 0 && endBlock > 0 && block.number > endBlock.add(1000)) {
rewardPerBlock = 0; // wait 1000 blocks for last pool updates of settlements
}
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
uint256 multiplier = curRewardBlock.sub(pool.lastRewardBlock);
uint256 tokenReward = multiplier.mul(rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
if (tokenReward > 0 && lpSupply > 0) {
rewardToken.safeTransferFrom(rewardSender, address(this), tokenReward);
pool.accRewardPerShare = pool.accRewardPerShare.add(tokenReward.mul(accRewardMultiplier).div(lpSupply));
}
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterChef for REWARD allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accRewardPerShare).div(accRewardMultiplier).sub(user.rewardDebt);
if(pending > 0) {
safeRewardTransfer(msg.sender, pending);
}
}
if(_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accRewardPerShare).div(accRewardMultiplier);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accRewardPerShare).div(accRewardMultiplier).sub(user.rewardDebt);
if(pending > 0) {
safeRewardTransfer(msg.sender, pending);
}
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accRewardPerShare).div(accRewardMultiplier);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.lpToken.safeTransfer(address(msg.sender), amount);
emit EmergencyWithdraw(msg.sender, _pid, amount);
}
// Safe rewardToken transfer function, just in case if rounding error causes pool to not have enough REWARDs.
function safeRewardTransfer(address _to, uint256 _amount) internal {
uint256 rewardTokenBal = rewardToken.balanceOf(address(this));
if (_amount > rewardTokenBal) {
_amount = rewardTokenBal;
}
rewardToken.transfer(_to, _amount);
}
// Set reward sender
function setRewardSender(address _newSender) public onlyOwner {
rewardSender = _newSender;
}
}
| contract RewardMasterChef is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool.
uint256 lastRewardBlock; // Last block number that REWARDs distribution occurs.
uint256 accRewardPerShare; // Accumulated REWARDs per share, times 'accRewardMultiplier'.
}
// mutiplier make accumulated REWARDs per share more accurate
uint256 public accRewardMultiplier = 1e12;
// The REWARD TOKEN!
IERC20 public rewardToken;
// REWARD sending from this address
address public rewardSender;
// REWARD tokens created per block.
uint256 public rewardPerBlock;
// reduce reward cycle (of block numbers)
uint256 public reduceCycle;
uint256 public reducePercent;
uint256 public lastReduceBlock;
// Info of each pool.
PoolInfo[] public poolInfo;
mapping (address => uint256) public poolIndex;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when REWARD mining starts.
uint256 public startBlock;
// The block number when REWARD mining ends.
uint256 public endBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
IERC20 _rewardToken,
uint256 _startBlock,
uint256 _rewardPerBlock
) public {
rewardToken = _rewardToken;
startBlock = _startBlock > 0 ? _startBlock : block.number;
rewardPerBlock = _rewardPerBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
function _getCurRewardBlock() internal view returns (uint256) {
return (block.number > endBlock && endBlock > 0) ? endBlock : block.number;
}
function setEndBlock(uint256 _endBlock) public onlyOwner {
require(_endBlock >= startBlock && _endBlock >= block.number, "end block is too low");
endBlock = _endBlock;
}
function setRewardPerBlock(uint256 _rewardPerBlock, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
rewardPerBlock = _rewardPerBlock;
}
function setReduce(uint256 _start, uint256 _reduceCycle, uint256 _reducePercent) public onlyOwner {
require(block.number < _start.add(_reduceCycle), "passed cycle");
lastReduceBlock = _start;
reduceCycle = _reduceCycle;
reducePercent = _reducePercent;
}
// Add a new lp to the pool. Can only be called by the owner.
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
require(poolIndex[address(_lpToken)] == 0, "exist");
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accRewardPerShare: 0
}));
poolIndex[address(_lpToken)] = poolInfo.length;
}
// Update the given pool's REWARD allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// View function to see pending REWARDs on frontend.
function pendingReward(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accRewardPerShare = pool.accRewardPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
uint256 curRewardBlock = _getCurRewardBlock();
if (curRewardBlock > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = curRewardBlock.sub(pool.lastRewardBlock);
uint256 tokenReward = multiplier.mul(rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accRewardPerShare = accRewardPerShare.add(tokenReward.mul(accRewardMultiplier).div(lpSupply));
}
return user.amount.mul(accRewardPerShare).div(accRewardMultiplier).sub(user.rewardDebt);
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reduce cycle
function updateReduce() public {
if (reduceCycle == 0 || reducePercent == 100) {
return;
}
while (block.number >= lastReduceBlock.add(reduceCycle)) {
lastReduceBlock = lastReduceBlock.add(reduceCycle);
rewardPerBlock = rewardPerBlock.mul(reducePercent).div(100);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
updateReduce();
PoolInfo storage pool = poolInfo[_pid];
uint256 curRewardBlock = _getCurRewardBlock();
if (curRewardBlock <= pool.lastRewardBlock) {
if (rewardPerBlock > 0 && endBlock > 0 && block.number > endBlock.add(1000)) {
rewardPerBlock = 0; // wait 1000 blocks for last pool updates of settlements
}
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
uint256 multiplier = curRewardBlock.sub(pool.lastRewardBlock);
uint256 tokenReward = multiplier.mul(rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
if (tokenReward > 0 && lpSupply > 0) {
rewardToken.safeTransferFrom(rewardSender, address(this), tokenReward);
pool.accRewardPerShare = pool.accRewardPerShare.add(tokenReward.mul(accRewardMultiplier).div(lpSupply));
}
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterChef for REWARD allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accRewardPerShare).div(accRewardMultiplier).sub(user.rewardDebt);
if(pending > 0) {
safeRewardTransfer(msg.sender, pending);
}
}
if(_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accRewardPerShare).div(accRewardMultiplier);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accRewardPerShare).div(accRewardMultiplier).sub(user.rewardDebt);
if(pending > 0) {
safeRewardTransfer(msg.sender, pending);
}
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accRewardPerShare).div(accRewardMultiplier);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.lpToken.safeTransfer(address(msg.sender), amount);
emit EmergencyWithdraw(msg.sender, _pid, amount);
}
// Safe rewardToken transfer function, just in case if rounding error causes pool to not have enough REWARDs.
function safeRewardTransfer(address _to, uint256 _amount) internal {
uint256 rewardTokenBal = rewardToken.balanceOf(address(this));
if (_amount > rewardTokenBal) {
_amount = rewardTokenBal;
}
rewardToken.transfer(_to, _amount);
}
// Set reward sender
function setRewardSender(address _newSender) public onlyOwner {
rewardSender = _newSender;
}
}
| 25,257 |
7 | // Offload local vars from stack | uint256 reserveLQFD;
uint256 reserveToken;
uint256 targetReserveToken;
uint256 targetReserveLQFD;
uint256 swapTargetToken;
uint256 swapTargetLQFD;
uint256 tokenSwapped;
uint256 LQFDSwapped;
uint256 tokenReceived;
uint256 LQFDReceived;
| uint256 reserveLQFD;
uint256 reserveToken;
uint256 targetReserveToken;
uint256 targetReserveLQFD;
uint256 swapTargetToken;
uint256 swapTargetLQFD;
uint256 tokenSwapped;
uint256 LQFDSwapped;
uint256 tokenReceived;
uint256 LQFDReceived;
| 5,517 |
56 | // Expects to call only once to create a new lending market. _name Token name. _symbol Token symbol. _controller Core controller contract address. _interestRateModel Token interest rate model contract address. / | function _initialize(
string memory _name,
string memory _symbol,
uint8 _decimals,
IControllerInterface _controller,
IInterestRateModelInterface _interestRateModel
| function _initialize(
string memory _name,
string memory _symbol,
uint8 _decimals,
IControllerInterface _controller,
IInterestRateModelInterface _interestRateModel
| 27,307 |
431 | // round 39 | ark(i, q, 2781996465394730190470582631099299305677291329609718650018200531245670229393);
sbox_partial(i, q);
mix(i, q);
| ark(i, q, 2781996465394730190470582631099299305677291329609718650018200531245670229393);
sbox_partial(i, q);
mix(i, q);
| 48,718 |
226 | // Yearn Base Strategy yearn.finance BaseStrategy implements all of the required functionality to interoperate closely with the Vault contract. This contract should be inherited and the abstract methods implemented to adapt the Strategy to the particular needs it has to create a return.Of special interest is the relationship between `harvest()` and `vault.report()'. `harvest()` may be called simply because enough time has elapsed since the last report, and not because any funds need to be moved or positions adjusted. This is critical so that the Vault may maintain an accurate picture of the Strategy's performance. See`vault.report()`, `harvest()`, and `harvestTrigger()` for further details. | abstract contract BaseStrategy {
using SafeMath for uint256;
/**
* @notice
* Used to track which version of `StrategyAPI` this Strategy
* implements.
* @dev 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.3.0";
}
/**
* @notice This Strategy's name.
* @dev
* You can use this field to manage the "version" of this Strategy, e.g.
* `StrategySomethingOrOtherV1`. However, "API Version" is managed by
* `apiVersion()` function above.
* @return This Strategy's name.
*/
function name() external virtual view returns (string memory);
/**
* @notice
* The amount (priced in want) of the total assets managed by this strategy should not count
* towards Yearn's TVL calculations.
* @dev
* You can override this field to set it to a non-zero value if some of the assets of this
* Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault.
* Note that this value must be strictly less than or equal to the amount provided by
* `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets.
* @return
* The amount of assets this strategy manages that should not be included in Yearn's Total Value
* Locked (TVL) calculation across it's ecosystem.
*/
function delegatedAssets() external virtual view returns (uint256) {
return 0;
}
VaultAPI public vault;
address public strategist;
address public rewards;
address public keeper;
IERC20 public want;
// So indexers can keep track of this
event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding);
event UpdatedStrategist(address newStrategist);
event UpdatedKeeper(address newKeeper);
event UpdatedRewards(address rewards);
event UpdatedReportDelay(uint256 delay);
event UpdatedProfitFactor(uint256 profitFactor);
event UpdatedDebtThreshold(uint256 debtThreshold);
event EmergencyExitEnabled();
// The maximum number of seconds between harvest calls. See
// `setMaxReportDelay()` for more details.
uint256 public maxReportDelay = 86400; // ~ once a day
// The minimum multiple that `callCost` must be above the credit/profit to
// be "justifiable". See `setProfitFactor()` for more details.
uint256 public profitFactor = 100;
// Use this to adjust the threshold at which running a debt causes a
// harvest trigger. See `setDebtThreshold()` for more details.
uint256 public debtThreshold = 0;
// See note on `setEmergencyExit()`.
bool public emergencyExit;
// modifiers
modifier onlyAuthorized() {
require(msg.sender == strategist || msg.sender == governance(), "!authorized");
_;
}
modifier onlyStrategist() {
require(msg.sender == strategist, "!strategist");
_;
}
modifier onlyGovernance() {
require(msg.sender == governance(), "!authorized");
_;
}
modifier onlyKeepers() {
require(msg.sender == keeper || msg.sender == strategist || msg.sender == governance(), "!authorized");
_;
}
/**
* @notice
* Initializes the Strategy, this is called only once, when the
* contract is deployed.
* @dev `_vault` should implement `VaultAPI`.
* @param _vault The address of the Vault responsible for this Strategy.
*/
constructor(address _vault) public {
vault = VaultAPI(_vault);
want = IERC20(vault.token());
want.approve(_vault, uint256(-1)); // Give Vault unlimited access (might save gas)
strategist = msg.sender;
rewards = msg.sender;
keeper = msg.sender;
}
/**
* @notice
* Used to change `strategist`.
*
* This may only be called by governance or the existing strategist.
* @param _strategist The new address to assign as `strategist`.
*/
function setStrategist(address _strategist) external onlyAuthorized {
require(_strategist != address(0));
strategist = _strategist;
emit UpdatedStrategist(_strategist);
}
/**
* @notice
* Used to change `keeper`.
*
* `keeper` is the only address that may call `tend()` or `harvest()`,
* other than `governance()` or `strategist`. However, unlike
* `governance()` or `strategist`, `keeper` may *only* call `tend()`
* and `harvest()`, and no other authorized functions, following the
* principle of least privilege.
*
* This may only be called by governance or the strategist.
* @param _keeper The new address to assign as `keeper`.
*/
function setKeeper(address _keeper) external onlyAuthorized {
require(_keeper != address(0));
keeper = _keeper;
emit UpdatedKeeper(_keeper);
}
/**
* @notice
* Used to change `rewards`. Any distributed rewards will cease flowing
* to the old address and begin flowing to this address once the change
* is in effect.
*
* This may only be called by the strategist.
* @param _rewards The address to use for collecting rewards.
*/
function setRewards(address _rewards) external onlyStrategist {
require(_rewards != address(0));
rewards = _rewards;
emit UpdatedRewards(_rewards);
}
/**
* @notice
* Used to change `maxReportDelay`. `maxReportDelay` is the maximum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the maximum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The maximum number of seconds to wait between harvests.
*/
function setMaxReportDelay(uint256 _delay) external onlyAuthorized {
maxReportDelay = _delay;
emit UpdatedReportDelay(_delay);
}
/**
* @notice
* Used to change `profitFactor`. `profitFactor` is used to determine
* if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _profitFactor A ratio to multiply anticipated
* `harvest()` gas cost against.
*/
function setProfitFactor(uint256 _profitFactor) external onlyAuthorized {
profitFactor = _profitFactor;
emit UpdatedProfitFactor(_profitFactor);
}
/**
* @notice
* Sets how far the Strategy can go into loss without a harvest and report
* being required.
*
* By default this is 0, meaning any losses would cause a harvest which
* will subsequently report the loss to the Vault for tracking. (See
* `harvestTrigger()` for more details.)
*
* This may only be called by governance or the strategist.
* @param _debtThreshold How big of a loss this Strategy may carry without
* being required to report to the Vault.
*/
function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized {
debtThreshold = _debtThreshold;
emit UpdatedDebtThreshold(_debtThreshold);
}
/**
* Resolve governance address from Vault contract, used to make assertions
* on protected functions in the Strategy.
*/
function governance() internal view returns (address) {
return vault.governance();
}
/**
* @notice
* Provide an accurate estimate for the total amount of assets
* (principle + return) that this Strategy is currently managing,
* denominated in terms of `want` tokens.
*
* This total should be "realizable" e.g. the total value that could
* *actually* be obtained from this Strategy if it were to divest its
* entire position based on current on-chain conditions.
* @dev
* Care must be taken in using this function, since it relies on external
* systems, which could be manipulated by the attacker to give an inflated
* (or reduced) value produced by this function, based on current on-chain
* conditions (e.g. this function is possible to influence through
* flashloan attacks, oracle manipulations, or other DeFi attack
* mechanisms).
*
* It is up to governance to use this function to correctly order this
* Strategy relative to its peers in the withdrawal queue to minimize
* losses for the Vault based on sudden withdrawals. This value should be
* higher than the total debt of the Strategy and higher than its expected
* value to be "safe".
* @return The estimated total assets in this Strategy.
*/
function estimatedTotalAssets() public virtual view returns (uint256);
/*
* @notice
* Provide an indication of whether this strategy is currently "active"
* in that it is managing an active position, or will manage a position in
* the future. This should correlate to `harvest()` activity, so that Harvest
* events can be tracked externally by indexing agents.
* @return True if the strategy is actively managing a position.
*/
function isActive() public view returns (bool) {
return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0;
}
/**
* Perform any Strategy unwinding or other calls necessary to capture the
* "free return" this Strategy has generated since the last time its core
* position(s) were adjusted. Examples include unwrapping extra rewards.
* This call is only used during "normal operation" of a Strategy, and
* should be optimized to minimize losses as much as possible.
*
* This method returns any realized profits and/or realized losses
* incurred, and should return the total amounts of profits/losses/debt
* payments (in `want` tokens) for the Vault's accounting (e.g.
* `want.balanceOf(this) >= _debtPayment + _profit - _loss`).
*
* `_debtOutstanding` will be 0 if the Strategy is not past the configured
* debt limit, otherwise its value will be how far past the debt limit
* the Strategy is. The Strategy's debt limit is configured in the Vault.
*
* NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`.
* It is okay for it to be less than `_debtOutstanding`, as that
* should only used as a guide for how much is left to pay back.
* Payments should be made to minimize loss from slippage, debt,
* withdrawal fees, etc.
*
* See `vault.debtOutstanding()`.
*/
function prepareReturn(uint256 _debtOutstanding)
internal
virtual
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
);
/**
* Perform any adjustments to the core position(s) of this Strategy given
* what change the Vault made in the "investable capital" available to the
* Strategy. Note that all "free capital" in the Strategy after the report
* was made is available for reinvestment. Also note that this number
* could be 0, and you should handle that scenario accordingly.
*
* See comments regarding `_debtOutstanding` on `prepareReturn()`.
*/
function adjustPosition(uint256 _debtOutstanding) internal virtual;
/**
* Liquidate up to `_amountNeeded` of `want` of this strategy's positions,
* irregardless of slippage. Any excess will be re-invested with `adjustPosition()`.
* This function should return the amount of `want` tokens made available by the
* liquidation. If there is a difference between them, `_loss` indicates whether the
* difference is due to a realized loss, or if there is some other sitution at play
* (e.g. locked funds). This function is used during emergency exit instead of
* `prepareReturn()` to liquidate all of the Strategy's positions back to the Vault.
*
* NOTE: The invariant `_amountFreed + _loss <= _amountNeeded` should always be maintained
*/
function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss);
/**
* `Harvest()` calls this function after shares are created during
* `vault.report()`. You can customize this function to any share
* distribution mechanism you want.
*
* See `vault.report()` for further details.
*/
function distributeRewards() internal virtual {
// Transfer 100% of newly-minted shares awarded to this contract to the rewards address.
uint256 balance = vault.balanceOf(address(this));
if (balance > 0) {
vault.transfer(rewards, balance);
}
}
/**
* @notice
* Provide a signal to the keeper that `tend()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `tend()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `tend()` is not called
* shortly, then this can return `true` even if the keeper might be
* "at a loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCost` must be priced in terms of `want`.
*
* This call and `harvestTrigger()` should never return `true` at the same
* time.
* @param callCost The keeper's estimated cast cost to call `tend()`.
* @return `true` if `tend()` should be called, `false` otherwise.
*/
function tendTrigger(uint256 callCost) public virtual view returns (bool) {
// We usually don't need tend, but if there are positions that need
// active maintainence, overriding this function is how you would
// signal for that.
return false;
}
/**
* @notice
* Adjust the Strategy's position. The purpose of tending isn't to
* realize gains, but to maximize yield by reinvesting any returns.
*
* See comments on `adjustPosition()`.
*
* This may only be called by governance, the strategist, or the keeper.
*/
function tend() external onlyKeepers {
// Don't take profits with this call, but adjust for better gains
adjustPosition(vault.debtOutstanding());
}
/**
* @notice
* Provide a signal to the keeper that `harvest()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `harvest()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `harvest()` is not called
* shortly, then this can return `true` even if the keeper might be "at a
* loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCost` must be priced in terms of `want`.
*
* This call and `tendTrigger` should never return `true` at the
* same time.
*
* See `maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the
* strategist-controlled parameters that will influence whether this call
* returns `true` or not. These parameters will be used in conjunction
* with the parameters reported to the Vault (see `params`) to determine
* if calling `harvest()` is merited.
*
* It is expected that an external system will check `harvestTrigger()`.
* This could be a script run off a desktop or cloud bot (e.g.
* https://github.com/iearn-finance/yearn-vaults/blob/master/scripts/keep.py),
* or via an integration with the Keep3r network (e.g.
* https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol).
* @param callCost The keeper's estimated cast cost to call `harvest()`.
* @return `true` if `harvest()` should be called, `false` otherwise.
*/
function harvestTrigger(uint256 callCost) public virtual view returns (bool) {
StrategyParams memory params = vault.strategies(address(this));
// Should not trigger if Strategy is not activated
if (params.activation == 0) return false;
// Should trigger if hasn't been called in a while
if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true;
// If some amount is owed, pay it back
// NOTE: Since debt is based on deposits, it makes sense to guard against large
// changes to the value from triggering a harvest directly through user
// behavior. This should ensure reasonable resistance to manipulation
// from user-initiated withdrawals as the outstanding debt fluctuates.
uint256 outstanding = vault.debtOutstanding();
if (outstanding > debtThreshold) return true;
// Check for profits and losses
uint256 total = estimatedTotalAssets();
// Trigger if we have a loss to report
if (total.add(debtThreshold) < params.totalDebt) return true;
uint256 profit = 0;
if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit!
// Otherwise, only trigger if it "makes sense" economically (gas cost
// is <N% of value moved)
uint256 credit = vault.creditAvailable();
return (profitFactor.mul(callCost) < credit.add(profit));
}
/**
* @notice
* Harvests the Strategy, recognizing any profits or losses and adjusting
* the Strategy's position.
*
* In the rare case the Strategy is in emergency shutdown, this will exit
* the Strategy's position.
*
* This may only be called by governance, the strategist, or the keeper.
* @dev
* When `harvest()` is called, the Strategy reports to the Vault (via
* `vault.report()`), so in some cases `harvest()` must be called in order
* to take in profits, to borrow newly available funds from the Vault, or
* otherwise adjust its position. In other cases `harvest()` must be
* called to report to the Vault on the Strategy's position, especially if
* any losses have occurred.
*/
function harvest() external onlyKeepers {
uint256 profit = 0;
uint256 loss = 0;
uint256 debtOutstanding = vault.debtOutstanding();
uint256 debtPayment = 0;
if (emergencyExit) {
// Free up as much capital as possible
uint256 totalAssets = estimatedTotalAssets();
// NOTE: use the larger of total assets or debt outstanding to book losses properly
(debtPayment, loss) = liquidatePosition(totalAssets > debtOutstanding ? totalAssets : debtOutstanding);
// NOTE: take up any remainder here as profit
if (debtPayment > debtOutstanding) {
profit = debtPayment.sub(debtOutstanding);
debtPayment = debtOutstanding;
}
} else {
// Free up returns for Vault to pull
(profit, loss, debtPayment) = prepareReturn(debtOutstanding);
}
// Allow Vault to take up to the "harvested" balance of this contract,
// which is the amount it has earned since the last time it reported to
// the Vault.
debtOutstanding = vault.report(profit, loss, debtPayment);
// Distribute any reward shares earned by the strategy on this report
distributeRewards();
// Check if free returns are left, and re-invest them
adjustPosition(debtOutstanding);
emit Harvested(profit, loss, debtPayment, debtOutstanding);
}
/**
* @notice
* Withdraws `_amountNeeded` to `vault`.
*
* This may only be called by the Vault.
* @param _amountNeeded How much `want` to withdraw.
* @return _loss Any realized losses
*/
function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) {
require(msg.sender == address(vault), "!vault");
// Liquidate as much as possible to `want`, up to `_amount`
uint256 amountFreed;
(amountFreed, _loss) = liquidatePosition(_amountNeeded);
// Send it directly back (NOTE: Using `msg.sender` saves some gas here)
want.transfer(msg.sender, amountFreed);
// NOTE: Reinvest anything leftover on next `tend`/`harvest`
}
/**
* Do anything necessary to prepare this Strategy for migration, such as
* transferring any reserve or LP tokens, CDPs, or other tokens or stores of
* value.
*/
function prepareMigration(address _newStrategy) internal virtual;
/**
* @notice
* Transfers all `want` from this Strategy to `_newStrategy`.
*
* This may only be called by governance or the Vault.
* @dev
* The new Strategy's Vault must be the same as this Strategy's Vault.
* @param _newStrategy The Strategy to migrate to.
*/
function migrate(address _newStrategy) external {
require(msg.sender == address(vault) || msg.sender == governance());
require(BaseStrategy(_newStrategy).vault() == vault);
prepareMigration(_newStrategy);
want.transfer(_newStrategy, want.balanceOf(address(this)));
}
/**
* @notice
* Activates emergency exit. Once activated, the Strategy will exit its
* position upon the next harvest, depositing all funds into the Vault as
* quickly as is reasonable given on-chain conditions.
*
* This may only be called by governance or the strategist.
* @dev
* See `vault.setEmergencyShutdown()` and `harvest()` for further details.
*/
function setEmergencyExit() external onlyAuthorized {
emergencyExit = true;
vault.revokeStrategy();
emit EmergencyExitEnabled();
}
/**
* Override this to add all tokens/tokenized positions this contract
* manages on a *persistent* basis (e.g. not just for swapping back to
* want ephemerally).
*
* NOTE: Do *not* include `want`, already included in `sweep` below.
*
* Example:
*
* function protectedTokens() internal override view returns (address[] memory) {
* address[] memory protected = new address[](3);
* protected[0] = tokenA;
* protected[1] = tokenB;
* protected[2] = tokenC;
* return protected;
* }
*/
function protectedTokens() internal virtual view returns (address[] memory);
/**
* @notice
* Removes tokens from this Strategy that are not the type of tokens
* managed by this Strategy. This may be used in case of accidentally
* sending the wrong kind of token to this Strategy.
*
* Tokens will be sent to `governance()`.
*
* This will fail if an attempt is made to sweep `want`, or any tokens
* that are protected by this Strategy.
*
* This may only be called by governance.
* @dev
* Implement `protectedTokens()` to specify any additional tokens that
* should be protected from sweeping in addition to `want`.
* @param _token The token to transfer out of this vault.
*/
function sweep(address _token) external onlyGovernance {
require(_token != address(want), "!want");
require(_token != address(vault), "!shares");
address[] memory _protectedTokens = protectedTokens();
for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected");
IERC20(_token).transfer(governance(), IERC20(_token).balanceOf(address(this)));
}
}
| abstract contract BaseStrategy {
using SafeMath for uint256;
/**
* @notice
* Used to track which version of `StrategyAPI` this Strategy
* implements.
* @dev 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.3.0";
}
/**
* @notice This Strategy's name.
* @dev
* You can use this field to manage the "version" of this Strategy, e.g.
* `StrategySomethingOrOtherV1`. However, "API Version" is managed by
* `apiVersion()` function above.
* @return This Strategy's name.
*/
function name() external virtual view returns (string memory);
/**
* @notice
* The amount (priced in want) of the total assets managed by this strategy should not count
* towards Yearn's TVL calculations.
* @dev
* You can override this field to set it to a non-zero value if some of the assets of this
* Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault.
* Note that this value must be strictly less than or equal to the amount provided by
* `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets.
* @return
* The amount of assets this strategy manages that should not be included in Yearn's Total Value
* Locked (TVL) calculation across it's ecosystem.
*/
function delegatedAssets() external virtual view returns (uint256) {
return 0;
}
VaultAPI public vault;
address public strategist;
address public rewards;
address public keeper;
IERC20 public want;
// So indexers can keep track of this
event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding);
event UpdatedStrategist(address newStrategist);
event UpdatedKeeper(address newKeeper);
event UpdatedRewards(address rewards);
event UpdatedReportDelay(uint256 delay);
event UpdatedProfitFactor(uint256 profitFactor);
event UpdatedDebtThreshold(uint256 debtThreshold);
event EmergencyExitEnabled();
// The maximum number of seconds between harvest calls. See
// `setMaxReportDelay()` for more details.
uint256 public maxReportDelay = 86400; // ~ once a day
// The minimum multiple that `callCost` must be above the credit/profit to
// be "justifiable". See `setProfitFactor()` for more details.
uint256 public profitFactor = 100;
// Use this to adjust the threshold at which running a debt causes a
// harvest trigger. See `setDebtThreshold()` for more details.
uint256 public debtThreshold = 0;
// See note on `setEmergencyExit()`.
bool public emergencyExit;
// modifiers
modifier onlyAuthorized() {
require(msg.sender == strategist || msg.sender == governance(), "!authorized");
_;
}
modifier onlyStrategist() {
require(msg.sender == strategist, "!strategist");
_;
}
modifier onlyGovernance() {
require(msg.sender == governance(), "!authorized");
_;
}
modifier onlyKeepers() {
require(msg.sender == keeper || msg.sender == strategist || msg.sender == governance(), "!authorized");
_;
}
/**
* @notice
* Initializes the Strategy, this is called only once, when the
* contract is deployed.
* @dev `_vault` should implement `VaultAPI`.
* @param _vault The address of the Vault responsible for this Strategy.
*/
constructor(address _vault) public {
vault = VaultAPI(_vault);
want = IERC20(vault.token());
want.approve(_vault, uint256(-1)); // Give Vault unlimited access (might save gas)
strategist = msg.sender;
rewards = msg.sender;
keeper = msg.sender;
}
/**
* @notice
* Used to change `strategist`.
*
* This may only be called by governance or the existing strategist.
* @param _strategist The new address to assign as `strategist`.
*/
function setStrategist(address _strategist) external onlyAuthorized {
require(_strategist != address(0));
strategist = _strategist;
emit UpdatedStrategist(_strategist);
}
/**
* @notice
* Used to change `keeper`.
*
* `keeper` is the only address that may call `tend()` or `harvest()`,
* other than `governance()` or `strategist`. However, unlike
* `governance()` or `strategist`, `keeper` may *only* call `tend()`
* and `harvest()`, and no other authorized functions, following the
* principle of least privilege.
*
* This may only be called by governance or the strategist.
* @param _keeper The new address to assign as `keeper`.
*/
function setKeeper(address _keeper) external onlyAuthorized {
require(_keeper != address(0));
keeper = _keeper;
emit UpdatedKeeper(_keeper);
}
/**
* @notice
* Used to change `rewards`. Any distributed rewards will cease flowing
* to the old address and begin flowing to this address once the change
* is in effect.
*
* This may only be called by the strategist.
* @param _rewards The address to use for collecting rewards.
*/
function setRewards(address _rewards) external onlyStrategist {
require(_rewards != address(0));
rewards = _rewards;
emit UpdatedRewards(_rewards);
}
/**
* @notice
* Used to change `maxReportDelay`. `maxReportDelay` is the maximum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the maximum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The maximum number of seconds to wait between harvests.
*/
function setMaxReportDelay(uint256 _delay) external onlyAuthorized {
maxReportDelay = _delay;
emit UpdatedReportDelay(_delay);
}
/**
* @notice
* Used to change `profitFactor`. `profitFactor` is used to determine
* if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _profitFactor A ratio to multiply anticipated
* `harvest()` gas cost against.
*/
function setProfitFactor(uint256 _profitFactor) external onlyAuthorized {
profitFactor = _profitFactor;
emit UpdatedProfitFactor(_profitFactor);
}
/**
* @notice
* Sets how far the Strategy can go into loss without a harvest and report
* being required.
*
* By default this is 0, meaning any losses would cause a harvest which
* will subsequently report the loss to the Vault for tracking. (See
* `harvestTrigger()` for more details.)
*
* This may only be called by governance or the strategist.
* @param _debtThreshold How big of a loss this Strategy may carry without
* being required to report to the Vault.
*/
function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized {
debtThreshold = _debtThreshold;
emit UpdatedDebtThreshold(_debtThreshold);
}
/**
* Resolve governance address from Vault contract, used to make assertions
* on protected functions in the Strategy.
*/
function governance() internal view returns (address) {
return vault.governance();
}
/**
* @notice
* Provide an accurate estimate for the total amount of assets
* (principle + return) that this Strategy is currently managing,
* denominated in terms of `want` tokens.
*
* This total should be "realizable" e.g. the total value that could
* *actually* be obtained from this Strategy if it were to divest its
* entire position based on current on-chain conditions.
* @dev
* Care must be taken in using this function, since it relies on external
* systems, which could be manipulated by the attacker to give an inflated
* (or reduced) value produced by this function, based on current on-chain
* conditions (e.g. this function is possible to influence through
* flashloan attacks, oracle manipulations, or other DeFi attack
* mechanisms).
*
* It is up to governance to use this function to correctly order this
* Strategy relative to its peers in the withdrawal queue to minimize
* losses for the Vault based on sudden withdrawals. This value should be
* higher than the total debt of the Strategy and higher than its expected
* value to be "safe".
* @return The estimated total assets in this Strategy.
*/
function estimatedTotalAssets() public virtual view returns (uint256);
/*
* @notice
* Provide an indication of whether this strategy is currently "active"
* in that it is managing an active position, or will manage a position in
* the future. This should correlate to `harvest()` activity, so that Harvest
* events can be tracked externally by indexing agents.
* @return True if the strategy is actively managing a position.
*/
function isActive() public view returns (bool) {
return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0;
}
/**
* Perform any Strategy unwinding or other calls necessary to capture the
* "free return" this Strategy has generated since the last time its core
* position(s) were adjusted. Examples include unwrapping extra rewards.
* This call is only used during "normal operation" of a Strategy, and
* should be optimized to minimize losses as much as possible.
*
* This method returns any realized profits and/or realized losses
* incurred, and should return the total amounts of profits/losses/debt
* payments (in `want` tokens) for the Vault's accounting (e.g.
* `want.balanceOf(this) >= _debtPayment + _profit - _loss`).
*
* `_debtOutstanding` will be 0 if the Strategy is not past the configured
* debt limit, otherwise its value will be how far past the debt limit
* the Strategy is. The Strategy's debt limit is configured in the Vault.
*
* NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`.
* It is okay for it to be less than `_debtOutstanding`, as that
* should only used as a guide for how much is left to pay back.
* Payments should be made to minimize loss from slippage, debt,
* withdrawal fees, etc.
*
* See `vault.debtOutstanding()`.
*/
function prepareReturn(uint256 _debtOutstanding)
internal
virtual
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
);
/**
* Perform any adjustments to the core position(s) of this Strategy given
* what change the Vault made in the "investable capital" available to the
* Strategy. Note that all "free capital" in the Strategy after the report
* was made is available for reinvestment. Also note that this number
* could be 0, and you should handle that scenario accordingly.
*
* See comments regarding `_debtOutstanding` on `prepareReturn()`.
*/
function adjustPosition(uint256 _debtOutstanding) internal virtual;
/**
* Liquidate up to `_amountNeeded` of `want` of this strategy's positions,
* irregardless of slippage. Any excess will be re-invested with `adjustPosition()`.
* This function should return the amount of `want` tokens made available by the
* liquidation. If there is a difference between them, `_loss` indicates whether the
* difference is due to a realized loss, or if there is some other sitution at play
* (e.g. locked funds). This function is used during emergency exit instead of
* `prepareReturn()` to liquidate all of the Strategy's positions back to the Vault.
*
* NOTE: The invariant `_amountFreed + _loss <= _amountNeeded` should always be maintained
*/
function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss);
/**
* `Harvest()` calls this function after shares are created during
* `vault.report()`. You can customize this function to any share
* distribution mechanism you want.
*
* See `vault.report()` for further details.
*/
function distributeRewards() internal virtual {
// Transfer 100% of newly-minted shares awarded to this contract to the rewards address.
uint256 balance = vault.balanceOf(address(this));
if (balance > 0) {
vault.transfer(rewards, balance);
}
}
/**
* @notice
* Provide a signal to the keeper that `tend()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `tend()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `tend()` is not called
* shortly, then this can return `true` even if the keeper might be
* "at a loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCost` must be priced in terms of `want`.
*
* This call and `harvestTrigger()` should never return `true` at the same
* time.
* @param callCost The keeper's estimated cast cost to call `tend()`.
* @return `true` if `tend()` should be called, `false` otherwise.
*/
function tendTrigger(uint256 callCost) public virtual view returns (bool) {
// We usually don't need tend, but if there are positions that need
// active maintainence, overriding this function is how you would
// signal for that.
return false;
}
/**
* @notice
* Adjust the Strategy's position. The purpose of tending isn't to
* realize gains, but to maximize yield by reinvesting any returns.
*
* See comments on `adjustPosition()`.
*
* This may only be called by governance, the strategist, or the keeper.
*/
function tend() external onlyKeepers {
// Don't take profits with this call, but adjust for better gains
adjustPosition(vault.debtOutstanding());
}
/**
* @notice
* Provide a signal to the keeper that `harvest()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `harvest()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `harvest()` is not called
* shortly, then this can return `true` even if the keeper might be "at a
* loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCost` must be priced in terms of `want`.
*
* This call and `tendTrigger` should never return `true` at the
* same time.
*
* See `maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the
* strategist-controlled parameters that will influence whether this call
* returns `true` or not. These parameters will be used in conjunction
* with the parameters reported to the Vault (see `params`) to determine
* if calling `harvest()` is merited.
*
* It is expected that an external system will check `harvestTrigger()`.
* This could be a script run off a desktop or cloud bot (e.g.
* https://github.com/iearn-finance/yearn-vaults/blob/master/scripts/keep.py),
* or via an integration with the Keep3r network (e.g.
* https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol).
* @param callCost The keeper's estimated cast cost to call `harvest()`.
* @return `true` if `harvest()` should be called, `false` otherwise.
*/
function harvestTrigger(uint256 callCost) public virtual view returns (bool) {
StrategyParams memory params = vault.strategies(address(this));
// Should not trigger if Strategy is not activated
if (params.activation == 0) return false;
// Should trigger if hasn't been called in a while
if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true;
// If some amount is owed, pay it back
// NOTE: Since debt is based on deposits, it makes sense to guard against large
// changes to the value from triggering a harvest directly through user
// behavior. This should ensure reasonable resistance to manipulation
// from user-initiated withdrawals as the outstanding debt fluctuates.
uint256 outstanding = vault.debtOutstanding();
if (outstanding > debtThreshold) return true;
// Check for profits and losses
uint256 total = estimatedTotalAssets();
// Trigger if we have a loss to report
if (total.add(debtThreshold) < params.totalDebt) return true;
uint256 profit = 0;
if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit!
// Otherwise, only trigger if it "makes sense" economically (gas cost
// is <N% of value moved)
uint256 credit = vault.creditAvailable();
return (profitFactor.mul(callCost) < credit.add(profit));
}
/**
* @notice
* Harvests the Strategy, recognizing any profits or losses and adjusting
* the Strategy's position.
*
* In the rare case the Strategy is in emergency shutdown, this will exit
* the Strategy's position.
*
* This may only be called by governance, the strategist, or the keeper.
* @dev
* When `harvest()` is called, the Strategy reports to the Vault (via
* `vault.report()`), so in some cases `harvest()` must be called in order
* to take in profits, to borrow newly available funds from the Vault, or
* otherwise adjust its position. In other cases `harvest()` must be
* called to report to the Vault on the Strategy's position, especially if
* any losses have occurred.
*/
function harvest() external onlyKeepers {
uint256 profit = 0;
uint256 loss = 0;
uint256 debtOutstanding = vault.debtOutstanding();
uint256 debtPayment = 0;
if (emergencyExit) {
// Free up as much capital as possible
uint256 totalAssets = estimatedTotalAssets();
// NOTE: use the larger of total assets or debt outstanding to book losses properly
(debtPayment, loss) = liquidatePosition(totalAssets > debtOutstanding ? totalAssets : debtOutstanding);
// NOTE: take up any remainder here as profit
if (debtPayment > debtOutstanding) {
profit = debtPayment.sub(debtOutstanding);
debtPayment = debtOutstanding;
}
} else {
// Free up returns for Vault to pull
(profit, loss, debtPayment) = prepareReturn(debtOutstanding);
}
// Allow Vault to take up to the "harvested" balance of this contract,
// which is the amount it has earned since the last time it reported to
// the Vault.
debtOutstanding = vault.report(profit, loss, debtPayment);
// Distribute any reward shares earned by the strategy on this report
distributeRewards();
// Check if free returns are left, and re-invest them
adjustPosition(debtOutstanding);
emit Harvested(profit, loss, debtPayment, debtOutstanding);
}
/**
* @notice
* Withdraws `_amountNeeded` to `vault`.
*
* This may only be called by the Vault.
* @param _amountNeeded How much `want` to withdraw.
* @return _loss Any realized losses
*/
function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) {
require(msg.sender == address(vault), "!vault");
// Liquidate as much as possible to `want`, up to `_amount`
uint256 amountFreed;
(amountFreed, _loss) = liquidatePosition(_amountNeeded);
// Send it directly back (NOTE: Using `msg.sender` saves some gas here)
want.transfer(msg.sender, amountFreed);
// NOTE: Reinvest anything leftover on next `tend`/`harvest`
}
/**
* Do anything necessary to prepare this Strategy for migration, such as
* transferring any reserve or LP tokens, CDPs, or other tokens or stores of
* value.
*/
function prepareMigration(address _newStrategy) internal virtual;
/**
* @notice
* Transfers all `want` from this Strategy to `_newStrategy`.
*
* This may only be called by governance or the Vault.
* @dev
* The new Strategy's Vault must be the same as this Strategy's Vault.
* @param _newStrategy The Strategy to migrate to.
*/
function migrate(address _newStrategy) external {
require(msg.sender == address(vault) || msg.sender == governance());
require(BaseStrategy(_newStrategy).vault() == vault);
prepareMigration(_newStrategy);
want.transfer(_newStrategy, want.balanceOf(address(this)));
}
/**
* @notice
* Activates emergency exit. Once activated, the Strategy will exit its
* position upon the next harvest, depositing all funds into the Vault as
* quickly as is reasonable given on-chain conditions.
*
* This may only be called by governance or the strategist.
* @dev
* See `vault.setEmergencyShutdown()` and `harvest()` for further details.
*/
function setEmergencyExit() external onlyAuthorized {
emergencyExit = true;
vault.revokeStrategy();
emit EmergencyExitEnabled();
}
/**
* Override this to add all tokens/tokenized positions this contract
* manages on a *persistent* basis (e.g. not just for swapping back to
* want ephemerally).
*
* NOTE: Do *not* include `want`, already included in `sweep` below.
*
* Example:
*
* function protectedTokens() internal override view returns (address[] memory) {
* address[] memory protected = new address[](3);
* protected[0] = tokenA;
* protected[1] = tokenB;
* protected[2] = tokenC;
* return protected;
* }
*/
function protectedTokens() internal virtual view returns (address[] memory);
/**
* @notice
* Removes tokens from this Strategy that are not the type of tokens
* managed by this Strategy. This may be used in case of accidentally
* sending the wrong kind of token to this Strategy.
*
* Tokens will be sent to `governance()`.
*
* This will fail if an attempt is made to sweep `want`, or any tokens
* that are protected by this Strategy.
*
* This may only be called by governance.
* @dev
* Implement `protectedTokens()` to specify any additional tokens that
* should be protected from sweeping in addition to `want`.
* @param _token The token to transfer out of this vault.
*/
function sweep(address _token) external onlyGovernance {
require(_token != address(want), "!want");
require(_token != address(vault), "!shares");
address[] memory _protectedTokens = protectedTokens();
for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected");
IERC20(_token).transfer(governance(), IERC20(_token).balanceOf(address(this)));
}
}
| 9,042 |
1 | // On construction, set auth fields. | constructor() public {
reserveAddress = _msgSender();
emit ReserveAddressTransferred(address(0), reserveAddress);
}
| constructor() public {
reserveAddress = _msgSender();
emit ReserveAddressTransferred(address(0), reserveAddress);
}
| 27,823 |
94 | // Implementation of the basic standard multi-token. _Available since v3.1._ / | contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using Address for address;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/**
* @dev See {_setURI}.
*/
constructor(string memory uri_) {
_setURI(uri_);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_safeTransferFrom(from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][to] += amount;
emit TransferSingle(operator, address(0), to, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `from`
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `from` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address from,
uint256 id,
uint256 amount
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
emit TransferSingle(operator, from, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(
address from,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
}
emit TransferBatch(operator, from, address(0), ids, amounts);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC1155: setting approval status for self");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver.onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
bytes4 response
) {
if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
| contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using Address for address;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/**
* @dev See {_setURI}.
*/
constructor(string memory uri_) {
_setURI(uri_);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_safeTransferFrom(from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][to] += amount;
emit TransferSingle(operator, address(0), to, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `from`
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `from` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address from,
uint256 id,
uint256 amount
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
emit TransferSingle(operator, from, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(
address from,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
}
emit TransferBatch(operator, from, address(0), ids, amounts);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC1155: setting approval status for self");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver.onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
bytes4 response
) {
if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
| 2,719 |
12 | // Liquidate pool due to funds running too low, distribute funds to all users and send `LIQUIDITY_POOL_LIQUIDATION_FEE` to caller. _pool The MarginLiquidityPool. / | function liquidateLiquidityPool(MarginLiquidityPoolInterface _pool) external nonReentrant poolIsVerified(_pool) {
// close positions as much as possible, send fee back to caller
(Percentage.Percent memory enp, Percentage.Percent memory ell) = getEnpAndEll(_pool);
(uint256 enpThreshold, uint256 ellThreshold) = market.config.getEnpAndEllLiquidateThresholds();
require(enp.value <= enpThreshold || ell.value <= ellThreshold, "PL1");
market.protocolLiquidated.__stopPool(_pool);
MarginFlowProtocol.TradingPair[] memory pairs = market.config.getTradingPairs();
uint256 penalty = 0;
Percentage.Percent memory usdBasePrice = Percentage.Percent(market.protocolLiquidated.poolBasePrices(_pool));
for (uint256 i = 0; i < pairs.length; i++) {
penalty = penalty.add(_getPairPenalty(_pool, pairs[i].base, pairs[i].quote, usdBasePrice));
}
uint256 realizedPenalty = Math.min(_pool.getLiquidity(), market.moneyMarket.convertAmountFromBase(penalty.mul(2)));
// approve might fail if MAX UINT is already approved
try _pool.increaseAllowanceForProtocolSafety(realizedPenalty) {
this; // ignore empty code
} catch (bytes memory) {
this; // ignore empty code
}
market.moneyMarket.iToken().safeTransferFrom(address(_pool), laminarTreasury, realizedPenalty);
uint256 depositedITokens = market.liquidityPoolRegistry.liquidatePool(_pool);
market.moneyMarket.redeemTo(msg.sender, depositedITokens);
emit LiquidityPoolLiquidated(address(_pool));
}
| function liquidateLiquidityPool(MarginLiquidityPoolInterface _pool) external nonReentrant poolIsVerified(_pool) {
// close positions as much as possible, send fee back to caller
(Percentage.Percent memory enp, Percentage.Percent memory ell) = getEnpAndEll(_pool);
(uint256 enpThreshold, uint256 ellThreshold) = market.config.getEnpAndEllLiquidateThresholds();
require(enp.value <= enpThreshold || ell.value <= ellThreshold, "PL1");
market.protocolLiquidated.__stopPool(_pool);
MarginFlowProtocol.TradingPair[] memory pairs = market.config.getTradingPairs();
uint256 penalty = 0;
Percentage.Percent memory usdBasePrice = Percentage.Percent(market.protocolLiquidated.poolBasePrices(_pool));
for (uint256 i = 0; i < pairs.length; i++) {
penalty = penalty.add(_getPairPenalty(_pool, pairs[i].base, pairs[i].quote, usdBasePrice));
}
uint256 realizedPenalty = Math.min(_pool.getLiquidity(), market.moneyMarket.convertAmountFromBase(penalty.mul(2)));
// approve might fail if MAX UINT is already approved
try _pool.increaseAllowanceForProtocolSafety(realizedPenalty) {
this; // ignore empty code
} catch (bytes memory) {
this; // ignore empty code
}
market.moneyMarket.iToken().safeTransferFrom(address(_pool), laminarTreasury, realizedPenalty);
uint256 depositedITokens = market.liquidityPoolRegistry.liquidatePool(_pool);
market.moneyMarket.redeemTo(msg.sender, depositedITokens);
emit LiquidityPoolLiquidated(address(_pool));
}
| 46,145 |
15 | // Creates a new position wrapped in a NFT/Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized/ a method does not exist, i.e. the pool is assumed to be initialized./params The params necessary to mint a position, encoded as `MintParams` in calldata/ return tokenId The ID of the token that represents the minted position/ return liquidity The amount of liquidity for this position/ return amount0 The amount of token0/ return amount1 The amount of token1 | function mint(MintParams calldata params)
external
payable
returns (
uint256 tokenId,
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
| function mint(MintParams calldata params)
external
payable
returns (
uint256 tokenId,
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
| 18,477 |
59 | // tokens purchase | function buyTokens(address beneficiary) public withinCrowdsaleTime withinCap payable {
uint256 wei_amount = msg.value;
require(beneficiary != address(0));
require(wei_amount != 0);
// calculate token amount to be sold
uint256 tokens = getTokenAmount(wei_amount);
// update state
wei_raised = wei_raised.add(wei_amount);
require(wei_raised <= hard_cap_wei);
// deliver tokens
token.transfer(beneficiary, tokens);
TokenPurchase(beneficiary, wei_amount, tokens);
// deliver ether
owner.transfer(msg.value);
}
| function buyTokens(address beneficiary) public withinCrowdsaleTime withinCap payable {
uint256 wei_amount = msg.value;
require(beneficiary != address(0));
require(wei_amount != 0);
// calculate token amount to be sold
uint256 tokens = getTokenAmount(wei_amount);
// update state
wei_raised = wei_raised.add(wei_amount);
require(wei_raised <= hard_cap_wei);
// deliver tokens
token.transfer(beneficiary, tokens);
TokenPurchase(beneficiary, wei_amount, tokens);
// deliver ether
owner.transfer(msg.value);
}
| 8,910 |
1 | // ============ Events ============ // ============ Modifiers ============ //Throws if claim is confined to the manager and caller is not the manager / | modifier onlyValidCaller(ISetToken _setToken) {
require(_isValidCaller(_setToken), "Must be valid caller");
_;
}
| modifier onlyValidCaller(ISetToken _setToken) {
require(_isValidCaller(_setToken), "Must be valid caller");
_;
}
| 3,479 |
5 | // Subtracts two unsigned integers, reverts on underflow (i.e. if subtrahend is greater than minuend). / | function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
| function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
| 903 |
33 | // Increase the amount of Nordic Energy tokens that an owner allowed to a spender.approve should be called when allowed_[_spender] == 0. To incrementallowed value is better to use this function to avoid 2 calls (and wait untilthe first transaction is mined)From MonolithDAO Token.solEmits an Approval event. spender The address which will spend the funds. addedValue The amount of Nordic Energy tokens to increase the allowance by. / | function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue); //injected INTEGER OVERFLOW OR UNDERFLOW
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
| function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue); //injected INTEGER OVERFLOW OR UNDERFLOW
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
| 27,695 |
178 | // Remove a issuer from trading availability | function deactivateIssuer(address issuer) external onlyOwnerExecActivator {
activeIssuers[issuer] = false;
}
| function deactivateIssuer(address issuer) external onlyOwnerExecActivator {
activeIssuers[issuer] = false;
}
| 7,515 |
387 | // Helper function to read params from storage and apply offset to the given timestamp. Recall that the formula for epoch number is `n = (t - b) / a`.NOTE: Reverts if epoch zero has not started. return The values `a` and `(t - b)`. / | function _getIntervalAndOffsetTimestamp()
private
view
returns (uint256, uint256)
| function _getIntervalAndOffsetTimestamp()
private
view
returns (uint256, uint256)
| 43,947 |
9 | // Downsize the array to fit. | assembly {
mstore(tokenIds, tokenIdsIdx)
}
| assembly {
mstore(tokenIds, tokenIdsIdx)
}
| 34,651 |
87 | // Allows {owner} to withdraw all funds from this contract. Note that caller must be {owner}. Emits a {OwnerWithdrawFunds} event. / | function withdrawContractFunds(uint256 _amount) external;
| function withdrawContractFunds(uint256 _amount) external;
| 70,717 |
4 | // moves ether from user to owner | function subtractAmountFromUser(uint amount) private {
balances[msg.sender] = balances[msg.sender].sub(amount);
balances[owner] = balances[owner].add(amount);
}
| function subtractAmountFromUser(uint amount) private {
balances[msg.sender] = balances[msg.sender].sub(amount);
balances[owner] = balances[owner].add(amount);
}
| 3,010 |
212 | // Transfer remaining to Vault to handle withdrawal | _transferToVault(_toWithdraw.sub(_fee));
| _transferToVault(_toWithdraw.sub(_fee));
| 8,848 |
189 | // Owner functions //Reserve a few Goats e.g. for giveaways / | function reserveMint(uint16 numberOfTokens , address _to) external onlyOwner {
require(goatsMintedForPromotion.add(numberOfTokens) <= MAX_MintedForPromotion, "Cannot mint more goats for promotion");
require(totalSupply().add(numberOfTokens) < collection_Supply, "Insufficient supply");
goatsMintedForPromotion += numberOfTokens;
_mintTokens(numberOfTokens,_to);
}
| function reserveMint(uint16 numberOfTokens , address _to) external onlyOwner {
require(goatsMintedForPromotion.add(numberOfTokens) <= MAX_MintedForPromotion, "Cannot mint more goats for promotion");
require(totalSupply().add(numberOfTokens) < collection_Supply, "Insufficient supply");
goatsMintedForPromotion += numberOfTokens;
_mintTokens(numberOfTokens,_to);
}
| 77,754 |
24 | // Keep track of the old provenance hash for emitting with the event. |
bytes32 oldProvenanceHash = ERC721ContractMetadataStorage
.layout()
._provenanceHash;
|
bytes32 oldProvenanceHash = ERC721ContractMetadataStorage
.layout()
._provenanceHash;
| 30,655 |
9 | // --- Variables --- | address public priceSource;
uint16 constant ONE_HOUR = uint16(3600);
uint16 public updateDelay = ONE_HOUR;
uint64 public lastUpdateTime;
| address public priceSource;
uint16 constant ONE_HOUR = uint16(3600);
uint16 public updateDelay = ONE_HOUR;
uint64 public lastUpdateTime;
| 10,828 |
120 | // First check most recent balance | if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
| if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
| 186 |
31 | // Unique ID for each different type of signed message in the protocol/ | enum MessageTypeId {
None,
Cashout,
Puzzle,
Refund
}
| enum MessageTypeId {
None,
Cashout,
Puzzle,
Refund
}
| 39,357 |
8 | // The main decoder for memory bs The bytes array to be decodedreturn The decoded struct / | function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
| function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
| 39,148 |
66 | // Winners can claim their own prizes using this.If they dosomething stupid like use a contract, this gives them aa second chance at withdrawing their funds.Note thatthis shares an interlock with `distributeWinnings`. / | function claimPrize() afterDraw {
if (winningsClaimable[msg.sender] == false) {
// get. out!
throw;
}
winningsClaimable[msg.sender] = false;
if (!msg.sender.send(prizeValue)) {
// you really are a dumbshit, aren't you.
throw;
}
}
| function claimPrize() afterDraw {
if (winningsClaimable[msg.sender] == false) {
// get. out!
throw;
}
winningsClaimable[msg.sender] = false;
if (!msg.sender.send(prizeValue)) {
// you really are a dumbshit, aren't you.
throw;
}
}
| 11,453 |
124 | // transfer function that sets up the context so that the _tokenTransfer function can do the accounting work to perform the transfer function | function _transfer(
address sender,
address recipient,
uint256 amountOfTokens
| function _transfer(
address sender,
address recipient,
uint256 amountOfTokens
| 9,640 |
23 | // Value of a ticket in each winning tier | mapping (uint256 => uint256) caste;
| mapping (uint256 => uint256) caste;
| 44,648 |
179 | // update the pauser role / | function updatePauser(address _newPauser) external onlyOwner {
require(
_newPauser != address(0),
"Pausable: new pauser is the zero address"
);
_pauser = _newPauser;
emit PauserChanged(_pauser);
}
| function updatePauser(address _newPauser) external onlyOwner {
require(
_newPauser != address(0),
"Pausable: new pauser is the zero address"
);
_pauser = _newPauser;
emit PauserChanged(_pauser);
}
| 28,178 |
481 | // grabBooty sends to message sender his booty in WEI / | function grabBooty() external {
uint256 booty = ownerToBooty[msg.sender];
require(booty > 0);
require(totalBooty >= booty);
ownerToBooty[msg.sender] = 0;
totalBooty -= booty;
msg.sender.transfer(booty);
//emit event
BootyGrabbed(msg.sender, booty);
}
| function grabBooty() external {
uint256 booty = ownerToBooty[msg.sender];
require(booty > 0);
require(totalBooty >= booty);
ownerToBooty[msg.sender] = 0;
totalBooty -= booty;
msg.sender.transfer(booty);
//emit event
BootyGrabbed(msg.sender, booty);
}
| 40,983 |
272 | // Transfers `tokenId` from `from` to `to`. | * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
| * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
| 30,541 |
73 | // _mint(_msgSender(), 10001018);for testing lockupPeriods[0] = Lockup(200, 1e15); for testing | lockupPeriods[0] = Lockup(604800, 1e15);
lockupPeriods[1] = Lockup(2592000, 4e15);
lockupPeriods[2] = Lockup(5184000, 8e15);
lockupPeriods[3] = Lockup(7776000, 12e15);
lockupPeriods[4] = Lockup(15552000, 24e15);
lockupPeriods[5] = Lockup(31104000, 48e15);
lockupPeriods[6] = Lockup(63113904, 96e15);
lockupPeriods[7] = Lockup(126227808, 192e15);
| lockupPeriods[0] = Lockup(604800, 1e15);
lockupPeriods[1] = Lockup(2592000, 4e15);
lockupPeriods[2] = Lockup(5184000, 8e15);
lockupPeriods[3] = Lockup(7776000, 12e15);
lockupPeriods[4] = Lockup(15552000, 24e15);
lockupPeriods[5] = Lockup(31104000, 48e15);
lockupPeriods[6] = Lockup(63113904, 96e15);
lockupPeriods[7] = Lockup(126227808, 192e15);
| 16,970 |
263 | // IERC165 getter/interfaceId interfaceId bytes4 to check support for | function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721Upgradeable, IERC165Upgradeable)
returns (bool)
| function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721Upgradeable, IERC165Upgradeable)
returns (bool)
| 7,371 |
75 | // Find the FROM address | address fromWithSubstitution = _tokenOwnerWithSubstitutions[_tokenId];
address from = fromWithSubstitution;
if (fromWithSubstitution == address(0)) {
from = address(this);
}
| address fromWithSubstitution = _tokenOwnerWithSubstitutions[_tokenId];
address from = fromWithSubstitution;
if (fromWithSubstitution == address(0)) {
from = address(this);
}
| 47,326 |
24 | // UPDATE TOTAL | if (rewardAmount > 0) {
curTotalSupply = getValueAt(totalSupplyHistory, block.number);
if (curTotalSupply + rewardAmount < curTotalSupply) throw; // Check for overflow
updateValueAtNow(totalSupplyHistory, curTotalSupply + rewardAmount);
}
| if (rewardAmount > 0) {
curTotalSupply = getValueAt(totalSupplyHistory, block.number);
if (curTotalSupply + rewardAmount < curTotalSupply) throw; // Check for overflow
updateValueAtNow(totalSupplyHistory, curTotalSupply + rewardAmount);
}
| 7,960 |
12 | // Kyber Network main contract, takes some fee and reports actual dest amount minus Fees. | contract MaliciousKyberNetwork is KyberNetwork {
address public myWallet = 0x1234;
uint public myFeeWei = 10;
function MaliciousKyberNetwork(address _admin) public KyberNetwork(_admin) { }
/* solhint-disable function-max-lines */
/// @notice use token address ETH_TOKEN_ADDRESS for ether
/// @dev trade api for kyber network.
/// @param tradeInput structure of trade inputs
function trade(TradeInput tradeInput) internal returns(uint) {
require(isEnabled);
require(tx.gasprice <= maxGasPriceValue);
BestRateResult memory rateResult =
findBestRateTokenToToken(tradeInput.src, tradeInput.dest, tradeInput.srcAmount);
require(rateResult.rate > 0);
require(rateResult.rate < MAX_RATE);
require(rateResult.rate >= tradeInput.minConversionRate);
uint actualDestAmount;
uint weiAmount;
uint actualSrcAmount;
(actualSrcAmount, weiAmount, actualDestAmount) = calcActualAmounts(tradeInput.src,
tradeInput.dest,
tradeInput.srcAmount,
tradeInput.maxDestAmount,
rateResult);
if (actualSrcAmount < tradeInput.srcAmount) {
//if there is "change" send back to trader
if (tradeInput.src == ETH_TOKEN_ADDRESS) {
tradeInput.trader.transfer(tradeInput.srcAmount - actualSrcAmount);
} else {
tradeInput.src.transfer(tradeInput.trader, (tradeInput.srcAmount - actualSrcAmount));
}
}
// verify trade size is smaller than user cap
require(weiAmount <= getUserCapInWei(tradeInput.trader));
//do the trade
//src to ETH
require(doReserveTrade(
tradeInput.src,
actualSrcAmount,
ETH_TOKEN_ADDRESS,
this,
weiAmount,
KyberReserveInterface(rateResult.reserve1),
rateResult.rateSrcToEth,
true));
//Eth to dest
require(doReserveTrade(
ETH_TOKEN_ADDRESS,
weiAmount,
tradeInput.dest,
tradeInput.destAddress,
actualDestAmount,
KyberReserveInterface(rateResult.reserve2),
rateResult.rateEthToDest,
true));
return (actualDestAmount - myFeeWei);
}
/* solhint-enable function-max-lines */
function setMyFeeWei(uint fee) public {
myFeeWei = fee;
}
/// @notice use token address ETH_TOKEN_ADDRESS for ether
/// @dev do one trade with a reserve
/// @param src Src token
/// @param amount amount of src tokens
/// @param dest Destination token
/// @param destAddress Address to send tokens to
/// @param reserve Reserve to use
/// @param validate If true, additional validations are applicable
/// @return true if trade is successful
function doReserveTrade(
ERC20 src,
uint amount,
ERC20 dest,
address destAddress,
uint expectedDestAmount,
KyberReserveInterface reserve,
uint conversionRate,
bool validate
)
internal
returns(bool)
{
uint callValue = 0;
if (src == dest) {
//this is for a "fake" trade when both src and dest are ethers.
if (destAddress != (address(this))) {
destAddress.transfer(amount - myFeeWei);
myWallet.transfer(myFeeWei);
}
return true;
}
if (src == ETH_TOKEN_ADDRESS) {
callValue = amount;
}
// reserve sends tokens/eth to network. network sends it to destination
require(reserve.trade.value(callValue)(src, amount, dest, this, conversionRate, validate));
if (destAddress != address(this)) {
//for token to token dest address is network. and Ether / token already here...
if (dest == ETH_TOKEN_ADDRESS) {
destAddress.transfer(expectedDestAmount);
} else {
require(dest.transfer(destAddress, (expectedDestAmount - myFeeWei)));
dest.transfer(myWallet, myFeeWei);
}
}
return true;
}
}
| contract MaliciousKyberNetwork is KyberNetwork {
address public myWallet = 0x1234;
uint public myFeeWei = 10;
function MaliciousKyberNetwork(address _admin) public KyberNetwork(_admin) { }
/* solhint-disable function-max-lines */
/// @notice use token address ETH_TOKEN_ADDRESS for ether
/// @dev trade api for kyber network.
/// @param tradeInput structure of trade inputs
function trade(TradeInput tradeInput) internal returns(uint) {
require(isEnabled);
require(tx.gasprice <= maxGasPriceValue);
BestRateResult memory rateResult =
findBestRateTokenToToken(tradeInput.src, tradeInput.dest, tradeInput.srcAmount);
require(rateResult.rate > 0);
require(rateResult.rate < MAX_RATE);
require(rateResult.rate >= tradeInput.minConversionRate);
uint actualDestAmount;
uint weiAmount;
uint actualSrcAmount;
(actualSrcAmount, weiAmount, actualDestAmount) = calcActualAmounts(tradeInput.src,
tradeInput.dest,
tradeInput.srcAmount,
tradeInput.maxDestAmount,
rateResult);
if (actualSrcAmount < tradeInput.srcAmount) {
//if there is "change" send back to trader
if (tradeInput.src == ETH_TOKEN_ADDRESS) {
tradeInput.trader.transfer(tradeInput.srcAmount - actualSrcAmount);
} else {
tradeInput.src.transfer(tradeInput.trader, (tradeInput.srcAmount - actualSrcAmount));
}
}
// verify trade size is smaller than user cap
require(weiAmount <= getUserCapInWei(tradeInput.trader));
//do the trade
//src to ETH
require(doReserveTrade(
tradeInput.src,
actualSrcAmount,
ETH_TOKEN_ADDRESS,
this,
weiAmount,
KyberReserveInterface(rateResult.reserve1),
rateResult.rateSrcToEth,
true));
//Eth to dest
require(doReserveTrade(
ETH_TOKEN_ADDRESS,
weiAmount,
tradeInput.dest,
tradeInput.destAddress,
actualDestAmount,
KyberReserveInterface(rateResult.reserve2),
rateResult.rateEthToDest,
true));
return (actualDestAmount - myFeeWei);
}
/* solhint-enable function-max-lines */
function setMyFeeWei(uint fee) public {
myFeeWei = fee;
}
/// @notice use token address ETH_TOKEN_ADDRESS for ether
/// @dev do one trade with a reserve
/// @param src Src token
/// @param amount amount of src tokens
/// @param dest Destination token
/// @param destAddress Address to send tokens to
/// @param reserve Reserve to use
/// @param validate If true, additional validations are applicable
/// @return true if trade is successful
function doReserveTrade(
ERC20 src,
uint amount,
ERC20 dest,
address destAddress,
uint expectedDestAmount,
KyberReserveInterface reserve,
uint conversionRate,
bool validate
)
internal
returns(bool)
{
uint callValue = 0;
if (src == dest) {
//this is for a "fake" trade when both src and dest are ethers.
if (destAddress != (address(this))) {
destAddress.transfer(amount - myFeeWei);
myWallet.transfer(myFeeWei);
}
return true;
}
if (src == ETH_TOKEN_ADDRESS) {
callValue = amount;
}
// reserve sends tokens/eth to network. network sends it to destination
require(reserve.trade.value(callValue)(src, amount, dest, this, conversionRate, validate));
if (destAddress != address(this)) {
//for token to token dest address is network. and Ether / token already here...
if (dest == ETH_TOKEN_ADDRESS) {
destAddress.transfer(expectedDestAmount);
} else {
require(dest.transfer(destAddress, (expectedDestAmount - myFeeWei)));
dest.transfer(myWallet, myFeeWei);
}
}
return true;
}
}
| 43,946 |
9 | // initialize RewardDestribution | RewardDestribution['twitter'] = 2990000 * 10 ** uint256(18);
RewardDestribution['facebook'] = 3450000 * 10 ** uint256(18);
RewardDestribution['content'] = 6900000 * 10 ** uint256(18);
RewardDestribution['youtube'] = 2760000 * 10 ** uint256(18);
RewardDestribution['telegram'] = 4600000 * 10 ** uint256(18);
RewardDestribution['instagram'] = 2300000 * 10 ** uint256(18);
RewardDestribution['event'] = 1000000 * 10 ** uint256(18);
RewardDestribution['quiz'] = 500000 * 10 ** uint256(18);
RewardDestribution['partnership'] = 5500000 * 10 ** uint256(18);
| RewardDestribution['twitter'] = 2990000 * 10 ** uint256(18);
RewardDestribution['facebook'] = 3450000 * 10 ** uint256(18);
RewardDestribution['content'] = 6900000 * 10 ** uint256(18);
RewardDestribution['youtube'] = 2760000 * 10 ** uint256(18);
RewardDestribution['telegram'] = 4600000 * 10 ** uint256(18);
RewardDestribution['instagram'] = 2300000 * 10 ** uint256(18);
RewardDestribution['event'] = 1000000 * 10 ** uint256(18);
RewardDestribution['quiz'] = 500000 * 10 ** uint256(18);
RewardDestribution['partnership'] = 5500000 * 10 ** uint256(18);
| 29,948 |
12 | // Lets a contract admin set the royalty recipient and bps for a particular token Id. | function _setupRoyaltyInfoForToken(
uint256 _tokenId,
address _recipient,
uint256 _bps
| function _setupRoyaltyInfoForToken(
uint256 _tokenId,
address _recipient,
uint256 _bps
| 528 |
109 | // turn off Allocator | deactivate(false);
emit MigrationExecuted(newAllocator);
| deactivate(false);
emit MigrationExecuted(newAllocator);
| 63,696 |
27 | // Administrators can manage the contract/ | mapping (address => bool) public administrators;
| mapping (address => bool) public administrators;
| 27,191 |
7 | // Memory address of the buffer data | let bufptr := mload(buf)
| let bufptr := mload(buf)
| 4,699 |
58 | // / | contract FlywheelDynamicRewards is IFlywheelRewards {
using SafeTransferLib for ERC20;
/// @notice the reward token paid
ERC20 public immutable rewardToken;
/// @notice the flywheel core contract
address public immutable flywheel;
constructor(ERC20 _rewardToken, address _flywheel) {
rewardToken = _rewardToken;
flywheel = _flywheel;
}
/**
@notice calculate and transfer accrued rewards to flywheel core
@param market the market to accrue rewards for
@return amount the amount of tokens accrued and transferred
*/
function getAccruedRewards(ERC20 market, uint32) external override returns (uint256 amount) {
require(msg.sender == flywheel, "!flywheel");
amount = rewardToken.balanceOf(address(market));
if (amount > 0) rewardToken.transferFrom(address(market), flywheel, amount);
}
} | contract FlywheelDynamicRewards is IFlywheelRewards {
using SafeTransferLib for ERC20;
/// @notice the reward token paid
ERC20 public immutable rewardToken;
/// @notice the flywheel core contract
address public immutable flywheel;
constructor(ERC20 _rewardToken, address _flywheel) {
rewardToken = _rewardToken;
flywheel = _flywheel;
}
/**
@notice calculate and transfer accrued rewards to flywheel core
@param market the market to accrue rewards for
@return amount the amount of tokens accrued and transferred
*/
function getAccruedRewards(ERC20 market, uint32) external override returns (uint256 amount) {
require(msg.sender == flywheel, "!flywheel");
amount = rewardToken.balanceOf(address(market));
if (amount > 0) rewardToken.transferFrom(address(market), flywheel, amount);
}
} | 38,174 |
2 | // store precommits | mapping(uint256 => PreAnchor) internal _preCommits;
| mapping(uint256 => PreAnchor) internal _preCommits;
| 38,433 |
155 | // Otherwise, use the previously stored number from the matrix. | value = tokenMatrix[random];
| value = tokenMatrix[random];
| 26,881 |
1,402 | // Settle null | _settleNull(msg.sender, MonetaryTypesLib.Currency(currencyCt, currencyId), standard);
| _settleNull(msg.sender, MonetaryTypesLib.Currency(currencyCt, currencyId), standard);
| 35,998 |
1 | // Mints debt token to the `onBehalfOf` address user The address receiving the borrowed underlying, being the delegatee in caseof credit delegate, or same as `onBehalfOf` otherwise onBehalfOf The address receiving the debt tokens amount The amount of debt being minted index The variable debt index of the reservereturn True if the previous balance of the user is 0, false otherwisereturn The scaled total debt of the reserve / | function mint(
address user,
address onBehalfOf,
uint256 amount,
uint256 index
) external returns (bool, uint256);
| function mint(
address user,
address onBehalfOf,
uint256 amount,
uint256 index
) external returns (bool, uint256);
| 2,479 |
7 | // Erase ownership information./ May only be called 6 weeks after/ the contract has been created. | function disown()
public
onlyBy(owner)
onlyAfter(creationTime + 6 weeks)
| function disown()
public
onlyBy(owner)
onlyAfter(creationTime + 6 weeks)
| 12,410 |
138 | // true if the locked tokens have been distributed | bool private lockedTokensDistributed;
| bool private lockedTokensDistributed;
| 37,810 |
211 | // Calculate the maximum token id that can ever be mintedreturn Maximum token id / | function maxTokenId() public view returns (uint256) {
uint256 maxOpenMints = maxTotalSupply - reservedAllowance;
return MAX_N_TOKEN_ID + maxOpenMints;
}
| function maxTokenId() public view returns (uint256) {
uint256 maxOpenMints = maxTotalSupply - reservedAllowance;
return MAX_N_TOKEN_ID + maxOpenMints;
}
| 55,463 |
37 | // empty the storedPayload | sp.payloadLength = 0;
sp.dstAddress = address(0);
sp.payloadHash = bytes32(0);
emit UaForceResumeReceive(_srcChainId, _srcAddress);
| sp.payloadLength = 0;
sp.dstAddress = address(0);
sp.payloadHash = bytes32(0);
emit UaForceResumeReceive(_srcChainId, _srcAddress);
| 24,342 |
4 | // Divides two unsigned 60.18-decimal fixed-point numbers, returning a new unsigned 60.18-decimal fixed-point number.//Uses mulDiv to enable overflow-safe multiplication and division.// Requirements:/ - The denominator cannot be zero.//x The numerator as an unsigned 60.18-decimal fixed-point number./y The denominator as an unsigned 60.18-decimal fixed-point number./result The quotient as an unsigned 60.18-decimal fixed-point number. | function div(uint256 x, uint256 y) internal pure returns (uint256 result) {
result = mulDiv(x, SCALE, y);
}
| function div(uint256 x, uint256 y) internal pure returns (uint256 result) {
result = mulDiv(x, SCALE, y);
}
| 25,344 |
708 | // res += valcoefficients[167]. | res := addmod(res,
mulmod(val, /*coefficients[167]*/ mload(0x1a20), PRIME),
PRIME)
| res := addmod(res,
mulmod(val, /*coefficients[167]*/ mload(0x1a20), PRIME),
PRIME)
| 51,730 |
52 | // TokenVesting A token holder contract that can release its token balance gradually like atypical vesting scheme, with a cliff and vesting period. Optionally revocable by theowner. / | contract TokenVesting is Ownable {
// The vesting schedule is time-based (i.e. using block timestamps as opposed to e.g. block numbers), and is
// therefore sensitive to timestamp manipulation (which is something miners can do, to a certain degree). Therefore,
// it is recommended to avoid using short time durations (less than a minute). Typical vesting schemes, with a
// cliff period of a year and a duration of four years, are safe to use.
// solhint-disable not-rely-on-time
using SafeMath for uint256;
using SafeERC20 for IERC20;
event TokensReleased(address token, uint256 amount);
event TokenVestingRevoked(address token);
// beneficiary of tokens after they are released
address private _beneficiary;
// Durations and timestamps are expressed in UNIX time, the same units as block.timestamp.
uint256 private _cliff;
uint256 private _start;
uint256 private _duration;
bool private _revocable;
mapping (address => uint256) private _released;
mapping (address => bool) private _revoked;
/**
* @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* beneficiary, gradually in a linear fashion until start + duration. By then all
* of the balance will have vested.
* @param beneficiary address of the beneficiary to whom vested tokens are transferred
* @param cliffDuration duration in seconds of the cliff in which tokens will begin to vest
* @param start the time (as Unix time) at which point vesting starts
* @param duration duration in seconds of the period in which the tokens will vest
* @param revocable whether the vesting is revocable or not
*/
constructor (address beneficiary, uint256 start, uint256 cliffDuration, uint256 duration, bool revocable) public {
require(beneficiary != address(0));
require(cliffDuration <= duration);
require(duration > 0);
require(start.add(duration) > block.timestamp);
_beneficiary = beneficiary;
_revocable = revocable;
_duration = duration;
_cliff = start.add(cliffDuration);
_start = start;
}
/**
* @return the beneficiary of the tokens.
*/
function beneficiary() public view returns (address) {
return _beneficiary;
}
/**
* @return the cliff time of the token vesting.
*/
function cliff() public view returns (uint256) {
return _cliff;
}
/**
* @return the start time of the token vesting.
*/
function start() public view returns (uint256) {
return _start;
}
/**
* @return the duration of the token vesting.
*/
function duration() public view returns (uint256) {
return _duration;
}
/**
* @return true if the vesting is revocable.
*/
function revocable() public view returns (bool) {
return _revocable;
}
/**
* @return the amount of the token released.
*/
function released(address token) public view returns (uint256) {
return _released[token];
}
/**
* @return true if the token is revoked.
*/
function revoked(address token) public view returns (bool) {
return _revoked[token];
}
/**
* @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
function release(IERC20 token) public {
uint256 unreleased = _releasableAmount(token);
require(unreleased > 0);
_released[address(token)] = _released[address(token)].add(unreleased);
token.safeTransfer(_beneficiary, unreleased);
emit TokensReleased(address(token), unreleased);
}
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
function revoke(IERC20 token) public onlyOwner {
require(_revocable);
require(!_revoked[address(token)]);
uint256 balance = token.balanceOf(address(this));
uint256 unreleased = _releasableAmount(token);
uint256 refund = balance.sub(unreleased);
_revoked[address(token)] = true;
token.safeTransfer(owner(), refund);
emit TokenVestingRevoked(address(token));
}
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/
function _releasableAmount(IERC20 token) private view returns (uint256) {
return _vestedAmount(token).sub(_released[address(token)]);
}
/**
* @dev Calculates the amount that has already vested.
* @param token ERC20 token which is being vested
*/
function _vestedAmount(IERC20 token) private view returns (uint256) {
uint256 currentBalance = token.balanceOf(address(this));
uint256 totalBalance = currentBalance.add(_released[address(token)]);
if (block.timestamp < _cliff) {
return 0;
} else if (block.timestamp >= _start.add(_duration) || _revoked[address(token)]) {
return totalBalance;
} else {
return totalBalance.mul(block.timestamp.sub(_start)).div(_duration);
}
}
} | contract TokenVesting is Ownable {
// The vesting schedule is time-based (i.e. using block timestamps as opposed to e.g. block numbers), and is
// therefore sensitive to timestamp manipulation (which is something miners can do, to a certain degree). Therefore,
// it is recommended to avoid using short time durations (less than a minute). Typical vesting schemes, with a
// cliff period of a year and a duration of four years, are safe to use.
// solhint-disable not-rely-on-time
using SafeMath for uint256;
using SafeERC20 for IERC20;
event TokensReleased(address token, uint256 amount);
event TokenVestingRevoked(address token);
// beneficiary of tokens after they are released
address private _beneficiary;
// Durations and timestamps are expressed in UNIX time, the same units as block.timestamp.
uint256 private _cliff;
uint256 private _start;
uint256 private _duration;
bool private _revocable;
mapping (address => uint256) private _released;
mapping (address => bool) private _revoked;
/**
* @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* beneficiary, gradually in a linear fashion until start + duration. By then all
* of the balance will have vested.
* @param beneficiary address of the beneficiary to whom vested tokens are transferred
* @param cliffDuration duration in seconds of the cliff in which tokens will begin to vest
* @param start the time (as Unix time) at which point vesting starts
* @param duration duration in seconds of the period in which the tokens will vest
* @param revocable whether the vesting is revocable or not
*/
constructor (address beneficiary, uint256 start, uint256 cliffDuration, uint256 duration, bool revocable) public {
require(beneficiary != address(0));
require(cliffDuration <= duration);
require(duration > 0);
require(start.add(duration) > block.timestamp);
_beneficiary = beneficiary;
_revocable = revocable;
_duration = duration;
_cliff = start.add(cliffDuration);
_start = start;
}
/**
* @return the beneficiary of the tokens.
*/
function beneficiary() public view returns (address) {
return _beneficiary;
}
/**
* @return the cliff time of the token vesting.
*/
function cliff() public view returns (uint256) {
return _cliff;
}
/**
* @return the start time of the token vesting.
*/
function start() public view returns (uint256) {
return _start;
}
/**
* @return the duration of the token vesting.
*/
function duration() public view returns (uint256) {
return _duration;
}
/**
* @return true if the vesting is revocable.
*/
function revocable() public view returns (bool) {
return _revocable;
}
/**
* @return the amount of the token released.
*/
function released(address token) public view returns (uint256) {
return _released[token];
}
/**
* @return true if the token is revoked.
*/
function revoked(address token) public view returns (bool) {
return _revoked[token];
}
/**
* @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
function release(IERC20 token) public {
uint256 unreleased = _releasableAmount(token);
require(unreleased > 0);
_released[address(token)] = _released[address(token)].add(unreleased);
token.safeTransfer(_beneficiary, unreleased);
emit TokensReleased(address(token), unreleased);
}
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
function revoke(IERC20 token) public onlyOwner {
require(_revocable);
require(!_revoked[address(token)]);
uint256 balance = token.balanceOf(address(this));
uint256 unreleased = _releasableAmount(token);
uint256 refund = balance.sub(unreleased);
_revoked[address(token)] = true;
token.safeTransfer(owner(), refund);
emit TokenVestingRevoked(address(token));
}
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/
function _releasableAmount(IERC20 token) private view returns (uint256) {
return _vestedAmount(token).sub(_released[address(token)]);
}
/**
* @dev Calculates the amount that has already vested.
* @param token ERC20 token which is being vested
*/
function _vestedAmount(IERC20 token) private view returns (uint256) {
uint256 currentBalance = token.balanceOf(address(this));
uint256 totalBalance = currentBalance.add(_released[address(token)]);
if (block.timestamp < _cliff) {
return 0;
} else if (block.timestamp >= _start.add(_duration) || _revoked[address(token)]) {
return totalBalance;
} else {
return totalBalance.mul(block.timestamp.sub(_start)).div(_duration);
}
}
} | 12,688 |
211 | // SAKE tokens created per block. | uint256 public sakePerBlock;
| uint256 public sakePerBlock;
| 48,033 |
56 | // recovers the signer address from a offer hash and signature | function signerOfHash(bytes32 offer_hash, bytes memory signature) public pure returns (address signer){
require(signature.length == 65, "sig wrong length");
bytes32 geth_modified_hash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", offer_hash));
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(signature, 32))
s := mload(add(signature, 64))
v := byte(0, mload(add(signature, 96)))
}
if (v < 27) {
v += 27;
}
require(v == 27 || v == 28, "bad sig v");
return ecrecover(geth_modified_hash, v, r, s);
}
| function signerOfHash(bytes32 offer_hash, bytes memory signature) public pure returns (address signer){
require(signature.length == 65, "sig wrong length");
bytes32 geth_modified_hash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", offer_hash));
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(signature, 32))
s := mload(add(signature, 64))
v := byte(0, mload(add(signature, 96)))
}
if (v < 27) {
v += 27;
}
require(v == 27 || v == 28, "bad sig v");
return ecrecover(geth_modified_hash, v, r, s);
}
| 26,775 |
142 | // make an internal approve - delegate to `__approve` | __approve(msg.sender, _approved, _tokenId);
| __approve(msg.sender, _approved, _tokenId);
| 50,401 |
95 | // Left > 0 means incomplete | return left > 0 ? ErrorCode.ERR_CONSTRUCT : ErrorCode.ERR_NONE;
| return left > 0 ? ErrorCode.ERR_CONSTRUCT : ErrorCode.ERR_NONE;
| 27,764 |
82 | // Get pending rewards amount | uint256 pendingRewards = _stkAave.getTotalRewardsBalance(address(this));
if (pendingRewards > 0) {
| uint256 pendingRewards = _stkAave.getTotalRewardsBalance(address(this));
if (pendingRewards > 0) {
| 38,078 |
196 | // the total borrows of the reserve at a stable rate. Expressed in the currency decimals | uint256 totalBorrowsStable;
| uint256 totalBorrowsStable;
| 18,530 |
35 | // [1] Total MV supply | totalSupply(),
| totalSupply(),
| 56,095 |
181 | // See {IERC721-transferFrom}. / | function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
| function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
| 6,474 |
333 | // The default OpenSea operator blocklist subscription. | address internal constant _DEFAULT_SUBSCRIPTION = 0x3cc6CddA760b79bAfa08dF41ECFA224f810dCeB6;
| address internal constant _DEFAULT_SUBSCRIPTION = 0x3cc6CddA760b79bAfa08dF41ECFA224f810dCeB6;
| 564 |
220 | // fee | uint256 public fee; // 0..100.00% (where 1 is 0.01%)
uint256 public feeMax = 5000; // 50.00%
uint256 public denominator = 10000; // 100.00%
| uint256 public fee; // 0..100.00% (where 1 is 0.01%)
uint256 public feeMax = 5000; // 50.00%
uint256 public denominator = 10000; // 100.00%
| 34,357 |
15 | // Reverts if request ID does not exist _requestId The given request ID to check in stored `commitments` / | modifier isValidRequest(bytes32 _requestId) {
require(commitments[_requestId].callbackAddr != address(0), "Must have a valid requestId");
_;
}
| modifier isValidRequest(bytes32 _requestId) {
require(commitments[_requestId].callbackAddr != address(0), "Must have a valid requestId");
_;
}
| 21,347 |
15 | // Function to mint tokens/to address to which new minted tokens are sent/amount of tokens to send / return A boolean that indicates if the operation was successful. | function mint(address to, uint256 amount) public isController() returns (bool) {
require(to != address(0), "Token:mint - Recipient address can't be 0");
_mint(to, amount);
return true;
}
| function mint(address to, uint256 amount) public isController() returns (bool) {
require(to != address(0), "Token:mint - Recipient address can't be 0");
_mint(to, amount);
return true;
}
| 44,446 |
2 | // string[] public orders; mapping(string => bool) _orderExists; | uint public nbOrder = 0;
| uint public nbOrder = 0;
| 19,378 |
42 | // transfer extra borrow amount from liquidator to lend pool | if (vars.extraDebtAmount > 0) {
IERC20Upgradeable(loanData.reserveAsset).safeTransferFrom(vars.initiator, address(this), vars.extraDebtAmount);
}
| if (vars.extraDebtAmount > 0) {
IERC20Upgradeable(loanData.reserveAsset).safeTransferFrom(vars.initiator, address(this), vars.extraDebtAmount);
}
| 13,668 |
70 | // Only once in life time ! Time bonuses is changable after 02.2018 require(timeSlicesCount == 0); | require(_timeSlices.length > 0);
require(_bonuses.length == _timeSlices.length);
uint lastSlice = 0;
uint lastBonus = 10000;
if (timeSlicesCount > 0) {
| require(_timeSlices.length > 0);
require(_bonuses.length == _timeSlices.length);
uint lastSlice = 0;
uint lastBonus = 10000;
if (timeSlicesCount > 0) {
| 71,139 |
12 | // biWidth / biHeight | buf.writeUint32LE(0x12, width);
buf.writeUint32LE(0x16, height);
| buf.writeUint32LE(0x12, width);
buf.writeUint32LE(0x16, height);
| 23,533 |
22 | // Set Gas cost for required transactions after collecting interest in collectInterest functionwe need this to know if caller has enough gas left to keep collecting interest _gasAmount The gas amount that needed for transactions / | function setGasCostExceptInterestCollect(uint256 _gasAmount) public {
_onlyAvatar();
gasCostExceptInterestCollect = _gasAmount;
emit GasCostExceptInterestCollectSet(_gasAmount);
}
| function setGasCostExceptInterestCollect(uint256 _gasAmount) public {
_onlyAvatar();
gasCostExceptInterestCollect = _gasAmount;
emit GasCostExceptInterestCollectSet(_gasAmount);
}
| 4,906 |
28 | // An event emitted when a vault is created | event VaultCreated(address indexed _owner, uint256 indexed _id);
| event VaultCreated(address indexed _owner, uint256 indexed _id);
| 34,429 |
199 | // Emitted when `amount` USDC is supplied to the vault / | event SupplyVault(uint256 amount);
| event SupplyVault(uint256 amount);
| 63,136 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.