// SPDX-License-Identifier: MITpragmasolidity ^0.8.17;import { Sickle } from"contracts/Sickle.sol";
import { SickleFactory } from"contracts/SickleFactory.sol";
contractAccessControlModule{
SickleFactory publicimmutable factory;
errorNotOwner(address sender); // 30cd7471errorNotOwnerOrInternal(); // 25fbbab5errorNotOwnerOrApproved();
errorNotOwnerOrApprovedOrInternal();
errorSickleNotDeployed();
errorNotRegisteredSickle();
constructor(SickleFactory factory_) {
factory = factory_;
}
modifieronlyRegisteredSickle() {
if (factory.admins(address(this)) ==address(0)) {
revert NotRegisteredSickle();
}
_;
}
// @dev allow access only to the sickle's owner// to use for all functions unless part of specific cases listed belowmodifiercheckOwner(address sickleAddress) {
// Calling the factory instead of the Sickle contract gives us the// guarantee that the Sickle contract is genuineif (msg.sender!= factory.admins(sickleAddress)) {
revert NotOwner(msg.sender);
}
_;
}
// @dev allow access only to the sickle's owner or addresses approved by him// to use only for functions such as claiming rewards or compounding rewardsmodifiercheckOwnerOrApproved(address sickleAddress) {
Sickle sickle = Sickle(payable(sickleAddress));
// Here we check if the Sickle was really deployed, this gives use the// guarantee that the contract that we are going to call is genuineif (factory.admins(sickleAddress) ==address(0)) {
revert SickleNotDeployed();
}
if (!sickle.isOwnerOrApproved(msg.sender)) revert NotOwnerOrApproved();
_;
}
}
Contract Source Code
File 2 of 26: Address.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)pragmasolidity ^0.8.1;/**
* @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
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/functionisContract(address account) internalviewreturns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0// for contracts in construction, since the code is only stored at the end// of the constructor execution.return account.code.length>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");
(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 functionCallWithValue(target, data, 0, "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");
(bool success, bytesmemory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, 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) {
(bool success, bytesmemory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, 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) {
(bool success, bytesmemory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/functionverifyCallResultFromTarget(address target,
bool success,
bytesmemory returndata,
stringmemory errorMessage
) internalviewreturns (bytesmemory) {
if (success) {
if (returndata.length==0) {
// only check isContract if the call was successful and the return data is empty// otherwise we already know that it was a contractrequire(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/functionverifyCallResult(bool success,
bytesmemory returndata,
stringmemory errorMessage
) internalpurereturns (bytesmemory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function_revert(bytesmemory returndata, stringmemory errorMessage) privatepure{
// 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/// @solidity memory-safe-assemblyassembly {
let returndata_size :=mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
Contract Source Code
File 3 of 26: Admin.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.17;/// @title Admin contract/// @author vfat.tools/// @notice Provides an administration mechanism allowing restricted functionsabstractcontractAdmin{
/// ERRORS ////// @notice Thrown when the caller is not the adminerrorNotAdminError(); //0xb5c42b3b/// EVENTS ////// @notice Emitted when a new admin is set/// @param oldAdmin Address of the old admin/// @param newAdmin Address of the new admineventAdminSet(address oldAdmin, address newAdmin);
/// STORAGE ////// @notice Address of the current adminaddresspublic admin;
/// MODIFIERS ////// @dev Restricts a function to the adminmodifieronlyAdmin() {
if (msg.sender!= admin) revert NotAdminError();
_;
}
/// WRITE FUNCTIONS ////// @param admin_ Address of the adminconstructor(address admin_) {
emit AdminSet(admin, admin_);
admin = admin_;
}
/// @notice Sets a new admin/// @param newAdmin Address of the new admin/// @custom:access Restricted to protocol admin.functionsetAdmin(address newAdmin) externalonlyAdmin{
emit AdminSet(admin, newAdmin);
admin = newAdmin;
}
}
Contract Source Code
File 4 of 26: Clones.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.8.0) (proxy/Clones.sol)pragmasolidity ^0.8.0;/**
* @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for
* deploying minimal proxy contracts, also known as "clones".
*
* > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
* > a minimal bytecode implementation that delegates all calls to a known, fixed address.
*
* The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
* (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
* deterministic method.
*
* _Available since v3.4._
*/libraryClones{
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
*
* This function uses the create opcode, which should never revert.
*/functionclone(address implementation) internalreturns (address instance) {
/// @solidity memory-safe-assemblyassembly {
// Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes// of the `implementation` address with the bytecode before the address.mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
// Packs the remaining 17 bytes of `implementation` with the bytecode after the address.mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
instance :=create(0, 0x09, 0x37)
}
require(instance !=address(0), "ERC1167: create failed");
}
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
*
* This function uses the create2 opcode and a `salt` to deterministically deploy
* the clone. Using the same `implementation` and `salt` multiple time will revert, since
* the clones cannot be deployed twice at the same address.
*/functioncloneDeterministic(address implementation, bytes32 salt) internalreturns (address instance) {
/// @solidity memory-safe-assemblyassembly {
// Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes// of the `implementation` address with the bytecode before the address.mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
// Packs the remaining 17 bytes of `implementation` with the bytecode after the address.mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
instance :=create2(0, 0x09, 0x37, salt)
}
require(instance !=address(0), "ERC1167: create2 failed");
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/functionpredictDeterministicAddress(address implementation,
bytes32 salt,
address deployer
) internalpurereturns (address predicted) {
/// @solidity memory-safe-assemblyassembly {
let ptr :=mload(0x40)
mstore(add(ptr, 0x38), deployer)
mstore(add(ptr, 0x24), 0x5af43d82803e903d91602b57fd5bf3ff)
mstore(add(ptr, 0x14), implementation)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73)
mstore(add(ptr, 0x58), salt)
mstore(add(ptr, 0x78), keccak256(add(ptr, 0x0c), 0x37))
predicted :=keccak256(add(ptr, 0x43), 0x55)
}
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/functionpredictDeterministicAddress(address implementation, bytes32 salt)
internalviewreturns (address predicted)
{
return predictDeterministicAddress(implementation, salt, address(this));
}
}
Contract Source Code
File 5 of 26: ConnectorRegistry.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.17;import { Admin } from"contracts/base/Admin.sol";
import { TimelockAdmin } from"contracts/base/TimelockAdmin.sol";
errorConnectorNotRegistered(address target);
interfaceICustomConnectorRegistry{
functionconnectorOf(address target) externalviewreturns (address);
}
contractConnectorRegistryisAdmin, TimelockAdmin{
eventConnectorChanged(address target, address connector);
eventCustomRegistryAdded(address registry);
eventCustomRegistryRemoved(address registry);
errorConnectorAlreadySet(address target);
errorConnectorNotSet(address target);
ICustomConnectorRegistry[] public customRegistries;
mapping(ICustomConnectorRegistry =>bool) public isCustomRegistry;
mapping(address target =>address connector) private connectors_;
constructor(address admin_,
address timelockAdmin_
) Admin(admin_) TimelockAdmin(timelockAdmin_) { }
/// @notice Update connector addresses for a batch of targets./// @dev Controls which connector contracts are used for the specified/// targets./// @custom:access Restricted to protocol admin.functionsetConnectors(address[] calldata targets,
address[] calldata connectors
) externalonlyAdmin{
for (uint256 i; i != targets.length;) {
if (connectors_[targets[i]] !=address(0)) {
revert ConnectorAlreadySet(targets[i]);
}
connectors_[targets[i]] = connectors[i];
emit ConnectorChanged(targets[i], connectors[i]);
unchecked {
++i;
}
}
}
functionupdateConnectors(address[] calldata targets,
address[] calldata connectors
) externalonlyTimelockAdmin{
for (uint256 i; i != targets.length;) {
if (connectors_[targets[i]] ==address(0)) {
revert ConnectorNotSet(targets[i]);
}
connectors_[targets[i]] = connectors[i];
emit ConnectorChanged(targets[i], connectors[i]);
unchecked {
++i;
}
}
}
/// @notice Append an address to the custom registries list./// @custom:access Restricted to protocol admin.functionaddCustomRegistry(ICustomConnectorRegistry registry)
externalonlyAdmin{
customRegistries.push(registry);
isCustomRegistry[registry] =true;
emit CustomRegistryAdded(address(registry));
}
/// @notice Replace an address in the custom registries list./// @custom:access Restricted to protocol admin.functionupdateCustomRegistry(uint256 index,
ICustomConnectorRegistry newRegistry
) externalonlyTimelockAdmin{
address oldRegistry =address(customRegistries[index]);
isCustomRegistry[customRegistries[index]] =false;
emit CustomRegistryRemoved(oldRegistry);
customRegistries[index] = newRegistry;
isCustomRegistry[newRegistry] =true;
if (address(newRegistry) !=address(0)) {
emit CustomRegistryAdded(address(newRegistry));
}
}
functionconnectorOf(address target) externalviewreturns (address) {
address connector = connectors_[target];
if (connector !=address(0)) {
return connector;
}
uint256 length = customRegistries.length;
for (uint256 i; i != length;) {
if (address(customRegistries[i]) !=address(0)) {
try customRegistries[i].connectorOf(target) returns (
address _connector
) {
if (_connector !=address(0)) {
return _connector;
}
} catch {
// Ignore
}
}
unchecked {
++i;
}
}
revert ConnectorNotRegistered(target);
}
functionhasConnector(address target) externalviewreturns (bool) {
if (connectors_[target] !=address(0)) {
returntrue;
}
uint256 length = customRegistries.length;
for (uint256 i; i != length;) {
if (address(customRegistries[i]) !=address(0)) {
try customRegistries[i].connectorOf(target) returns (
address _connector
) {
if (_connector !=address(0)) {
returntrue;
}
} catch {
// Ignore
}
unchecked {
++i;
}
}
}
returnfalse;
}
}
Contract Source Code
File 6 of 26: DelegateModule.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.17;contractDelegateModule{
function_delegateTo(address to,
bytesmemory data
) internalreturns (bytesmemory) {
(bool success, bytesmemory result) = to.delegatecall(data);
if (!success) {
if (result.length==0) revert();
assembly {
revert(add(32, result), mload(result))
}
}
return result;
}
}
Contract Source Code
File 7 of 26: ERC20.sol
// SPDX-License-Identifier: AGPL-3.0-onlypragmasolidity >=0.8.0;/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation./// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.abstractcontractERC20{
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/eventTransfer(addressindexedfrom, addressindexed to, uint256 amount);
eventApproval(addressindexed owner, addressindexed spender, uint256 amount);
/*//////////////////////////////////////////////////////////////
METADATA STORAGE
//////////////////////////////////////////////////////////////*/stringpublic name;
stringpublic symbol;
uint8publicimmutable decimals;
/*//////////////////////////////////////////////////////////////
ERC20 STORAGE
//////////////////////////////////////////////////////////////*/uint256public totalSupply;
mapping(address=>uint256) public balanceOf;
mapping(address=>mapping(address=>uint256)) public allowance;
/*//////////////////////////////////////////////////////////////
EIP-2612 STORAGE
//////////////////////////////////////////////////////////////*/uint256internalimmutable INITIAL_CHAIN_ID;
bytes32internalimmutable INITIAL_DOMAIN_SEPARATOR;
mapping(address=>uint256) public nonces;
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/constructor(stringmemory _name,
stringmemory _symbol,
uint8 _decimals
) {
name = _name;
symbol = _symbol;
decimals = _decimals;
INITIAL_CHAIN_ID =block.chainid;
INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
}
/*//////////////////////////////////////////////////////////////
ERC20 LOGIC
//////////////////////////////////////////////////////////////*/functionapprove(address spender, uint256 amount) publicvirtualreturns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
returntrue;
}
functiontransfer(address to, uint256 amount) publicvirtualreturns (bool) {
balanceOf[msg.sender] -= amount;
// Cannot overflow because the sum of all user// balances can't exceed the max uint256 value.unchecked {
balanceOf[to] += amount;
}
emit Transfer(msg.sender, to, amount);
returntrue;
}
functiontransferFrom(addressfrom,
address to,
uint256 amount
) publicvirtualreturns (bool) {
uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.if (allowed !=type(uint256).max) allowance[from][msg.sender] = allowed - amount;
balanceOf[from] -= amount;
// Cannot overflow because the sum of all user// balances can't exceed the max uint256 value.unchecked {
balanceOf[to] += amount;
}
emit Transfer(from, to, amount);
returntrue;
}
/*//////////////////////////////////////////////////////////////
EIP-2612 LOGIC
//////////////////////////////////////////////////////////////*/functionpermit(address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) publicvirtual{
require(deadline >=block.timestamp, "PERMIT_DEADLINE_EXPIRED");
// Unchecked because the only math done is incrementing// the owner's nonce which cannot realistically overflow.unchecked {
address recoveredAddress =ecrecover(
keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR(),
keccak256(
abi.encode(
keccak256(
"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
),
owner,
spender,
value,
nonces[owner]++,
deadline
)
)
)
),
v,
r,
s
);
require(recoveredAddress !=address(0) && recoveredAddress == owner, "INVALID_SIGNER");
allowance[recoveredAddress][spender] = value;
}
emit Approval(owner, spender, value);
}
functionDOMAIN_SEPARATOR() publicviewvirtualreturns (bytes32) {
returnblock.chainid== INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();
}
functioncomputeDomainSeparator() internalviewvirtualreturns (bytes32) {
returnkeccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(name)),
keccak256("1"),
block.chainid,
address(this)
)
);
}
/*//////////////////////////////////////////////////////////////
INTERNAL MINT/BURN LOGIC
//////////////////////////////////////////////////////////////*/function_mint(address to, uint256 amount) internalvirtual{
totalSupply += amount;
// Cannot overflow because the sum of all user// balances can't exceed the max uint256 value.unchecked {
balanceOf[to] += amount;
}
emit Transfer(address(0), to, amount);
}
function_burn(addressfrom, uint256 amount) internalvirtual{
balanceOf[from] -= amount;
// Cannot underflow because a user's balance// will never be larger than the total supply.unchecked {
totalSupply -= amount;
}
emit Transfer(from, address(0), amount);
}
}
Contract Source Code
File 8 of 26: FeesLib.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.17;import { SafeTransferLib } from"solmate/utils/SafeTransferLib.sol";
import { WETH } from"solmate/tokens/WETH.sol";
import { IERC20 } from"@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { Sickle } from"contracts/Sickle.sol";
import { SickleRegistry } from"contracts/SickleRegistry.sol";
contractFeesLib{
eventFeeCharged(address strategy, bytes4 feeDescriptor, uint256 amount, address token
);
eventTransactionCostCharged(address recipient, uint256 amount);
/// @notice Fees library versionuint256publicconstant VERSION =1;
/// @notice Sickle registry address
SickleRegistry publicimmutable registry;
/// @notice WETH9 token address
WETH publicimmutable weth;
addresspublicconstant ETH =0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
constructor(SickleRegistry registry_, WETH weth_) {
registry = registry_;
weth = weth_;
}
/**
* @notice Strategy contract charges fee to user depending on the type of
* action and sends funds to the collector address
* @param strategy Address of the strategy contract
* @param feeDescriptor Descriptor of the fee to be charged
* @param feeToken Address of the token from which an amount will be
* @param feeBasis Amount to be charged (zero if on full amount)
* charged (zero address if native token)
*/functionchargeFee(address strategy,
bytes4 feeDescriptor,
address feeToken,
uint256 feeBasis
) publicpayablereturns (uint256 remainder) {
uint256 fee = registry.feeRegistry(
keccak256(abi.encodePacked(strategy, feeDescriptor))
);
if (feeBasis ==0) {
if (feeToken == ETH) {
uint256 wethBalance = weth.balanceOf(address(this));
if (wethBalance >0) {
weth.withdraw(wethBalance);
}
feeBasis =address(this).balance;
} else {
feeBasis = IERC20(feeToken).balanceOf(address(this));
}
}
if (fee ==0) {
return feeBasis;
}
uint256 amountToCharge = feeBasis * fee /10_000;
if (feeToken ==0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {
SafeTransferLib.safeTransferETH(
registry.collector(), amountToCharge
);
} else {
SafeTransferLib.safeTransfer(
feeToken, registry.collector(), amountToCharge
);
}
emit FeeCharged(strategy, feeDescriptor, amountToCharge, feeToken);
return feeBasis - amountToCharge;
}
functionchargeFees(address strategy,
bytes4 feeDescriptor,
address[] memory feeTokens
) external{
for (uint256 i =0; i < feeTokens.length;) {
chargeFee(strategy, feeDescriptor, feeTokens[i], 0);
unchecked {
i++;
}
}
}
functiongetBalance(
Sickle sickle,
address token
) publicviewreturns (uint256) {
if (token == ETH) {
return weth.balanceOf(address(sickle));
}
return IERC20(token).balanceOf(address(sickle));
}
}
Contract Source Code
File 9 of 26: IERC20.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)pragmasolidity ^0.8.0;/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/interfaceIERC20{
/**
* @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);
/**
* @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 `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/functiontransfer(address to, 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 `from` to `to` 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(addressfrom,
address to,
uint256 amount
) externalreturns (bool);
}
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.8.1) (proxy/utils/Initializable.sol)pragmasolidity ^0.8.2;import"../../utils/Address.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/abstractcontractInitializable{
/**
* @dev Indicates that the contract has been initialized.
* @custom:oz-retyped-from bool
*/uint8private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/boolprivate _initializing;
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/eventInitialized(uint8 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
* constructor.
*
* Emits an {Initialized} event.
*/modifierinitializer() {
bool isTopLevelCall =!_initializing;
require(
(isTopLevelCall && _initialized <1) || (!Address.isContract(address(this)) && _initialized ==1),
"Initializable: contract is already initialized"
);
_initialized =1;
if (isTopLevelCall) {
_initializing =true;
}
_;
if (isTopLevelCall) {
_initializing =false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: setting the version to 255 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/modifierreinitializer(uint8 version) {
require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
_initialized = version;
_initializing =true;
_;
_initializing =false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/modifieronlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/function_disableInitializers() internalvirtual{
require(!_initializing, "Initializable: contract is initializing");
if (_initialized <type(uint8).max) {
_initialized =type(uint8).max;
emit Initialized(type(uint8).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/function_getInitializedVersion() internalviewreturns (uint8) {
return _initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/function_isInitializing() internalviewreturns (bool) {
return _initializing;
}
}
// SPDX-License-Identifier: MITpragmasolidity ^0.8.17;contractMsgValueModule{
errorIncorrectMsgValue();
function_checkMsgValue(uint256 inputAmount, bool isNative) internal{
if (
// Input is native token but user sent incorrect amount
(isNative && inputAmount !=msg.value)
// Input is ERC20 but user sent native token as well|| (!isNative &&msg.value>0)
) {
revert IncorrectMsgValue();
}
}
}
Contract Source Code
File 15 of 26: Multicall.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.17;import { SickleStorage } from"contracts/base/SickleStorage.sol";
import { SickleRegistry } from"contracts/SickleRegistry.sol";
/// @title Multicall contract/// @author vfat.tools/// @notice Enables calling multiple methods in a single call to the contractabstractcontractMulticallisSickleStorage{
/// ERRORS ///errorMulticallParamsMismatchError(); // 0xc1e637c9/// @notice Thrown when the target contract is not whitelisted/// @param target Address of the non-whitelisted targeterrorTargetNotWhitelisted(address target); // 0x47ccabe7/// @notice Thrown when the caller is not whitelisted/// @param caller Address of the non-whitelisted callererrorCallerNotWhitelisted(address caller); // 0x252c8273/// STORAGE ////// @notice Address of the SickleRegistry contract/// @dev Needs to be immutable so that it's accessible for Sickle proxies
SickleRegistry publicimmutable registry;
/// INITIALIZATION ////// @param registry_ Address of the SickleRegistry contractconstructor(SickleRegistry registry_) initializer{
registry = registry_;
}
/// WRITE FUNCTIONS ////// @notice Batch multiple calls together (calls or delegatecalls)/// @param targets Array of targets to call/// @param data Array of data to pass with the callsfunctionmulticall(address[] calldata targets,
bytes[] calldata data
) externalpayable{
if (targets.length!= data.length) {
revert MulticallParamsMismatchError();
}
if (!registry.isWhitelistedCaller(msg.sender)) {
revert CallerNotWhitelisted(msg.sender);
}
for (uint256 i =0; i != data.length;) {
if (targets[i] ==address(0)) {
unchecked {
++i;
}
continue; // No-op
}
if (targets[i] !=address(this)) {
if (!registry.isWhitelistedTarget(targets[i])) {
revert TargetNotWhitelisted(targets[i]);
}
}
(bool success, bytesmemory result) =
targets[i].delegatecall(data[i]);
if (!success) {
if (result.length==0) revert();
assembly {
revert(add(32, result), mload(result))
}
}
unchecked {
++i;
}
}
}
}
Contract Source Code
File 16 of 26: SafeTransferLib.sol
// SPDX-License-Identifier: AGPL-3.0-onlypragmasolidity >=0.8.0;import {ERC20} from"../tokens/ERC20.sol";
/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values./// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)/// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer./// @dev Note that none of the functions in this library check that a token has code at all! That responsibility is delegated to the caller.librarySafeTransferLib{
/*//////////////////////////////////////////////////////////////
ERRORS
//////////////////////////////////////////////////////////////*/errorETHTransferFailed();
errorTransferFromFailed();
errorTransferFailed();
errorApproveFailed();
/*//////////////////////////////////////////////////////////////
ETH OPERATIONS
//////////////////////////////////////////////////////////////*/functionsafeTransferETH(address to, uint256 amount) internal{
bool success;
/// @solidity memory-safe-assemblyassembly {
// Transfer the ETH and store if it succeeded or not.
success :=call(gas(), to, amount, 0, 0, 0, 0)
}
if (!success) revert ETHTransferFailed();
}
/*//////////////////////////////////////////////////////////////
ERC20 OPERATIONS
//////////////////////////////////////////////////////////////*/functionsafeTransferFrom(address token,
addressfrom,
address to,
uint256 amount
) internal{
bool success;
/// @solidity memory-safe-assemblyassembly {
// Get a pointer to some free memory.let freeMemoryPointer :=mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000)
mstore(add(freeMemoryPointer, 4), from) // Append the "from" argument.mstore(add(freeMemoryPointer, 36), to) // Append the "to" argument.mstore(add(freeMemoryPointer, 68), amount) // Append the "amount" argument.
success :=and(
// Set success to whether the call reverted, if not we check it either// returned exactly 1 (can't just be non-zero data), or had no return data.or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
// We use 100 because the length of our calldata totals up like so: 4 + 32 * 3.// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.// Counterintuitively, this call must be positioned second to the or() call in the// surrounding and() call or else returndatasize() will be zero during the computation.call(gas(), token, 0, freeMemoryPointer, 100, 0, 32)
)
}
if (!success) revert TransferFromFailed();
}
functionsafeTransfer(address token,
address to,
uint256 amount
) internal{
bool success;
/// @solidity memory-safe-assemblyassembly {
// Get a pointer to some free memory.let freeMemoryPointer :=mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
mstore(add(freeMemoryPointer, 4), to) // Append the "to" argument.mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument.
success :=and(
// Set success to whether the call reverted, if not we check it either// returned exactly 1 (can't just be non-zero data), or had no return data.or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
// We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.// Counterintuitively, this call must be positioned second to the or() call in the// surrounding and() call or else returndatasize() will be zero during the computation.call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
)
}
if (!success) revert TransferFailed();
}
functionsafeApprove(address token,
address to,
uint256 amount
) internal{
bool success;
/// @solidity memory-safe-assemblyassembly {
// Get a pointer to some free memory.let freeMemoryPointer :=mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000)
mstore(add(freeMemoryPointer, 4), to) // Append the "to" argument.mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument.
success :=and(
// Set success to whether the call reverted, if not we check it either// returned exactly 1 (can't just be non-zero data), or had no return data.or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
// We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.// Counterintuitively, this call must be positioned second to the or() call in the// surrounding and() call or else returndatasize() will be zero during the computation.call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
)
}
if (!success) revert ApproveFailed();
}
}
// SPDX-License-Identifier: MITpragmasolidity ^0.8.17;import { Clones } from"@openzeppelin/contracts/proxy/Clones.sol";
import { SickleRegistry } from"contracts/SickleRegistry.sol";
import { Sickle } from"contracts/Sickle.sol";
import { Admin } from"contracts/base/Admin.sol";
/// @title SickleFactory contract/// @author vfat.tools/// @notice Factory deploying new Sickle contractscontractSickleFactoryisAdmin{
/// EVENTS ////// @notice Emitted when a new Sickle contract is deployed/// @param admin Address receiving the admin rights of the Sickle contract/// @param sickle Address of the newly deployed Sickle contracteventDeploy(addressindexed admin, address sickle);
/// @notice Thrown when the caller is not whitelisted/// @param caller Address of the non-whitelisted callererrorCallerNotWhitelisted(address caller); // 0x252c8273/// @notice Thrown when the factory is not active and a deploy is attemptederrorNotActive(); // 0x80cb55e2/// @notice Thrown when a Sickle contract is already deployed for a usererrorSickleAlreadyDeployed(); //0xf6782ef1/// STORAGE ///mapping(address=>address) private _sickles;
mapping(address=>address) private _admins;
mapping(address=>bytes32) public _referralCodes;
/// @notice Address of the SickleRegistry contract
SickleRegistry publicimmutable registry;
/// @notice Address of the Sickle implementation contractaddresspublicimmutable implementation;
/// @notice Address of the previous SickleFactory contract (if applicable)
SickleFactory publicimmutable previousFactory;
/// @notice Whether the factory is active (can deploy new Sickle contracts)boolpublic isActive =true;
/// WRITE FUNCTIONS ////// @param admin_ Address of the admin/// @param sickleRegistry_ Address of the SickleRegistry contract/// @param sickleImplementation_ Address of the Sickle implementation/// contract/// @param previousFactory_ Address of the previous SickleFactory contract/// if applicableconstructor(address admin_,
address sickleRegistry_,
address sickleImplementation_,
address previousFactory_
) Admin(admin_) {
registry = SickleRegistry(sickleRegistry_);
implementation = sickleImplementation_;
previousFactory = SickleFactory(previousFactory_);
}
/// @notice Update the isActive flag./// @dev Effectively pauses and unpauses new Sickle deployments./// @custom:access Restricted to protocol admin.functionsetActive(bool active) externalonlyAdmin{
isActive = active;
}
function_deploy(address admin,
address approved,
bytes32 referralCode
) internalreturns (address sickle) {
sickle = Clones.cloneDeterministic(
implementation, keccak256(abi.encode(admin))
);
Sickle(payable(sickle)).initialize(admin, approved);
_sickles[admin] = sickle;
_admins[sickle] = admin;
if (referralCode !=bytes32(0)) {
_referralCodes[sickle] = referralCode;
}
emit Deploy(admin, sickle);
}
function_getSickle(address admin) internalreturns (address sickle) {
sickle = _sickles[admin];
if (sickle !=address(0)) {
return sickle;
}
if (address(previousFactory) !=address(0)) {
sickle = previousFactory.sickles(admin);
if (sickle !=address(0)) {
_sickles[admin] = sickle;
_admins[sickle] = admin;
_referralCodes[sickle] = previousFactory.referralCodes(sickle);
return sickle;
}
}
}
/// @notice Predict the address of a Sickle contract for a specific user/// @param admin Address receiving the admin rights of the Sickle contract/// @return sickle Address of the predicted Sickle contractfunctionpredict(address admin) externalviewreturns (address) {
bytes32 salt =keccak256(abi.encode(admin));
return Clones.predictDeterministicAddress(implementation, salt);
}
/// @notice Returns the Sickle contract for a specific user/// @param admin Address that owns the Sickle contract/// @return sickle Address of the Sickle contractfunctionsickles(address admin) externalviewreturns (address sickle) {
sickle = _sickles[admin];
if (sickle ==address(0) &&address(previousFactory) !=address(0)) {
sickle = previousFactory.sickles(admin);
}
}
/// @notice Returns the admin for a specific Sickle contract/// @param sickle Address of the Sickle contract/// @return admin Address that owns the Sickle contractfunctionadmins(address sickle) externalviewreturns (address admin) {
admin = _admins[sickle];
if (admin ==address(0) &&address(previousFactory) !=address(0)) {
admin = previousFactory.admins(sickle);
}
}
/// @notice Returns the referral code for a specific Sickle contract/// @param sickle Address of the Sickle contract/// @return referralCode Referral code for the userfunctionreferralCodes(address sickle)
externalviewreturns (bytes32 referralCode)
{
referralCode = _referralCodes[sickle];
if (
referralCode ==bytes32(0) &&address(previousFactory) !=address(0)
) {
referralCode = previousFactory.referralCodes(sickle);
}
}
/// @notice Deploys a new Sickle contract for a specific user, or returns/// the existing one if it exists/// @param admin Address receiving the admin rights of the Sickle contract/// @param referralCode Referral code for the user/// @return sickle Address of the deployed Sickle contractfunctiongetOrDeploy(address admin,
address approved,
bytes32 referralCode
) externalreturns (address sickle) {
if (!isActive) {
revert NotActive();
}
if (!registry.isWhitelistedCaller(msg.sender)) {
revert CallerNotWhitelisted(msg.sender);
}
if ((sickle = _getSickle(admin)) !=address(0)) {
return sickle;
}
return _deploy(admin, approved, referralCode);
}
/// @notice Deploys a new Sickle contract for a specific user/// @dev Sickle contracts are deployed with create2, the address of the/// admin is used as a salt, so all the Sickle addresses can be pre-computed/// and only 1 Sickle will exist per address/// @param referralCode Referral code for the user/// @return sickle Address of the deployed Sickle contractfunctiondeploy(address approved,
bytes32 referralCode
) externalreturns (address sickle) {
if (!isActive) {
revert NotActive();
}
if (_getSickle(msg.sender) !=address(0)) {
revert SickleAlreadyDeployed();
}
return _deploy(msg.sender, approved, referralCode);
}
}
Contract Source Code
File 19 of 26: SickleRegistry.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.17;import { Admin } from"contracts/base/Admin.sol";
librarySickleRegistryEvents{
eventCollectorChanged(address newCollector);
eventFeesUpdated(bytes32[] feeHashes, uint256[] feesInBP);
eventReferralCodeCreated(bytes32indexed code, addressindexed referrer);
// Multicall caller and target whitelist status changeseventCallerStatusChanged(address caller, bool isWhitelisted);
eventTargetStatusChanged(address target, bool isWhitelisted);
}
/// @title SickleRegistry contract/// @author vfat.tools/// @notice Manages the whitelisted contracts and the collector addresscontractSickleRegistryisAdmin{
/// ERRORS ///errorArrayLengthMismatch(); // 0xa24a13a6errorFeeAboveMaxLimit(); // 0xd6cf7b5eerrorInvalidReferralCode(); // 0xe55b4629/// STORAGE ////// @notice Address of the fee collectoraddresspublic collector;
/// @notice Tracks the contracts that can be called through Sickle multicall/// @return True if the contract is a whitelisted targetmapping(address=>bool) public isWhitelistedTarget;
/// @notice Tracks the contracts that can call Sickle multicall/// @return True if the contract is a whitelisted callermapping(address=>bool) public isWhitelistedCaller;
/// @notice Keeps track of the referrers and their associated codemapping(bytes32=>address) public referralCodes;
/// @notice Mapping for fee hashes (hash of the strategy contract addresses/// and the function selectors) and their associated fees/// @return The fee in basis points to apply to the transaction amountmapping(bytes32=>uint256) public feeRegistry;
/// WRITE FUNCTIONS ////// @param admin_ Address of the admin/// @param collector_ Address of the collectorconstructor(address admin_, address collector_) Admin(admin_) {
collector = collector_;
}
/// @notice Updates the whitelist status for multiple multicall targets/// @param targets Addresses of the contracts to update/// @param isApproved New status for the contracts/// @custom:access Restricted to protocol admin.functionsetWhitelistedTargets(address[] calldata targets,
bool isApproved
) externalonlyAdmin{
for (uint256 i; i < targets.length;) {
isWhitelistedTarget[targets[i]] = isApproved;
emit SickleRegistryEvents.TargetStatusChanged(
targets[i], isApproved
);
unchecked {
++i;
}
}
}
/// @notice Updates the fee collector address/// @param newCollector Address of the new fee collector/// @custom:access Restricted to protocol admin.functionupdateCollector(address newCollector) externalonlyAdmin{
collector = newCollector;
emit SickleRegistryEvents.CollectorChanged(newCollector);
}
/// @notice Update the whitelist status for multiple multicall callers/// @param callers Addresses of the callers/// @param isApproved New status for the caller/// @custom:access Restricted to protocol admin.functionsetWhitelistedCallers(address[] calldata callers,
bool isApproved
) externalonlyAdmin{
for (uint256 i; i < callers.length;) {
isWhitelistedCaller[callers[i]] = isApproved;
emit SickleRegistryEvents.CallerStatusChanged(
callers[i], isApproved
);
unchecked {
++i;
}
}
}
/// @notice Associates a referral code to the address of the callerfunctionsetReferralCode(bytes32 referralCode) external{
if (referralCodes[referralCode] !=address(0)) {
revert InvalidReferralCode();
}
referralCodes[referralCode] =msg.sender;
emit SickleRegistryEvents.ReferralCodeCreated(referralCode, msg.sender);
}
/// @notice Update the fees for multiple strategy functions/// @param feeHashes Array of fee hashes/// @param feesArray Array of fees to apply (in basis points)/// @custom:access Restricted to protocol admin.functionsetFees(bytes32[] calldata feeHashes,
uint256[] calldata feesArray
) externalonlyAdmin{
if (feeHashes.length!= feesArray.length) {
revert ArrayLengthMismatch();
}
for (uint256 i =0; i < feeHashes.length;) {
if (feesArray[i] <=500) {
// maximum fee of 5%
feeRegistry[feeHashes[i]] = feesArray[i];
} else {
revert FeeAboveMaxLimit();
}
unchecked {
++i;
}
}
emit SickleRegistryEvents.FeesUpdated(feeHashes, feesArray);
}
}
Contract Source Code
File 20 of 26: SickleStorage.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.17;import { Initializable } from"@openzeppelin/contracts/proxy/utils/Initializable.sol";
librarySickleStorageEvents{
eventApprovedAddressChanged(address newApproved);
}
/// @title SickleStorage contract/// @author vfat.tools/// @notice Base storage of the Sickle contract/// @dev This contract needs to be inherited by stub contracts meant to be used/// with `delegatecall`abstractcontractSickleStorageisInitializable{
/// ERRORS ////// @notice Thrown when the caller is not the owner of the Sickle contracterrorNotOwnerError(); // 0x74a21527/// @notice Thrown when the caller is not a strategy contract or the/// Flashloan StuberrorNotStrategyError(); // 0x4581ba62/// STORAGE ////// @notice Address of the owneraddresspublic owner;
/// @notice An address that can be set by the owner of the Sickle contract/// in order to trigger specific functions.addresspublic approved;
/// MODIFIERS ////// @dev Restricts a function call to the owner, however if the admin was/// not set yet,/// the modifier will not restrict the call, this allows the SickleFactory/// to perform/// some calls on the user's behalf before passing the admin rights to themmodifieronlyOwner() {
if (msg.sender!= owner) revert NotOwnerError();
_;
}
/// INITIALIZATION ////// @param owner_ Address of the owner of this Sickle contractfunction_SickleStorage_initialize(address owner_,
address approved_
) internalonlyInitializing{
owner = owner_;
approved = approved_;
}
/// WRITE FUNCTIONS ////// @notice Sets the approved address of this Sickle/// @param newApproved Address meant to be approved by the ownerfunctionsetApproved(address newApproved) externalonlyOwner{
approved = newApproved;
emit SickleStorageEvents.ApprovedAddressChanged(newApproved);
}
/// @notice Checks if `caller` is either the owner of the Sickle contract/// or was approved by them/// @param caller Address to check/// @return True if `caller` is either the owner of the Sickle contractfunctionisOwnerOrApproved(address caller) publicviewreturns (bool) {
return caller == owner || caller == approved;
}
}
// SPDX-License-Identifier: MITpragmasolidity ^0.8.17;import { IERC20 } from"@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeTransferLib } from"solmate/utils/SafeTransferLib.sol";
import { DelegateModule } from"contracts/modules/DelegateModule.sol";
import { ConnectorRegistry } from"contracts/ConnectorRegistry.sol";
import {
ILiquidityConnector,
SwapData
} from"contracts/interfaces/ILiquidityConnector.sol";
contractSwapLibisDelegateModule{
errorSwapAmountZero();
ConnectorRegistry immutable connectorRegistry;
constructor(ConnectorRegistry connectorRegistry_) {
connectorRegistry = connectorRegistry_;
}
functionswap(SwapData memory swapData) externalpayable{
_swap(swapData);
}
functionswapMultiple(SwapData[] memory swapData) external{
uint256 swapDataLength = swapData.length;
for (uint256 i; i < swapDataLength;) {
_swap(swapData[i]);
unchecked {
i++;
}
}
}
/* Internal Functions */function_swap(SwapData memory swapData) internal{
address tokenIn = swapData.tokenIn;
if (swapData.amountIn ==0) {
swapData.amountIn = IERC20(tokenIn).balanceOf(address(this));
}
if (swapData.amountIn ==0) {
revert SwapAmountZero();
}
// In case there is USDT dust approval, revoke it
SafeTransferLib.safeApprove(tokenIn, swapData.router, 0);
SafeTransferLib.safeApprove(tokenIn, swapData.router, swapData.amountIn);
address connectorAddress =
connectorRegistry.connectorOf(swapData.router);
ILiquidityConnector routerConnector =
ILiquidityConnector(connectorAddress);
_delegateTo(
address(routerConnector),
abi.encodeCall(routerConnector.swapExactTokensForTokens, swapData)
);
// Revoke any approval after swap in case the swap amount was estimated
SafeTransferLib.safeApprove(tokenIn, swapData.router, 0);
}
}
Contract Source Code
File 23 of 26: TimelockAdmin.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.17;/// @title TimelockAdmin contract/// @author vfat.tools/// @notice Provides an timelockAdministration mechanism allowing restricted/// functionsabstractcontractTimelockAdmin{
/// ERRORS ////// @notice Thrown when the caller is not the timelockAdminerrorNotTimelockAdminError();
/// EVENTS ////// @notice Emitted when a new timelockAdmin is set/// @param oldTimelockAdmin Address of the old timelockAdmin/// @param newTimelockAdmin Address of the new timelockAdmineventTimelockAdminSet(address oldTimelockAdmin, address newTimelockAdmin);
/// STORAGE ////// @notice Address of the current timelockAdminaddresspublic timelockAdmin;
/// MODIFIERS ////// @dev Restricts a function to the timelockAdminmodifieronlyTimelockAdmin() {
if (msg.sender!= timelockAdmin) revert NotTimelockAdminError();
_;
}
/// WRITE FUNCTIONS ////// @param timelockAdmin_ Address of the timelockAdminconstructor(address timelockAdmin_) {
emit TimelockAdminSet(timelockAdmin, timelockAdmin_);
timelockAdmin = timelockAdmin_;
}
/// @notice Sets a new timelockAdmin/// @dev Can only be called by the current timelockAdmin/// @param newTimelockAdmin Address of the new timelockAdminfunctionsetTimelockAdmin(address newTimelockAdmin)
externalonlyTimelockAdmin{
emit TimelockAdminSet(timelockAdmin, newTimelockAdmin);
timelockAdmin = newTimelockAdmin;
}
}
Contract Source Code
File 24 of 26: TransferLib.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.17;import { MsgValueModule } from"contracts/modules/MsgValueModule.sol";
import { WETH } from"lib/solmate/src/tokens/WETH.sol";
import { Sickle } from"contracts/Sickle.sol";
import { SafeTransferLib } from"lib/solmate/src/utils/SafeTransferLib.sol";
import { IERC20 } from"lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol";
import { FeesLib } from"contracts/libraries/FeesLib.sol";
import { DelegateModule } from"contracts/modules/DelegateModule.sol";
contractTransferLibisMsgValueModule, DelegateModule{
errorArrayLengthMismatch();
errorTokenInRequired();
addresspublicconstant ETH =0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
WETH publicimmutable weth;
FeesLib publicimmutable feesLib;
constructor(FeesLib feseLib_, WETH weth_) {
feesLib = feseLib_;
weth = weth_;
}
/// @dev Transfers the balance of {token} from the contract to the/// sickle owner/// @param token Address of the token to transferfunctiontransferTokenToUser(address token) publicpayable{
address recipient = Sickle(payable(address(this))).owner();
if (token ==address(0)) {
return;
}
if (token == ETH) {
uint256 wethBalance = weth.balanceOf(address(this));
if (wethBalance >0) {
weth.withdraw(wethBalance);
}
if (address(this).balance>0) {
SafeTransferLib.safeTransferETH(
recipient, address(this).balance
);
}
} else {
uint256 balance = IERC20(token).balanceOf(address(this));
if (balance >0) {
SafeTransferLib.safeTransfer(token, recipient, balance);
}
}
}
/// @dev Transfers all balances of {tokens} and/or ETH from the contract/// to the sickle owner/// @param tokens An array of token addressesfunctiontransferTokensToUser(address[] memory tokens) externalpayable{
for (uint256 i =0; i != tokens.length;) {
transferTokenToUser(tokens[i]);
unchecked {
i++;
}
}
}
/// @dev Transfers {amountIn} of {tokenIn} from the user to the Sickle/// contract, charging the fees and converting the amount to WETH if/// necessary/// @param tokenIn Address of the token to transfer/// @param amountIn Amount of the token to transfer/// @param strategy Address of the caller strategy/// @param feeSelector Selector of the caller functionfunctiontransferTokenFromUser(address tokenIn,
uint256 amountIn,
address strategy,
bytes4 feeSelector
) publicpayable{
_checkMsgValue(amountIn, tokenIn == ETH);
_transferTokenFromUser(tokenIn, amountIn, strategy, feeSelector);
}
/// @dev Transfers {amountIn} of {tokenIn} from the user to the Sickle/// contract, charging the fees and converting the amount to WETH if/// necessary/// @param tokensIn Addresses of the tokens to transfer/// @param amountsIn Amounts of the tokens to transfer/// @param strategy Address of the caller strategy/// @param feeSelector Selector of the caller functionfunctiontransferTokensFromUser(address[] memory tokensIn,
uint256[] memory amountsIn,
address strategy,
bytes4 feeSelector
) externalpayable{
if (tokensIn.length!= amountsIn.length) {
revert ArrayLengthMismatch();
}
if (tokensIn.length==0) {
revert TokenInRequired();
}
bool hasEth =false;
for (uint256 i =0; i < tokensIn.length; i++) {
if (tokensIn[i] == ETH) {
_checkMsgValue(amountsIn[i], true);
hasEth =true;
}
_transferTokenFromUser(
tokensIn[i], amountsIn[i], strategy, feeSelector
);
}
if (!hasEth) {
// Revert if ETH was sent but not used
_checkMsgValue(0, false);
}
}
/* Internal functions */function_transferTokenFromUser(address tokenIn,
uint256 amountIn,
address strategy,
bytes4 feeSelector
) internal{
if (tokenIn != ETH) {
SafeTransferLib.safeTransferFrom(
tokenIn,
Sickle(payable(address(this))).owner(),
address(this),
amountIn
);
}
bytesmemory result = _delegateTo(
address(feesLib),
abi.encodeCall(
FeesLib.chargeFee, (strategy, feeSelector, tokenIn, 0)
)
);
uint256 remainder =abi.decode(result, (uint256));
if (tokenIn == ETH) {
weth.deposit{ value: remainder }();
}
}
}