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
|
---|---|---|---|---|
56 | // Returns an `Bytes32Slot` with member `value` located at `slot`. / | function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly {
r.slot := slot
}
}
| function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly {
r.slot := slot
}
}
| 93 |
17 | // returns the length of retirees list / | function getRetiredCount() external view returns (uint256);
| function getRetiredCount() external view returns (uint256);
| 13,499 |
332 | // if (compareStrings(cToken.symbol(), "cETH")) { return 1e18; } else { return prices[address(CErc20(address(cToken)).underlying())]; } | address _aggregator = aggregator[address(CErc20(address(cToken)).underlying())];
return uint(AccessControlledAggregator(_aggregator).latestAnswer());
| address _aggregator = aggregator[address(CErc20(address(cToken)).underlying())];
return uint(AccessControlledAggregator(_aggregator).latestAnswer());
| 41,718 |
276 | // Fail gracefully if protocol has insufficient underlying cash | if (getCashPrior() < reduceAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE);
}
| if (getCashPrior() < reduceAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE);
}
| 13,668 |
23 | // Standard ERC20 token Based on code by FirstBlood: / | contract StandardToken is BasicToken, ERC20 {
mapping(address => mapping(address => uint256)) private allowed;
function transferFrom(
address _from,
address _to,
uint256 _value
) public override returns (bool) {
uint256 _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already revert
// if this condition is not met
require(_value <= _allowance, "transfer more then allowed");
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public override returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender)
public
view
override
returns (uint256 remaining)
{
return allowed[_owner][_spender];
}
}
| contract StandardToken is BasicToken, ERC20 {
mapping(address => mapping(address => uint256)) private allowed;
function transferFrom(
address _from,
address _to,
uint256 _value
) public override returns (bool) {
uint256 _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already revert
// if this condition is not met
require(_value <= _allowance, "transfer more then allowed");
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public override returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender)
public
view
override
returns (uint256 remaining)
{
return allowed[_owner][_spender];
}
}
| 23,941 |
3 | // Whether or not new Noun parts can be added | bool public override arePartsLocked;
| bool public override arePartsLocked;
| 36,115 |
37 | // Gauge whether message sender is operator or not/ return true if msg.sender is operator, else false | function isOperator()
internal
view
returns (bool)
| function isOperator()
internal
view
returns (bool)
| 39,965 |
70 | // delete the rest of the data in the record | delete self.proposal_[_whatProposal];
| delete self.proposal_[_whatProposal];
| 242 |
215 | // MANAGER ONLY. Adds a module into a PENDING state; Module must later be initialized via module's initialize function / | function addModule(address _module) external onlyManager {
require(moduleStates[_module] == ISetToken.ModuleState.NONE, "Module must not be added");
require(controller.isModule(_module), "Must be enabled on Controller");
moduleStates[_module] = ISetToken.ModuleState.PENDING;
emit ModuleAdded(_module);
}
| function addModule(address _module) external onlyManager {
require(moduleStates[_module] == ISetToken.ModuleState.NONE, "Module must not be added");
require(controller.isModule(_module), "Must be enabled on Controller");
moduleStates[_module] = ISetToken.ModuleState.PENDING;
emit ModuleAdded(_module);
}
| 25,902 |
303 | // Calculate the combined boost | uint256 liquidity = thisStake.liquidity;
uint256 combined_boosted_amount = liquidity + ((liquidity * (midpoint_lock_multiplier + midpoint_vefxs_multiplier)) / MULTIPLIER_PRECISION);
new_combined_weight += combined_boosted_amount;
| uint256 liquidity = thisStake.liquidity;
uint256 combined_boosted_amount = liquidity + ((liquidity * (midpoint_lock_multiplier + midpoint_vefxs_multiplier)) / MULTIPLIER_PRECISION);
new_combined_weight += combined_boosted_amount;
| 17,892 |
115 | // Claims pixels and requires to have the sender enough unlocked tokens. Has a modifier to take some of the "stack burden" from the proxy function. | function claimShortParams(Rect _rect)
enoughTokens(_rect.width, _rect.height)
internal returns (uint id)
| function claimShortParams(Rect _rect)
enoughTokens(_rect.width, _rect.height)
internal returns (uint id)
| 26,424 |
9 | // 10. send this contract's remaining ETH to the attacker | payable(attacker).sendValue(address(this).balance);
| payable(attacker).sendValue(address(this).balance);
| 26,192 |
4 | // turn on/off public mint / | function flipMintStatePublic() external onlyOwner {
mintIsActivePublic = !mintIsActivePublic;
}
| function flipMintStatePublic() external onlyOwner {
mintIsActivePublic = !mintIsActivePublic;
}
| 12,342 |
2 | // Returns the latest price return latest price / | function getLatestPrice() internal view returns (uint256) {
AggregatorV3Interface priceFeed = getPriceFeed();
(, int256 price, , , ) = priceFeed.latestRoundData();
uint256 newPrice = uint256(price);
return newPrice; // $1500
}
| function getLatestPrice() internal view returns (uint256) {
AggregatorV3Interface priceFeed = getPriceFeed();
(, int256 price, , , ) = priceFeed.latestRoundData();
uint256 newPrice = uint256(price);
return newPrice; // $1500
}
| 35,746 |
28 | // this locks in the pass into the staking contract for X amount of time, this will give access to the application until the lock up period is over | function lockIn(uint256 tokenId, uint256 period) public isLockupAvailable isNotContract {
LockedUp storage _lockedup = lockedup[msg.sender];
require(!_lockedup.hasToken, "You need to withdraw your current token first");
require(period > 0 && period <= 3, "You can only lock in your token for 30 to 90 days!");
mp.transferFrom(msg.sender, address(this), tokenId);
_lockedup.owner = msg.sender;
_lockedup.until = block.timestamp + (30 days * period);
_lockedup.token = tokenId;
_lockedup.hasToken = true;
totalStaked += 1;
emit LockedToken(msg.sender, tokenId, _lockedup.until);
}
| function lockIn(uint256 tokenId, uint256 period) public isLockupAvailable isNotContract {
LockedUp storage _lockedup = lockedup[msg.sender];
require(!_lockedup.hasToken, "You need to withdraw your current token first");
require(period > 0 && period <= 3, "You can only lock in your token for 30 to 90 days!");
mp.transferFrom(msg.sender, address(this), tokenId);
_lockedup.owner = msg.sender;
_lockedup.until = block.timestamp + (30 days * period);
_lockedup.token = tokenId;
_lockedup.hasToken = true;
totalStaked += 1;
emit LockedToken(msg.sender, tokenId, _lockedup.until);
}
| 29,969 |
8 | // Retrieve output token addresses | function getOutputTokens() external view returns (address[] memory) {
return outputTokens;
}
| function getOutputTokens() external view returns (address[] memory) {
return outputTokens;
}
| 35,895 |
109 | // fprintf(stdout, "INFO: PQCLEAN_FALCON512_CLEAN_to_ntt_monty() ENTRY\n"); | mq_NTT(h, logn);
mq_poly_tomonty(h, logn);
| mq_NTT(h, logn);
mq_poly_tomonty(h, logn);
| 14,292 |
153 | // Get the total supply of a campaign _id Campaign to get the supply of / | function totalSupply(uint256 _id) external view returns (uint256) {
return tokenSupply[_id];
}
| function totalSupply(uint256 _id) external view returns (uint256) {
return tokenSupply[_id];
}
| 32,957 |
75 | // enable trading once enabled, it can't be disabled / | function enableTrading () external onlyOwner {
require (!isTradingEnabled, "trading is already live");
isTradingEnabled = true;
}
| function enableTrading () external onlyOwner {
require (!isTradingEnabled, "trading is already live");
isTradingEnabled = true;
}
| 42,945 |
180 | // escrow finalization task, called when owner calls finalize() / | function finalization() internal {
if (goalReached()) {
escrow.close();
escrow.beneficiaryWithdraw();
} else {
escrow.enableRefunds();
}
super.finalization();
}
| function finalization() internal {
if (goalReached()) {
escrow.close();
escrow.beneficiaryWithdraw();
} else {
escrow.enableRefunds();
}
super.finalization();
}
| 3,366 |
4 | // Allows to upgrade the contract. This can only be done via a Safe transaction./_masterCopy New contract address. | function changeMasterCopy(address _masterCopy)
public
authorized
| function changeMasterCopy(address _masterCopy)
public
authorized
| 16,412 |
30 | // Returns the symbol of the token, usually a shorter version of thename. / | function symbol() public view virtual returns (string memory) {
return _symbol;
}
| function symbol() public view virtual returns (string memory) {
return _symbol;
}
| 1,016 |
39 | // {ERC20-approve}, and its usage is discouraged. / | function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
| function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
| 15,449 |
67 | // Contract that will work with ERC223 tokens./ | contract ERC223ReceivingContract {
/**
* @dev Standard ERC223 function that will handle incoming token transfers.
*
* @param _from Token sender address.
* @param _value Amount of tokens.
* @param _data Transaction metadata.
*/
function tokenFallback(address _from, uint _value, bytes _data);
}
| contract ERC223ReceivingContract {
/**
* @dev Standard ERC223 function that will handle incoming token transfers.
*
* @param _from Token sender address.
* @param _value Amount of tokens.
* @param _data Transaction metadata.
*/
function tokenFallback(address _from, uint _value, bytes _data);
}
| 79,927 |
14 | // 正如其名, 这个是增发gas用的.. | function addSupply(uint256 _value) public returns (bool success) {
require(owner == msg.sender);
balanceOf[msg.sender] += _value;
totalSupply += _value;
emit AddSupply(msg.sender, _value);
return true;
}
| function addSupply(uint256 _value) public returns (bool success) {
require(owner == msg.sender);
balanceOf[msg.sender] += _value;
totalSupply += _value;
emit AddSupply(msg.sender, _value);
return true;
}
| 19,116 |
183 | // assetModify is suToken | if (vars.isSuToken) {
vars.sumCollateral = mul_ScalarTruncateAddUInt(
vars.suTokenCollateralRate,
groupVars[i].cTokenBalanceSum,
vars.sumCollateral
);
vars.sumCollateral = mul_ScalarTruncateAddUInt(
vars.inGroupSuTokenCollateralRate,
groupVars[i].suTokenBalanceSum,
vars.sumCollateral
| if (vars.isSuToken) {
vars.sumCollateral = mul_ScalarTruncateAddUInt(
vars.suTokenCollateralRate,
groupVars[i].cTokenBalanceSum,
vars.sumCollateral
);
vars.sumCollateral = mul_ScalarTruncateAddUInt(
vars.inGroupSuTokenCollateralRate,
groupVars[i].suTokenBalanceSum,
vars.sumCollateral
| 28,517 |
28 | // This is removed for optimization (lower gas consumption for each call) Please see 'setAllSupply' function allBalances+=tokenCount | }
| }
| 17,545 |
662 | // moved to initializer to fit proxy safe requirements | _remixContract = remixContract; //set once, never changes
_commitmentId = 1; //set once, can never be set again (contract updates this value)
_verifyAttestation = verificationContract;
_remixFeePercentage = 0;
_dvpContract = dvpContract;
_attestorAddress = 0x538080305560986811c3c1A2c5BCb4F37670EF7e; //Attestor key, needs to match key in Attestation.id
| _remixContract = remixContract; //set once, never changes
_commitmentId = 1; //set once, can never be set again (contract updates this value)
_verifyAttestation = verificationContract;
_remixFeePercentage = 0;
_dvpContract = dvpContract;
_attestorAddress = 0x538080305560986811c3c1A2c5BCb4F37670EF7e; //Attestor key, needs to match key in Attestation.id
| 36,312 |
9 | // Check if the active jackpot is full and finish it if so | if (activeJackpotId != 0 && activeJackpot.participants.length == maxParticipants) {
_finishJackpot(activeJackpotId);
}
| if (activeJackpotId != 0 && activeJackpot.participants.length == maxParticipants) {
_finishJackpot(activeJackpotId);
}
| 27,826 |
1 | // Indicates an error related to the current `balance` of a `sender`. Used in transfers. sender Address whose tokens are being transferred. balance Current balance for the interacting account. needed Minimum amount required to perform a transfer. / | error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
| error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
| 4,311 |
110 | // Fees are added after scaling happens, to reduce the complexity of the rounding direction analysis. This is amount + fee amount, so we round up (favoring a higher fee amount). | return amountIn.divUp(getSwapFeePercentage().complement());
| return amountIn.divUp(getSwapFeePercentage().complement());
| 52,196 |
15 | // Minting Tokens | function unlockMintingTokens(uint256 _amount) external onlyAdmin {
require(_mintingTokensUnlocked <= _mintingTokens);
_mintingTokensUnlocked = add(_mintingTokensUnlocked, _amount);
_totalsupply = add(_totalsupply, _amount);
balances[mintingAdmin] = add(balances[mintingAdmin], _amount);
_lastMintingUnlock = now;
emit Transfer(0, mintingAdmin, _amount);
}
| function unlockMintingTokens(uint256 _amount) external onlyAdmin {
require(_mintingTokensUnlocked <= _mintingTokens);
_mintingTokensUnlocked = add(_mintingTokensUnlocked, _amount);
_totalsupply = add(_totalsupply, _amount);
balances[mintingAdmin] = add(balances[mintingAdmin], _amount);
_lastMintingUnlock = now;
emit Transfer(0, mintingAdmin, _amount);
}
| 41,383 |
3 | // Used to send unclaimed IERC20 funds after claim close date to default destination. Can be called only byadmins. / | function sendUnclaimedFunds() public override onlyAdmin {
super.sendUnclaimedFunds();
Season memory season = seasons[seasonIndex];
SafeERC20.safeTransfer(
IERC20(tokenAddress),
season.defaultDestination,
season.totalRewards - season.claimedRewards
);
}
| function sendUnclaimedFunds() public override onlyAdmin {
super.sendUnclaimedFunds();
Season memory season = seasons[seasonIndex];
SafeERC20.safeTransfer(
IERC20(tokenAddress),
season.defaultDestination,
season.totalRewards - season.claimedRewards
);
}
| 18,912 |
173 | // IdleAdapter Contract/Enzyme Council <[email protected]>/Adapter for Idle Lending <https:idle.finance/>/There are some idiosyncrasies of reward accrual and claiming in IdleTokens that/ are handled by this adapter:/ - Rewards accrue to the IdleToken holder, but the accrued/ amount is passed to the recipient of a transfer./ - Claiming rewards cannot be done on behalf of a holder, but must be done directly./ - Claiming rewards occurs automatically upon redeeming, but there are situations when/ it is difficult to know whether to expect incoming rewards (e.g., after a user mints/ idleTokens and then redeems before any other user has interacted with the protocol,/ | contract IdleAdapter is AdapterBase2, IdleV4ActionsMixin, UniswapV2ActionsMixin {
using AddressArrayLib for address[];
address private immutable IDLE_PRICE_FEED;
address private immutable WETH_TOKEN;
constructor(
address _integrationManager,
address _idlePriceFeed,
address _wethToken,
address _uniswapV2Router2
) public AdapterBase2(_integrationManager) UniswapV2ActionsMixin(_uniswapV2Router2) {
IDLE_PRICE_FEED = _idlePriceFeed;
WETH_TOKEN = _wethToken;
}
/// @notice Provides a constant string identifier for an adapter
/// @return identifier_ An identifier string
function identifier() external pure override returns (string memory identifier_) {
return "IDLE";
}
/// @notice Approves assets from the vault to be used by this contract.
/// @dev No logic necessary. Exists only to grant adapter with necessary approvals from the vault,
/// which takes place in the IntegrationManager.
function approveAssets(
address,
bytes calldata,
bytes calldata
) external {}
/// @notice Claims rewards for a givenIdleToken
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function claimRewards(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
postActionSpendAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(, address idleToken) = __decodeClaimRewardsCallArgs(_encodedCallArgs);
__idleV4ClaimRewards(idleToken);
__pushFullAssetBalances(_vaultProxy, __idleV4GetRewardsTokens(idleToken));
}
/// @notice Claims rewards and then compounds the rewards tokens back into the idleToken
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
/// @dev The `useFullBalances` option indicates whether to use only the newly claimed balances of
/// rewards tokens, or whether to use the full balances of these assets in the vault.
/// If full asset balances are to be used, then this requires the adapter to be granted
/// an allowance of each reward token by the vault.
/// For supported assets (e.g., COMP), this must be done via the `approveAssets()` function in this adapter.
/// For unsupported assets (e.g., IDLE), this must be done via `ComptrollerProxy.vaultCallOnContract()`, if allowed.
function claimRewardsAndReinvest(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
// The idleToken is both the spend asset and the incoming asset in this case
postActionSpendAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(, address idleToken, , bool useFullBalances) = __decodeClaimRewardsAndReinvestCallArgs(
_encodedCallArgs
);
address underlying = __getUnderlyingForIdleToken(idleToken);
require(underlying != address(0), "claimRewardsAndReinvest: Unsupported idleToken");
(
address[] memory rewardsTokens,
uint256[] memory rewardsTokenAmountsToUse
) = __claimRewardsAndPullRewardsTokens(_vaultProxy, idleToken, useFullBalances);
// Swap all reward tokens to the idleToken's underlying via UniswapV2,
// using WETH as the intermediary where necessary
__uniswapV2SwapManyToOne(
address(this),
rewardsTokens,
rewardsTokenAmountsToUse,
underlying,
WETH_TOKEN
);
// Lend all received underlying asset for the idleToken
uint256 underlyingBalance = ERC20(underlying).balanceOf(address(this));
if (underlyingBalance > 0) {
__idleV4Lend(idleToken, underlying, underlyingBalance);
}
}
/// @notice Claims rewards and then swaps the rewards tokens to the specified asset via UniswapV2
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
/// @dev The `useFullBalances` option indicates whether to use only the newly claimed balances of
/// rewards tokens, or whether to use the full balances of these assets in the vault.
/// If full asset balances are to be used, then this requires the adapter to be granted
/// an allowance of each reward token by the vault.
/// For supported assets (e.g., COMP), this must be done via the `approveAssets()` function in this adapter.
/// For unsupported assets (e.g., IDLE), this must be done via `ComptrollerProxy.vaultCallOnContract()`, if allowed.
function claimRewardsAndSwap(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
postActionSpendAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(
,
address idleToken,
address incomingAsset,
,
bool useFullBalances
) = __decodeClaimRewardsAndSwapCallArgs(_encodedCallArgs);
(
address[] memory rewardsTokens,
uint256[] memory rewardsTokenAmountsToUse
) = __claimRewardsAndPullRewardsTokens(_vaultProxy, idleToken, useFullBalances);
// Swap all reward tokens to the designated incomingAsset via UniswapV2,
// using WETH as the intermediary where necessary
__uniswapV2SwapManyToOne(
_vaultProxy,
rewardsTokens,
rewardsTokenAmountsToUse,
incomingAsset,
WETH_TOKEN
);
}
/// @notice Lends an amount of a token for idleToken
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function lend(
address _vaultProxy,
bytes calldata,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
// More efficient to parse all from _encodedAssetTransferArgs
(
,
address[] memory spendAssets,
uint256[] memory spendAssetAmounts,
address[] memory incomingAssets
) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs);
__idleV4Lend(incomingAssets[0], spendAssets[0], spendAssetAmounts[0]);
}
/// @notice Redeems an amount of idleToken for its underlying asset
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
/// @dev This will also pay out any due gov token rewards
function redeem(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(address idleToken, uint256 outgoingIdleTokenAmount, ) = __decodeRedeemCallArgs(
_encodedCallArgs
);
__idleV4Redeem(idleToken, outgoingIdleTokenAmount);
__pushFullAssetBalances(_vaultProxy, __idleV4GetRewardsTokens(idleToken));
}
/// @dev Helper to claim rewards and pull rewards tokens from the vault
/// to the current contract, as needed
function __claimRewardsAndPullRewardsTokens(
address _vaultProxy,
address _idleToken,
bool _useFullBalances
)
private
returns (address[] memory rewardsTokens_, uint256[] memory rewardsTokenAmountsToUse_)
{
__idleV4ClaimRewards(_idleToken);
rewardsTokens_ = __idleV4GetRewardsTokens(_idleToken);
if (_useFullBalances) {
__pullFullAssetBalances(_vaultProxy, rewardsTokens_);
}
return (rewardsTokens_, __getAssetBalances(address(this), rewardsTokens_));
}
/// @dev Helper to get the underlying for a given IdleToken
function __getUnderlyingForIdleToken(address _idleToken)
private
view
returns (address underlying_)
{
return IdlePriceFeed(IDLE_PRICE_FEED).getUnderlyingForDerivative(_idleToken);
}
/////////////////////////////
// PARSE ASSETS FOR METHOD //
/////////////////////////////
/// @notice Parses the expected assets to receive from a call on integration
/// @param _selector The function selector for the callOnIntegration
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
if (_selector == APPROVE_ASSETS_SELECTOR) {
return __parseAssetsForApproveAssets(_encodedCallArgs);
} else if (_selector == CLAIM_REWARDS_SELECTOR) {
return __parseAssetsForClaimRewards(_encodedCallArgs);
} else if (_selector == CLAIM_REWARDS_AND_REINVEST_SELECTOR) {
return __parseAssetsForClaimRewardsAndReinvest(_encodedCallArgs);
} else if (_selector == CLAIM_REWARDS_AND_SWAP_SELECTOR) {
return __parseAssetsForClaimRewardsAndSwap(_encodedCallArgs);
} else if (_selector == LEND_SELECTOR) {
return __parseAssetsForLend(_encodedCallArgs);
} else if (_selector == REDEEM_SELECTOR) {
return __parseAssetsForRedeem(_encodedCallArgs);
}
revert("parseAssetsForMethod: _selector invalid");
}
/// @dev Helper function to parse spend and incoming assets from encoded call args
/// during approveAssets() calls
function __parseAssetsForApproveAssets(bytes calldata _encodedCallArgs)
private
view
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
address idleToken;
(idleToken, spendAssets_, spendAssetAmounts_) = __decodeApproveAssetsCallArgs(
_encodedCallArgs
);
require(
__getUnderlyingForIdleToken(idleToken) != address(0),
"__parseAssetsForApproveAssets: Unsupported idleToken"
);
require(
spendAssets_.length == spendAssetAmounts_.length,
"__parseAssetsForApproveAssets: Unequal arrays"
);
// Validate that only rewards tokens are given allowances
address[] memory rewardsTokens = __idleV4GetRewardsTokens(idleToken);
for (uint256 i; i < spendAssets_.length; i++) {
// Allow revoking approval for any asset
if (spendAssetAmounts_[i] > 0) {
require(
rewardsTokens.contains(spendAssets_[i]),
"__parseAssetsForApproveAssets: Invalid reward token"
);
}
}
return (
IIntegrationManager.SpendAssetsHandleType.Approve,
spendAssets_,
spendAssetAmounts_,
new address[](0),
new uint256[](0)
);
}
/// @dev Helper function to parse spend and incoming assets from encoded call args
/// during claimRewards() calls
function __parseAssetsForClaimRewards(bytes calldata _encodedCallArgs)
private
view
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
(address vaultProxy, address idleToken) = __decodeClaimRewardsCallArgs(_encodedCallArgs);
require(
__getUnderlyingForIdleToken(idleToken) != address(0),
"__parseAssetsForClaimRewards: Unsupported idleToken"
);
(spendAssets_, spendAssetAmounts_) = __parseSpendAssetsForClaimRewardsCalls(
vaultProxy,
idleToken
);
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
new address[](0),
new uint256[](0)
);
}
/// @dev Helper function to parse spend and incoming assets from encoded call args
/// during claimRewardsAndReinvest() calls.
function __parseAssetsForClaimRewardsAndReinvest(bytes calldata _encodedCallArgs)
private
view
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
(
address vaultProxy,
address idleToken,
uint256 minIncomingIdleTokenAmount,
) = __decodeClaimRewardsAndReinvestCallArgs(_encodedCallArgs);
// Does not validate idleToken here as we need to do fetch the underlying during the action
(spendAssets_, spendAssetAmounts_) = __parseSpendAssetsForClaimRewardsCalls(
vaultProxy,
idleToken
);
incomingAssets_ = new address[](1);
incomingAssets_[0] = idleToken;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIncomingIdleTokenAmount;
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @dev Helper function to parse spend and incoming assets from encoded call args
/// during claimRewardsAndSwap() calls.
function __parseAssetsForClaimRewardsAndSwap(bytes calldata _encodedCallArgs)
private
view
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
(
address vaultProxy,
address idleToken,
address incomingAsset,
uint256 minIncomingAssetAmount,
) = __decodeClaimRewardsAndSwapCallArgs(_encodedCallArgs);
require(
__getUnderlyingForIdleToken(idleToken) != address(0),
"__parseAssetsForClaimRewardsAndSwap: Unsupported idleToken"
);
(spendAssets_, spendAssetAmounts_) = __parseSpendAssetsForClaimRewardsCalls(
vaultProxy,
idleToken
);
incomingAssets_ = new address[](1);
incomingAssets_[0] = incomingAsset;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIncomingAssetAmount;
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @dev Helper function to parse spend and incoming assets from encoded call args
/// during lend() calls
function __parseAssetsForLend(bytes calldata _encodedCallArgs)
private
view
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
(
address idleToken,
uint256 outgoingUnderlyingAmount,
uint256 minIncomingIdleTokenAmount
) = __decodeLendCallArgs(_encodedCallArgs);
address underlying = __getUnderlyingForIdleToken(idleToken);
require(underlying != address(0), "__parseAssetsForLend: Unsupported idleToken");
spendAssets_ = new address[](1);
spendAssets_[0] = underlying;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingUnderlyingAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = idleToken;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIncomingIdleTokenAmount;
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @dev Helper function to parse spend and incoming assets from encoded call args
/// during redeem() calls
function __parseAssetsForRedeem(bytes calldata _encodedCallArgs)
private
view
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
(
address idleToken,
uint256 outgoingIdleTokenAmount,
uint256 minIncomingUnderlyingAmount
) = __decodeRedeemCallArgs(_encodedCallArgs);
address underlying = __getUnderlyingForIdleToken(idleToken);
require(underlying != address(0), "__parseAssetsForRedeem: Unsupported idleToken");
spendAssets_ = new address[](1);
spendAssets_[0] = idleToken;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingIdleTokenAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = underlying;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIncomingUnderlyingAmount;
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @dev Helper function to parse spend assets for calls to claim rewards
function __parseSpendAssetsForClaimRewardsCalls(address _vaultProxy, address _idleToken)
private
view
returns (address[] memory spendAssets_, uint256[] memory spendAssetAmounts_)
{
spendAssets_ = new address[](1);
spendAssets_[0] = _idleToken;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = ERC20(_idleToken).balanceOf(_vaultProxy);
return (spendAssets_, spendAssetAmounts_);
}
///////////////////////
// ENCODED CALL ARGS //
///////////////////////
/// @dev Helper to decode the encoded call arguments for approving asset allowances
function __decodeApproveAssetsCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
address idleToken_,
address[] memory assets_,
uint256[] memory amounts_
)
{
return abi.decode(_encodedCallArgs, (address, address[], uint256[]));
}
/// @dev Helper to decode callArgs for claiming rewards tokens
function __decodeClaimRewardsCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (address vaultProxy_, address idleToken_)
{
return abi.decode(_encodedCallArgs, (address, address));
}
/// @dev Helper to decode the encoded call arguments for claiming rewards and reinvesting
function __decodeClaimRewardsAndReinvestCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
address vaultProxy_,
address idleToken_,
uint256 minIncomingIdleTokenAmount_,
bool useFullBalances_
)
{
return abi.decode(_encodedCallArgs, (address, address, uint256, bool));
}
/// @dev Helper to decode the encoded call arguments for claiming rewards and swapping
function __decodeClaimRewardsAndSwapCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
address vaultProxy_,
address idleToken_,
address incomingAsset_,
uint256 minIncomingAssetAmount_,
bool useFullBalances_
)
{
return abi.decode(_encodedCallArgs, (address, address, address, uint256, bool));
}
/// @dev Helper to decode callArgs for lending
function __decodeLendCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
address idleToken_,
uint256 outgoingUnderlyingAmount_,
uint256 minIncomingIdleTokenAmount_
)
{
return abi.decode(_encodedCallArgs, (address, uint256, uint256));
}
/// @dev Helper to decode callArgs for redeeming
function __decodeRedeemCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
address idleToken_,
uint256 outgoingIdleTokenAmount_,
uint256 minIncomingUnderlyingAmount_
)
{
return abi.decode(_encodedCallArgs, (address, uint256, uint256));
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `IDLE_PRICE_FEED` variable
/// @return idlePriceFeed_ The `IDLE_PRICE_FEED` variable value
function getIdlePriceFeed() external view returns (address idlePriceFeed_) {
return IDLE_PRICE_FEED;
}
/// @notice Gets the `WETH_TOKEN` variable
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() external view returns (address wethToken_) {
return WETH_TOKEN;
}
}
| contract IdleAdapter is AdapterBase2, IdleV4ActionsMixin, UniswapV2ActionsMixin {
using AddressArrayLib for address[];
address private immutable IDLE_PRICE_FEED;
address private immutable WETH_TOKEN;
constructor(
address _integrationManager,
address _idlePriceFeed,
address _wethToken,
address _uniswapV2Router2
) public AdapterBase2(_integrationManager) UniswapV2ActionsMixin(_uniswapV2Router2) {
IDLE_PRICE_FEED = _idlePriceFeed;
WETH_TOKEN = _wethToken;
}
/// @notice Provides a constant string identifier for an adapter
/// @return identifier_ An identifier string
function identifier() external pure override returns (string memory identifier_) {
return "IDLE";
}
/// @notice Approves assets from the vault to be used by this contract.
/// @dev No logic necessary. Exists only to grant adapter with necessary approvals from the vault,
/// which takes place in the IntegrationManager.
function approveAssets(
address,
bytes calldata,
bytes calldata
) external {}
/// @notice Claims rewards for a givenIdleToken
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function claimRewards(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
postActionSpendAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(, address idleToken) = __decodeClaimRewardsCallArgs(_encodedCallArgs);
__idleV4ClaimRewards(idleToken);
__pushFullAssetBalances(_vaultProxy, __idleV4GetRewardsTokens(idleToken));
}
/// @notice Claims rewards and then compounds the rewards tokens back into the idleToken
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
/// @dev The `useFullBalances` option indicates whether to use only the newly claimed balances of
/// rewards tokens, or whether to use the full balances of these assets in the vault.
/// If full asset balances are to be used, then this requires the adapter to be granted
/// an allowance of each reward token by the vault.
/// For supported assets (e.g., COMP), this must be done via the `approveAssets()` function in this adapter.
/// For unsupported assets (e.g., IDLE), this must be done via `ComptrollerProxy.vaultCallOnContract()`, if allowed.
function claimRewardsAndReinvest(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
// The idleToken is both the spend asset and the incoming asset in this case
postActionSpendAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(, address idleToken, , bool useFullBalances) = __decodeClaimRewardsAndReinvestCallArgs(
_encodedCallArgs
);
address underlying = __getUnderlyingForIdleToken(idleToken);
require(underlying != address(0), "claimRewardsAndReinvest: Unsupported idleToken");
(
address[] memory rewardsTokens,
uint256[] memory rewardsTokenAmountsToUse
) = __claimRewardsAndPullRewardsTokens(_vaultProxy, idleToken, useFullBalances);
// Swap all reward tokens to the idleToken's underlying via UniswapV2,
// using WETH as the intermediary where necessary
__uniswapV2SwapManyToOne(
address(this),
rewardsTokens,
rewardsTokenAmountsToUse,
underlying,
WETH_TOKEN
);
// Lend all received underlying asset for the idleToken
uint256 underlyingBalance = ERC20(underlying).balanceOf(address(this));
if (underlyingBalance > 0) {
__idleV4Lend(idleToken, underlying, underlyingBalance);
}
}
/// @notice Claims rewards and then swaps the rewards tokens to the specified asset via UniswapV2
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
/// @dev The `useFullBalances` option indicates whether to use only the newly claimed balances of
/// rewards tokens, or whether to use the full balances of these assets in the vault.
/// If full asset balances are to be used, then this requires the adapter to be granted
/// an allowance of each reward token by the vault.
/// For supported assets (e.g., COMP), this must be done via the `approveAssets()` function in this adapter.
/// For unsupported assets (e.g., IDLE), this must be done via `ComptrollerProxy.vaultCallOnContract()`, if allowed.
function claimRewardsAndSwap(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
postActionSpendAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(
,
address idleToken,
address incomingAsset,
,
bool useFullBalances
) = __decodeClaimRewardsAndSwapCallArgs(_encodedCallArgs);
(
address[] memory rewardsTokens,
uint256[] memory rewardsTokenAmountsToUse
) = __claimRewardsAndPullRewardsTokens(_vaultProxy, idleToken, useFullBalances);
// Swap all reward tokens to the designated incomingAsset via UniswapV2,
// using WETH as the intermediary where necessary
__uniswapV2SwapManyToOne(
_vaultProxy,
rewardsTokens,
rewardsTokenAmountsToUse,
incomingAsset,
WETH_TOKEN
);
}
/// @notice Lends an amount of a token for idleToken
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function lend(
address _vaultProxy,
bytes calldata,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
// More efficient to parse all from _encodedAssetTransferArgs
(
,
address[] memory spendAssets,
uint256[] memory spendAssetAmounts,
address[] memory incomingAssets
) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs);
__idleV4Lend(incomingAssets[0], spendAssets[0], spendAssetAmounts[0]);
}
/// @notice Redeems an amount of idleToken for its underlying asset
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
/// @dev This will also pay out any due gov token rewards
function redeem(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(address idleToken, uint256 outgoingIdleTokenAmount, ) = __decodeRedeemCallArgs(
_encodedCallArgs
);
__idleV4Redeem(idleToken, outgoingIdleTokenAmount);
__pushFullAssetBalances(_vaultProxy, __idleV4GetRewardsTokens(idleToken));
}
/// @dev Helper to claim rewards and pull rewards tokens from the vault
/// to the current contract, as needed
function __claimRewardsAndPullRewardsTokens(
address _vaultProxy,
address _idleToken,
bool _useFullBalances
)
private
returns (address[] memory rewardsTokens_, uint256[] memory rewardsTokenAmountsToUse_)
{
__idleV4ClaimRewards(_idleToken);
rewardsTokens_ = __idleV4GetRewardsTokens(_idleToken);
if (_useFullBalances) {
__pullFullAssetBalances(_vaultProxy, rewardsTokens_);
}
return (rewardsTokens_, __getAssetBalances(address(this), rewardsTokens_));
}
/// @dev Helper to get the underlying for a given IdleToken
function __getUnderlyingForIdleToken(address _idleToken)
private
view
returns (address underlying_)
{
return IdlePriceFeed(IDLE_PRICE_FEED).getUnderlyingForDerivative(_idleToken);
}
/////////////////////////////
// PARSE ASSETS FOR METHOD //
/////////////////////////////
/// @notice Parses the expected assets to receive from a call on integration
/// @param _selector The function selector for the callOnIntegration
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
if (_selector == APPROVE_ASSETS_SELECTOR) {
return __parseAssetsForApproveAssets(_encodedCallArgs);
} else if (_selector == CLAIM_REWARDS_SELECTOR) {
return __parseAssetsForClaimRewards(_encodedCallArgs);
} else if (_selector == CLAIM_REWARDS_AND_REINVEST_SELECTOR) {
return __parseAssetsForClaimRewardsAndReinvest(_encodedCallArgs);
} else if (_selector == CLAIM_REWARDS_AND_SWAP_SELECTOR) {
return __parseAssetsForClaimRewardsAndSwap(_encodedCallArgs);
} else if (_selector == LEND_SELECTOR) {
return __parseAssetsForLend(_encodedCallArgs);
} else if (_selector == REDEEM_SELECTOR) {
return __parseAssetsForRedeem(_encodedCallArgs);
}
revert("parseAssetsForMethod: _selector invalid");
}
/// @dev Helper function to parse spend and incoming assets from encoded call args
/// during approveAssets() calls
function __parseAssetsForApproveAssets(bytes calldata _encodedCallArgs)
private
view
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
address idleToken;
(idleToken, spendAssets_, spendAssetAmounts_) = __decodeApproveAssetsCallArgs(
_encodedCallArgs
);
require(
__getUnderlyingForIdleToken(idleToken) != address(0),
"__parseAssetsForApproveAssets: Unsupported idleToken"
);
require(
spendAssets_.length == spendAssetAmounts_.length,
"__parseAssetsForApproveAssets: Unequal arrays"
);
// Validate that only rewards tokens are given allowances
address[] memory rewardsTokens = __idleV4GetRewardsTokens(idleToken);
for (uint256 i; i < spendAssets_.length; i++) {
// Allow revoking approval for any asset
if (spendAssetAmounts_[i] > 0) {
require(
rewardsTokens.contains(spendAssets_[i]),
"__parseAssetsForApproveAssets: Invalid reward token"
);
}
}
return (
IIntegrationManager.SpendAssetsHandleType.Approve,
spendAssets_,
spendAssetAmounts_,
new address[](0),
new uint256[](0)
);
}
/// @dev Helper function to parse spend and incoming assets from encoded call args
/// during claimRewards() calls
function __parseAssetsForClaimRewards(bytes calldata _encodedCallArgs)
private
view
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
(address vaultProxy, address idleToken) = __decodeClaimRewardsCallArgs(_encodedCallArgs);
require(
__getUnderlyingForIdleToken(idleToken) != address(0),
"__parseAssetsForClaimRewards: Unsupported idleToken"
);
(spendAssets_, spendAssetAmounts_) = __parseSpendAssetsForClaimRewardsCalls(
vaultProxy,
idleToken
);
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
new address[](0),
new uint256[](0)
);
}
/// @dev Helper function to parse spend and incoming assets from encoded call args
/// during claimRewardsAndReinvest() calls.
function __parseAssetsForClaimRewardsAndReinvest(bytes calldata _encodedCallArgs)
private
view
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
(
address vaultProxy,
address idleToken,
uint256 minIncomingIdleTokenAmount,
) = __decodeClaimRewardsAndReinvestCallArgs(_encodedCallArgs);
// Does not validate idleToken here as we need to do fetch the underlying during the action
(spendAssets_, spendAssetAmounts_) = __parseSpendAssetsForClaimRewardsCalls(
vaultProxy,
idleToken
);
incomingAssets_ = new address[](1);
incomingAssets_[0] = idleToken;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIncomingIdleTokenAmount;
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @dev Helper function to parse spend and incoming assets from encoded call args
/// during claimRewardsAndSwap() calls.
function __parseAssetsForClaimRewardsAndSwap(bytes calldata _encodedCallArgs)
private
view
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
(
address vaultProxy,
address idleToken,
address incomingAsset,
uint256 minIncomingAssetAmount,
) = __decodeClaimRewardsAndSwapCallArgs(_encodedCallArgs);
require(
__getUnderlyingForIdleToken(idleToken) != address(0),
"__parseAssetsForClaimRewardsAndSwap: Unsupported idleToken"
);
(spendAssets_, spendAssetAmounts_) = __parseSpendAssetsForClaimRewardsCalls(
vaultProxy,
idleToken
);
incomingAssets_ = new address[](1);
incomingAssets_[0] = incomingAsset;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIncomingAssetAmount;
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @dev Helper function to parse spend and incoming assets from encoded call args
/// during lend() calls
function __parseAssetsForLend(bytes calldata _encodedCallArgs)
private
view
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
(
address idleToken,
uint256 outgoingUnderlyingAmount,
uint256 minIncomingIdleTokenAmount
) = __decodeLendCallArgs(_encodedCallArgs);
address underlying = __getUnderlyingForIdleToken(idleToken);
require(underlying != address(0), "__parseAssetsForLend: Unsupported idleToken");
spendAssets_ = new address[](1);
spendAssets_[0] = underlying;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingUnderlyingAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = idleToken;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIncomingIdleTokenAmount;
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @dev Helper function to parse spend and incoming assets from encoded call args
/// during redeem() calls
function __parseAssetsForRedeem(bytes calldata _encodedCallArgs)
private
view
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
(
address idleToken,
uint256 outgoingIdleTokenAmount,
uint256 minIncomingUnderlyingAmount
) = __decodeRedeemCallArgs(_encodedCallArgs);
address underlying = __getUnderlyingForIdleToken(idleToken);
require(underlying != address(0), "__parseAssetsForRedeem: Unsupported idleToken");
spendAssets_ = new address[](1);
spendAssets_[0] = idleToken;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingIdleTokenAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = underlying;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIncomingUnderlyingAmount;
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @dev Helper function to parse spend assets for calls to claim rewards
function __parseSpendAssetsForClaimRewardsCalls(address _vaultProxy, address _idleToken)
private
view
returns (address[] memory spendAssets_, uint256[] memory spendAssetAmounts_)
{
spendAssets_ = new address[](1);
spendAssets_[0] = _idleToken;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = ERC20(_idleToken).balanceOf(_vaultProxy);
return (spendAssets_, spendAssetAmounts_);
}
///////////////////////
// ENCODED CALL ARGS //
///////////////////////
/// @dev Helper to decode the encoded call arguments for approving asset allowances
function __decodeApproveAssetsCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
address idleToken_,
address[] memory assets_,
uint256[] memory amounts_
)
{
return abi.decode(_encodedCallArgs, (address, address[], uint256[]));
}
/// @dev Helper to decode callArgs for claiming rewards tokens
function __decodeClaimRewardsCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (address vaultProxy_, address idleToken_)
{
return abi.decode(_encodedCallArgs, (address, address));
}
/// @dev Helper to decode the encoded call arguments for claiming rewards and reinvesting
function __decodeClaimRewardsAndReinvestCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
address vaultProxy_,
address idleToken_,
uint256 minIncomingIdleTokenAmount_,
bool useFullBalances_
)
{
return abi.decode(_encodedCallArgs, (address, address, uint256, bool));
}
/// @dev Helper to decode the encoded call arguments for claiming rewards and swapping
function __decodeClaimRewardsAndSwapCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
address vaultProxy_,
address idleToken_,
address incomingAsset_,
uint256 minIncomingAssetAmount_,
bool useFullBalances_
)
{
return abi.decode(_encodedCallArgs, (address, address, address, uint256, bool));
}
/// @dev Helper to decode callArgs for lending
function __decodeLendCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
address idleToken_,
uint256 outgoingUnderlyingAmount_,
uint256 minIncomingIdleTokenAmount_
)
{
return abi.decode(_encodedCallArgs, (address, uint256, uint256));
}
/// @dev Helper to decode callArgs for redeeming
function __decodeRedeemCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
address idleToken_,
uint256 outgoingIdleTokenAmount_,
uint256 minIncomingUnderlyingAmount_
)
{
return abi.decode(_encodedCallArgs, (address, uint256, uint256));
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `IDLE_PRICE_FEED` variable
/// @return idlePriceFeed_ The `IDLE_PRICE_FEED` variable value
function getIdlePriceFeed() external view returns (address idlePriceFeed_) {
return IDLE_PRICE_FEED;
}
/// @notice Gets the `WETH_TOKEN` variable
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() external view returns (address wethToken_) {
return WETH_TOKEN;
}
}
| 60,838 |
23 | // This loses control of execution, yet no variables are set yet This means no interim state will be represented if asked Combined with the re-entrancy guard, this is secure | universalSingularTransferFrom(listing.currency, amount);
| universalSingularTransferFrom(listing.currency, amount);
| 48,320 |
128 | // ERC20 modified transfer that also update the delegatesrecipient : recipient account amount : value to transferreturn : flag whether transfer was successful or not / | function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(msg.sender, recipient, amount);
_moveDelegates(delegates[msg.sender], delegates[recipient], amount);
return true;
}
| function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(msg.sender, recipient, amount);
_moveDelegates(delegates[msg.sender], delegates[recipient], amount);
return true;
}
| 55,250 |
56 | // If no period is desired, instead set startBonus = 100% and bonusPeriod to a small value like 1sec. | require(bonusPeriodSec_ != 0, 'TokenGeyser: bonus period is zero');
require(initialSharesPerToken > 0, 'TokenGeyser: initialSharesPerToken is zero');
_stakingPool = new TokenPool(stakingToken);
_unlockedPool = new TokenPool(distributionToken);
_lockedPool = new TokenPool(distributionToken);
startBonus = startBonus_;
bonusPeriodSec = bonusPeriodSec_;
_maxUnlockSchedules = maxUnlockSchedules;
_initialSharesPerToken = initialSharesPerToken;
| require(bonusPeriodSec_ != 0, 'TokenGeyser: bonus period is zero');
require(initialSharesPerToken > 0, 'TokenGeyser: initialSharesPerToken is zero');
_stakingPool = new TokenPool(stakingToken);
_unlockedPool = new TokenPool(distributionToken);
_lockedPool = new TokenPool(distributionToken);
startBonus = startBonus_;
bonusPeriodSec = bonusPeriodSec_;
_maxUnlockSchedules = maxUnlockSchedules;
_initialSharesPerToken = initialSharesPerToken;
| 23,560 |
154 | // name Name of the token symbol A symbol to be used as ticker / | constructor (string memory name, string memory symbol) ERC20(name, symbol) {
// register the supported interfaces to conform to ERC1363 via ERC165
_registerInterface(_INTERFACE_ID_ERC1363_TRANSFER);
_registerInterface(_INTERFACE_ID_ERC1363_APPROVE);
}
| constructor (string memory name, string memory symbol) ERC20(name, symbol) {
// register the supported interfaces to conform to ERC1363 via ERC165
_registerInterface(_INTERFACE_ID_ERC1363_TRANSFER);
_registerInterface(_INTERFACE_ID_ERC1363_APPROVE);
}
| 2,163 |
35 | // Returns the addition of two signed integers, reverting onoverflow. Counterpart to Solidity's `+` operator. Requirements: - Addition cannot overflow. / | function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
return c;
}
| function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
return c;
}
| 14,371 |
108 | // @Dev use better naming conventions next time (actually just updates internal accting) | function depositToIdle(address depositor, uint256 amount, uint256 shares) internal {
require(amount != 0, "no tokens to deposit");
totalDeposits += int(amount);
uint256 mintedTokens = amount;
// Update internal accounting
members[depositor].iTB += amount;
members[depositor].iVal += amount;
unsafeAddToBalance(GUILD, wETH, mintedTokens);
// Checks to see if goal has been reached with this deposit
goalHit = checkGoal();
emit MakeDeposit(depositor, amount, mintedTokens, shares, goalHit);
}
| function depositToIdle(address depositor, uint256 amount, uint256 shares) internal {
require(amount != 0, "no tokens to deposit");
totalDeposits += int(amount);
uint256 mintedTokens = amount;
// Update internal accounting
members[depositor].iTB += amount;
members[depositor].iVal += amount;
unsafeAddToBalance(GUILD, wETH, mintedTokens);
// Checks to see if goal has been reached with this deposit
goalHit = checkGoal();
emit MakeDeposit(depositor, amount, mintedTokens, shares, goalHit);
}
| 1,529 |
70 | // added this | function setBot(address blist) external onlyOwner returns (bool){
bot[blist] = !bot[blist];
return bot[blist];
}
| function setBot(address blist) external onlyOwner returns (bool){
bot[blist] = !bot[blist];
return bot[blist];
}
| 12,109 |
22 | // Testing refuseSale() function | function testOnlyInvestorCanRefusePurchase() public {
protocol.buyAsset.value(1050 finney)(assets[0]);
protocol.buyAsset.value(1050 finney)(assets[1]);
protocol.buyAsset.value(1050 finney)(assets[2]);
address(throwableProtocol).call(abi.encodeWithSignature("refuseSale(address[])", assets));
throwProxy.shouldThrow();
}
| function testOnlyInvestorCanRefusePurchase() public {
protocol.buyAsset.value(1050 finney)(assets[0]);
protocol.buyAsset.value(1050 finney)(assets[1]);
protocol.buyAsset.value(1050 finney)(assets[2]);
address(throwableProtocol).call(abi.encodeWithSignature("refuseSale(address[])", assets));
throwProxy.shouldThrow();
}
| 3,414 |
4 | // return {bytes} payload for a `createdBlock` call to an external contract or proxy/ | function createdBlock(
)public pure override returns(
bytes memory
){
return abiEncoderEIP801.SIG_CREATED_BLOCK;
}
| function createdBlock(
)public pure override returns(
bytes memory
){
return abiEncoderEIP801.SIG_CREATED_BLOCK;
}
| 42,119 |
285 | // if the user is redirecting his interest towards someone else,we update the redirected balance of the redirection address by adding the accrued interestand the amount deposited | updateRedirectedBalanceOfRedirectionAddressInternal(_account, balanceIncrease.add(_amount), 0);
| updateRedirectedBalanceOfRedirectionAddressInternal(_account, balanceIncrease.add(_amount), 0);
| 15,205 |
68 | // check the dnsName (byte format) for validity/ | function isAValidDNSNameString(string _dnsName) public view returns (bool _isValid) {
//get bytes32 representation of the _dnsName
bytes32 dnsNameLookupValue = toBytes32(_dnsName);
return isAValidDNSName(dnsNameLookupValue);
}
| function isAValidDNSNameString(string _dnsName) public view returns (bool _isValid) {
//get bytes32 representation of the _dnsName
bytes32 dnsNameLookupValue = toBytes32(_dnsName);
return isAValidDNSName(dnsNameLookupValue);
}
| 53,572 |
29 | // Size must be 20 / 40 / 60 pixels | require(_size == 1 || _size == 2 || _size == 3);
require(maxBridgeHeight >= (_y + _size) && maxBridgeWidth >= (_x + _size));
require(msg.value >= calculateCost(_size, _skin));
| require(_size == 1 || _size == 2 || _size == 3);
require(maxBridgeHeight >= (_y + _size) && maxBridgeWidth >= (_x + _size));
require(msg.value >= calculateCost(_size, _skin));
| 37,698 |
3 | // Transfers vested tokens to beneficiary. / | function release() external {
uint256 vested = vestedAmount();
require(vested > 0, "Cliff: No tokens to release");
released = released.add(vested);
token.safeTransfer(beneficiary, vested);
emit Released(vested);
}
| function release() external {
uint256 vested = vestedAmount();
require(vested > 0, "Cliff: No tokens to release");
released = released.add(vested);
token.safeTransfer(beneficiary, vested);
emit Released(vested);
}
| 17,124 |
126 | // View function to see pending reward on frontend. _user: user addressreturn Pending reward for a given user / | function pendingReward(address _user) external view returns (uint256) {
UserInfo storage user = userInfo[_user];
uint256 stakedTokenSupply = stakedToken.balanceOf(address(this));
if (block.number > lastRewardBlock && stakedTokenSupply != 0) {
uint256 multiplier = _getMultiplier(lastRewardBlock, block.number);
uint256 cakeReward = multiplier.mul(rewardPerBlock);
uint256 adjustedTokenPerShare =
accTokenPerShare.add(cakeReward.mul(PRECISION_FACTOR).div(stakedTokenSupply));
return user.amount.mul(adjustedTokenPerShare).div(PRECISION_FACTOR).sub(user.rewardDebt);
} else {
return user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR).sub(user.rewardDebt);
}
}
| function pendingReward(address _user) external view returns (uint256) {
UserInfo storage user = userInfo[_user];
uint256 stakedTokenSupply = stakedToken.balanceOf(address(this));
if (block.number > lastRewardBlock && stakedTokenSupply != 0) {
uint256 multiplier = _getMultiplier(lastRewardBlock, block.number);
uint256 cakeReward = multiplier.mul(rewardPerBlock);
uint256 adjustedTokenPerShare =
accTokenPerShare.add(cakeReward.mul(PRECISION_FACTOR).div(stakedTokenSupply));
return user.amount.mul(adjustedTokenPerShare).div(PRECISION_FACTOR).sub(user.rewardDebt);
} else {
return user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR).sub(user.rewardDebt);
}
}
| 17,314 |
350 | // If there is no debt to repay we can withdraw all the locked collateral | if (totalDebt == 0) {
return totalCollateral;
}
| if (totalDebt == 0) {
return totalCollateral;
}
| 69,475 |
40 | // Addresses allowed to create tokens / | mapping (address => bool) public isMintingManager;
| mapping (address => bool) public isMintingManager;
| 50,761 |
47 | // refund user | address(uint160(member.userAddress)).transfer(
member.amtContributed
);
| address(uint160(member.userAddress)).transfer(
member.amtContributed
);
| 23,407 |
1 | // Net Asset Value, can't store as float | uint256 totalValue;
uint256 totalUnit;
| uint256 totalValue;
uint256 totalUnit;
| 25,876 |
35 | // contract addresses | address public adapterDeployer;
address public assessor;
address public poolAdmin;
address public seniorTranche;
address public juniorTranche;
address public seniorOperator;
address public juniorOperator;
address public reserve;
address public coordinator;
| address public adapterDeployer;
address public assessor;
address public poolAdmin;
address public seniorTranche;
address public juniorTranche;
address public seniorOperator;
address public juniorOperator;
address public reserve;
address public coordinator;
| 42,919 |
9 | // Convert an hexadecimal string to raw bytes | function fromHex(string memory s) public pure returns (bytes memory) {
bytes memory ss = bytes(s);
require(ss.length%2 == 0); // length must be even
bytes memory r = new bytes(ss.length/2);
for (uint i=0; i<ss.length/2; ++i) {
r[i] = bytes1(fromHexChar(uint8(ss[2*i])) * 16 +
fromHexChar(uint8(ss[2*i+1])));
}
return r;
}
| function fromHex(string memory s) public pure returns (bytes memory) {
bytes memory ss = bytes(s);
require(ss.length%2 == 0); // length must be even
bytes memory r = new bytes(ss.length/2);
for (uint i=0; i<ss.length/2; ++i) {
r[i] = bytes1(fromHexChar(uint8(ss[2*i])) * 16 +
fromHexChar(uint8(ss[2*i+1])));
}
return r;
}
| 18,356 |
126 | // pool does not exist | return 0;
| return 0;
| 38,538 |
102 | // --- Core Auction Logic ---/ Start a new collateral auction forgoneCollateralReceiver Who receives leftover collateral that is not auctioned auctionIncomeRecipient Who receives the amount raised in the auction amountToRaise Total amount of coins to raise (rad) amountToSell Total amount of collateral available to sell (wad) initialBid Unused / | function startAuction(
address forgoneCollateralReceiver,
address auctionIncomeRecipient,
uint256 amountToRaise,
uint256 amountToSell,
uint256 initialBid
| function startAuction(
address forgoneCollateralReceiver,
address auctionIncomeRecipient,
uint256 amountToRaise,
uint256 amountToSell,
uint256 initialBid
| 22,029 |
255 | // Calldata version of {verify} _Available since v4.7._ / | function verifyCalldata(
bytes32[] calldata proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProofCalldata(proof, leaf) == root;
}
| function verifyCalldata(
bytes32[] calldata proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProofCalldata(proof, leaf) == root;
}
| 47,962 |
6 | // Borrower creates a loan proposal. / | function create(uint256 _itemId, uint256 _loanAmount, uint256 _feeAmount, uint256 _minutesDuration) public {
require(_loanAmount >= 1 * (10**18), "CoralLoan: Minimum loan amount is 1 REEF.");
require(_feeAmount >= 1 * (10**18), "CoralLoan: Minimum fee amount is 1 REEF.");
require(_minutesDuration > 0 && _minutesDuration <= 2628000, "CoralLoan: Minutes of duration must be between 1 and 2,628,000."); // 2,628,000 min = 5 years
ICoralMarketplace.MarketItem memory marketItem = ICoralMarketplace(marketplaceAddress).fetchItem(_itemId);
// Transfer ownership of the token to this contract
IERC721(marketItem.nftContract).transferFrom(msg.sender, address(this), marketItem.tokenId);
// Map new Loan
_loanIds.increment();
uint256 loanId = _loanIds.current();
idToLoan[loanId] = Loan(loanId, msg.sender, _itemId, marketItem.nftContract, marketItem.tokenId, _loanAmount, _feeAmount, _minutesDuration, address(0), 0, LoanState.Open);
// Update owner in market contract
ICoralMarketplace(marketplaceAddress).updateMarketItemOwner(_itemId, address(this));
emit LoanCreated(loanId, msg.sender, _itemId, marketItem.nftContract, marketItem.tokenId, _loanAmount, _feeAmount, _minutesDuration);
}
| function create(uint256 _itemId, uint256 _loanAmount, uint256 _feeAmount, uint256 _minutesDuration) public {
require(_loanAmount >= 1 * (10**18), "CoralLoan: Minimum loan amount is 1 REEF.");
require(_feeAmount >= 1 * (10**18), "CoralLoan: Minimum fee amount is 1 REEF.");
require(_minutesDuration > 0 && _minutesDuration <= 2628000, "CoralLoan: Minutes of duration must be between 1 and 2,628,000."); // 2,628,000 min = 5 years
ICoralMarketplace.MarketItem memory marketItem = ICoralMarketplace(marketplaceAddress).fetchItem(_itemId);
// Transfer ownership of the token to this contract
IERC721(marketItem.nftContract).transferFrom(msg.sender, address(this), marketItem.tokenId);
// Map new Loan
_loanIds.increment();
uint256 loanId = _loanIds.current();
idToLoan[loanId] = Loan(loanId, msg.sender, _itemId, marketItem.nftContract, marketItem.tokenId, _loanAmount, _feeAmount, _minutesDuration, address(0), 0, LoanState.Open);
// Update owner in market contract
ICoralMarketplace(marketplaceAddress).updateMarketItemOwner(_itemId, address(this));
emit LoanCreated(loanId, msg.sender, _itemId, marketItem.nftContract, marketItem.tokenId, _loanAmount, _feeAmount, _minutesDuration);
}
| 41,114 |
62 | // buy | newAmount = _takeFee(from, to, amount, true);
| newAmount = _takeFee(from, to, amount, true);
| 38,857 |
93 | // exclude from the Max wallet balance | _isExcludedFromMaxWallet[owner()] = true;
_isExcludedFromMaxWallet[address(this)] = true;
_isExcludedFromMaxWallet[_burnAddress] = true;
_isExcludedFromMaxWallet[_devAddress] = true;
| _isExcludedFromMaxWallet[owner()] = true;
_isExcludedFromMaxWallet[address(this)] = true;
_isExcludedFromMaxWallet[_burnAddress] = true;
_isExcludedFromMaxWallet[_devAddress] = true;
| 37,816 |
0 | // Simplified contract of a `../Swapper.sol` / | contract SwapperLike {
function fromDaiToBTU(address, uint256) external;
}
| contract SwapperLike {
function fromDaiToBTU(address, uint256) external;
}
| 20,509 |
6 | // do bookkeeping | accruedRewards[msg.sender] = accruedRewards[msg.sender] + stakeAmounts[msg.sender]*(block.timestamp - stakeTimes[msg.sender]);
ISTAKING(staking).unstakeFor(msg.sender, amount, msg.sender);
stakeAmounts[msg.sender] = stakeAmounts[msg.sender] - amount;
stakeTimes[msg.sender] = block.timestamp;
| accruedRewards[msg.sender] = accruedRewards[msg.sender] + stakeAmounts[msg.sender]*(block.timestamp - stakeTimes[msg.sender]);
ISTAKING(staking).unstakeFor(msg.sender, amount, msg.sender);
stakeAmounts[msg.sender] = stakeAmounts[msg.sender] - amount;
stakeTimes[msg.sender] = block.timestamp;
| 50,318 |
116 | // ------------------------------------------------------------------------ |
function allowance(address tokenOwner, address spender)
public
onlyMembers(msg.sender)
|
function allowance(address tokenOwner, address spender)
public
onlyMembers(msg.sender)
| 15,220 |
3 | // Internal Functions // / | function _processResponse(
TellerCommon.InterestRequest memory request,
TellerCommon.InterestResponse memory response,
bytes32 requestHash
| function _processResponse(
TellerCommon.InterestRequest memory request,
TellerCommon.InterestResponse memory response,
bytes32 requestHash
| 8,834 |
142 | // Set initial PLOT/ETH pair cummulative price / | function setInitialCummulativePrice() public {
require(msg.sender == initiater);
require(plotETHpair == address(0),"Already initialised");
plotETHpair = uniswapFactory.getPair(plotToken, weth);
UniswapPriceData storage _priceData = uniswapPairData[plotETHpair];
(
uint256 price0Cumulative,
uint256 price1Cumulative,
uint32 blockTimestamp
) = UniswapV2OracleLibrary.currentCumulativePrices(plotETHpair);
_priceData.price0CumulativeLast = price0Cumulative;
_priceData.price1CumulativeLast = price1Cumulative;
_priceData.blockTimestampLast = blockTimestamp;
}
| function setInitialCummulativePrice() public {
require(msg.sender == initiater);
require(plotETHpair == address(0),"Already initialised");
plotETHpair = uniswapFactory.getPair(plotToken, weth);
UniswapPriceData storage _priceData = uniswapPairData[plotETHpair];
(
uint256 price0Cumulative,
uint256 price1Cumulative,
uint32 blockTimestamp
) = UniswapV2OracleLibrary.currentCumulativePrices(plotETHpair);
_priceData.price0CumulativeLast = price0Cumulative;
_priceData.price1CumulativeLast = price1Cumulative;
_priceData.blockTimestampLast = blockTimestamp;
}
| 26,807 |
46 | // 15% for founders | uint256 constant FOUNDERS_AMOUNT = 15 * onePercent;
| uint256 constant FOUNDERS_AMOUNT = 15 * onePercent;
| 8,568 |
10 | // Estimate reinvest rewardreturn reward tokens / | function estimateReinvestReward() external view returns (uint256) {
uint256 unclaimedRewards = checkReward();
if (unclaimedRewards >= MIN_TOKENS_TO_REINVEST) {
return unclaimedRewards.mul(REINVEST_REWARD_BIPS).div(BIPS_DIVISOR);
}
return 0;
}
| function estimateReinvestReward() external view returns (uint256) {
uint256 unclaimedRewards = checkReward();
if (unclaimedRewards >= MIN_TOKENS_TO_REINVEST) {
return unclaimedRewards.mul(REINVEST_REWARD_BIPS).div(BIPS_DIVISOR);
}
return 0;
}
| 2,388 |
11 | // Ownership of a position was transferred to a new address / | event PositionTransferred(
| event PositionTransferred(
| 39,071 |
11 | // Attempt to cancel an authorization Works only if the authorization is not yet used. authorizerAuthorizer's address nonce Nonce of the authorization v v of the signature r r of the signature s s of the signature / | function cancelAuthorization(
address authorizer,
bytes32 nonce,
uint8 v,
bytes32 r,
bytes32 s
| function cancelAuthorization(
address authorizer,
bytes32 nonce,
uint8 v,
bytes32 r,
bytes32 s
| 24,485 |
5 | // ERC20Basic Simpler version of ERC20 interface / | contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
| contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
| 74,260 |
329 | // Put all ERC20 tokens into the first Particlon to save a lot of gas | _chargeParticlon(newTokenId, "generic", assetAmount);
| _chargeParticlon(newTokenId, "generic", assetAmount);
| 16,463 |
38 | // Function to mint tokens_to The address that will recieve the minted tokens._amount The amount of tokens to mint. return A boolean that indicates if the operation was successful./ | function mint(address _to, uint256 _amount) whenNotPaused onlyOwner returns (bool) {
return mintInternal(_to, _amount);
}
| function mint(address _to, uint256 _amount) whenNotPaused onlyOwner returns (bool) {
return mintInternal(_to, _amount);
}
| 22,903 |
62 | // Returns the threshold before swap and liquify. / | function minTokensBeforeSwap() external view virtual returns (uint256) {
return _minTokensBeforeSwap;
}
| function minTokensBeforeSwap() external view virtual returns (uint256) {
return _minTokensBeforeSwap;
}
| 21,667 |
71 | // husd3crv->husd | token.safeApprove(curve, 0);
token.safeApprove(curve, uint(-1));
| token.safeApprove(curve, 0);
token.safeApprove(curve, uint(-1));
| 7,494 |
54 | // Deprecated, use {_burn} instead.owner owner of the token to burntokenId uint256 ID of the token being burned/ | function _burn(address owner, uint256 tokenId) internal {
require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own");
_clearApproval(tokenId);
_ownedTokensCount[owner].decrement();
_tokenOwner[tokenId] = address(0);
emit Transfer(owner, address(0), tokenId);
}
| function _burn(address owner, uint256 tokenId) internal {
require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own");
_clearApproval(tokenId);
_ownedTokensCount[owner].decrement();
_tokenOwner[tokenId] = address(0);
emit Transfer(owner, address(0), tokenId);
}
| 39,070 |
87 | // //Migrate AAVE `aToken` underlying `amount` into COMP/CREAM `cToken` for benefit of `to` by batching calls to `aave` and `cToken`. | function aaveToCompound(address aToken, address cToken, address to, uint256 amount) external {
IERC20(aToken).safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` `aToken` `amount` into this contract
address underlying = IAaveBridge(aToken).UNDERLYING_ASSET_ADDRESS(); // sanity check for `underlying` token
aave.withdraw(underlying, amount, address(this)); // burn deposited `aToken` from `aave` into `underlying`
ICompoundBridge(cToken).mint(amount); // stake `underlying` into `cToken`
IERC20(cToken).safeTransfer(to, IERC20(cToken).balanceOf(address(this))); // transfer resulting `cToken` to `to`
}
| function aaveToCompound(address aToken, address cToken, address to, uint256 amount) external {
IERC20(aToken).safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` `aToken` `amount` into this contract
address underlying = IAaveBridge(aToken).UNDERLYING_ASSET_ADDRESS(); // sanity check for `underlying` token
aave.withdraw(underlying, amount, address(this)); // burn deposited `aToken` from `aave` into `underlying`
ICompoundBridge(cToken).mint(amount); // stake `underlying` into `cToken`
IERC20(cToken).safeTransfer(to, IERC20(cToken).balanceOf(address(this))); // transfer resulting `cToken` to `to`
}
| 38,763 |
24 | // total_withdraw is how much the participant has withdrawn during the lifetime of the channel. The actual amount which the participant withdrew is `total_withdraw - total_withdraw_from_previous_event_or_zero` | event ChannelWithdraw(
uint256 indexed channel_identifier,
address indexed participant,
uint256 total_withdraw
);
event ChannelClosed(
uint256 indexed channel_identifier,
address indexed closing_participant,
uint256 indexed nonce
| event ChannelWithdraw(
uint256 indexed channel_identifier,
address indexed participant,
uint256 total_withdraw
);
event ChannelClosed(
uint256 indexed channel_identifier,
address indexed closing_participant,
uint256 indexed nonce
| 16,871 |
78 | // Called by Armor for now--we confirm a hack happened and give a timestamp for what time it was. _protocol The address of the protocol that has been hacked (address that would be on yNFT). _hackTime The timestamp of the time the hack occurred./ | {
require(_hackTime < now, "Cannot confirm future");
bytes32 hackId = keccak256(abi.encodePacked(_protocol, _hackTime));
confirmedHacks[hackId] = true;
emit ConfirmedHack(hackId, _protocol, _hackTime);
}
| {
require(_hackTime < now, "Cannot confirm future");
bytes32 hackId = keccak256(abi.encodePacked(_protocol, _hackTime));
confirmedHacks[hackId] = true;
emit ConfirmedHack(hackId, _protocol, _hackTime);
}
| 64,569 |
2 | // bridge router contract | BridgeRouter public immutable bridge;
| BridgeRouter public immutable bridge;
| 7,087 |
11 | // - both parties can {lock} for `resolver`. /receiver The account that receives funds./resolver The account that unlock funds./token The asset used for funds./value The amount of funds - if `nft`, the 'tokenId' in first value is used./termination Unix time upon which `depositor` can claim back funds./nft If 'false', ERC-20 is assumed, otherwise, non-fungible asset./details Describes context of escrow - stamped into event. | function deposit(
address receiver,
address resolver,
address token,
uint256 value,
uint256 termination,
bool nft,
string memory details
) public payable returns (uint256 registration) {
require(resolvers[resolver].active, "resolver not active");
| function deposit(
address receiver,
address resolver,
address token,
uint256 value,
uint256 termination,
bool nft,
string memory details
) public payable returns (uint256 registration) {
require(resolvers[resolver].active, "resolver not active");
| 16,317 |
20 | // Time to mint some tokens | _mintPoolToken(balance1, 0, _reservePair1, anchorPoolToken, _to, true);
_mintPoolToken(balance0, 0, _reservePair0, floatPoolToken, _to, false);
| _mintPoolToken(balance1, 0, _reservePair1, anchorPoolToken, _to, true);
_mintPoolToken(balance0, 0, _reservePair0, floatPoolToken, _to, false);
| 44,317 |
34 | // _amount is the amount of EC20 token sent with the transaction. should be > 0 | if (_amount == 0 || msg.value > 0) {
revert BadPayment();
}
| if (_amount == 0 || msg.value > 0) {
revert BadPayment();
}
| 16,785 |
18 | // Users want to know when the auction ends, seconds from 1970-01-01 | function auctionEndTime() constant returns (uint256) {
return auctionStart + biddingPeriod;
}
| function auctionEndTime() constant returns (uint256) {
return auctionStart + biddingPeriod;
}
| 22,250 |
75 | // create the lp data for the amm | (LiquidityPoolData memory liquidityPoolData, uint256 mainTokenAmount) = _addLiquidity(request.setupIndex, request);
| (LiquidityPoolData memory liquidityPoolData, uint256 mainTokenAmount) = _addLiquidity(request.setupIndex, request);
| 40,065 |
10 | // Emitted when the timelock controller used to queue a proposal to the timelock. / | event ProposalQueued(uint256 proposalId, uint256 eta);
| event ProposalQueued(uint256 proposalId, uint256 eta);
| 24,030 |
45 | // assignOperators _role operator role. May be a role not defined yet. _operators addresses / | function assignOperators(bytes32 _role, address[] memory _operators)
public onlySysOp returns (bool)
| function assignOperators(bytes32 _role, address[] memory _operators)
public onlySysOp returns (bool)
| 30,460 |
10 | // Calculate the cost of a number of items (in ether) | function getItemsCost(uint _items) public view returns(uint) {
return _items * itemCost;
}
| function getItemsCost(uint _items) public view returns(uint) {
return _items * itemCost;
}
| 53,805 |
37 | // Reward logic but will have to address decimals problem in ERC20 contracts If enter stake of 31,536,000 will get APY in years in seconds | uint256 aprPerSecond = (staker.lockedAPY * avoidFloat) / 365 / 86400;
uint256 reward = (aprPerSecond *
(block.timestamp - staker.startTime) *
depositAmount) /
(avoidFloat * 100) -
staker.rewardClaimed;
if (reward == 0) {
revert("No rewards available!");
}
| uint256 aprPerSecond = (staker.lockedAPY * avoidFloat) / 365 / 86400;
uint256 reward = (aprPerSecond *
(block.timestamp - staker.startTime) *
depositAmount) /
(avoidFloat * 100) -
staker.rewardClaimed;
if (reward == 0) {
revert("No rewards available!");
}
| 4,936 |
69 | // Remainig tokens that are left after week 155 | uint256 FOR_156_WEEK = 151110 * SCALING_FACTOR;
uint256 week = 1 weeks;
| uint256 FOR_156_WEEK = 151110 * SCALING_FACTOR;
uint256 week = 1 weeks;
| 38,443 |
0 | // transfer token to a contract address with additional data if the recipient is a contact._to The address to transfer to._value The amount to be transferred._data The extra data to be passed to the receiving contract./ | function transferAndCall(address _to, uint _value, bytes memory _data)
public
override
returns (bool success)
| function transferAndCall(address _to, uint _value, bytes memory _data)
public
override
returns (bool success)
| 14,220 |
44 | // User does not have permissions to join garden | uint256 internal constant USER_CANNOT_JOIN = 29;
| uint256 internal constant USER_CANNOT_JOIN = 29;
| 15,859 |
191 | // withdraw any available funds left in the contract, up to _amount, after accounting for the funds due to participants in past reports _recipient address to send funds to _amount maximum amount to withdraw, denominated in LINK-wei. access control provided by billingAccessController / | function withdrawFunds(address _recipient, uint256 _amount)
external
| function withdrawFunds(address _recipient, uint256 _amount)
external
| 26,015 |
32 | // check if address is member of Blocksquare_member Address of member return True if member is member of Blocksquare, false instead/ | function isBS(address _member) public constant returns (bool) {
return memberOfBS[_member];
}
| function isBS(address _member) public constant returns (bool) {
return memberOfBS[_member];
}
| 28,901 |
75 | // {IERC20-approve}, and its usage is discouraged. Whenever possible, use {safeIncreaseAllowance} and {safeDecreaseAllowance} instead./ | function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
| function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
| 35,883 |
28 | // limit in wei for stage 612 + 1296 + 2052 + 2880 | uint[4] internal stageLimits = [
612 ether, //4800000 tokens 10% of ICO tokens (ICO token 40% of all (48 000 000) )
1296 ether, //9600000 tokens 20% of ICO tokens
2052 ether, //14400000 tokens 30% of ICO tokens
2880 ether //19200000 tokens 40% of ICO tokens
];
mapping(address => bool) public referrals;
mapping(address => uint) public reservedTokens;
mapping(address => uint) public reservedRefsTokens;
| uint[4] internal stageLimits = [
612 ether, //4800000 tokens 10% of ICO tokens (ICO token 40% of all (48 000 000) )
1296 ether, //9600000 tokens 20% of ICO tokens
2052 ether, //14400000 tokens 30% of ICO tokens
2880 ether //19200000 tokens 40% of ICO tokens
];
mapping(address => bool) public referrals;
mapping(address => uint) public reservedTokens;
mapping(address => uint) public reservedRefsTokens;
| 8,915 |
14 | // Update integral of 1/supply | if (block.timestamp > _st.period_time) {
uint256 _prev_week_time = _st.period_time;
uint256 _week_time;
unchecked {
_week_time = min(
((_st.period_time + WEEK) / WEEK) * WEEK,
block.timestamp
);
}
| if (block.timestamp > _st.period_time) {
uint256 _prev_week_time = _st.period_time;
uint256 _week_time;
unchecked {
_week_time = min(
((_st.period_time + WEEK) / WEEK) * WEEK,
block.timestamp
);
}
| 79,562 |
51 | // Reverts if not in crowdsale time range. / | modifier onlyWhileOpen {
require(now >= openingTime && now <= closingTime);
_;
}
| modifier onlyWhileOpen {
require(now >= openingTime && now <= closingTime);
_;
}
| 50,688 |
35 | // Return the epoch calculated from current timestamp / | function getCurrentEpochId() external view returns (uint256) {
BeaconSpec memory beaconSpec = _getBeaconSpec();
return _getCurrentEpochId(beaconSpec);
}
| function getCurrentEpochId() external view returns (uint256) {
BeaconSpec memory beaconSpec = _getBeaconSpec();
return _getCurrentEpochId(beaconSpec);
}
| 27,070 |
22 | // Ensure buyer chose a valid eshop | require(po.eShopId.length > 0, "eShopId must be specified");
IPoTypes.Eshop memory eShop = businessPartnerStorageGlobal.getEshop(po.eShopId);
require(eShop.purchasingContractAddress != address(0), "eShop has no purchasing address");
require(eShop.quoteSignerCount > 0, "No quote signers found for eShop");
require(po.eShopId == eShopId, "eShopId is not correct for this contract"); // must be "our" eShop
require(eShop.isActive == true, "eShop is inactive");
| require(po.eShopId.length > 0, "eShopId must be specified");
IPoTypes.Eshop memory eShop = businessPartnerStorageGlobal.getEshop(po.eShopId);
require(eShop.purchasingContractAddress != address(0), "eShop has no purchasing address");
require(eShop.quoteSignerCount > 0, "No quote signers found for eShop");
require(po.eShopId == eShopId, "eShopId is not correct for this contract"); // must be "our" eShop
require(eShop.isActive == true, "eShop is inactive");
| 8,198 |
7 | // Set the initial tracked addresses | for (uint256 i = 0; i < _initial_tracked_addresses.length; i++){
address tracked_addr = _initial_tracked_addresses[i];
tracked_addresses.push(tracked_addr);
is_address_tracked[tracked_addr] = true;
}
| for (uint256 i = 0; i < _initial_tracked_addresses.length; i++){
address tracked_addr = _initial_tracked_addresses[i];
tracked_addresses.push(tracked_addr);
is_address_tracked[tracked_addr] = true;
}
| 48,003 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.