// SPDX-License-Identifier: MITpragmasolidity ^0.8.0;/**
* @dev Collection of functions related to the address type
*/libraryAddress{
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/functionisContract(address account) internalviewreturns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in// construction, since the code is only stored at the end of the// constructor execution.uint256 size;
// solhint-disable-next-line no-inline-assemblyassembly {
size :=extcodesize(account)
}
return size >0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/functionsendValue(addresspayable recipient, uint256 amount) internal{
require(
address(this).balance>= amount,
"Address: insufficient balance"
);
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/functionfunctionCall(address target, bytesmemory data)
internalreturns (bytesmemory)
{
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/functionfunctionCall(address target,
bytesmemory data,
stringmemory errorMessage
) internalreturns (bytesmemory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/functionfunctionCallWithValue(address target,
bytesmemory data,
uint256 value
) internalreturns (bytesmemory) {
return
functionCallWithValue(
target,
data,
value,
"Address: low-level call with value failed"
);
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/functionfunctionCallWithValue(address target,
bytesmemory data,
uint256 value,
stringmemory errorMessage
) internalreturns (bytesmemory) {
require(
address(this).balance>= value,
"Address: insufficient balance for call"
);
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytesmemory returndata) =
target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/functionfunctionStaticCall(address target, bytesmemory data)
internalviewreturns (bytesmemory)
{
return
functionStaticCall(
target,
data,
"Address: low-level static call failed"
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/functionfunctionStaticCall(address target,
bytesmemory data,
stringmemory errorMessage
) internalviewreturns (bytesmemory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytesmemory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/functionfunctionDelegateCall(address target, bytesmemory data)
internalreturns (bytesmemory)
{
return
functionDelegateCall(
target,
data,
"Address: low-level delegate call failed"
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/functionfunctionDelegateCall(address target,
bytesmemory data,
stringmemory errorMessage
) internalreturns (bytesmemory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytesmemory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function_verifyCallResult(bool success,
bytesmemory returndata,
stringmemory errorMessage
) privatepurereturns (bytesmemory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if presentif (returndata.length>0) {
// The easiest way to bubble the revert reason is using memory via assembly// solhint-disable-next-line no-inline-assemblyassembly {
let returndata_size :=mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
Contract Source Code
File 2 of 9: Context.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.0;/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/abstractcontractContext{
function_msgSender() internalviewvirtualreturns (address) {
returnmsg.sender;
}
function_msgData() internalviewvirtualreturns (bytescalldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691returnmsg.data;
}
}
Contract Source Code
File 3 of 9: IERC20.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.0;/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/interfaceIERC20{
/**
* @dev Returns the amount of tokens in existence.
*/functiontotalSupply() externalviewreturns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/functionbalanceOf(address account) externalviewreturns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/functiontransfer(address recipient, uint256 amount)
externalreturns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/functionallowance(address owner, address spender)
externalviewreturns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/functionapprove(address spender, uint256 amount) externalreturns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/functiontransferFrom(address sender,
address recipient,
uint256 amount
) externalreturns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/eventTransfer(addressindexedfrom, addressindexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/eventApproval(addressindexed owner,
addressindexed spender,
uint256 value
);
}
Contract Source Code
File 4 of 9: IERC20Metadata.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.0;import"../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/interfaceIERC20MetadataisIERC20{
/**
* @dev Returns the name of the token.
*/functionname() externalviewreturns (stringmemory);
/**
* @dev Returns the symbol of the token.
*/functionsymbol() externalviewreturns (stringmemory);
/**
* @dev Returns the decimals places of the token.
*/functiondecimals() externalviewreturns (uint8);
}
Contract Source Code
File 5 of 9: Ownable.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.0;import"../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/abstractcontractOwnableisContext{
addressprivate _owner;
eventOwnershipTransferred(addressindexed previousOwner,
addressindexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/constructor() {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/functionowner() publicviewvirtualreturns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/modifieronlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/functionrenounceOwnership() publicvirtualonlyOwner{
emit OwnershipTransferred(_owner, address(0));
_owner =address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/functiontransferOwnership(address newOwner) publicvirtualonlyOwner{
require(
newOwner !=address(0),
"Ownable: new owner is the zero address"
);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
Contract Source Code
File 6 of 9: SafeERC20.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.0;import"../IERC20.sol";
import"../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/librarySafeERC20{
usingAddressforaddress;
functionsafeTransfer(
IERC20 token,
address to,
uint256 value
) internal{
_callOptionalReturn(
token,
abi.encodeWithSelector(token.transfer.selector, to, value)
);
}
functionsafeTransferFrom(
IERC20 token,
addressfrom,
address to,
uint256 value
) internal{
_callOptionalReturn(
token,
abi.encodeWithSelector(token.transferFrom.selector, from, to, value)
);
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/functionsafeApprove(
IERC20 token,
address spender,
uint256 value
) internal{
// safeApprove should only be called when setting an initial allowance,// or when resetting it to zero. To increase and decrease it, use// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'// solhint-disable-next-line max-line-lengthrequire(
(value ==0) || (token.allowance(address(this), spender) ==0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(
token,
abi.encodeWithSelector(token.approve.selector, spender, value)
);
}
functionsafeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal{
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(
token,
abi.encodeWithSelector(
token.approve.selector,
spender,
newAllowance
)
);
}
functionsafeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal{
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(
oldAllowance >= value,
"SafeERC20: decreased allowance below zero"
);
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(
token,
abi.encodeWithSelector(
token.approve.selector,
spender,
newAllowance
)
);
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/function_callOptionalReturn(IERC20 token, bytesmemory data) private{
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that// the target address contains contract code and also asserts for success in the low-level call.bytesmemory returndata =address(token).functionCall(
data,
"SafeERC20: low-level call failed"
);
if (returndata.length>0) {
// Return data is optional// solhint-disable-next-line max-line-lengthrequire(
abi.decode(returndata, (bool)),
"SafeERC20: ERC20 operation did not succeed"
);
}
}
}
Contract Source Code
File 7 of 9: ZapBaseV2_1.sol
// ███████╗░█████╗░██████╗░██████╗░███████╗██████╗░░░░███████╗██╗// ╚════██║██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔══██╗░░░██╔════╝██║// ░░███╔═╝███████║██████╔╝██████╔╝█████╗░░██████╔╝░░░█████╗░░██║// ██╔══╝░░██╔══██║██╔═══╝░██╔═══╝░██╔══╝░░██╔══██╗░░░██╔══╝░░██║// ███████╗██║░░██║██║░░░░░██║░░░░░███████╗██║░░██║██╗██║░░░░░██║// ╚══════╝╚═╝░░╚═╝╚═╝░░░░░╚═╝░░░░░╚══════╝╚═╝░░╚═╝╚═╝╚═╝░░░░░╚═╝// Copyright (C) 2021 zapper// This program is free software: you can redistribute it and/or modify// it under the terms of the GNU Affero General Public License as published by// the Free Software Foundation, either version 2 of the License, or// (at your option) any later version.//// This program is distributed in the hope that it will be useful,// but WITHOUT ANY WARRANTY; without even the implied warranty of// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the// GNU Affero General Public License for more details.///// @author Zapper/// @notice This abstract contract, which is inherited by Zaps,/// provides utility functions for moving tokens, checking allowances/// and balances, and accounting/// for fees.// SPDX-License-Identifier: GPL-2.0pragmasolidity ^0.8.0;import"../oz/0.8.0/access/Ownable.sol";
import"../oz/0.8.0/token/ERC20/utils/SafeERC20.sol";
import"../oz/0.8.0/token/ERC20/extensions/IERC20Metadata.sol";
abstractcontractZapBaseV2_1isOwnable{
usingSafeERC20forIERC20;
boolpublic stopped =false;
// if true, goodwill is not deductedmapping(address=>bool) public feeWhitelist;
uint256public goodwill;
// % share of goodwill (0-100 %)uint256 affiliateSplit;
// restrict affiliatesmapping(address=>bool) public affiliates;
// affiliate => token => amountmapping(address=>mapping(address=>uint256)) public affiliateBalance;
// token => amountmapping(address=>uint256) public totalAffiliateBalance;
// swapTarget => approval statusmapping(address=>bool) public approvedTargets;
addressinternalconstant ETHAddress =0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
addressinternalconstant ZapperAdmin =0x3CE37278de6388532C3949ce4e886F365B14fB56;
constructor(uint256 _goodwill, uint256 _affiliateSplit) {
goodwill = _goodwill;
affiliateSplit = _affiliateSplit;
}
// circuit breaker modifiersmodifierstopInEmergency{
if (stopped) {
revert("Paused");
} else {
_;
}
}
function_getBalance(address token)
internalviewreturns (uint256 balance)
{
if (token ==address(0)) {
balance =address(this).balance;
} else {
balance = IERC20(token).balanceOf(address(this));
}
}
function_approveToken(address token, address spender) internal{
IERC20 _token = IERC20(token);
if (_token.allowance(address(this), spender) >0) return;
else {
_token.safeApprove(spender, type(uint256).max);
}
}
function_approveToken(address token,
address spender,
uint256 amount
) internal{
IERC20(token).safeApprove(spender, 0);
IERC20(token).safeApprove(spender, amount);
}
// - to Pause the contractfunctiontoggleContractActive() publiconlyOwner{
stopped =!stopped;
}
functionset_feeWhitelist(address zapAddress, bool status)
externalonlyOwner{
feeWhitelist[zapAddress] = status;
}
functionset_new_goodwill(uint256 _new_goodwill) publiconlyOwner{
require(
_new_goodwill >=0&& _new_goodwill <=100,
"GoodWill Value not allowed"
);
goodwill = _new_goodwill;
}
functionset_new_affiliateSplit(uint256 _new_affiliateSplit)
externalonlyOwner{
require(
_new_affiliateSplit <=100,
"Affiliate Split Value not allowed"
);
affiliateSplit = _new_affiliateSplit;
}
functionset_affiliate(address _affiliate, bool _status)
externalonlyOwner{
affiliates[_affiliate] = _status;
}
///@notice Withdraw goodwill share, retaining affilliate sharefunctionwithdrawTokens(address[] calldata tokens) externalonlyOwner{
for (uint256 i =0; i < tokens.length; i++) {
uint256 qty;
if (tokens[i] == ETHAddress) {
qty =address(this).balance- totalAffiliateBalance[tokens[i]];
Address.sendValue(payable(owner()), qty);
} else {
qty =
IERC20(tokens[i]).balanceOf(address(this)) -
totalAffiliateBalance[tokens[i]];
IERC20(tokens[i]).safeTransfer(owner(), qty);
}
}
}
///@notice Withdraw affilliate share, retaining goodwill sharefunctionaffilliateWithdraw(address[] calldata tokens) external{
uint256 tokenBal;
for (uint256 i =0; i < tokens.length; i++) {
tokenBal = affiliateBalance[msg.sender][tokens[i]];
affiliateBalance[msg.sender][tokens[i]] =0;
totalAffiliateBalance[tokens[i]] =
totalAffiliateBalance[tokens[i]] -
tokenBal;
if (tokens[i] == ETHAddress) {
Address.sendValue(payable(msg.sender), tokenBal);
} else {
IERC20(tokens[i]).safeTransfer(msg.sender, tokenBal);
}
}
}
functionsetApprovedTargets(address[] calldata targets,
bool[] calldata isApproved
) externalonlyOwner{
require(targets.length== isApproved.length, "Invalid Input length");
for (uint256 i =0; i < targets.length; i++) {
approvedTargets[targets[i]] = isApproved[i];
}
}
function_subtractGoodwill(address token,
uint256 amount,
address affiliate,
bool enableGoodwill
) internalreturns (uint256 totalGoodwillPortion) {
bool whitelisted = feeWhitelist[msg.sender];
if (enableGoodwill &&!whitelisted && goodwill >0) {
totalGoodwillPortion = (amount * goodwill) /10000;
if (affiliates[affiliate]) {
if (token ==address(0)) {
token = ETHAddress;
}
uint256 affiliatePortion =
(totalGoodwillPortion * affiliateSplit) /100;
affiliateBalance[affiliate][token] += affiliatePortion;
totalAffiliateBalance[token] += affiliatePortion;
}
}
}
receive() externalpayable{
require(msg.sender!=tx.origin, "Do not send ETH directly");
}
}
Contract Source Code
File 8 of 9: ZapInBaseV3_1.sol
// ███████╗░█████╗░██████╗░██████╗░███████╗██████╗░░░░███████╗██╗// ╚════██║██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔══██╗░░░██╔════╝██║// ░░███╔═╝███████║██████╔╝██████╔╝█████╗░░██████╔╝░░░█████╗░░██║// ██╔══╝░░██╔══██║██╔═══╝░██╔═══╝░██╔══╝░░██╔══██╗░░░██╔══╝░░██║// ███████╗██║░░██║██║░░░░░██║░░░░░███████╗██║░░██║██╗██║░░░░░██║// ╚══════╝╚═╝░░╚═╝╚═╝░░░░░╚═╝░░░░░╚══════╝╚═╝░░╚═╝╚═╝╚═╝░░░░░╚═╝// Copyright (C) 2021 zapper// This program is free software: you can redistribute it and/or modify// it under the terms of the GNU Affero General Public License as published by// the Free Software Foundation, either version 2 of the License, or// (at your option) any later version.//// This program is distributed in the hope that it will be useful,// but WITHOUT ANY WARRANTY; without even the implied warranty of// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the// GNU Affero General Public License for more details.///// @author Zapper/// @notice This abstract contract provides utility functions for moving tokens.// SPDX-License-Identifier: GPL-2.0pragmasolidity ^0.8.0;import"./ZapBaseV2_1.sol";
abstractcontractZapInBaseV3_1isZapBaseV2_1{
usingSafeERC20forIERC20;
/**
@dev Transfer tokens (including ETH) from msg.sender to this contract
@param token The ERC20 token to transfer to this contract (0 address if ETH)
@return Quantity of tokens transferred to this contract
*/function_pullTokens(address token,
uint256 amount,
address affiliate,
bool enableGoodwill
) internalreturns (uint256) {
uint256 totalGoodwillPortion;
if (token ==address(0)) {
require(msg.value>0, "No eth sent");
// subtract goodwill
totalGoodwillPortion = _subtractGoodwill(
ETHAddress,
msg.value,
affiliate,
enableGoodwill
);
returnmsg.value- totalGoodwillPortion;
}
require(amount >0, "Invalid token amount");
require(msg.value==0, "Eth sent with token");
//transfer token
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
// subtract goodwill
totalGoodwillPortion = _subtractGoodwill(
token,
amount,
affiliate,
enableGoodwill
);
return amount - totalGoodwillPortion;
}
}
Contract Source Code
File 9 of 9: yVault_ZapIn_V5_1.sol
// ███████╗░█████╗░██████╗░██████╗░███████╗██████╗░░░░███████╗██╗// ╚════██║██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔══██╗░░░██╔════╝██║// ░░███╔═╝███████║██████╔╝██████╔╝█████╗░░██████╔╝░░░█████╗░░██║// ██╔══╝░░██╔══██║██╔═══╝░██╔═══╝░██╔══╝░░██╔══██╗░░░██╔══╝░░██║// ███████╗██║░░██║██║░░░░░██║░░░░░███████╗██║░░██║██╗██║░░░░░██║// ╚══════╝╚═╝░░╚═╝╚═╝░░░░░╚═╝░░░░░╚══════╝╚═╝░░╚═╝╚═╝╚═╝░░░░░╚═╝// Copyright (C) 2022 zapper// This program is free software: you can redistribute it and/or modify// it under the terms of the GNU Affero General Public License as published by// the Free Software Foundation, either version 2 of the License, or// (at your option) any later version.//// This program is distributed in the hope that it will be useful,// but WITHOUT ANY WARRANTY; without even the implied warranty of// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the// GNU Affero General Public License for more details./////@author Zapper///@notice This contract adds liquidity to Yearn Vaults using ETH or ERC20 Tokens.// SPDX-License-Identifier: GPL-2.0pragmasolidity ^0.8.0;import"../_base/ZapInBaseV3_1.sol";
interfaceIWETH{
functiondeposit() externalpayable;
functiontransfer(address to, uint256 value) externalreturns (bool);
functionwithdraw(uint256) external;
}
interfaceIYearnPartnerTracker{
functiondeposit(address vault,
address partnerId,
uint256 amount
) externalreturns (uint256);
}
interfaceIYVault{
functiondeposit(uint256) external;
functionwithdraw(uint256) external;
functiontoken() externalviewreturns (address);
// V2functionpricePerShare() externalviewreturns (uint256);
}
// -- Aave --interfaceIAaveLendingPoolAddressesProvider{
functiongetLendingPool() externalviewreturns (address);
functiongetLendingPoolCore() externalviewreturns (addresspayable);
}
interfaceIAaveLendingPoolCore{
functiongetReserveATokenAddress(address _reserve)
externalviewreturns (address);
}
interfaceIAaveLendingPool{
functiondeposit(address _reserve,
uint256 _amount,
uint16 _referralCode
) externalpayable;
}
contractyVault_ZapIn_V5_1isZapInBaseV3_1{
usingSafeERC20forIERC20;
IAaveLendingPoolAddressesProvider
privateconstant lendingPoolAddressProvider =
IAaveLendingPoolAddressesProvider(
0x24a42fD28C976A61Df5D00D0599C34c4f90748c8
);
addressprivateconstant wethTokenAddress =0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
IYearnPartnerTracker privateconstant yearnPartnerTracker =
IYearnPartnerTracker(0x8ee392a4787397126C163Cb9844d7c447da419D8);
addressprivateconstant yveCRV =0xc5bDdf9843308380375a611c18B50Fb9341f502A;
eventzapIn(address sender, address pool, uint256 tokensRec);
constructor(address _curveZapIn,
uint256 _goodwill,
uint256 _affiliateSplit
) ZapBaseV2_1(_goodwill, _affiliateSplit) {
// Curve ZapIn
approvedTargets[_curveZapIn] =true;
// 0x exchange
approvedTargets[0xDef1C0ded9bec7F1a1670819833240f027b25EfF] =true;
}
/**
@notice This function adds liquidity to a Yearn vaults with ETH or ERC20 tokens
@param fromToken The token used for entry (address(0) if ether)
@param amountIn The amount of fromToken to invest
@param toVault Yearn vault address
@param superVault Super vault to depoist toVault tokens into (address(0) if none)
@param isAaveUnderlying True if vault contains aave token
@param minYVTokens The minimum acceptable quantity vault tokens to receive. Reverts otherwise
@param intermediateToken Token to swap fromToken to before entering vault
@param swapTarget Excecution target for the swap or Zap
@param swapData DEX quote or Zap data
@param affiliate Affiliate address
@param partnerId PartnerId for YearnPartnerTracker
@return tokensReceived Quantity of Vault tokens received
*/functionZapIn(address fromToken,
uint256 amountIn,
address toVault,
address superVault,
bool isAaveUnderlying,
uint256 minYVTokens,
address intermediateToken,
address swapTarget,
bytescalldata swapData,
address affiliate,
address partnerId
) externalpayablestopInEmergencyreturns (uint256 tokensReceived) {
// get incoming tokensuint256 toInvest = _pullTokens(fromToken, amountIn, affiliate, true);
// get intermediate tokenuint256 intermediateAmt =
_fillQuote(
fromToken,
intermediateToken,
toInvest,
swapTarget,
swapData
);
// get 'aIntermediateToken'if (isAaveUnderlying) {
address aaveLendingPoolCore =
lendingPoolAddressProvider.getLendingPoolCore();
_approveToken(intermediateToken, aaveLendingPoolCore);
IAaveLendingPool(lendingPoolAddressProvider.getLendingPool())
.deposit(intermediateToken, intermediateAmt, 0);
intermediateToken = IAaveLendingPoolCore(aaveLendingPoolCore)
.getReserveATokenAddress(intermediateToken);
}
return
_zapIn(
toVault,
superVault,
minYVTokens,
intermediateToken,
intermediateAmt,
partnerId
);
}
function_zapIn(address toVault,
address superVault,
uint256 minYVTokens,
address intermediateToken,
uint256 intermediateAmt,
address partnerId
) internalreturns (uint256 tokensReceived) {
// Deposit to Vaultif (superVault ==address(0)) {
tokensReceived = _vaultDeposit(
intermediateToken,
intermediateAmt,
toVault,
minYVTokens,
true,
partnerId
);
} else {
uint256 intermediateYVTokens =
_vaultDeposit(
intermediateToken,
intermediateAmt,
toVault,
0,
false,
partnerId
);
// deposit to super vault
tokensReceived = _vaultDeposit(
IYVault(superVault).token(),
intermediateYVTokens,
superVault,
minYVTokens,
true,
partnerId
);
}
}
function_vaultDeposit(address underlyingVaultToken,
uint256 amount,
address toVault,
uint256 minTokensRec,
bool shouldTransfer,
address partnerId
) internalreturns (uint256 tokensReceived) {
if (toVault == yveCRV) {
_approveToken(underlyingVaultToken, toVault);
uint256 iniYVaultBal = IERC20(toVault).balanceOf(address(this));
IYVault(toVault).deposit(amount);
tokensReceived =
IERC20(toVault).balanceOf(address(this)) -
iniYVaultBal;
} else {
_approveToken(underlyingVaultToken, address(yearnPartnerTracker));
tokensReceived = yearnPartnerTracker.deposit(
toVault,
partnerId,
amount
);
}
require(tokensReceived >= minTokensRec, "Err: High Slippage");
if (shouldTransfer) {
IERC20(toVault).safeTransfer(msg.sender, tokensReceived);
emit zapIn(msg.sender, toVault, tokensReceived);
}
}
function_fillQuote(address _fromTokenAddress,
address toToken,
uint256 _amount,
address _swapTarget,
bytesmemory swapData
) internalreturns (uint256 amtBought) {
if (_fromTokenAddress == toToken) {
return _amount;
}
if (_fromTokenAddress ==address(0) && toToken == wethTokenAddress) {
IWETH(wethTokenAddress).deposit{ value: _amount }();
return _amount;
}
uint256 valueToSend;
if (_fromTokenAddress ==address(0)) {
valueToSend = _amount;
} else {
_approveToken(_fromTokenAddress, _swapTarget);
}
uint256 iniBal = _getBalance(toToken);
require(approvedTargets[_swapTarget], "Target not Authorized");
(bool success, ) = _swapTarget.call{ value: valueToSend }(swapData);
require(success, "Error Swapping Tokens 1");
uint256 finalBal = _getBalance(toToken);
amtBought = finalBal - iniBal;
}
}