Verified contractExactMIT
BinSettingsRegistryV2
Address0xd4e591b2204c598aaf8144beecfe2d40725135d4
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.19
- Same code
Only this contract
Details
- Compiler
- solc 0.8.19+commit.7dd6d404
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- paris
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,346,419
- Creation transaction
- 0x67ba6fe282…6dc353211d
20 files
- contracts/BinSettingsRegistryV2.solmain25.8 KB
- contracts/BinSettingsRegistry.sol23.02 KB
- contracts/Sickle.sol1.84 KB
- contracts/SickleFactory.sol7.18 KB
- contracts/SickleRegistry.sol4.93 KB
- contracts/base/Admin.sol1.3 KB
- contracts/base/Multicall.sol2.46 KB
- contracts/base/SickleStorage.sol2.22 KB
- contracts/interfaces/external/lfj/ILBPair.sol3.55 KB
- contracts/structs/BinFarmStrategyStructs.sol2.81 KB
- contracts/structs/BinSettingsStructs.sol1.21 KB
- contracts/structs/FarmStrategyStructs.sol1.02 KB
- contracts/structs/LiquidityStructs.sol398 B
- contracts/structs/PositionSettingsStructs.sol1.55 KB
- contracts/structs/SwapStructs.sol268 B
- contracts/structs/ZapStructs.sol407 B
- lib/openzeppelin-contracts/contracts/proxy/Clones.sol4.04 KB
- lib/openzeppelin-contracts/contracts/proxy/utils/Initializable.sol6.61 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.77 KB
- lib/openzeppelin-contracts/contracts/utils/Address.sol9.16 KB
contracts/BinSettingsRegistryV2.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import { BinSettingsRegistry } from "contracts/BinSettingsRegistry.sol";
import { SickleFactory } from "contracts/SickleFactory.sol";
import { Admin } from "contracts/base/Admin.sol";
import { BinKey, BinSettings } from "contracts/structs/BinSettingsStructs.sol";
import { BinAddLiquidity } from "contracts/structs/BinFarmStrategyStructs.sol";
import { RewardBehavior } from "contracts/structs/PositionSettingsStructs.sol";
import { ILBPair } from "contracts/interfaces/external/lfj/ILBPair.sol";
/// @notice Per-pair consent for automated Liquidity Book positions.
/// @dev An owner opts in to a bin range, rather than an NFT token ID. A keeper
/// may only withdraw shares from that range; rebalance updates it atomically.
/// @dev Kept in a separate source unit: changing the legacy registry would
/// change the metadata of the unchanged BinFarmStrategy that imports it.
contract BinSettingsRegistryV2 is Admin {
error SickleNotDeployed();
error InvalidPreviousRegistry();
error InvalidPair();
error InvalidRange();
error InvalidRewardConfig();
error InvalidTrigger();
error AutoDepositNotSet();
error AutoHarvestNotSet();
error AutoCompoundNotSet();
error AutoExitNotSet();
error AutoRebalanceNotSet();
error ActiveIdWithinRange();
error ActiveIdOutsideCutoff();
error ActiveIdOutsideBounds();
error BinOutsideRange(uint256 id);
error IdSlippageTooHigh();
error RebalanceShapeMismatch();
error ShiftRequiresRebalance();
error ShiftTargetMismatch(uint24 expectedLow, uint24 expectedHigh);
error ShiftMintMismatch(uint24 expectedLow, uint24 expectedHigh);
error ShiftTargetUnchanged();
error ShiftTargetTwoCycle();
error ShiftTargetOutsideCutoff();
error IncompleteWithdrawal(uint256 id);
error OnlyStrategy();
event BinSettingsSet(BinKey key, BinSettings settings);
event BinRangeUpdated(BinKey key, uint24 rangeLow, uint24 rangeHigh);
event BinSettingsCleared(BinKey key);
event StrategySet(address strategy);
event BridgeStrategySet(address strategy);
SickleFactory public immutable factory;
address public strategy;
address public bridgeStrategy;
mapping(bytes32 => BinSettings) private settingsMap;
/// @notice Untouched positions read through the current predecessor.
BinSettingsRegistry public immutable previousRegistry;
/// @notice Local writes, including disabled/cleared settings, suppress
/// fallback. A zero struct alone cannot represent an owner's revocation.
mapping(bytes32 => bool) public overridesPrevious;
/// @notice Cleanup uses the executing Sickle's revocable caller policy.
uint256 public constant OWNER_EXIT_VERSION = 2;
constructor(
SickleFactory factory_,
address admin_,
BinSettingsRegistry previousRegistry_
) Admin(admin_) {
if (address(previousRegistry_) != address(0)) {
// Same typed probe as the NFT/position registries. It checks the
// current ABI, not the provenance of every historical ancestor.
BinKey memory probe;
try previousRegistry_.getBinSettings(probe) returns (
BinSettings memory
) { }
catch {
revert InvalidPreviousRegistry();
}
if (previousRegistry_.factory() != factory_) {
revert InvalidPreviousRegistry();
}
}
factory = factory_;
previousRegistry = previousRegistry_;
}
function setStrategy(
address strategy_
) external onlyAdmin {
if (strategy_.code.length == 0) revert OnlyStrategy();
strategy = strategy_;
emit StrategySet(strategy_);
}
function setBridgeStrategy(
address strategy_
) external onlyAdmin {
if (strategy_.code.length == 0) revert OnlyStrategy();
bridgeStrategy = strategy_;
emit BridgeStrategySet(strategy_);
}
function getBinSettings(
BinKey memory key
) public view returns (BinSettings memory) {
bytes32 hash = keccak256(abi.encode(key));
if (overridesPrevious[hash] || address(previousRegistry) == address(0))
{
return settingsMap[hash];
}
return previousRegistry.getBinSettings(key);
}
/// @notice Whether burning this share balance returns at least one token.
/// LBPair rounds each token output down and rejects a zero/zero burn.
function isBurnable(
ILBPair pair,
uint256 id,
uint256 balance
) public view returns (bool) {
if (balance == 0) return false;
if (id > type(uint24).max) revert InvalidRange();
uint256 supply = pair.totalSupply(id);
if (supply == 0) return false;
(uint128 reserveX, uint128 reserveY) = pair.getBin(uint24(id));
return (reserveX != 0 && balance > (supply - 1) / reserveX)
|| (reserveY != 0 && balance > (supply - 1) / reserveY);
}
/// @notice Read current balances and omit shares that cannot be burned.
function burnableBalances(
address sickle,
ILBPair pair,
uint256[] calldata requestedIds
) external view returns (uint256[] memory ids, uint256[] memory amounts) {
uint256[] memory keptIds = new uint256[](requestedIds.length);
uint256[] memory keptAmounts = new uint256[](requestedIds.length);
uint256 count;
for (uint256 i; i < requestedIds.length; ++i) {
uint256 id = requestedIds[i];
if (i != 0 && id <= requestedIds[i - 1]) revert InvalidRange();
uint256 balance = pair.balanceOf(sickle, id);
if (!isBurnable(pair, id, balance)) continue;
keptIds[count] = id;
keptAmounts[count] = balance;
++count;
}
if (count == 0) revert InvalidRange();
ids = new uint256[](count);
amounts = new uint256[](count);
for (uint256 i; i < count; ++i) {
ids[i] = keptIds[i];
amounts[i] = keptAmounts[i];
}
}
/// @notice The Sickle owner opts the entire configured bin range into
/// keeper operations. Setting all flags false disables automation.
function setBinSettings(
BinKey calldata key,
BinSettings calldata settings
) external {
if (factory.admins(address(key.sickle)) != msg.sender) {
revert SickleNotDeployed();
}
_setBinSettings(key, settings);
}
/// @notice Install owner-supplied automation settings for the bins actually
/// minted by an owner deposit or move. The strategy authenticates the
/// owner.
function setAfterMint(
BinKey calldata key,
BinSettings calldata settings,
uint256[] calldata mintedIds,
uint256[] calldata mintedAmounts
) external {
_requireOwnerStrategy();
(uint24 low, uint24 high) = _mintedRange(mintedIds, mintedAmounts);
BinSettings memory previous = getBinSettings(key);
BinSettings memory actual = settings;
// A second deposit into the same pair/farm adds to the existing
// position. Keep every bin with shares inside the consent range.
actual.rangeLow = previous.rangeHigh == 0 || low < previous.rangeLow
? low
: previous.rangeLow;
actual.rangeHigh = high > previous.rangeHigh ? high : previous.rangeHigh;
if (
previous.rangeHigh != 0 && actual.autoRebalance
&& (actual.rangeLow < actual.cutoffLow
|| actual.rangeHigh > actual.cutoffHigh
|| (actual.shiftConfig.enabled
&& uint256(actual.rangeHigh) - actual.rangeLow
!= uint256(previous.rangeHigh) - previous.rangeLow))
) {
actual.autoRebalance = false;
actual.shiftConfig.enabled = false;
}
_setBinSettings(key, actual);
}
function _setBinSettings(
BinKey memory key,
BinSettings memory settings
) private {
if (address(key.lbPair) == address(0)) revert InvalidPair();
if (settings.rangeLow > settings.rangeHigh) revert InvalidRange();
if (
!settings.automateRewards
&& settings.rewardConfig.rewardBehavior != RewardBehavior.None
) revert InvalidRewardConfig();
if (
settings.automateRewards
&& (key.stakingContract == address(0)
|| settings.rewardConfig.rewardBehavior
== RewardBehavior.None)
) revert InvalidRewardConfig();
if (
settings.rewardConfig.rewardBehavior != RewardBehavior.Harvest
&& settings.rewardConfig.harvestTokenOut != address(0)
) revert InvalidRewardConfig();
if (
settings.autoRebalance
&& (settings.cutoffLow > settings.cutoffHigh
|| settings.rangeLow < settings.cutoffLow
|| settings.rangeHigh > settings.cutoffHigh
|| int256(uint256(settings.rangeLow))
- settings.rebalanceBufferBelow
> int256(uint256(settings.rangeHigh))
+ settings.rebalanceBufferAbove)
) revert InvalidTrigger();
if (settings.autoRebalance && settings.rebalanceShapeHash == bytes32(0))
{
revert RebalanceShapeMismatch();
}
if (settings.shiftConfig.enabled && !settings.autoRebalance) {
revert ShiftRequiresRebalance();
}
bytes32 hash = keccak256(abi.encode(key));
overridesPrevious[hash] = true;
settingsMap[hash] = settings;
emit BinSettingsSet(key, settings);
}
function validateDepositFor(
BinKey calldata key
) external view {
if (!getBinSettings(key).autoDeposit) revert AutoDepositNotSet();
}
function validateMinted(
BinKey calldata key,
uint256[] calldata ids
) external view {
_validateIds(getBinSettings(key), ids);
}
function validateHarvestFor(
BinKey calldata key
) external view {
BinSettings memory settings = getBinSettings(key);
if (
!settings.automateRewards
|| settings.rewardConfig.rewardBehavior
!= RewardBehavior.Harvest
) revert AutoHarvestNotSet();
}
function validateCompoundFor(
BinKey calldata key
) external view {
BinSettings memory settings = getBinSettings(key);
if (
!settings.automateRewards
|| settings.rewardConfig.rewardBehavior
!= RewardBehavior.Compound
) revert AutoCompoundNotSet();
}
function validateExitFor(
BinKey calldata key,
uint256[] calldata ids,
uint256[] calldata amounts
) external view {
BinSettings memory settings = getBinSettings(key);
if (!settings.autoExit) revert AutoExitNotSet();
_validateIds(settings, ids);
_validateFullWithdrawal(key, settings, ids, amounts);
uint256 activeId = key.lbPair.getActiveId();
if (
activeId >= _lower(settings.rangeLow, settings.exitBufferBelow)
&& activeId
<= uint256(settings.rangeHigh) + settings.exitBufferAbove
) revert ActiveIdWithinRange();
}
function validateRebalanceFor(
BinKey calldata key,
uint256[] calldata ids,
uint256[] calldata amounts,
BinAddLiquidity calldata addLp,
uint24 minActiveId,
uint24 maxActiveId
) external view returns (uint64 shiftTarget) {
BinSettings memory settings = getBinSettings(key);
if (!settings.autoRebalance) revert AutoRebalanceNotSet();
_validateIds(settings, ids);
if (addLp.idSlippage > settings.maxIdSlippage) {
revert IdSlippageTooHigh();
}
if (
keccak256(
abi.encode(
addLp.deltaIds, addLp.distributionX, addLp.distributionY
)
) != settings.rebalanceShapeHash
) {
revert RebalanceShapeMismatch();
}
uint256 activeId = key.lbPair.getActiveId();
bool below = _validateRebalanceTrigger(
settings, activeId, minActiveId, maxActiveId
);
_validateFullWithdrawal(key, settings, ids, amounts);
if (!settings.shiftConfig.enabled) return 0;
return _validateShiftTarget(settings, addLp, activeId, below);
}
function _validateRebalanceTrigger(
BinSettings memory settings,
uint256 activeId,
uint24 minActiveId,
uint24 maxActiveId
) private pure returns (bool below) {
if (
(minActiveId != 0 || maxActiveId != 0)
&& (activeId < minActiveId || activeId > maxActiveId)
) revert ActiveIdOutsideBounds();
int256 lowerTrigger =
int256(uint256(settings.rangeLow)) - settings.rebalanceBufferBelow;
int256 upperTrigger =
int256(uint256(settings.rangeHigh)) + settings.rebalanceBufferAbove;
below = int256(activeId) < lowerTrigger;
bool above = int256(activeId) > upperTrigger;
if (!below && !above) revert ActiveIdWithinRange();
if (activeId < settings.cutoffLow || activeId > settings.cutoffHigh) {
revert ActiveIdOutsideCutoff();
}
}
function _validateShiftTarget(
BinSettings memory settings,
BinAddLiquidity calldata addLp,
uint256 activeId,
bool below
) private pure returns (uint64) {
uint256 width = uint256(settings.rangeHigh) - settings.rangeLow;
uint256 low;
uint256 high;
if (below) {
high = activeId + settings.shiftConfig.entryBinsDown;
if (high < width) revert InvalidRange();
low = high - width;
} else {
if (activeId < settings.shiftConfig.entryBinsUp) {
revert InvalidRange();
}
low = activeId - settings.shiftConfig.entryBinsUp;
high = low + width;
}
if (high > type(uint24).max) revert InvalidRange();
if (low == settings.rangeLow) revert ShiftTargetUnchanged();
_validateNoTwoCycle(settings, activeId, low);
if (low < settings.cutoffLow || high > settings.cutoffHigh) {
revert ShiftTargetOutsideCutoff();
}
if (
addLp.deltaIds.length == 0
|| int256(addLp.activeIdDesired) + addLp.deltaIds[0]
!= int256(low)
|| int256(addLp.activeIdDesired)
+ addLp.deltaIds[addLp.deltaIds.length - 1]
!= int256(high)
) revert ShiftTargetMismatch(uint24(low), uint24(high));
return (uint64(1) << 48) | (uint64(low) << 24) | uint64(high);
}
function _validateNoTwoCycle(
BinSettings memory settings,
uint256 activeId,
uint256 targetLow
) private pure {
uint256 width = uint256(settings.rangeHigh) - settings.rangeLow;
if (activeId < settings.shiftConfig.entryBinsUp) return;
uint256 upLow = activeId - settings.shiftConfig.entryBinsUp;
uint256 downHigh = activeId + settings.shiftConfig.entryBinsDown;
if (downHigh < width) return;
uint256 downLow = downHigh - width;
if (
upLow != downLow
&& ((settings.rangeLow == upLow && targetLow == downLow)
|| (settings.rangeLow == downLow && targetLow == upLow))
) revert ShiftTargetTwoCycle();
}
/// @notice Owner moves and rebalances may include bins outside the keeper
/// consent range. Every supplied bin must be withdrawn in full, and every
/// held bin inside the recorded range must be supplied.
function validateOwnerFullWithdrawal(
BinKey calldata key,
uint256[] calldata ids,
uint256[] calldata amounts
) external view {
BinSettings memory settings = getBinSettings(key);
if (ids.length == 0 || ids.length != amounts.length) {
revert InvalidRange();
}
for (uint256 i; i < ids.length; ++i) {
if (i != 0 && ids[i] <= ids[i - 1]) revert InvalidRange();
if (amounts[i] != key.lbPair.balanceOf(address(key.sickle), ids[i]))
{
revert IncompleteWithdrawal(ids[i]);
}
}
uint256 next;
for (uint256 id = settings.rangeLow; id <= settings.rangeHigh; ++id) {
while (next < ids.length && ids[next] < id) ++next;
uint256 balance = key.lbPair.balanceOf(address(key.sickle), id);
if (
(next == ids.length || ids[next] != id)
&& isBurnable(key.lbPair, id, balance)
) revert IncompleteWithdrawal(id);
}
}
function _validateFullWithdrawal(
BinKey calldata key,
BinSettings memory settings,
uint256[] calldata ids,
uint256[] calldata amounts
) private view {
if (ids.length != amounts.length) revert InvalidRange();
uint256 next;
for (uint256 id = settings.rangeLow; id <= settings.rangeHigh; ++id) {
uint256 balance = key.lbPair.balanceOf(address(key.sickle), id);
if (next < ids.length && ids[next] == id) {
if (amounts[next] != balance) {
revert IncompleteWithdrawal(id);
}
++next;
} else if (isBurnable(key.lbPair, id, balance)) {
revert IncompleteWithdrawal(id);
}
}
if (next != ids.length) revert IncompleteWithdrawal(ids[next]);
}
/// @dev Run after a successful keeper mint, before returning to Automation.
/// The strategy address is the only writer of keeper-derived ranges.
function updateRangeAfterRebalance(
BinKey calldata key,
uint256[] calldata mintedIds,
uint256[] calldata mintedAmounts,
uint64 shiftTarget
) external {
if (msg.sender != strategy) revert OnlyStrategy();
(uint24 low, uint24 high) = _mintedRange(mintedIds, mintedAmounts);
if (
shiftTarget != 0
&& (low != uint24(shiftTarget >> 24)
|| high != uint24(shiftTarget))
) {
revert ShiftMintMismatch(
uint24(shiftTarget >> 24), uint24(shiftTarget)
);
}
bytes32 hash = keccak256(abi.encode(key));
_materializePrevious(key, hash);
settingsMap[hash].rangeLow = low;
settingsMap[hash].rangeHigh = high;
emit BinRangeUpdated(key, low, high);
}
/// @notice Owner rebalances choose a new relative shape. Keep future
/// keeper actions bound to the position the owner actually minted.
function updateAfterOwnerRebalance(
BinKey calldata key,
uint256[] calldata mintedIds,
uint256[] calldata mintedAmounts,
BinAddLiquidity calldata addLp
) external {
if (msg.sender != strategy) revert OnlyStrategy();
(uint24 low, uint24 high) = _mintedRange(mintedIds, mintedAmounts);
bytes32 hash = keccak256(abi.encode(key));
_materializePrevious(key, hash);
BinSettings storage settings = settingsMap[hash];
settings.rangeLow = low;
settings.rangeHigh = high;
if (settings.autoRebalance) {
settings.rebalanceShapeHash = keccak256(
abi.encode(
addLp.deltaIds, addLp.distributionX, addLp.distributionY
)
);
}
emit BinRangeUpdated(key, low, high);
}
/// @notice Owner minting more shares keeps the consent range aligned with
/// the complete position. Keeper mints are separately limited to the
/// existing range and do not extend owner consent.
function includeAfterOwnerMint(
BinKey calldata key,
uint256[] calldata mintedIds,
uint256[] calldata mintedAmounts
) external {
_requireOwnerStrategy();
(uint24 low, uint24 high) = _mintedRange(mintedIds, mintedAmounts);
bytes32 hash = keccak256(abi.encode(key));
_materializePrevious(key, hash);
BinSettings storage settings = settingsMap[hash];
if (settings.rangeHigh == 0) {
// A full owner withdrawal clears automation consent. A later
// owner increase starts a new, unautomated position that can
// still be moved or rebalanced without manual registry repair.
settings.rangeLow = low;
settings.rangeHigh = high;
emit BinRangeUpdated(key, low, high);
return;
}
uint256 oldWidth = uint256(settings.rangeHigh) - settings.rangeLow;
if (low < settings.rangeLow) settings.rangeLow = low;
if (high > settings.rangeHigh) settings.rangeHigh = high;
if (
settings.autoRebalance
&& (settings.rangeLow < settings.cutoffLow
|| settings.rangeHigh > settings.cutoffHigh
|| (settings.shiftConfig.enabled
&& uint256(settings.rangeHigh) - settings.rangeLow
!= oldWidth))
) {
settings.autoRebalance = false;
settings.shiftConfig.enabled = false;
emit BinSettingsSet(key, settings);
}
emit BinRangeUpdated(key, settings.rangeLow, settings.rangeHigh);
}
function _mintedRange(
uint256[] calldata mintedIds,
uint256[] calldata mintedAmounts
) private pure returns (uint24 low, uint24 high) {
if (mintedIds.length == 0 || mintedIds.length != mintedAmounts.length) {
revert InvalidRange();
}
uint256 lowId = type(uint24).max;
uint256 highId;
for (uint256 i; i < mintedIds.length; ++i) {
if (mintedAmounts[i] == 0) continue;
uint256 id = mintedIds[i];
if (id > type(uint24).max) revert InvalidRange();
if (id < lowId) lowId = id;
if (id > highId) highId = id;
}
if (lowId == type(uint24).max && highId == 0) revert InvalidRange();
return (uint24(lowId), uint24(highId));
}
/// @notice Preserve owner consent after a partial withdrawal, narrowing
/// the range to bins that still hold shares. Clear it only when empty.
function syncAfterOwnerWithdrawal(
BinKey calldata key
) external {
// Existing owner strategies retain their ABI/roles. Other exit
// orchestrators already have full authority over factory Sickles via
// this same live caller policy; only balance-derived cleanup is open
// to them. Installing/expanding consent remains owner/strategy-only.
if (
msg.sender != strategy && msg.sender != bridgeStrategy
&& !factory.registry().isWhitelistedCaller(msg.sender)
) {
revert OnlyStrategy();
}
if (factory.admins(address(key.sickle)) == address(0)) {
revert SickleNotDeployed();
}
bytes32 hash = keccak256(abi.encode(key));
_materializePrevious(key, hash);
BinSettings storage settings = settingsMap[hash];
uint256 low = type(uint24).max;
uint256 high;
for (uint256 id = settings.rangeLow; id <= settings.rangeHigh; ++id) {
if (!isBurnable(
key.lbPair,
id,
key.lbPair.balanceOf(address(key.sickle), id)
)) continue;
if (id < low) low = id;
high = id;
}
if (low == type(uint24).max) {
delete settingsMap[hash];
emit BinSettingsCleared(key);
} else {
uint256 oldWidth = uint256(settings.rangeHigh) - settings.rangeLow;
settings.rangeLow = uint24(low);
settings.rangeHigh = uint24(high);
if (
settings.autoRebalance && settings.shiftConfig.enabled
&& uint256(high) - low != oldWidth
) {
settings.autoRebalance = false;
settings.shiftConfig.enabled = false;
emit BinSettingsSet(key, settings);
}
emit BinRangeUpdated(key, uint24(low), uint24(high));
}
}
function _materializePrevious(
BinKey memory key,
bytes32 hash
) private {
if (overridesPrevious[hash]) return;
if (address(previousRegistry) != address(0)) {
settingsMap[hash] = previousRegistry.getBinSettings(key);
}
overridesPrevious[hash] = true;
}
function _requireOwnerStrategy() private view {
if (msg.sender != strategy && msg.sender != bridgeStrategy) {
revert OnlyStrategy();
}
}
function _validateIds(
BinSettings memory settings,
uint256[] calldata ids
) private pure {
if (ids.length == 0) revert InvalidRange();
for (uint256 i; i < ids.length; ++i) {
if (ids[i] < settings.rangeLow || ids[i] > settings.rangeHigh) {
revert BinOutsideRange(ids[i]);
}
}
}
function _lower(
uint24 rangeLow,
uint24 buffer
) private pure returns (uint256) {
return rangeLow > buffer ? rangeLow - buffer : 0;
}
}
contracts/BinSettingsRegistry.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import { SickleFactory } from "contracts/SickleFactory.sol";
import { Admin } from "contracts/base/Admin.sol";
import { BinKey, BinSettings } from "contracts/structs/BinSettingsStructs.sol";
import { BinAddLiquidity } from "contracts/structs/BinFarmStrategyStructs.sol";
import { RewardBehavior } from "contracts/structs/PositionSettingsStructs.sol";
import { ILBPair } from "contracts/interfaces/external/lfj/ILBPair.sol";
/// @notice Per-pair consent for automated Liquidity Book positions.
/// @dev An owner opts in to a bin range, rather than an NFT token ID. A keeper
/// may only withdraw shares from that range; rebalance updates it atomically.
contract BinSettingsRegistry is Admin {
error SickleNotDeployed();
error InvalidPair();
error InvalidRange();
error InvalidRewardConfig();
error InvalidTrigger();
error AutoDepositNotSet();
error AutoHarvestNotSet();
error AutoCompoundNotSet();
error AutoExitNotSet();
error AutoRebalanceNotSet();
error ActiveIdWithinRange();
error ActiveIdOutsideCutoff();
error ActiveIdOutsideBounds();
error BinOutsideRange(uint256 id);
error IdSlippageTooHigh();
error RebalanceShapeMismatch();
error ShiftRequiresRebalance();
error ShiftTargetMismatch(uint24 expectedLow, uint24 expectedHigh);
error ShiftMintMismatch(uint24 expectedLow, uint24 expectedHigh);
error ShiftTargetUnchanged();
error ShiftTargetTwoCycle();
error ShiftTargetOutsideCutoff();
error IncompleteWithdrawal(uint256 id);
error OnlyStrategy();
event BinSettingsSet(BinKey key, BinSettings settings);
event BinRangeUpdated(BinKey key, uint24 rangeLow, uint24 rangeHigh);
event BinSettingsCleared(BinKey key);
event StrategySet(address strategy);
event BridgeStrategySet(address strategy);
SickleFactory public immutable factory;
address public strategy;
address public bridgeStrategy;
mapping(bytes32 => BinSettings) private settingsMap;
constructor(
SickleFactory factory_,
address admin_
) Admin(admin_) {
factory = factory_;
}
function setStrategy(
address strategy_
) external onlyAdmin {
if (strategy_.code.length == 0) revert OnlyStrategy();
strategy = strategy_;
emit StrategySet(strategy_);
}
function setBridgeStrategy(
address strategy_
) external onlyAdmin {
if (strategy_.code.length == 0) revert OnlyStrategy();
bridgeStrategy = strategy_;
emit BridgeStrategySet(strategy_);
}
function getBinSettings(
BinKey memory key
) public view returns (BinSettings memory) {
return settingsMap[keccak256(abi.encode(key))];
}
/// @notice Whether burning this share balance returns at least one token.
/// LBPair rounds each token output down and rejects a zero/zero burn.
function isBurnable(
ILBPair pair,
uint256 id,
uint256 balance
) public view returns (bool) {
if (balance == 0) return false;
if (id > type(uint24).max) revert InvalidRange();
uint256 supply = pair.totalSupply(id);
if (supply == 0) return false;
(uint128 reserveX, uint128 reserveY) = pair.getBin(uint24(id));
return (reserveX != 0 && balance > (supply - 1) / reserveX)
|| (reserveY != 0 && balance > (supply - 1) / reserveY);
}
/// @notice Read current balances and omit shares that cannot be burned.
function burnableBalances(
address sickle,
ILBPair pair,
uint256[] calldata requestedIds
) external view returns (uint256[] memory ids, uint256[] memory amounts) {
uint256[] memory keptIds = new uint256[](requestedIds.length);
uint256[] memory keptAmounts = new uint256[](requestedIds.length);
uint256 count;
for (uint256 i; i < requestedIds.length; ++i) {
uint256 id = requestedIds[i];
if (i != 0 && id <= requestedIds[i - 1]) revert InvalidRange();
uint256 balance = pair.balanceOf(sickle, id);
if (!isBurnable(pair, id, balance)) continue;
keptIds[count] = id;
keptAmounts[count] = balance;
++count;
}
if (count == 0) revert InvalidRange();
ids = new uint256[](count);
amounts = new uint256[](count);
for (uint256 i; i < count; ++i) {
ids[i] = keptIds[i];
amounts[i] = keptAmounts[i];
}
}
/// @notice The Sickle owner opts the entire configured bin range into
/// keeper operations. Setting all flags false disables automation.
function setBinSettings(
BinKey calldata key,
BinSettings calldata settings
) external {
if (factory.admins(address(key.sickle)) != msg.sender) {
revert SickleNotDeployed();
}
_setBinSettings(key, settings);
}
/// @notice Install owner-supplied automation settings for the bins actually
/// minted by an owner deposit or move. The strategy authenticates the
/// owner.
function setAfterMint(
BinKey calldata key,
BinSettings calldata settings,
uint256[] calldata mintedIds,
uint256[] calldata mintedAmounts
) external {
_requireOwnerStrategy();
(uint24 low, uint24 high) = _mintedRange(mintedIds, mintedAmounts);
BinSettings memory previous = getBinSettings(key);
BinSettings memory actual = settings;
// A second deposit into the same pair/farm adds to the existing
// position. Keep every bin with shares inside the consent range.
actual.rangeLow = previous.rangeHigh == 0 || low < previous.rangeLow
? low
: previous.rangeLow;
actual.rangeHigh = high > previous.rangeHigh ? high : previous.rangeHigh;
if (
previous.rangeHigh != 0 && actual.autoRebalance
&& (actual.rangeLow < actual.cutoffLow
|| actual.rangeHigh > actual.cutoffHigh
|| (actual.shiftConfig.enabled
&& uint256(actual.rangeHigh) - actual.rangeLow
!= uint256(previous.rangeHigh) - previous.rangeLow))
) {
actual.autoRebalance = false;
actual.shiftConfig.enabled = false;
}
_setBinSettings(key, actual);
}
function _setBinSettings(
BinKey memory key,
BinSettings memory settings
) private {
if (address(key.lbPair) == address(0)) revert InvalidPair();
if (settings.rangeLow > settings.rangeHigh) revert InvalidRange();
if (
!settings.automateRewards
&& settings.rewardConfig.rewardBehavior != RewardBehavior.None
) revert InvalidRewardConfig();
if (
settings.automateRewards
&& (key.stakingContract == address(0)
|| settings.rewardConfig.rewardBehavior
== RewardBehavior.None)
) revert InvalidRewardConfig();
if (
settings.rewardConfig.rewardBehavior != RewardBehavior.Harvest
&& settings.rewardConfig.harvestTokenOut != address(0)
) revert InvalidRewardConfig();
if (
settings.autoRebalance
&& (settings.cutoffLow > settings.cutoffHigh
|| settings.rangeLow < settings.cutoffLow
|| settings.rangeHigh > settings.cutoffHigh
|| int256(uint256(settings.rangeLow))
- settings.rebalanceBufferBelow
> int256(uint256(settings.rangeHigh))
+ settings.rebalanceBufferAbove)
) revert InvalidTrigger();
if (settings.autoRebalance && settings.rebalanceShapeHash == bytes32(0))
{
revert RebalanceShapeMismatch();
}
if (settings.shiftConfig.enabled && !settings.autoRebalance) {
revert ShiftRequiresRebalance();
}
settingsMap[keccak256(abi.encode(key))] = settings;
emit BinSettingsSet(key, settings);
}
function validateDepositFor(
BinKey calldata key
) external view {
if (!getBinSettings(key).autoDeposit) revert AutoDepositNotSet();
}
function validateMinted(
BinKey calldata key,
uint256[] calldata ids
) external view {
_validateIds(getBinSettings(key), ids);
}
function validateHarvestFor(
BinKey calldata key
) external view {
BinSettings memory settings = getBinSettings(key);
if (
!settings.automateRewards
|| settings.rewardConfig.rewardBehavior
!= RewardBehavior.Harvest
) revert AutoHarvestNotSet();
}
function validateCompoundFor(
BinKey calldata key
) external view {
BinSettings memory settings = getBinSettings(key);
if (
!settings.automateRewards
|| settings.rewardConfig.rewardBehavior
!= RewardBehavior.Compound
) revert AutoCompoundNotSet();
}
function validateExitFor(
BinKey calldata key,
uint256[] calldata ids,
uint256[] calldata amounts
) external view {
BinSettings memory settings = getBinSettings(key);
if (!settings.autoExit) revert AutoExitNotSet();
_validateIds(settings, ids);
_validateFullWithdrawal(key, settings, ids, amounts);
uint256 activeId = key.lbPair.getActiveId();
if (
activeId >= _lower(settings.rangeLow, settings.exitBufferBelow)
&& activeId
<= uint256(settings.rangeHigh) + settings.exitBufferAbove
) revert ActiveIdWithinRange();
}
function validateRebalanceFor(
BinKey calldata key,
uint256[] calldata ids,
uint256[] calldata amounts,
BinAddLiquidity calldata addLp,
uint24 minActiveId,
uint24 maxActiveId
) external view returns (uint64 shiftTarget) {
BinSettings memory settings = getBinSettings(key);
if (!settings.autoRebalance) revert AutoRebalanceNotSet();
_validateIds(settings, ids);
if (addLp.idSlippage > settings.maxIdSlippage) {
revert IdSlippageTooHigh();
}
if (
keccak256(
abi.encode(
addLp.deltaIds, addLp.distributionX, addLp.distributionY
)
) != settings.rebalanceShapeHash
) {
revert RebalanceShapeMismatch();
}
uint256 activeId = key.lbPair.getActiveId();
bool below = _validateRebalanceTrigger(
settings, activeId, minActiveId, maxActiveId
);
_validateFullWithdrawal(key, settings, ids, amounts);
if (!settings.shiftConfig.enabled) return 0;
return _validateShiftTarget(settings, addLp, activeId, below);
}
function _validateRebalanceTrigger(
BinSettings memory settings,
uint256 activeId,
uint24 minActiveId,
uint24 maxActiveId
) private pure returns (bool below) {
if (
(minActiveId != 0 || maxActiveId != 0)
&& (activeId < minActiveId || activeId > maxActiveId)
) revert ActiveIdOutsideBounds();
int256 lowerTrigger =
int256(uint256(settings.rangeLow)) - settings.rebalanceBufferBelow;
int256 upperTrigger =
int256(uint256(settings.rangeHigh)) + settings.rebalanceBufferAbove;
below = int256(activeId) < lowerTrigger;
bool above = int256(activeId) > upperTrigger;
if (!below && !above) revert ActiveIdWithinRange();
if (activeId < settings.cutoffLow || activeId > settings.cutoffHigh) {
revert ActiveIdOutsideCutoff();
}
}
function _validateShiftTarget(
BinSettings memory settings,
BinAddLiquidity calldata addLp,
uint256 activeId,
bool below
) private pure returns (uint64) {
uint256 width = uint256(settings.rangeHigh) - settings.rangeLow;
uint256 low;
uint256 high;
if (below) {
high = activeId + settings.shiftConfig.entryBinsDown;
if (high < width) revert InvalidRange();
low = high - width;
} else {
if (activeId < settings.shiftConfig.entryBinsUp) {
revert InvalidRange();
}
low = activeId - settings.shiftConfig.entryBinsUp;
high = low + width;
}
if (high > type(uint24).max) revert InvalidRange();
if (low == settings.rangeLow) revert ShiftTargetUnchanged();
_validateNoTwoCycle(settings, activeId, low);
if (low < settings.cutoffLow || high > settings.cutoffHigh) {
revert ShiftTargetOutsideCutoff();
}
if (
addLp.deltaIds.length == 0
|| int256(addLp.activeIdDesired) + addLp.deltaIds[0]
!= int256(low)
|| int256(addLp.activeIdDesired)
+ addLp.deltaIds[addLp.deltaIds.length - 1]
!= int256(high)
) revert ShiftTargetMismatch(uint24(low), uint24(high));
return (uint64(1) << 48) | (uint64(low) << 24) | uint64(high);
}
function _validateNoTwoCycle(
BinSettings memory settings,
uint256 activeId,
uint256 targetLow
) private pure {
uint256 width = uint256(settings.rangeHigh) - settings.rangeLow;
if (activeId < settings.shiftConfig.entryBinsUp) return;
uint256 upLow = activeId - settings.shiftConfig.entryBinsUp;
uint256 downHigh = activeId + settings.shiftConfig.entryBinsDown;
if (downHigh < width) return;
uint256 downLow = downHigh - width;
if (
upLow != downLow
&& ((settings.rangeLow == upLow && targetLow == downLow)
|| (settings.rangeLow == downLow && targetLow == upLow))
) revert ShiftTargetTwoCycle();
}
/// @notice Owner moves and rebalances may include bins outside the keeper
/// consent range. Every supplied bin must be withdrawn in full, and every
/// held bin inside the recorded range must be supplied.
function validateOwnerFullWithdrawal(
BinKey calldata key,
uint256[] calldata ids,
uint256[] calldata amounts
) external view {
BinSettings memory settings = getBinSettings(key);
if (ids.length == 0 || ids.length != amounts.length) {
revert InvalidRange();
}
for (uint256 i; i < ids.length; ++i) {
if (i != 0 && ids[i] <= ids[i - 1]) revert InvalidRange();
if (amounts[i] != key.lbPair.balanceOf(address(key.sickle), ids[i]))
{
revert IncompleteWithdrawal(ids[i]);
}
}
uint256 next;
for (uint256 id = settings.rangeLow; id <= settings.rangeHigh; ++id) {
while (next < ids.length && ids[next] < id) ++next;
uint256 balance = key.lbPair.balanceOf(address(key.sickle), id);
if (
(next == ids.length || ids[next] != id)
&& isBurnable(key.lbPair, id, balance)
) revert IncompleteWithdrawal(id);
}
}
function _validateFullWithdrawal(
BinKey calldata key,
BinSettings memory settings,
uint256[] calldata ids,
uint256[] calldata amounts
) private view {
if (ids.length != amounts.length) revert InvalidRange();
uint256 next;
for (uint256 id = settings.rangeLow; id <= settings.rangeHigh; ++id) {
uint256 balance = key.lbPair.balanceOf(address(key.sickle), id);
if (next < ids.length && ids[next] == id) {
if (amounts[next] != balance) {
revert IncompleteWithdrawal(id);
}
++next;
} else if (isBurnable(key.lbPair, id, balance)) {
revert IncompleteWithdrawal(id);
}
}
if (next != ids.length) revert IncompleteWithdrawal(ids[next]);
}
/// @dev Run after a successful keeper mint, before returning to Automation.
/// The strategy address is the only writer of keeper-derived ranges.
function updateRangeAfterRebalance(
BinKey calldata key,
uint256[] calldata mintedIds,
uint256[] calldata mintedAmounts,
uint64 shiftTarget
) external {
if (msg.sender != strategy) revert OnlyStrategy();
(uint24 low, uint24 high) = _mintedRange(mintedIds, mintedAmounts);
if (
shiftTarget != 0
&& (low != uint24(shiftTarget >> 24)
|| high != uint24(shiftTarget))
) {
revert ShiftMintMismatch(
uint24(shiftTarget >> 24), uint24(shiftTarget)
);
}
bytes32 hash = keccak256(abi.encode(key));
settingsMap[hash].rangeLow = low;
settingsMap[hash].rangeHigh = high;
emit BinRangeUpdated(key, low, high);
}
/// @notice Owner rebalances choose a new relative shape. Keep future
/// keeper actions bound to the position the owner actually minted.
function updateAfterOwnerRebalance(
BinKey calldata key,
uint256[] calldata mintedIds,
uint256[] calldata mintedAmounts,
BinAddLiquidity calldata addLp
) external {
if (msg.sender != strategy) revert OnlyStrategy();
(uint24 low, uint24 high) = _mintedRange(mintedIds, mintedAmounts);
bytes32 hash = keccak256(abi.encode(key));
BinSettings storage settings = settingsMap[hash];
settings.rangeLow = low;
settings.rangeHigh = high;
if (settings.autoRebalance) {
settings.rebalanceShapeHash = keccak256(
abi.encode(
addLp.deltaIds, addLp.distributionX, addLp.distributionY
)
);
}
emit BinRangeUpdated(key, low, high);
}
/// @notice Owner minting more shares keeps the consent range aligned with
/// the complete position. Keeper mints are separately limited to the
/// existing range and do not extend owner consent.
function includeAfterOwnerMint(
BinKey calldata key,
uint256[] calldata mintedIds,
uint256[] calldata mintedAmounts
) external {
_requireOwnerStrategy();
(uint24 low, uint24 high) = _mintedRange(mintedIds, mintedAmounts);
BinSettings storage settings = settingsMap[keccak256(abi.encode(key))];
if (settings.rangeHigh == 0) {
// A full owner withdrawal clears automation consent. A later
// owner increase starts a new, unautomated position that can
// still be moved or rebalanced without manual registry repair.
settings.rangeLow = low;
settings.rangeHigh = high;
emit BinRangeUpdated(key, low, high);
return;
}
uint256 oldWidth = uint256(settings.rangeHigh) - settings.rangeLow;
if (low < settings.rangeLow) settings.rangeLow = low;
if (high > settings.rangeHigh) settings.rangeHigh = high;
if (
settings.autoRebalance
&& (settings.rangeLow < settings.cutoffLow
|| settings.rangeHigh > settings.cutoffHigh
|| (settings.shiftConfig.enabled
&& uint256(settings.rangeHigh) - settings.rangeLow
!= oldWidth))
) {
settings.autoRebalance = false;
settings.shiftConfig.enabled = false;
emit BinSettingsSet(key, settings);
}
emit BinRangeUpdated(key, settings.rangeLow, settings.rangeHigh);
}
function _mintedRange(
uint256[] calldata mintedIds,
uint256[] calldata mintedAmounts
) private pure returns (uint24 low, uint24 high) {
if (mintedIds.length == 0 || mintedIds.length != mintedAmounts.length) {
revert InvalidRange();
}
uint256 lowId = type(uint24).max;
uint256 highId;
for (uint256 i; i < mintedIds.length; ++i) {
if (mintedAmounts[i] == 0) continue;
uint256 id = mintedIds[i];
if (id > type(uint24).max) revert InvalidRange();
if (id < lowId) lowId = id;
if (id > highId) highId = id;
}
if (lowId == type(uint24).max && highId == 0) revert InvalidRange();
return (uint24(lowId), uint24(highId));
}
/// @notice Preserve owner consent after a partial withdrawal, narrowing
/// the range to bins that still hold shares. Clear it only when empty.
function syncAfterOwnerWithdrawal(
BinKey calldata key
) external {
_requireOwnerStrategy();
bytes32 hash = keccak256(abi.encode(key));
BinSettings storage settings = settingsMap[hash];
uint256 low = type(uint24).max;
uint256 high;
for (uint256 id = settings.rangeLow; id <= settings.rangeHigh; ++id) {
if (!isBurnable(
key.lbPair,
id,
key.lbPair.balanceOf(address(key.sickle), id)
)) continue;
if (id < low) low = id;
high = id;
}
if (low == type(uint24).max) {
delete settingsMap[hash];
emit BinSettingsCleared(key);
} else {
uint256 oldWidth = uint256(settings.rangeHigh) - settings.rangeLow;
settings.rangeLow = uint24(low);
settings.rangeHigh = uint24(high);
if (
settings.autoRebalance && settings.shiftConfig.enabled
&& uint256(high) - low != oldWidth
) {
settings.autoRebalance = false;
settings.shiftConfig.enabled = false;
emit BinSettingsSet(key, settings);
}
emit BinRangeUpdated(key, uint24(low), uint24(high));
}
}
function _requireOwnerStrategy() private view {
if (msg.sender != strategy && msg.sender != bridgeStrategy) {
revert OnlyStrategy();
}
}
function _validateIds(
BinSettings memory settings,
uint256[] calldata ids
) private pure {
if (ids.length == 0) revert InvalidRange();
for (uint256 i; i < ids.length; ++i) {
if (ids[i] < settings.rangeLow || ids[i] > settings.rangeHigh) {
revert BinOutsideRange(ids[i]);
}
}
}
function _lower(
uint24 rangeLow,
uint24 buffer
) private pure returns (uint256) {
return rangeLow > buffer ? rangeLow - buffer : 0;
}
}
contracts/Sickle.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import { SickleStorage } from "contracts/base/SickleStorage.sol";
import { Multicall } from "contracts/base/Multicall.sol";
import { SickleRegistry } from "contracts/SickleRegistry.sol";
/// @title Sickle contract
/// @author vfat.tools
/// @notice Sickle facilitates farming and interactions with Masterchef
/// contracts
/// @dev Base contract inheriting from all the other "manager" contracts
contract Sickle is SickleStorage, Multicall {
/// @notice Function to receive ETH
receive() external payable { }
/// @param sickleRegistry_ Address of the SickleRegistry contract
constructor(
SickleRegistry sickleRegistry_
) Multicall(sickleRegistry_) {
_disableInitializers();
}
/// @param sickleOwner_ Address of the Sickle owner
function initialize(
address sickleOwner_,
address approved_
) external initializer {
SickleStorage._initializeSickleStorage(sickleOwner_, approved_);
}
/// INTERNALS ///
function onERC721Received(
address, // operator
address, // from
uint256, // tokenId
bytes calldata // data
) external pure returns (bytes4) {
return this.onERC721Received.selector;
}
function onERC1155Received(
address, // operator
address, // from
uint256, // id
uint256, // value
bytes calldata // data
) external pure returns (bytes4) {
return this.onERC1155Received.selector;
}
function onERC1155BatchReceived(
address, // operator
address, // from
uint256[] calldata, // ids
uint256[] calldata, // values
bytes calldata // data
) external pure returns (bytes4) {
return this.onERC1155BatchReceived.selector;
}
}
contracts/SickleFactory.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import { Clones } from "@openzeppelin/contracts/proxy/Clones.sol";
import { Sickle } from "contracts/Sickle.sol";
import { SickleRegistry } from "contracts/SickleRegistry.sol";
import { Admin } from "contracts/base/Admin.sol";
/// @title SickleFactory contract
/// @author vfat.tools
/// @notice Factory deploying new Sickle contracts
contract SickleFactory is Admin {
/// 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 contract
event Deploy(address indexed admin, address sickle);
/// @notice Thrown when the caller is not whitelisted
/// @param caller Address of the non-whitelisted caller
error CallerNotWhitelisted(address caller); // 0x252c8273
/// @notice Thrown when the factory is not active and a deploy is attempted
error NotActive(); // 0x80cb55e2
/// @notice Thrown when a Sickle contract is already deployed for a user
error SickleAlreadyDeployed(); //0xf6782ef1
/// STORAGE ///
mapping(address => address) private _sickles;
mapping(address => address) private _admins;
mapping(address => bytes32) public _referralCodes;
/// @notice Address of the SickleRegistry contract
SickleRegistry public immutable registry;
/// @notice Address of the Sickle implementation contract
address public immutable implementation;
/// @notice Address of the previous SickleFactory contract (if applicable)
SickleFactory public immutable previousFactory;
/// @notice Whether the factory is active (can deploy new Sickle contracts)
bool public 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 applicable
constructor(
address admin_,
address sickleRegistry_,
address sickleImplementation_,
address previousFactory_
) Admin(admin_) {
registry = SickleRegistry(sickleRegistry_);
implementation = sickleImplementation_;
previousFactory = SickleFactory(previousFactory_);
}
function setActive(
bool active
) external onlyAdmin {
isActive = active;
}
function _deploy(
address admin,
address approved,
bytes32 referralCode
) internal returns (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
) internal returns (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 contract
function predict(
address admin
) external view returns (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 contract
function sickles(
address admin
) external view returns (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 contract
function admins(
address sickle
) external view returns (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 user
function referralCodes(
address sickle
) external view returns (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 approved Address approved to manage automation
/// @param referralCode Referral code for the user
/// @return sickle Address of the deployed Sickle contract
function getOrDeploy(
address admin,
address approved,
bytes32 referralCode
) external returns (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 approved Address approved to manage automation
/// @param referralCode Referral code for the user
/// @return sickle Address of the deployed Sickle contract
function deploy(
address approved,
bytes32 referralCode
) external returns (address sickle) {
if (!isActive) {
revert NotActive();
}
if (_getSickle(msg.sender) != address(0)) {
revert SickleAlreadyDeployed();
}
return _deploy(msg.sender, approved, referralCode);
}
}
contracts/SickleRegistry.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import { Admin } from "contracts/base/Admin.sol";
library SickleRegistryEvents {
event CollectorChanged(address newCollector);
event FeesUpdated(bytes32[] feeHashes, uint256[] feesInBP);
event ReferralCodeCreated(bytes32 indexed code, address indexed referrer);
// Multicall caller and target whitelist status changes
event CallerStatusChanged(address caller, bool isWhitelisted);
event TargetStatusChanged(address target, bool isWhitelisted);
}
/// @title SickleRegistry contract
/// @author vfat.tools
/// @notice Manages the whitelisted contracts and the collector address
contract SickleRegistry is Admin {
/// CONSTANTS ///
uint256 constant MAX_FEE = 500; // 5%
/// ERRORS ///
error ArrayLengthMismatch(); // 0xa24a13a6
error FeeAboveMaxLimit(); // 0xd6cf7b5e
error InvalidReferralCode(); // 0xe55b4629
/// STORAGE ///
/// @notice Address of the fee collector
address public collector;
/// @notice Tracks the contracts that can be called through Sickle multicall
/// @return True if the contract is a whitelisted target
mapping(address => bool) public isWhitelistedTarget;
/// @notice Tracks the contracts that can call Sickle multicall
/// @return True if the contract is a whitelisted caller
mapping(address => bool) public isWhitelistedCaller;
/// @notice Keeps track of the referrers and their associated code
mapping(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 amount
mapping(bytes32 => uint256) public feeRegistry;
/// WRITE FUNCTIONS ///
/// @param admin_ Address of the admin
/// @param collector_ Address of the collector
constructor(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.
function setWhitelistedTargets(
address[] calldata targets,
bool isApproved
) external onlyAdmin {
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.
function updateCollector(
address newCollector
) external onlyAdmin {
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.
function setWhitelistedCallers(
address[] calldata callers,
bool isApproved
) external onlyAdmin {
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 caller
function setReferralCode(
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.
function setFees(
bytes32[] calldata feeHashes,
uint256[] calldata feesArray
) external onlyAdmin {
if (feeHashes.length != feesArray.length) {
revert ArrayLengthMismatch();
}
for (uint256 i = 0; i < feeHashes.length;) {
if (feesArray[i] <= MAX_FEE) {
feeRegistry[feeHashes[i]] = feesArray[i];
} else {
revert FeeAboveMaxLimit();
}
unchecked {
++i;
}
}
emit SickleRegistryEvents.FeesUpdated(feeHashes, feesArray);
}
}
contracts/base/Admin.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
/// @title Admin contract
/// @author vfat.tools
/// @notice Provides an administration mechanism allowing restricted functions
abstract contract Admin {
/// ERRORS ///
/// @notice Thrown when the caller is not the admin
error NotAdminError(); //0xb5c42b3b
/// EVENTS ///
/// @notice Emitted when a new admin is set
/// @param oldAdmin Address of the old admin
/// @param newAdmin Address of the new admin
event AdminSet(address oldAdmin, address newAdmin);
/// STORAGE ///
/// @notice Address of the current admin
address public admin;
/// MODIFIERS ///
/// @dev Restricts a function to the admin
modifier onlyAdmin() {
if (msg.sender != admin) revert NotAdminError();
_;
}
/// WRITE FUNCTIONS ///
/// @param admin_ Address of the admin
constructor(
address admin_
) {
emit AdminSet(address(0), admin_);
admin = admin_;
}
/// @notice Sets a new admin
/// @param newAdmin Address of the new admin
/// @custom:access Restricted to protocol admin.
function setAdmin(
address newAdmin
) external onlyAdmin {
emit AdminSet(admin, newAdmin);
admin = newAdmin;
}
}
contracts/base/Multicall.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import { SickleRegistry } from "contracts/SickleRegistry.sol";
/// @title Multicall contract
/// @author vfat.tools
/// @notice Enables calling multiple methods in a single call to the contract
abstract contract Multicall {
/// ERRORS ///
error MulticallParamsMismatchError(); // 0xc1e637c9
/// @notice Thrown when the target contract is not whitelisted
/// @param target Address of the non-whitelisted target
error TargetNotWhitelisted(address target); // 0x47ccabe7
/// @notice Thrown when the caller is not whitelisted
/// @param caller Address of the non-whitelisted caller
error CallerNotWhitelisted(address caller); // 0x252c8273
/// STORAGE ///
/// @notice Address of the SickleRegistry contract
/// @dev Needs to be immutable so that it's accessible for Sickle proxies
SickleRegistry public immutable registry;
/// INITIALIZATION ///
/// @param registry_ Address of the SickleRegistry contract
constructor(
SickleRegistry registry_
) {
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 calls
function multicall(
address[] calldata targets,
bytes[] calldata data
) external payable {
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, bytes memory result) =
targets[i].delegatecall(data[i]);
if (!success) {
if (result.length == 0) revert();
assembly {
revert(add(32, result), mload(result))
}
}
unchecked {
++i;
}
}
}
}
contracts/base/SickleStorage.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import { Initializable } from
"@openzeppelin/contracts/proxy/utils/Initializable.sol";
library SickleStorageEvents {
event ApprovedAddressChanged(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`
abstract contract SickleStorage is Initializable {
/// ERRORS ///
/// @notice Thrown when the caller is not the owner of the Sickle contract
error NotOwnerError(); // 0x74a21527
/// @notice Thrown when the caller is not a strategy contract or the
/// Flashloan Stub
error NotStrategyError(); // 0x4581ba62
/// STORAGE ///
/// @notice Address of the owner
address public owner;
/// @notice An address that can be set by the owner of the Sickle contract
/// in order to trigger specific functions.
address public approved;
/// MODIFIERS ///
/// @dev Restricts a function call to the owner of the Sickle contract
modifier onlyOwner() {
if (msg.sender != owner) revert NotOwnerError();
_;
}
/// INITIALIZATION ///
/// @param owner_ Address of the owner of this Sickle contract
function _initializeSickleStorage(
address owner_,
address approved_
) internal onlyInitializing {
owner = owner_;
approved = approved_;
}
/// WRITE FUNCTIONS ///
/// @notice Sets the approved address of this Sickle
/// @param newApproved Address meant to be approved by the owner
function setApproved(
address newApproved
) external onlyOwner {
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 contract
function isOwnerOrApproved(
address caller
) public view returns (bool) {
return caller == owner || caller == approved;
}
}
contracts/interfaces/external/lfj/ILBPair.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface ILBPair {
struct MintArrays {
uint256[] ids;
bytes32[] amounts;
uint256[] liquidityMinted;
}
function getTokenX() external view returns (IERC20);
function getTokenY() external view returns (IERC20);
function getFactory() external view returns (address);
function getBinStep() external pure returns (uint16);
function getActiveId() external view returns (uint24);
function getReserves()
external
view
returns (uint128 reserveX, uint128 reserveY);
function getBin(
uint24 id
) external view returns (uint128 binReserveX, uint128 binReserveY);
function getNextNonEmptyBin(
bool swapForY,
uint24 id
) external view returns (uint24);
function getOracleParameters()
external
view
returns (
uint8 sampleLifetime,
uint16 size,
uint16 activeSize,
uint40 lastUpdated,
uint40 firstTimestamp
);
function getOracleSampleAt(
uint40 lookupTimestamp
)
external
view
returns (
uint64 cumulativeId,
uint64 cumulativeVolatility,
uint64 cumulativeBinCrossed
);
function getPriceFromId(
uint24 id
) external pure returns (uint256);
function getIdFromPrice(
uint256 price
) external pure returns (uint24);
function getSwapIn(
uint128 amountOut,
bool swapForY
)
external
view
returns (uint128 amountIn, uint128 amountOutLeft, uint128 fee);
function getSwapOut(
uint128 amountIn,
bool swapForY
)
external
view
returns (uint128 amountInLeft, uint128 amountOut, uint128 fee);
function swap(
bool swapForY,
address to
) external returns (bytes32 amountsOut);
function flashLoan(
address receiver,
bytes32 amounts,
bytes calldata data
) external;
function mint(
address to,
bytes32[] calldata liquidityConfigs,
address refundTo
)
external
returns (
bytes32 amountsReceived,
bytes32 amountsLeft,
uint256[] memory liquidityMinted
);
function burn(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amountsToBurn
) external returns (bytes32[] memory amounts);
function collectProtocolFees()
external
returns (bytes32 collectedProtocolFees);
function balanceOf(
address account,
uint256 id
) external view returns (uint256);
function balanceOfBatch(
address[] calldata accounts,
uint256[] calldata ids
) external view returns (uint256[] memory);
function isApprovedForAll(
address owner,
address spender
) external view returns (bool);
function approveForAll(
address spender,
bool approved
) external;
function batchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts
) external;
function totalSupply(
uint256 id
) external view returns (uint256);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
}
contracts/structs/BinFarmStrategyStructs.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import { ILBPair } from "contracts/interfaces/external/lfj/ILBPair.sol";
import { SwapParams } from "contracts/structs/SwapStructs.sol";
import { Farm } from "contracts/structs/FarmStrategyStructs.sol";
/// @notice Represents a Liquidity Book position across multiple bins
struct BinPosition {
Farm farm;
ILBPair lbPair;
}
/// @notice Parameters for adding liquidity to a Liquidity Book pair
struct BinAddLiquidity {
ILBPair lbPair;
address tokenX;
address tokenY;
uint256 amountX;
uint256 amountY;
uint256 amountXMin;
uint256 amountYMin;
uint256 activeIdDesired;
uint256 idSlippage;
int256[] deltaIds;
uint256[] distributionX;
uint256[] distributionY;
}
/// @notice Parameters for removing liquidity from a Liquidity Book pair
struct BinRemoveLiquidity {
ILBPair lbPair;
address tokenX;
address tokenY;
uint256[] ids;
uint256[] amounts;
uint256 amountXMin;
uint256 amountYMin;
}
/// @notice Zap in parameters for bin-based liquidity
struct BinZapIn {
SwapParams[] swaps;
BinAddLiquidity addLiquidityParams;
}
/// @notice Zap out parameters for bin-based liquidity
struct BinZapOut {
BinRemoveLiquidity removeLiquidityParams;
SwapParams[] swaps;
}
/// @notice Parameters for increasing a bin position
struct BinIncrease {
address[] tokensIn;
uint256[] amountsIn;
BinZapIn zap;
bytes extraData;
}
/// @notice Parameters for depositing into a bin farm strategy
struct BinDeposit {
Farm farm;
ILBPair lbPair;
BinIncrease increase;
}
/// @notice Parameters for withdrawing from a bin farm strategy
struct BinWithdraw {
BinZapOut zap;
address[] tokensOut;
bytes extraData;
}
/// @notice Simple harvest parameters without swaps
struct SimpleBinHarvest {
address[] rewardTokens;
bytes extraData;
}
/// @notice Parameters for harvesting rewards from a bin farm
struct BinHarvest {
SimpleBinHarvest harvest;
SwapParams[] swaps;
address[] outputTokens;
address[] sweepTokens;
}
/// @notice Parameters for compounding a bin farm position
struct BinCompound {
SimpleBinHarvest harvest;
BinZapIn zap;
bytes depositExtraData;
}
/// @notice Parameters for rebalancing a bin position
struct BinRebalance {
BinPosition position;
uint256[] currentIds; // Current bin IDs to withdraw from
uint256[] currentAmounts; // Current amounts to withdraw
BinHarvest harvest;
BinWithdraw withdraw;
BinIncrease increase;
}
/// @notice Parameters for moving a bin position to a different farm
struct BinMove {
BinPosition position;
uint256[] currentIds;
uint256[] currentAmounts;
BinHarvest harvest;
BinWithdraw withdraw;
BinDeposit deposit;
}
contracts/structs/BinSettingsStructs.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import { Sickle } from "contracts/Sickle.sol";
import { ILBPair } from "contracts/interfaces/external/lfj/ILBPair.sol";
import { RewardConfig } from "contracts/structs/PositionSettingsStructs.sol";
/// @notice Automation consent applies to one pair and farm inside a Sickle.
/// The configured bin range is the set of shares the keeper may withdraw.
struct BinKey {
Sickle sickle;
ILBPair lbPair;
address stakingContract;
uint256 poolIndex;
}
/// @notice Exact geometry for an owner-approved keeper shift. The entry
/// offsets count bins between the active bin and the nearest target edge.
struct BinShiftConfig {
bool enabled;
uint24 entryBinsUp;
uint24 entryBinsDown;
}
struct BinSettings {
bool autoDeposit;
bool automateRewards;
RewardConfig rewardConfig;
bool autoExit;
bool autoRebalance;
uint24 rangeLow;
uint24 rangeHigh;
uint24 exitBufferBelow;
uint24 exitBufferAbove;
int24 rebalanceBufferBelow;
int24 rebalanceBufferAbove;
uint24 cutoffLow;
uint24 cutoffHigh;
uint256 maxIdSlippage;
bytes32 rebalanceShapeHash;
BinShiftConfig shiftConfig;
}
contracts/structs/FarmStrategyStructs.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import { ZapIn, ZapOut } from "contracts/structs/ZapStructs.sol";
import { SwapParams } from "contracts/structs/SwapStructs.sol";
struct Farm {
address stakingContract;
uint256 poolIndex;
}
struct DepositParams {
Farm farm;
address[] tokensIn;
uint256[] amountsIn;
ZapIn zap;
bytes extraData;
}
struct WithdrawParams {
bytes extraData;
ZapOut zap;
address[] tokensOut;
}
struct HarvestParams {
SwapParams[] swaps;
bytes extraData;
address[] tokensOut;
}
struct CompoundParams {
Farm claimFarm;
bytes claimExtraData;
address[] rewardTokens;
ZapIn zap;
Farm depositFarm;
bytes depositExtraData;
}
struct SimpleDepositParams {
Farm farm;
address lpToken;
uint256 amountIn;
bytes extraData;
}
struct SimpleHarvestParams {
address[] rewardTokens;
bytes extraData;
}
struct SimpleWithdrawParams {
address lpToken;
uint256 amountOut;
bytes extraData;
}
contracts/structs/LiquidityStructs.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
struct AddLiquidityParams {
address router;
address lpToken;
address[] tokens;
uint256[] desiredAmounts;
uint256[] minAmounts;
bytes extraData;
}
struct RemoveLiquidityParams {
address router;
address lpToken;
address[] tokens;
uint256 lpAmountIn;
uint256[] minAmountsOut;
bytes extraData;
}
contracts/structs/PositionSettingsStructs.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import { Sickle } from "contracts/Sickle.sol";
struct PositionKey {
Sickle sickle;
address stakingContract;
uint256 poolIndex;
}
enum RewardBehavior {
None,
Harvest,
Compound
}
struct RewardConfig {
RewardBehavior rewardBehavior;
address harvestTokenOut;
}
struct ExitConfig {
uint256 baseTokenIndex;
uint256 quoteTokenIndex;
uint256 triggerPriceLow;
address exitTokenOutLow;
uint256 triggerPriceHigh;
address exitTokenOutHigh;
uint256[] triggerReservesLow;
address[] triggerReservesTokensOut;
uint256 priceImpactBP;
uint256 slippageBP;
}
/**
* Settings for automating an ERC20 position
* @param pool: Uniswap or Aerodrome vAMM/sAMM pair for the position (requires
* ILiquidityConnector connector registered)
* @param router: Router for the pair (requires connector registration)
* @param automateRewards: Whether to automatically harvest or compound rewards
* for this position, regardless of rebalance settings.
* @param rewardConfig: Configuration for reward automation
* Harvest as-is, harvest and convert to a different token, or compound into the
* position.
* @param autoExit: Whether to automatically exit the position when it goes out
* of
* range
* @param exitConfig: Configuration for the above
*/
struct PositionSettings {
address pool;
address router;
bool automateRewards;
RewardConfig rewardConfig;
bool autoExit;
ExitConfig exitConfig;
bytes extraData;
}
contracts/structs/SwapStructs.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
struct SwapParams {
address tokenApproval;
address router;
uint256 amountIn;
uint256 desiredAmountOut;
uint256 minAmountOut;
address tokenIn;
address tokenOut;
bytes extraData;
}
contracts/structs/ZapStructs.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { SwapParams } from "contracts/structs/SwapStructs.sol";
import {
AddLiquidityParams,
RemoveLiquidityParams
} from "contracts/structs/LiquidityStructs.sol";
struct ZapIn {
SwapParams[] swaps;
AddLiquidityParams addLiquidityParams;
}
struct ZapOut {
RemoveLiquidityParams removeLiquidityParams;
SwapParams[] swaps;
}
lib/openzeppelin-contracts/contracts/proxy/Clones.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (proxy/Clones.sol)
pragma solidity ^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._
*/
library Clones {
/**
* @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.
*/
function clone(address implementation) internal returns (address instance) {
/// @solidity memory-safe-assembly
assembly {
// 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.
*/
function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {
/// @solidity memory-safe-assembly
assembly {
// 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}.
*/
function predictDeterministicAddress(
address implementation,
bytes32 salt,
address deployer
) internal pure returns (address predicted) {
/// @solidity memory-safe-assembly
assembly {
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}.
*/
function predictDeterministicAddress(address implementation, bytes32 salt)
internal
view
returns (address predicted)
{
return predictDeterministicAddress(implementation, salt, address(this));
}
}
lib/openzeppelin-contracts/contracts/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.1) (proxy/utils/Initializable.sol)
pragma solidity ^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();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
* @custom:oz-retyped-from bool
*/
uint8 private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(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.
*/
modifier initializer() {
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.
*/
modifier reinitializer(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.
*/
modifier onlyInitializing() {
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() internal virtual {
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() internal view returns (uint8) {
return _initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _initializing;
}
}
lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed 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.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (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.
*/
function transfer(address to, uint256 amount) external returns (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.
*/
function allowance(address owner, address spender) external view returns (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.
*/
function approve(address spender, uint256 amount) external returns (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.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
}
lib/openzeppelin-contracts/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @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.
* ====
*/
function isContract(address account) internal view returns (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].
*/
function sendValue(address payable 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._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
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._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
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._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
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._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory 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._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
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._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory 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._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
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._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory 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._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
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 contract
require(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._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "paris",
"remappings": [
"solmate/=lib/solmate/src/",
"@openzeppelin/=lib/openzeppelin-contracts/",
"@morpho-blue/=lib/morpho-blue/src/",
"ds-test/=lib/solmate/lib/ds-test/src/",
"forge-std/=lib/forge-std/src/",
"morpho-blue/=lib/morpho-blue/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.