|
{
|
|
"language": "Solidity",
|
|
"sources": {
|
|
"@sense-finance/v1-core/src/adapters/abstract/factories/ERC4626CropsFactory.sol": {
|
|
"content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity 0.8.11;\n\n// Internal references\nimport { Divider } from \"../../../Divider.sol\";\nimport { ERC4626CropsAdapter } from \"../erc4626/ERC4626CropsAdapter.sol\";\nimport { BaseAdapter } from \"../../abstract/BaseAdapter.sol\";\nimport { BaseFactory } from \"./BaseFactory.sol\";\nimport { Errors } from \"@sense-finance/v1-utils/src/libs/Errors.sol\";\nimport { Trust } from \"@sense-finance/v1-utils/src/Trust.sol\";\n\n// External references\nimport { Bytes32AddressLib } from \"@rari-capital/solmate/src/utils/Bytes32AddressLib.sol\";\n\ncontract ERC4626CropsFactory is BaseFactory {\n using Bytes32AddressLib for address;\n\n mapping(address => bool) public supportedTargets;\n\n constructor(\n address _divider,\n address _restrictedAdmin,\n address _rewardsRecipient,\n FactoryParams memory _factoryParams\n ) BaseFactory(_divider, _restrictedAdmin, _rewardsRecipient, _factoryParams) {}\n\n /// @notice Deploys an ERC4626Adapter contract\n /// @param _target The target address\n /// @param data ABI encoded data\n function deployAdapter(address _target, bytes memory data) external override returns (address adapter) {\n address[] memory rewardTokens = abi.decode(data, (address[]));\n\n /// Sanity checks\n if (Divider(divider).periphery() != msg.sender) revert Errors.OnlyPeriphery();\n if (!Divider(divider).permissionless() && !supportedTargets[_target]) revert Errors.TargetNotSupported();\n\n BaseAdapter.AdapterParams memory adapterParams = BaseAdapter.AdapterParams({\n oracle: factoryParams.oracle,\n stake: factoryParams.stake,\n stakeSize: factoryParams.stakeSize,\n minm: factoryParams.minm,\n maxm: factoryParams.maxm,\n mode: factoryParams.mode,\n tilt: factoryParams.tilt,\n level: DEFAULT_LEVEL\n });\n\n // Use the CREATE2 opcode to deploy a new Adapter contract.\n // This will revert if am ERC4626 adapter with the provided target has already\n // been deployed, as the salt would be the same and we can't deploy with it twice.\n adapter = address(\n new ERC4626CropsAdapter{ salt: _target.fillLast12Bytes() }(\n divider,\n _target,\n rewardsRecipient,\n factoryParams.ifee,\n adapterParams,\n rewardTokens\n )\n );\n\n _setGuard(adapter);\n\n BaseAdapter(adapter).setIsTrusted(restrictedAdmin, true);\n }\n\n /// @notice (Un)support target\n /// @param _target The target address\n /// @param supported Whether the target should be supported or not\n function supportTarget(address _target, bool supported) external requiresTrust {\n supportedTargets[_target] = supported;\n emit TargetSupported(_target, supported);\n }\n\n /// @notice (Un)support multiple target at once\n /// @param _targets Array of target addresses\n /// @param supported Whether the targets should be supported or not\n function supportTargets(address[] memory _targets, bool supported) external requiresTrust {\n for (uint256 i = 0; i < _targets.length; i++) {\n supportedTargets[_targets[i]] = supported;\n emit TargetSupported(_targets[i], supported);\n }\n }\n\n /* ========== LOGS ========== */\n\n event TargetSupported(address indexed target, bool indexed supported);\n}\n"
|
|
},
|
|
"@sense-finance/v1-core/src/Divider.sol": {
|
|
"content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity 0.8.11;\n\n// External references\nimport { Pausable } from \"@openzeppelin/contracts/security/Pausable.sol\";\nimport { ERC20 } from \"@rari-capital/solmate/src/tokens/ERC20.sol\";\nimport { SafeTransferLib } from \"@rari-capital/solmate/src/utils/SafeTransferLib.sol\";\nimport { ReentrancyGuard } from \"@rari-capital/solmate/src/utils/ReentrancyGuard.sol\";\nimport { DateTime } from \"./external/DateTime.sol\";\nimport { FixedMath } from \"./external/FixedMath.sol\";\n\n// Internal references\nimport { Errors } from \"@sense-finance/v1-utils/src/libs/Errors.sol\";\n\nimport { Levels } from \"@sense-finance/v1-utils/src/libs/Levels.sol\";\nimport { Trust } from \"@sense-finance/v1-utils/src/Trust.sol\";\nimport { YT } from \"./tokens/YT.sol\";\nimport { Token } from \"./tokens/Token.sol\";\nimport { BaseAdapter as Adapter } from \"./adapters/abstract/BaseAdapter.sol\";\n\n/// @title Sense Divider: Divide Assets in Two\n/// @author fedealconada + jparklev\n/// @notice You can use this contract to issue, combine, and redeem Sense ERC20 Principal and Yield Tokens\ncontract Divider is Trust, ReentrancyGuard, Pausable {\n using SafeTransferLib for ERC20;\n using FixedMath for uint256;\n using Levels for uint256;\n\n /* ========== PUBLIC CONSTANTS ========== */\n\n /// @notice Buffer before and after the actual maturity in which only the sponsor can settle the Series\n uint256 public constant SPONSOR_WINDOW = 3 hours;\n\n /// @notice Buffer after the sponsor window in which anyone can settle the Series\n uint256 public constant SETTLEMENT_WINDOW = 3 hours;\n\n /// @notice 5% issuance fee cap\n uint256 public constant ISSUANCE_FEE_CAP = 0.05e18;\n\n /* ========== PUBLIC MUTABLE STORAGE ========== */\n\n address public periphery;\n\n /// @notice Sense community multisig\n address public immutable cup;\n\n /// @notice Principal/Yield tokens deployer\n address public immutable tokenHandler;\n\n /// @notice Permissionless flag\n bool public permissionless;\n\n /// @notice Guarded launch flag\n bool public guarded = true;\n\n /// @notice Number of adapters (including turned off)\n uint248 public adapterCounter;\n\n /// @notice adapter ID -> adapter address\n mapping(uint256 => address) public adapterAddresses;\n\n /// @notice adapter data\n mapping(address => AdapterMeta) public adapterMeta;\n\n /// @notice adapter -> maturity -> Series\n mapping(address => mapping(uint256 => Series)) public series;\n\n /// @notice adapter -> maturity -> user -> lscale (last scale)\n mapping(address => mapping(uint256 => mapping(address => uint256))) public lscales;\n\n /* ========== DATA STRUCTURES ========== */\n\n struct Series {\n // Principal ERC20 token\n address pt;\n // Timestamp of series initialization\n uint48 issuance;\n // Yield ERC20 token\n address yt;\n // % of underlying principal initially reserved for Yield\n uint96 tilt;\n // Actor who initialized the Series\n address sponsor;\n // Tracks fees due to the series' settler\n uint256 reward;\n // Scale at issuance\n uint256 iscale;\n // Scale at maturity\n uint256 mscale;\n // Max scale value from this series' lifetime\n uint256 maxscale;\n }\n\n struct AdapterMeta {\n // Adapter ID\n uint248 id;\n // Adapter enabled/disabled\n bool enabled;\n // Max amount of Target allowed to be issued\n uint256 guard;\n // Adapter level\n uint248 level;\n }\n\n constructor(address _cup, address _tokenHandler) Trust(msg.sender) {\n cup = _cup;\n tokenHandler = _tokenHandler;\n }\n\n /* ========== MUTATIVE FUNCTIONS ========== */\n\n /// @notice Enable an adapter\n /// @dev when permissionless is disabled, only the Periphery can onboard adapters\n /// @dev after permissionless is enabled, anyone can onboard adapters\n /// @param adapter Adapter's address\n function addAdapter(address adapter) external whenNotPaused {\n if (!permissionless && msg.sender != periphery) revert Errors.OnlyPermissionless();\n if (adapterMeta[adapter].id > 0 && !adapterMeta[adapter].enabled) revert Errors.InvalidAdapter();\n _setAdapter(adapter, true);\n }\n\n /// @notice Initializes a new Series\n /// @dev Deploys two ERC20 contracts, one for PTs and the other one for YTs\n /// @dev Transfers some fixed amount of stake asset to this contract\n /// @param adapter Adapter to associate with the Series\n /// @param maturity Maturity date for the new Series, in units of unix time\n /// @param sponsor Sponsor of the Series that puts up a token stake and receives the issuance fees\n function initSeries(\n address adapter,\n uint256 maturity,\n address sponsor\n ) external nonReentrant whenNotPaused returns (address pt, address yt) {\n if (periphery != msg.sender) revert Errors.OnlyPeriphery();\n if (!adapterMeta[adapter].enabled) revert Errors.InvalidAdapter();\n if (_exists(adapter, maturity)) revert Errors.DuplicateSeries();\n if (!_isValid(adapter, maturity)) revert Errors.InvalidMaturity();\n\n // Transfer stake asset stake from caller to adapter\n (address target, address stake, uint256 stakeSize) = Adapter(adapter).getStakeAndTarget();\n\n // Deploy Principal & Yield Tokens for this new Series\n (pt, yt) = TokenHandler(tokenHandler).deploy(adapter, adapterMeta[adapter].id, maturity);\n\n // Initialize the new Series struct\n uint256 scale = Adapter(adapter).scale();\n\n series[adapter][maturity].pt = pt;\n series[adapter][maturity].issuance = uint48(block.timestamp);\n series[adapter][maturity].yt = yt;\n series[adapter][maturity].tilt = uint96(Adapter(adapter).tilt());\n series[adapter][maturity].sponsor = sponsor;\n series[adapter][maturity].iscale = scale;\n series[adapter][maturity].maxscale = scale;\n\n ERC20(stake).safeTransferFrom(msg.sender, adapter, stakeSize);\n\n emit SeriesInitialized(adapter, maturity, pt, yt, sponsor, target);\n }\n\n /// @notice Settles a Series and transfers the settlement reward to the caller\n /// @dev The Series' sponsor has a grace period where only they can settle the Series\n /// @dev After that, the reward becomes MEV\n /// @param adapter Adapter to associate with the Series\n /// @param maturity Maturity date for the new Series\n function settleSeries(address adapter, uint256 maturity) external nonReentrant whenNotPaused {\n if (!adapterMeta[adapter].enabled) revert Errors.InvalidAdapter();\n if (!_exists(adapter, maturity)) revert Errors.SeriesDoesNotExist();\n if (_settled(adapter, maturity)) revert Errors.AlreadySettled();\n if (!_canBeSettled(adapter, maturity)) revert Errors.OutOfWindowBoundaries();\n\n // The maturity scale value is all a Series needs for us to consider it \"settled\"\n uint256 mscale = Adapter(adapter).scale();\n series[adapter][maturity].mscale = mscale;\n\n if (mscale > series[adapter][maturity].maxscale) {\n series[adapter][maturity].maxscale = mscale;\n }\n\n // Reward the caller for doing the work of settling the Series at around the correct time\n (address target, address stake, uint256 stakeSize) = Adapter(adapter).getStakeAndTarget();\n ERC20(target).safeTransferFrom(adapter, msg.sender, series[adapter][maturity].reward);\n ERC20(stake).safeTransferFrom(adapter, msg.sender, stakeSize);\n\n emit SeriesSettled(adapter, maturity, msg.sender);\n }\n\n /// @notice Mint Principal & Yield Tokens of a specific Series\n /// @param adapter Adapter address for the Series\n /// @param maturity Maturity date for the Series [unix time]\n /// @param tBal Balance of Target to deposit\n /// @dev The balance of PTs and YTs minted will be the same value in units of underlying (less fees)\n function issue(\n address adapter,\n uint256 maturity,\n uint256 tBal\n ) external nonReentrant whenNotPaused returns (uint256 uBal) {\n if (!adapterMeta[adapter].enabled) revert Errors.InvalidAdapter();\n if (!_exists(adapter, maturity)) revert Errors.SeriesDoesNotExist();\n if (_settled(adapter, maturity)) revert Errors.IssueOnSettle();\n\n uint256 level = adapterMeta[adapter].level;\n if (level.issueRestricted() && msg.sender != adapter) revert Errors.IssuanceRestricted();\n\n ERC20 target = ERC20(Adapter(adapter).target());\n\n // Take the issuance fee out of the deposited Target, and put it towards the settlement reward\n uint256 issuanceFee = Adapter(adapter).ifee();\n if (issuanceFee > ISSUANCE_FEE_CAP) revert Errors.IssuanceFeeCapExceeded();\n uint256 fee = tBal.fmul(issuanceFee);\n\n unchecked {\n // Safety: bounded by the Target's total token supply\n series[adapter][maturity].reward += fee;\n }\n uint256 tBalSubFee = tBal - fee;\n\n // Ensure the caller won't hit the issuance cap with this action\n unchecked {\n // Safety: bounded by the Target's total token supply\n if (guarded && target.balanceOf(adapter) + tBal > adapterMeta[address(adapter)].guard)\n revert Errors.GuardCapReached();\n }\n\n // Update values on adapter\n Adapter(adapter).notify(msg.sender, tBalSubFee, true);\n\n uint256 scale = level.collectDisabled() ? series[adapter][maturity].iscale : Adapter(adapter).scale();\n\n // Determine the amount of Underlying equal to the Target being sent in (the principal)\n uBal = tBalSubFee.fmul(scale);\n\n // If the caller has not collected on YT before, use the current scale, otherwise\n // use the harmonic mean of the last and the current scale value\n lscales[adapter][maturity][msg.sender] = lscales[adapter][maturity][msg.sender] == 0\n ? scale\n : _reweightLScale(\n adapter,\n maturity,\n YT(series[adapter][maturity].yt).balanceOf(msg.sender),\n uBal,\n msg.sender,\n scale\n );\n\n // Mint equal amounts of PT and YT\n Token(series[adapter][maturity].pt).mint(msg.sender, uBal);\n YT(series[adapter][maturity].yt).mint(msg.sender, uBal);\n\n target.safeTransferFrom(msg.sender, adapter, tBal);\n\n emit Issued(adapter, maturity, uBal, msg.sender);\n }\n\n /// @notice Reconstitute Target by burning PT and YT\n /// @dev Explicitly burns YTs before maturity, and implicitly does it at/after maturity through `_collect()`\n /// @param adapter Adapter address for the Series\n /// @param maturity Maturity date for the Series\n /// @param uBal Balance of PT and YT to burn\n function combine(\n address adapter,\n uint256 maturity,\n uint256 uBal\n ) external nonReentrant whenNotPaused returns (uint256 tBal) {\n if (!adapterMeta[adapter].enabled) revert Errors.InvalidAdapter();\n if (!_exists(adapter, maturity)) revert Errors.SeriesDoesNotExist();\n\n uint256 level = adapterMeta[adapter].level;\n if (level.combineRestricted() && msg.sender != adapter) revert Errors.CombineRestricted();\n\n // Burn the PT\n Token(series[adapter][maturity].pt).burn(msg.sender, uBal);\n\n // Collect whatever excess is due\n uint256 collected = _collect(msg.sender, adapter, maturity, uBal, uBal, address(0));\n\n uint256 cscale = series[adapter][maturity].mscale;\n bool settled = _settled(adapter, maturity);\n if (!settled) {\n // If it's not settled, then YT won't be burned automatically in `_collect()`\n YT(series[adapter][maturity].yt).burn(msg.sender, uBal);\n // If collect has been restricted, use the initial scale, otherwise use the current scale\n cscale = level.collectDisabled()\n ? series[adapter][maturity].iscale\n : lscales[adapter][maturity][msg.sender];\n }\n\n // Convert from units of Underlying to units of Target\n tBal = uBal.fdiv(cscale);\n ERC20(Adapter(adapter).target()).safeTransferFrom(adapter, msg.sender, tBal);\n\n // Notify only when Series is not settled as when it is, the _collect() call above would trigger a _redeemYT which will call notify\n if (!settled) Adapter(adapter).notify(msg.sender, tBal, false);\n unchecked {\n // Safety: bounded by the Target's total token supply\n tBal += collected;\n }\n emit Combined(adapter, maturity, tBal, msg.sender);\n }\n\n /// @notice Burn PT of a Series once it's been settled\n /// @dev The balance of redeemable Target is a function of the change in Scale\n /// @param adapter Adapter address for the Series\n /// @param maturity Maturity date for the Series\n /// @param uBal Amount of PT to burn, which should be equivalent to the amount of Underlying owed to the caller\n function redeem(\n address adapter,\n uint256 maturity,\n uint256 uBal\n ) external nonReentrant whenNotPaused returns (uint256 tBal) {\n // If a Series is settled, we know that it must have existed as well, so that check is unnecessary\n if (!_settled(adapter, maturity)) revert Errors.NotSettled();\n\n uint256 level = adapterMeta[adapter].level;\n if (level.redeemRestricted() && msg.sender == adapter) revert Errors.RedeemRestricted();\n\n // Burn the caller's PT\n Token(series[adapter][maturity].pt).burn(msg.sender, uBal);\n\n // Principal Token holder's share of the principal = (1 - part of the principal that belongs to Yield)\n uint256 zShare = FixedMath.WAD - series[adapter][maturity].tilt;\n\n // If Principal Token are at a loss and Yield have some principal to help cover the shortfall,\n // take what we can from Yield Token's principal\n if (series[adapter][maturity].mscale.fdiv(series[adapter][maturity].maxscale) >= zShare) {\n tBal = (uBal * zShare) / series[adapter][maturity].mscale;\n } else {\n tBal = uBal.fdiv(series[adapter][maturity].maxscale);\n }\n\n if (!level.redeemHookDisabled()) {\n Adapter(adapter).onRedeem(uBal, series[adapter][maturity].mscale, series[adapter][maturity].maxscale, tBal);\n }\n\n ERC20(Adapter(adapter).target()).safeTransferFrom(adapter, msg.sender, tBal);\n emit PTRedeemed(adapter, maturity, tBal);\n }\n\n function collect(\n address usr,\n address adapter,\n uint256 maturity,\n uint256 uBalTransfer,\n address to\n ) external nonReentrant onlyYT(adapter, maturity) whenNotPaused returns (uint256 collected) {\n uint256 uBal = YT(msg.sender).balanceOf(usr);\n return _collect(usr, adapter, maturity, uBal, uBalTransfer > 0 ? uBalTransfer : uBal, to);\n }\n\n /// @notice Collect YT excess before, at, or after maturity\n /// @dev If `to` is set, we copy the lscale value from usr to this address\n /// @param usr User who's collecting for their YTs\n /// @param adapter Adapter address for the Series\n /// @param maturity Maturity date for the Series\n /// @param uBal yield Token balance\n /// @param uBalTransfer original transfer value\n /// @param to address to set the lscale value from usr\n function _collect(\n address usr,\n address adapter,\n uint256 maturity,\n uint256 uBal,\n uint256 uBalTransfer,\n address to\n ) internal returns (uint256 collected) {\n if (!_exists(adapter, maturity)) revert Errors.SeriesDoesNotExist();\n\n // If the adapter is disabled, its Yield Token can only collect\n // if associated Series has been settled, which implies that an admin\n // has backfilled it\n if (!adapterMeta[adapter].enabled && !_settled(adapter, maturity)) revert Errors.InvalidAdapter();\n\n Series memory _series = series[adapter][maturity];\n\n // Get the scale value from the last time this holder collected (default to maturity)\n uint256 lscale = lscales[adapter][maturity][usr];\n\n uint256 level = adapterMeta[adapter].level;\n if (level.collectDisabled()) {\n // If this Series has been settled, we ensure everyone's YT will\n // collect yield accrued since issuance\n if (_settled(adapter, maturity)) {\n lscale = series[adapter][maturity].iscale;\n // If the Series is not settled, we ensure no collections can happen\n } else {\n return 0;\n }\n }\n\n // If the Series has been settled, this should be their last collect, so redeem the user's Yield Tokens for them\n if (_settled(adapter, maturity)) {\n _redeemYT(usr, adapter, maturity, uBal);\n } else {\n // If we're not settled and we're past maturity + the sponsor window,\n // anyone can settle this Series so revert until someone does\n if (block.timestamp > maturity + SPONSOR_WINDOW) {\n revert Errors.CollectNotSettled();\n // Otherwise, this is a valid pre-settlement collect and we need to determine the scale value\n } else {\n uint256 cscale = Adapter(adapter).scale();\n // If this is larger than the largest scale we've seen for this Series, use it\n if (cscale > _series.maxscale) {\n _series.maxscale = cscale;\n lscales[adapter][maturity][usr] = cscale;\n // If not, use the previously noted max scale value\n } else {\n lscales[adapter][maturity][usr] = _series.maxscale;\n }\n }\n }\n\n // Determine how much underlying has accrued since the last time this user collected, in units of Target.\n // (Or take the last time as issuance if they haven't yet)\n //\n // Reminder: `Underlying / Scale = Target`\n // So the following equation is saying, for some amount of Underlying `u`:\n // \"Balance of Target that equaled `u` at the last collection _minus_ Target that equals `u` now\"\n //\n // Because maxscale must be increasing, the Target balance needed to equal `u` decreases, and that \"excess\"\n // is what Yield holders are collecting\n uint256 tBalNow = uBal.fdivUp(_series.maxscale); // preventive round-up towards the protocol\n uint256 tBalPrev = uBal.fdiv(lscale);\n unchecked {\n collected = tBalPrev > tBalNow ? tBalPrev - tBalNow : 0;\n }\n ERC20(Adapter(adapter).target()).safeTransferFrom(adapter, usr, collected);\n Adapter(adapter).notify(usr, collected, false); // Distribute reward tokens\n\n // If this collect is a part of a token transfer to another address, set the receiver's\n // last collection to a synthetic scale weighted based on the scale on their last collect,\n // the time elapsed, and the current scale\n if (to != address(0)) {\n uint256 ytBal = YT(_series.yt).balanceOf(to);\n // If receiver holds yields, we set lscale to a computed \"synthetic\" lscales value that,\n // for the updated yield balance, still assigns the correct amount of yield.\n lscales[adapter][maturity][to] = ytBal > 0\n ? _reweightLScale(adapter, maturity, ytBal, uBalTransfer, to, _series.maxscale)\n : _series.maxscale;\n uint256 tBalTransfer = uBalTransfer.fdiv(_series.maxscale);\n Adapter(adapter).notify(usr, tBalTransfer, false);\n Adapter(adapter).notify(to, tBalTransfer, true);\n }\n series[adapter][maturity] = _series;\n\n emit Collected(adapter, maturity, collected);\n }\n\n /// @notice calculate the harmonic mean of the current scale and the last scale,\n /// weighted by amounts associated with each\n function _reweightLScale(\n address adapter,\n uint256 maturity,\n uint256 ytBal,\n uint256 uBal,\n address receiver,\n uint256 scale\n ) internal view returns (uint256) {\n // Target Decimals * 18 Decimals [from fdiv] / (Target Decimals * 18 Decimals [from fdiv] / 18 Decimals)\n // = 18 Decimals, which is the standard for scale values\n return (ytBal + uBal).fdiv((ytBal.fdiv(lscales[adapter][maturity][receiver]) + uBal.fdiv(scale)));\n }\n\n function _redeemYT(\n address usr,\n address adapter,\n uint256 maturity,\n uint256 uBal\n ) internal {\n // Burn the users's YTs\n YT(series[adapter][maturity].yt).burn(usr, uBal);\n\n // Default principal for a YT\n uint256 tBal = 0;\n\n // Principal Token holder's share of the principal = (1 - part of the principal that belongs to Yield Tokens)\n uint256 zShare = FixedMath.WAD - series[adapter][maturity].tilt;\n\n // If PTs are at a loss and YTs had their principal cut to help cover the shortfall,\n // calculate how much YTs have left\n if (series[adapter][maturity].mscale.fdiv(series[adapter][maturity].maxscale) >= zShare) {\n tBal = uBal.fdiv(series[adapter][maturity].maxscale) - (uBal * zShare) / series[adapter][maturity].mscale;\n ERC20(Adapter(adapter).target()).safeTransferFrom(adapter, usr, tBal);\n }\n\n // Always notify the Adapter of the full Target balance that will no longer\n // have its rewards distributed\n Adapter(adapter).notify(usr, uBal.fdivUp(series[adapter][maturity].maxscale), false);\n\n emit YTRedeemed(adapter, maturity, tBal);\n }\n\n /* ========== ADMIN ========== */\n\n /// @notice Enable or disable a adapter\n /// @param adapter Adapter's address\n /// @param isOn Flag setting this adapter to enabled or disabled\n function setAdapter(address adapter, bool isOn) public requiresTrust {\n _setAdapter(adapter, isOn);\n }\n\n /// @notice Set adapter's guard\n /// @param adapter Adapter address\n /// @param cap The max target that can be deposited on the Adapter\n function setGuard(address adapter, uint256 cap) external requiresTrust {\n adapterMeta[adapter].guard = cap;\n emit GuardChanged(adapter, cap);\n }\n\n /// @notice Set guarded mode\n /// @param _guarded bool\n function setGuarded(bool _guarded) external requiresTrust {\n guarded = _guarded;\n emit GuardedChanged(_guarded);\n }\n\n /// @notice Set periphery's contract\n /// @param _periphery Target address\n function setPeriphery(address _periphery) external requiresTrust {\n periphery = _periphery;\n emit PeripheryChanged(_periphery);\n }\n\n /// @notice Set paused flag\n /// @param _paused boolean\n function setPaused(bool _paused) external requiresTrust {\n _paused ? _pause() : _unpause();\n }\n\n /// @notice Set permissioless mode\n /// @param _permissionless bool\n function setPermissionless(bool _permissionless) external requiresTrust {\n permissionless = _permissionless;\n emit PermissionlessChanged(_permissionless);\n }\n\n /// @notice Backfill a Series' Scale value at maturity if keepers failed to settle it\n /// @param adapter Adapter's address\n /// @param maturity Maturity date for the Series\n /// @param mscale Value to set as the Series' Scale value at maturity\n /// @param _usrs Values to set on lscales mapping\n /// @param _lscales Values to set on lscales mapping\n function backfillScale(\n address adapter,\n uint256 maturity,\n uint256 mscale,\n address[] calldata _usrs,\n uint256[] calldata _lscales\n ) external requiresTrust {\n if (!_exists(adapter, maturity)) revert Errors.SeriesDoesNotExist();\n\n uint256 cutoff = maturity + SPONSOR_WINDOW + SETTLEMENT_WINDOW;\n // Admin can never backfill before maturity\n if (block.timestamp <= cutoff) revert Errors.OutOfWindowBoundaries();\n\n // Set user's last scale values the Series (needed for the `collect` method)\n for (uint256 i = 0; i < _usrs.length; i++) {\n lscales[adapter][maturity][_usrs[i]] = _lscales[i];\n }\n\n if (mscale > 0) {\n Series memory _series = series[adapter][maturity];\n // Set the maturity scale for the Series (needed for `redeem` methods)\n series[adapter][maturity].mscale = mscale;\n if (mscale > _series.maxscale) {\n series[adapter][maturity].maxscale = mscale;\n }\n\n (address target, address stake, uint256 stakeSize) = Adapter(adapter).getStakeAndTarget();\n\n address stakeDst = adapterMeta[adapter].enabled ? cup : _series.sponsor;\n ERC20(target).safeTransferFrom(adapter, cup, _series.reward);\n series[adapter][maturity].reward = 0;\n ERC20(stake).safeTransferFrom(adapter, stakeDst, stakeSize);\n }\n\n emit Backfilled(adapter, maturity, mscale, _usrs, _lscales);\n }\n\n /* ========== INTERNAL VIEWS ========== */\n\n function _exists(address adapter, uint256 maturity) internal view returns (bool) {\n return series[adapter][maturity].pt != address(0);\n }\n\n function _settled(address adapter, uint256 maturity) internal view returns (bool) {\n return series[adapter][maturity].mscale > 0;\n }\n\n function _canBeSettled(address adapter, uint256 maturity) internal view returns (bool) {\n uint256 cutoff = maturity + SPONSOR_WINDOW + SETTLEMENT_WINDOW;\n // If the sender is the sponsor for the Series\n if (msg.sender == series[adapter][maturity].sponsor) {\n return maturity - SPONSOR_WINDOW <= block.timestamp && cutoff >= block.timestamp;\n } else {\n return maturity + SPONSOR_WINDOW < block.timestamp && cutoff >= block.timestamp;\n }\n }\n\n function _isValid(address adapter, uint256 maturity) internal view returns (bool) {\n (uint256 minm, uint256 maxm) = Adapter(adapter).getMaturityBounds();\n if (maturity < block.timestamp + minm || maturity > block.timestamp + maxm) return false;\n (, , uint256 day, uint256 hour, uint256 minute, uint256 second) = DateTime.timestampToDateTime(maturity);\n\n if (hour != 0 || minute != 0 || second != 0) return false;\n uint256 mode = Adapter(adapter).mode();\n if (mode == 0) {\n return day == 1;\n }\n if (mode == 1) {\n return DateTime.getDayOfWeek(maturity) == 1;\n }\n return false;\n }\n\n /* ========== INTERNAL UTILS ========== */\n\n function _setAdapter(address adapter, bool isOn) internal {\n AdapterMeta memory am = adapterMeta[adapter];\n if (am.enabled == isOn) revert Errors.ExistingValue();\n am.enabled = isOn;\n\n // If this adapter is being added for the first time\n if (isOn && am.id == 0) {\n am.id = ++adapterCounter;\n adapterAddresses[am.id] = adapter;\n }\n\n // Set level and target (can only be done once);\n am.level = uint248(Adapter(adapter).level());\n adapterMeta[adapter] = am;\n emit AdapterChanged(adapter, am.id, isOn);\n }\n\n /* ========== PUBLIC GETTERS ========== */\n\n /// @notice Returns address of Principal Token\n function pt(address adapter, uint256 maturity) public view returns (address) {\n return series[adapter][maturity].pt;\n }\n\n /// @notice Returns address of Yield Token\n function yt(address adapter, uint256 maturity) public view returns (address) {\n return series[adapter][maturity].yt;\n }\n\n function mscale(address adapter, uint256 maturity) public view returns (uint256) {\n return series[adapter][maturity].mscale;\n }\n\n /* ========== MODIFIERS ========== */\n\n modifier onlyYT(address adapter, uint256 maturity) {\n if (series[adapter][maturity].yt != msg.sender) revert Errors.OnlyYT();\n _;\n }\n\n /* ========== LOGS ========== */\n\n /// @notice Admin\n event Backfilled(\n address indexed adapter,\n uint256 indexed maturity,\n uint256 mscale,\n address[] _usrs,\n uint256[] _lscales\n );\n event GuardChanged(address indexed adapter, uint256 cap);\n event AdapterChanged(address indexed adapter, uint256 indexed id, bool indexed isOn);\n event PeripheryChanged(address indexed periphery);\n\n /// @notice Series lifecycle\n /// *---- beginning\n event SeriesInitialized(\n address adapter,\n uint256 indexed maturity,\n address pt,\n address yt,\n address indexed sponsor,\n address indexed target\n );\n /// -***- middle\n event Issued(address indexed adapter, uint256 indexed maturity, uint256 balance, address indexed sender);\n event Combined(address indexed adapter, uint256 indexed maturity, uint256 balance, address indexed sender);\n event Collected(address indexed adapter, uint256 indexed maturity, uint256 collected);\n /// ----* end\n event SeriesSettled(address indexed adapter, uint256 indexed maturity, address indexed settler);\n event PTRedeemed(address indexed adapter, uint256 indexed maturity, uint256 redeemed);\n event YTRedeemed(address indexed adapter, uint256 indexed maturity, uint256 redeemed);\n /// *----* misc\n event GuardedChanged(bool indexed guarded);\n event PermissionlessChanged(bool indexed permissionless);\n}\n\ncontract TokenHandler is Trust {\n /// @notice Program state\n address public divider;\n\n constructor() Trust(msg.sender) {}\n\n function init(address _divider) external requiresTrust {\n if (divider != address(0)) revert Errors.AlreadyInitialized();\n divider = _divider;\n }\n\n function deploy(\n address adapter,\n uint248 id,\n uint256 maturity\n ) external returns (address pt, address yt) {\n if (msg.sender != divider) revert Errors.OnlyDivider();\n\n ERC20 target = ERC20(Adapter(adapter).target());\n uint8 decimals = target.decimals();\n string memory symbol = target.symbol();\n (string memory d, string memory m, string memory y) = DateTime.toDateString(maturity);\n string memory date = DateTime.format(maturity);\n string memory datestring = string(abi.encodePacked(d, \"-\", m, \"-\", y));\n string memory adapterId = DateTime.uintToString(id);\n pt = address(\n new Token(\n string(abi.encodePacked(date, \" \", symbol, \" Sense Principal Token, A\", adapterId)),\n string(abi.encodePacked(\"sP-\", symbol, \":\", datestring, \":\", adapterId)),\n decimals,\n divider\n )\n );\n\n yt = address(\n new YT(\n adapter,\n maturity,\n string(abi.encodePacked(date, \" \", symbol, \" Sense Yield Token, A\", adapterId)),\n string(abi.encodePacked(\"sY-\", symbol, \":\", datestring, \":\", adapterId)),\n decimals,\n divider\n )\n );\n }\n}\n"
|
|
},
|
|
"@sense-finance/v1-core/src/adapters/abstract/erc4626/ERC4626CropsAdapter.sol": {
|
|
"content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity 0.8.11;\n\nimport { ERC4626Adapter } from \"./ERC4626Adapter.sol\";\nimport { BaseAdapter } from \"../BaseAdapter.sol\";\nimport { Crops } from \"../extensions/Crops.sol\";\nimport { Errors } from \"@sense-finance/v1-utils/src/libs/Errors.sol\";\nimport { ERC20 } from \"@rari-capital/solmate/src/tokens/ERC20.sol\";\nimport { SafeTransferLib } from \"@rari-capital/solmate/src/utils/SafeTransferLib.sol\";\n\n/// @notice Adapter contract for ERC4626 Vaults\ncontract ERC4626CropsAdapter is ERC4626Adapter, Crops {\n using SafeTransferLib for ERC20;\n\n constructor(\n address _divider,\n address _target,\n address _rewardsRecipient,\n uint128 _ifee,\n AdapterParams memory _adapterParams,\n address[] memory _rewardTokens\n ) ERC4626Adapter(_divider, _target, _rewardsRecipient, _ifee, _adapterParams) Crops(_divider, _rewardTokens) {}\n\n function notify(\n address _usr,\n uint256 amt,\n bool join\n ) public override(BaseAdapter, Crops) {\n super.notify(_usr, amt, join);\n }\n\n function extractToken(address token) external override {\n for (uint256 i = 0; i < rewardTokens.length; ) {\n if (token == rewardTokens[i]) revert Errors.TokenNotSupported();\n unchecked {\n ++i;\n }\n }\n\n // Check that token is neither the target nor the stake\n if (token == target || token == adapterParams.stake) revert Errors.TokenNotSupported();\n ERC20 t = ERC20(token);\n uint256 tBal = t.balanceOf(address(this));\n t.safeTransfer(rewardsRecipient, tBal);\n emit RewardsClaimed(token, rewardsRecipient, tBal);\n }\n}\n"
|
|
},
|
|
"@sense-finance/v1-core/src/adapters/abstract/BaseAdapter.sol": {
|
|
"content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity 0.8.11;\n\n// External references\nimport { ERC20 } from \"@rari-capital/solmate/src/tokens/ERC20.sol\";\nimport { SafeTransferLib } from \"@rari-capital/solmate/src/utils/SafeTransferLib.sol\";\nimport { IERC3156FlashLender } from \"../../external/flashloan/IERC3156FlashLender.sol\";\nimport { IERC3156FlashBorrower } from \"../../external/flashloan/IERC3156FlashBorrower.sol\";\n\n// Internal references\nimport { Divider } from \"../../Divider.sol\";\nimport { Crop } from \"./extensions/Crop.sol\";\nimport { Crops } from \"./extensions/Crops.sol\";\nimport { Errors } from \"@sense-finance/v1-utils/src/libs/Errors.sol\";\nimport { Trust } from \"@sense-finance/v1-utils/src/Trust.sol\";\n\n/// @title Assign value to Target tokens\nabstract contract BaseAdapter is Trust, IERC3156FlashLender {\n using SafeTransferLib for ERC20;\n\n /* ========== CONSTANTS ========== */\n\n bytes32 public constant CALLBACK_SUCCESS = keccak256(\"ERC3156FlashBorrower.onFlashLoan\");\n\n /* ========== PUBLIC IMMUTABLES ========== */\n\n /// @notice Sense core Divider address\n address public immutable divider;\n\n /// @notice Target token to divide\n address public immutable target;\n\n /// @notice Underlying for the Target\n address public immutable underlying;\n\n /// @notice Issuance fee\n uint128 public immutable ifee;\n\n /// @notice Rewards recipient\n address public rewardsRecipient;\n\n /// @notice adapter params\n AdapterParams public adapterParams;\n\n /* ========== DATA STRUCTURES ========== */\n\n struct AdapterParams {\n /// @notice Oracle address\n address oracle;\n /// @notice Token to stake at issuance\n address stake;\n /// @notice Amount to stake at issuance\n uint256 stakeSize;\n /// @notice Min maturity (seconds after block.timstamp)\n uint256 minm;\n /// @notice Max maturity (seconds after block.timstamp)\n uint256 maxm;\n /// @notice WAD number representing the percentage of the total\n /// principal that's set aside for Yield Tokens (e.g. 0.1e18 means that 10% of the principal is reserved).\n /// @notice If `0`, it means no principal is set aside for Yield Tokens\n uint64 tilt;\n /// @notice The number this function returns will be used to determine its access by checking for binary\n /// digits using the following scheme: <onRedeem(y/n)><collect(y/n)><combine(y/n)><issue(y/n)>\n /// (e.g. 0101 enables `collect` and `issue`, but not `combine`)\n uint48 level;\n /// @notice 0 for monthly, 1 for weekly\n uint16 mode;\n }\n\n /* ========== METADATA STORAGE ========== */\n\n string public name;\n\n string public symbol;\n\n constructor(\n address _divider,\n address _target,\n address _underlying,\n address _rewardsRecipient,\n uint128 _ifee,\n AdapterParams memory _adapterParams\n ) Trust(msg.sender) {\n divider = _divider;\n target = _target;\n underlying = _underlying;\n rewardsRecipient = _rewardsRecipient;\n ifee = _ifee;\n adapterParams = _adapterParams;\n\n name = string(abi.encodePacked(ERC20(_target).name(), \" Adapter\"));\n symbol = string(abi.encodePacked(ERC20(_target).symbol(), \"-adapter\"));\n\n ERC20(_target).safeApprove(divider, type(uint256).max);\n ERC20(_adapterParams.stake).safeApprove(divider, type(uint256).max);\n }\n\n /// @notice Loan `amount` target to `receiver`, and takes it back after the callback.\n /// @param receiver The contract receiving target, needs to implement the\n /// `onFlashLoan(address user, address adapter, uint256 maturity, uint256 amount)` interface.\n /// @param amount The amount of target lent.\n /// @param data (encoded adapter address, maturity and YT amount the use has sent in)\n function flashLoan(\n IERC3156FlashBorrower receiver,\n address, /* fee */\n uint256 amount,\n bytes calldata data\n ) external returns (bool) {\n if (Divider(divider).periphery() != msg.sender) revert Errors.OnlyPeriphery();\n ERC20(target).safeTransfer(address(receiver), amount);\n bytes32 keccak = IERC3156FlashBorrower(receiver).onFlashLoan(msg.sender, target, amount, 0, data);\n if (keccak != CALLBACK_SUCCESS) revert Errors.FlashCallbackFailed();\n ERC20(target).safeTransferFrom(address(receiver), address(this), amount);\n return true;\n }\n\n /* ========== REQUIRED VALUE GETTERS ========== */\n\n /// @notice Calculate and return this adapter's Scale value for the current timestamp. To be overriden by child contracts\n /// @dev For some Targets, such as cTokens, this is simply the exchange rate, or `supply cToken / supply underlying`\n /// @dev For other Targets, such as AMM LP shares, specialized logic will be required\n /// @dev This function _must_ return a WAD number representing the current exchange rate\n /// between the Target and the Underlying.\n /// @return value WAD Scale value\n function scale() external virtual returns (uint256);\n\n /// @notice Cached scale value getter\n /// @dev For situations where you need scale from a view function\n function scaleStored() external view virtual returns (uint256);\n\n /// @notice Returns the current price of the underlying in ETH terms\n function getUnderlyingPrice() external view virtual returns (uint256);\n\n /* ========== REQUIRED UTILITIES ========== */\n\n /// @notice Deposits underlying `amount`in return for target. Must be overriden by child contracts\n /// @param amount Underlying amount\n /// @return amount of target returned\n function wrapUnderlying(uint256 amount) external virtual returns (uint256);\n\n /// @notice Deposits target `amount`in return for underlying. Must be overriden by child contracts\n /// @param amount Target amount\n /// @return amount of underlying returned\n function unwrapTarget(uint256 amount) external virtual returns (uint256);\n\n function flashFee(address token, uint256) external view returns (uint256) {\n if (token != target) revert Errors.TokenNotSupported();\n return 0;\n }\n\n function maxFlashLoan(address token) external view override returns (uint256) {\n return ERC20(token).balanceOf(address(this));\n }\n\n function setRewardsRecipient(address recipient) external requiresTrust {\n emit RewardsRecipientChanged(rewardsRecipient, recipient);\n rewardsRecipient = recipient;\n }\n\n /// @notice Transfers reward tokens from the adapter to Sense's reward container\n /// @dev If adapter is either Crop or Crops, we check token is not any of the reward tokens\n function extractToken(address token) external virtual;\n\n /* ========== OPTIONAL HOOKS ========== */\n\n /// @notice Notification whenever the Divider adds or removes Target\n function notify(\n address, /* usr */\n uint256, /* amt */\n bool /* join */\n ) public virtual {\n return;\n }\n\n /// @notice Hook called whenever a user redeems PT\n function onRedeem(\n uint256, /* uBal */\n uint256, /* mscale */\n uint256, /* maxscale */\n uint256 /* tBal */\n ) public virtual {\n return;\n }\n\n /* ========== PUBLIC STORAGE ACCESSORS ========== */\n\n function getMaturityBounds() external view virtual returns (uint256, uint256) {\n return (adapterParams.minm, adapterParams.maxm);\n }\n\n function getStakeAndTarget()\n external\n view\n returns (\n address,\n address,\n uint256\n )\n {\n return (target, adapterParams.stake, adapterParams.stakeSize);\n }\n\n function mode() external view returns (uint256) {\n return adapterParams.mode;\n }\n\n function tilt() external view returns (uint256) {\n return adapterParams.tilt;\n }\n\n function level() external view returns (uint256) {\n return adapterParams.level;\n }\n\n /* ========== LOGS ========== */\n\n event RewardsRecipientChanged(address indexed oldRecipient, address indexed newRecipient);\n event RewardsClaimed(address indexed token, address indexed recipient, uint256 indexed amount);\n}\n"
|
|
},
|
|
"@sense-finance/v1-core/src/adapters/abstract/factories/BaseFactory.sol": {
|
|
"content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity 0.8.11;\n\n// Internal references\nimport { Errors } from \"@sense-finance/v1-utils/src/libs/Errors.sol\";\nimport { BaseAdapter } from \"../BaseAdapter.sol\";\nimport { Divider } from \"../../../Divider.sol\";\nimport { FixedMath } from \"../../../external/FixedMath.sol\";\nimport { Trust } from \"@sense-finance/v1-utils/src/Trust.sol\";\n\ninterface ERC20 {\n function decimals() external view returns (uint256 decimals);\n}\n\ninterface ChainlinkOracleLike {\n function latestRoundData()\n external\n view\n returns (\n uint80 roundId,\n int256 answer,\n uint256 startedAt,\n uint256 updatedAt,\n uint80 answeredInRound\n );\n\n function decimals() external view returns (uint256 decimals);\n}\n\nabstract contract BaseFactory is Trust {\n using FixedMath for uint256;\n\n /* ========== CONSTANTS ========== */\n\n address public constant ETH_USD_PRICEFEED = 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419; // Chainlink ETH-USD price feed\n\n /// @notice Sets level to `31` by default, which keeps all Divider lifecycle methods public\n /// (`issue`, `combine`, `collect`, etc), but not the `onRedeem` hook.\n uint48 public constant DEFAULT_LEVEL = 31;\n\n /* ========== PUBLIC IMMUTABLES ========== */\n\n /// @notice Sense core Divider address\n address public immutable divider;\n\n /// @notice Adapter admin address\n address public restrictedAdmin;\n\n /// @notice Rewards recipient\n address public rewardsRecipient;\n\n /// @notice params for adapters deployed with this factory\n FactoryParams public factoryParams;\n\n /* ========== DATA STRUCTURES ========== */\n\n struct FactoryParams {\n address oracle; // oracle address\n address stake; // token to stake at issuance\n uint256 stakeSize; // amount to stake at issuance\n uint256 minm; // min maturity (seconds after block.timstamp)\n uint256 maxm; // max maturity (seconds after block.timstamp)\n uint128 ifee; // issuance fee\n uint16 mode; // 0 for monthly, 1 for weekly\n uint64 tilt; // tilt\n uint256 guard; // adapter guard (in usd, 18 decimals)\n }\n\n constructor(\n address _divider,\n address _restrictedAdmin,\n address _rewardsRecipient,\n FactoryParams memory _factoryParams\n ) Trust(msg.sender) {\n divider = _divider;\n restrictedAdmin = _restrictedAdmin;\n rewardsRecipient = _rewardsRecipient;\n factoryParams = _factoryParams;\n }\n\n /* ========== REQUIRED DEPLOY ========== */\n\n /// @notice Deploys both an adapter and a target wrapper for the given _target\n /// @param _target Address of the Target token\n /// @param _data Additional data needed to deploy the adapter\n function deployAdapter(address _target, bytes memory _data) external virtual returns (address adapter) {}\n\n /// Set adapter's guard to $100`000 in target\n /// @notice if Underlying-ETH price feed returns 0, we set the guard to 100000 target.\n function _setGuard(address _adapter) internal {\n // We only want to execute this if divider is guarded\n if (Divider(divider).guarded()) {\n BaseAdapter adapter = BaseAdapter(_adapter);\n\n // Get Underlying-ETH price (18 decimals)\n try adapter.getUnderlyingPrice() returns (uint256 underlyingPriceInEth) {\n // Get ETH-USD price from Chainlink (8 decimals)\n (, int256 ethPrice, , uint256 ethUpdatedAt, ) = ChainlinkOracleLike(ETH_USD_PRICEFEED)\n .latestRoundData();\n\n if (block.timestamp - ethUpdatedAt > 2 hours) revert Errors.InvalidPrice();\n\n // Calculate Underlying-USD price (normalised to 18 deicmals)\n uint256 price = underlyingPriceInEth.fmul(uint256(ethPrice), 1e8);\n\n // Calculate Target-USD price (scale and price are in 18 decimals)\n price = adapter.scale().fmul(price);\n\n // Calculate guard with factory guard (18 decimals) and target price (18 decimals)\n // normalised to target decimals and set it\n Divider(divider).setGuard(\n _adapter,\n factoryParams.guard.fdiv(price, 10**ERC20(adapter.target()).decimals())\n );\n } catch {}\n }\n }\n\n function setAdapterAdmin(address _restrictedAdmin) external requiresTrust {\n emit AdapterAdminChanged(restrictedAdmin, _restrictedAdmin);\n restrictedAdmin = _restrictedAdmin;\n }\n\n /// Set factory rewards recipient\n /// @notice all future deployed adapters will have the new rewards recipient\n /// @dev existing adapters rewards recipients will not be changed and can be\n /// done through `setRewardsRecipient` on each adapter contract\n function setRewardsRecipient(address _recipient) external requiresTrust {\n emit RewardsRecipientChanged(rewardsRecipient, _recipient);\n rewardsRecipient = _recipient;\n }\n\n /* ========== LOGS ========== */\n\n event RewardsRecipientChanged(address indexed oldRecipient, address indexed newRecipient);\n event AdapterAdminChanged(address indexed oldAdmin, address indexed newAdmin);\n}\n"
|
|
},
|
|
"@sense-finance/v1-utils/src/libs/Errors.sol": {
|
|
"content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.4;\n\nlibrary Errors {\n // Auth\n error CombineRestricted();\n error IssuanceRestricted();\n error NotAuthorized();\n error OnlyYT();\n error OnlyDivider();\n error OnlyPeriphery();\n error OnlyPermissionless();\n error RedeemRestricted();\n error Untrusted();\n\n // Adapters\n error TokenNotSupported();\n error FlashCallbackFailed();\n error SenderNotEligible();\n error TargetMismatch();\n error TargetNotSupported();\n error InvalidAdapterType();\n error PriceOracleNotFound();\n\n // Divider\n error AlreadySettled();\n error CollectNotSettled();\n error GuardCapReached();\n error IssuanceFeeCapExceeded();\n error IssueOnSettle();\n error NotSettled();\n\n // Input & validations\n error AlreadyInitialized();\n error DuplicateSeries();\n error ExistingValue();\n error InvalidAdapter();\n error InvalidMaturity();\n error InvalidParam();\n error NotImplemented();\n error OutOfWindowBoundaries();\n error SeriesDoesNotExist();\n error SwapTooSmall();\n error TargetParamsNotSet();\n error PoolParamsNotSet();\n error PTParamsNotSet();\n error AttemptFailed();\n error InvalidPrice();\n error BadContractInteration();\n\n // Periphery\n error FactoryNotSupported();\n error FlashBorrowFailed();\n error FlashUntrustedBorrower();\n error FlashUntrustedLoanInitiator();\n error UnexpectedSwapAmount();\n error TooMuchLeftoverTarget();\n\n // Fuse\n error AdapterNotSet();\n error FailedBecomeAdmin();\n error FailedAddTargetMarket();\n error FailedToAddPTMarket();\n error FailedAddLpMarket();\n error OracleNotReady();\n error PoolAlreadyDeployed();\n error PoolNotDeployed();\n error PoolNotSet();\n error SeriesNotQueued();\n error TargetExists();\n error TargetNotInFuse();\n\n // Tokens\n error MintFailed();\n error RedeemFailed();\n error TransferFailed();\n}\n"
|
|
},
|
|
"@sense-finance/v1-utils/src/Trust.sol": {
|
|
"content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.7.0;\n\n/// @notice Ultra minimal authorization logic for smart contracts.\n/// @author From https://github.com/Rari-Capital/solmate/blob/fab107565a51674f3a3b5bfdaacc67f6179b1a9b/src/auth/Trust.sol\nabstract contract Trust {\n event UserTrustUpdated(address indexed user, bool trusted);\n\n mapping(address => bool) public isTrusted;\n\n constructor(address initialUser) {\n isTrusted[initialUser] = true;\n\n emit UserTrustUpdated(initialUser, true);\n }\n\n function setIsTrusted(address user, bool trusted) public virtual requiresTrust {\n isTrusted[user] = trusted;\n\n emit UserTrustUpdated(user, trusted);\n }\n\n modifier requiresTrust() {\n require(isTrusted[msg.sender], \"UNTRUSTED\");\n\n _;\n }\n}\n"
|
|
},
|
|
"@rari-capital/solmate/src/utils/Bytes32AddressLib.sol": {
|
|
"content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\n/// @notice Library for converting between addresses and bytes32 values.\n/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/Bytes32AddressLib.sol)\nlibrary Bytes32AddressLib {\n function fromLast20Bytes(bytes32 bytesValue) internal pure returns (address) {\n return address(uint160(uint256(bytesValue)));\n }\n\n function fillLast12Bytes(address addressValue) internal pure returns (bytes32) {\n return bytes32(bytes20(addressValue));\n }\n}\n"
|
|
},
|
|
"@openzeppelin/contracts/security/Pausable.sol": {
|
|
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/Context.sol\";\n\n/**\n * @dev Contract module which allows children to implement an emergency stop\n * mechanism that can be triggered by an authorized account.\n *\n * This module is used through inheritance. It will make available the\n * modifiers `whenNotPaused` and `whenPaused`, which can be applied to\n * the functions of your contract. Note that they will not be pausable by\n * simply including this module, only once the modifiers are put in place.\n */\nabstract contract Pausable is Context {\n /**\n * @dev Emitted when the pause is triggered by `account`.\n */\n event Paused(address account);\n\n /**\n * @dev Emitted when the pause is lifted by `account`.\n */\n event Unpaused(address account);\n\n bool private _paused;\n\n /**\n * @dev Initializes the contract in unpaused state.\n */\n constructor() {\n _paused = false;\n }\n\n /**\n * @dev Modifier to make a function callable only when the contract is not paused.\n *\n * Requirements:\n *\n * - The contract must not be paused.\n */\n modifier whenNotPaused() {\n _requireNotPaused();\n _;\n }\n\n /**\n * @dev Modifier to make a function callable only when the contract is paused.\n *\n * Requirements:\n *\n * - The contract must be paused.\n */\n modifier whenPaused() {\n _requirePaused();\n _;\n }\n\n /**\n * @dev Returns true if the contract is paused, and false otherwise.\n */\n function paused() public view virtual returns (bool) {\n return _paused;\n }\n\n /**\n * @dev Throws if the contract is paused.\n */\n function _requireNotPaused() internal view virtual {\n require(!paused(), \"Pausable: paused\");\n }\n\n /**\n * @dev Throws if the contract is not paused.\n */\n function _requirePaused() internal view virtual {\n require(paused(), \"Pausable: not paused\");\n }\n\n /**\n * @dev Triggers stopped state.\n *\n * Requirements:\n *\n * - The contract must not be paused.\n */\n function _pause() internal virtual whenNotPaused {\n _paused = true;\n emit Paused(_msgSender());\n }\n\n /**\n * @dev Returns to normal state.\n *\n * Requirements:\n *\n * - The contract must be paused.\n */\n function _unpause() internal virtual whenPaused {\n _paused = false;\n emit Unpaused(_msgSender());\n }\n}\n"
|
|
},
|
|
"@rari-capital/solmate/src/tokens/ERC20.sol": {
|
|
"content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\n/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.\n/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC20.sol)\n/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)\n/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.\nabstract contract ERC20 {\n /*//////////////////////////////////////////////////////////////\n EVENTS\n //////////////////////////////////////////////////////////////*/\n\n event Transfer(address indexed from, address indexed to, uint256 amount);\n\n event Approval(address indexed owner, address indexed spender, uint256 amount);\n\n /*//////////////////////////////////////////////////////////////\n METADATA STORAGE\n //////////////////////////////////////////////////////////////*/\n\n string public name;\n\n string public symbol;\n\n uint8 public immutable decimals;\n\n /*//////////////////////////////////////////////////////////////\n ERC20 STORAGE\n //////////////////////////////////////////////////////////////*/\n\n uint256 public totalSupply;\n\n mapping(address => uint256) public balanceOf;\n\n mapping(address => mapping(address => uint256)) public allowance;\n\n /*//////////////////////////////////////////////////////////////\n EIP-2612 STORAGE\n //////////////////////////////////////////////////////////////*/\n\n uint256 internal immutable INITIAL_CHAIN_ID;\n\n bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;\n\n mapping(address => uint256) public nonces;\n\n /*//////////////////////////////////////////////////////////////\n CONSTRUCTOR\n //////////////////////////////////////////////////////////////*/\n\n constructor(\n string memory _name,\n string memory _symbol,\n uint8 _decimals\n ) {\n name = _name;\n symbol = _symbol;\n decimals = _decimals;\n\n INITIAL_CHAIN_ID = block.chainid;\n INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();\n }\n\n /*//////////////////////////////////////////////////////////////\n ERC20 LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function approve(address spender, uint256 amount) public virtual returns (bool) {\n allowance[msg.sender][spender] = amount;\n\n emit Approval(msg.sender, spender, amount);\n\n return true;\n }\n\n function transfer(address to, uint256 amount) public virtual returns (bool) {\n balanceOf[msg.sender] -= amount;\n\n // Cannot overflow because the sum of all user\n // balances can't exceed the max uint256 value.\n unchecked {\n balanceOf[to] += amount;\n }\n\n emit Transfer(msg.sender, to, amount);\n\n return true;\n }\n\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) public virtual returns (bool) {\n uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.\n\n if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;\n\n balanceOf[from] -= amount;\n\n // Cannot overflow because the sum of all user\n // balances can't exceed the max uint256 value.\n unchecked {\n balanceOf[to] += amount;\n }\n\n emit Transfer(from, to, amount);\n\n return true;\n }\n\n /*//////////////////////////////////////////////////////////////\n EIP-2612 LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function permit(\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) public virtual {\n require(deadline >= block.timestamp, \"PERMIT_DEADLINE_EXPIRED\");\n\n // Unchecked because the only math done is incrementing\n // the owner's nonce which cannot realistically overflow.\n unchecked {\n address recoveredAddress = ecrecover(\n keccak256(\n abi.encodePacked(\n \"\\x19\\x01\",\n DOMAIN_SEPARATOR(),\n keccak256(\n abi.encode(\n keccak256(\n \"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)\"\n ),\n owner,\n spender,\n value,\n nonces[owner]++,\n deadline\n )\n )\n )\n ),\n v,\n r,\n s\n );\n\n require(recoveredAddress != address(0) && recoveredAddress == owner, \"INVALID_SIGNER\");\n\n allowance[recoveredAddress][spender] = value;\n }\n\n emit Approval(owner, spender, value);\n }\n\n function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {\n return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();\n }\n\n function computeDomainSeparator() internal view virtual returns (bytes32) {\n return\n keccak256(\n abi.encode(\n keccak256(\"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\"),\n keccak256(bytes(name)),\n keccak256(\"1\"),\n block.chainid,\n address(this)\n )\n );\n }\n\n /*//////////////////////////////////////////////////////////////\n INTERNAL MINT/BURN LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function _mint(address to, uint256 amount) internal virtual {\n totalSupply += amount;\n\n // Cannot overflow because the sum of all user\n // balances can't exceed the max uint256 value.\n unchecked {\n balanceOf[to] += amount;\n }\n\n emit Transfer(address(0), to, amount);\n }\n\n function _burn(address from, uint256 amount) internal virtual {\n balanceOf[from] -= amount;\n\n // Cannot underflow because a user's balance\n // will never be larger than the total supply.\n unchecked {\n totalSupply -= amount;\n }\n\n emit Transfer(from, address(0), amount);\n }\n}\n"
|
|
},
|
|
"@rari-capital/solmate/src/utils/SafeTransferLib.sol": {
|
|
"content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\nimport {ERC20} from \"../tokens/ERC20.sol\";\n\n/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.\n/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/SafeTransferLib.sol)\n/// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.\n/// @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.\nlibrary SafeTransferLib {\n event Debug(bool one, bool two, uint256 retsize);\n\n /*//////////////////////////////////////////////////////////////\n ETH OPERATIONS\n //////////////////////////////////////////////////////////////*/\n\n function safeTransferETH(address to, uint256 amount) internal {\n bool success;\n\n assembly {\n // Transfer the ETH and store if it succeeded or not.\n success := call(gas(), to, amount, 0, 0, 0, 0)\n }\n\n require(success, \"ETH_TRANSFER_FAILED\");\n }\n\n /*//////////////////////////////////////////////////////////////\n ERC20 OPERATIONS\n //////////////////////////////////////////////////////////////*/\n\n function safeTransferFrom(\n ERC20 token,\n address from,\n address to,\n uint256 amount\n ) internal {\n bool success;\n\n assembly {\n // Get a pointer to some free memory.\n let freeMemoryPointer := mload(0x40)\n\n // Write the abi-encoded calldata into memory, beginning with the function selector.\n mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000)\n mstore(add(freeMemoryPointer, 4), from) // Append the \"from\" argument.\n mstore(add(freeMemoryPointer, 36), to) // Append the \"to\" argument.\n mstore(add(freeMemoryPointer, 68), amount) // Append the \"amount\" argument.\n\n success := and(\n // Set success to whether the call reverted, if not we check it either\n // returned exactly 1 (can't just be non-zero data), or had no return data.\n or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),\n // We use 100 because the length of our calldata totals up like so: 4 + 32 * 3.\n // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.\n // Counterintuitively, this call must be positioned second to the or() call in the\n // surrounding and() call or else returndatasize() will be zero during the computation.\n call(gas(), token, 0, freeMemoryPointer, 100, 0, 32)\n )\n }\n\n require(success, \"TRANSFER_FROM_FAILED\");\n }\n\n function safeTransfer(\n ERC20 token,\n address to,\n uint256 amount\n ) internal {\n bool success;\n\n assembly {\n // Get a pointer to some free memory.\n let freeMemoryPointer := mload(0x40)\n\n // Write the abi-encoded calldata into memory, beginning with the function selector.\n mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)\n mstore(add(freeMemoryPointer, 4), to) // Append the \"to\" argument.\n mstore(add(freeMemoryPointer, 36), amount) // Append the \"amount\" argument.\n\n success := and(\n // Set success to whether the call reverted, if not we check it either\n // returned exactly 1 (can't just be non-zero data), or had no return data.\n or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),\n // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.\n // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.\n // Counterintuitively, this call must be positioned second to the or() call in the\n // surrounding and() call or else returndatasize() will be zero during the computation.\n call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)\n )\n }\n\n require(success, \"TRANSFER_FAILED\");\n }\n\n function safeApprove(\n ERC20 token,\n address to,\n uint256 amount\n ) internal {\n bool success;\n\n assembly {\n // Get a pointer to some free memory.\n let freeMemoryPointer := mload(0x40)\n\n // Write the abi-encoded calldata into memory, beginning with the function selector.\n mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000)\n mstore(add(freeMemoryPointer, 4), to) // Append the \"to\" argument.\n mstore(add(freeMemoryPointer, 36), amount) // Append the \"amount\" argument.\n\n success := and(\n // Set success to whether the call reverted, if not we check it either\n // returned exactly 1 (can't just be non-zero data), or had no return data.\n or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),\n // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.\n // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.\n // Counterintuitively, this call must be positioned second to the or() call in the\n // surrounding and() call or else returndatasize() will be zero during the computation.\n call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)\n )\n }\n\n require(success, \"APPROVE_FAILED\");\n }\n}\n"
|
|
},
|
|
"@rari-capital/solmate/src/utils/ReentrancyGuard.sol": {
|
|
"content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\n/// @notice Gas optimized reentrancy protection for smart contracts.\n/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/ReentrancyGuard.sol)\n/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol)\nabstract contract ReentrancyGuard {\n uint256 private locked = 1;\n\n modifier nonReentrant() {\n require(locked == 1, \"REENTRANCY\");\n\n locked = 2;\n\n _;\n\n locked = 1;\n }\n}\n"
|
|
},
|
|
"@sense-finance/v1-core/src/external/DateTime.sol": {
|
|
"content": "pragma solidity 0.8.11;\n\n/// @author Taken from: https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary\nlibrary DateTime {\n uint256 constant SECONDS_PER_DAY = 24 * 60 * 60;\n uint256 constant SECONDS_PER_HOUR = 60 * 60;\n uint256 constant SECONDS_PER_MINUTE = 60;\n int256 constant OFFSET19700101 = 2440588;\n\n function timestampToDate(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);\n }\n\n function timestampToDateTime(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n )\n {\n (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);\n uint256 secs = timestamp % SECONDS_PER_DAY;\n hour = secs / SECONDS_PER_HOUR;\n secs = secs % SECONDS_PER_HOUR;\n minute = secs / SECONDS_PER_MINUTE;\n second = secs % SECONDS_PER_MINUTE;\n }\n\n function toDateString(uint256 _timestamp)\n internal\n pure\n returns (\n string memory d,\n string memory m,\n string memory y\n )\n {\n (uint256 year, uint256 month, uint256 day) = timestampToDate(_timestamp);\n d = uintToString(day);\n m = uintToString(month);\n y = uintToString(year);\n // append a 0 to numbers < 10 so we should, e.g, 01 instead of just 1\n if (day < 10) d = string(abi.encodePacked(\"0\", d));\n if (month < 10) m = string(abi.encodePacked(\"0\", m));\n }\n\n function format(uint256 _timestamp) internal pure returns (string memory datestring) {\n string[12] memory months = [\n \"Jan\",\n \"Feb\",\n \"Mar\",\n \"Apr\",\n \"May\",\n \"June\",\n \"July\",\n \"Aug\",\n \"Sept\",\n \"Oct\",\n \"Nov\",\n \"Dec\"\n ];\n (uint256 year, uint256 month, uint256 day) = timestampToDate(_timestamp);\n uint256 last = day % 10;\n string memory suffix = \"th\";\n if (day < 11 || day > 20) {\n if (last == 1) suffix = \"st\";\n if (last == 2) suffix = \"nd\";\n if (last == 3) suffix = \"rd\";\n }\n return string(abi.encodePacked(uintToString(day), suffix, \" \", months[month - 1], \" \", uintToString(year)));\n }\n\n function getDayOfWeek(uint256 timestamp) internal pure returns (uint256 dayOfWeek) {\n uint256 _days = timestamp / SECONDS_PER_DAY;\n dayOfWeek = ((_days + 3) % 7) + 1;\n }\n\n /// Taken from https://stackoverflow.com/questions/47129173/how-to-convert-uint-to-string-in-solidity\n function uintToString(uint256 _i) internal pure returns (string memory _uintAsString) {\n if (_i == 0) return \"0\";\n uint256 j = _i;\n uint256 len;\n while (j != 0) {\n len++;\n j /= 10;\n }\n bytes memory bstr = new bytes(len);\n uint256 k = len;\n while (_i != 0) {\n k = k - 1;\n uint8 temp = (48 + uint8(_i - (_i / 10) * 10));\n bytes1 b1 = bytes1(temp);\n bstr[k] = b1;\n _i /= 10;\n }\n return string(bstr);\n }\n\n // ------------------------------------------------------------------------\n // Calculate the number of days from 1970/01/01 to year/month/day using\n // the date conversion algorithm from\n // http://aa.usno.navy.mil/faq/docs/JD_Formula.php\n // and subtracting the offset 2440588 so that 1970/01/01 is day 0\n //\n // days = day\n // - 32075\n // + 1461 * (year + 4800 + (month - 14) / 12) / 4\n // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12\n // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4\n // - offset\n // ------------------------------------------------------------------------\n function _daysFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (uint256 _days) {\n require(year >= 1970);\n int256 _year = int256(year);\n int256 _month = int256(month);\n int256 _day = int256(day);\n\n int256 __days = _day -\n 32075 +\n (1461 * (_year + 4800 + (_month - 14) / 12)) /\n 4 +\n (367 * (_month - 2 - ((_month - 14) / 12) * 12)) /\n 12 -\n (3 * ((_year + 4900 + (_month - 14) / 12) / 100)) /\n 4 -\n OFFSET19700101;\n\n _days = uint256(__days);\n }\n\n // ------------------------------------------------------------------------\n // Calculate year/month/day from the number of days since 1970/01/01 using\n // the date conversion algorithm from\n // http://aa.usno.navy.mil/faq/docs/JD_Formula.php\n // and adding the offset 2440588 so that 1970/01/01 is day 0\n //\n // int L = days + 68569 + offset\n // int N = 4 * L / 146097\n // L = L - (146097 * N + 3) / 4\n // year = 4000 * (L + 1) / 1461001\n // L = L - 1461 * year / 4 + 31\n // month = 80 * L / 2447\n // dd = L - 2447 * month / 80\n // L = month / 11\n // month = month + 2 - 12 * L\n // year = 100 * (N - 49) + year + L\n // ------------------------------------------------------------------------\n function _daysToDate(uint256 _days)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n int256 __days = int256(_days);\n\n int256 L = __days + 68569 + OFFSET19700101;\n int256 N = (4 * L) / 146097;\n L = L - (146097 * N + 3) / 4;\n int256 _year = (4000 * (L + 1)) / 1461001;\n L = L - (1461 * _year) / 4 + 31;\n int256 _month = (80 * L) / 2447;\n int256 _day = L - (2447 * _month) / 80;\n L = _month / 11;\n _month = _month + 2 - 12 * L;\n _year = 100 * (N - 49) + _year + L;\n\n year = uint256(_year);\n month = uint256(_month);\n day = uint256(_day);\n }\n}\n"
|
|
},
|
|
"@sense-finance/v1-core/src/external/FixedMath.sol": {
|
|
"content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity 0.8.11;\n\n/// @title Fixed point arithmetic library\n/// @author Taken from https://github.com/Rari-Capital/solmate/blob/main/src/utils/FixedPointMathLib.sol\nlibrary FixedMath {\n uint256 internal constant WAD = 1e18;\n uint256 internal constant RAY = 1e27;\n\n function fmul(\n uint256 x,\n uint256 y,\n uint256 baseUnit\n ) internal pure returns (uint256) {\n return mulDivDown(x, y, baseUnit); // Equivalent to (x * y) / baseUnit rounded down.\n }\n\n function fmul(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.\n }\n\n function fmulUp(\n uint256 x,\n uint256 y,\n uint256 baseUnit\n ) internal pure returns (uint256) {\n return mulDivUp(x, y, baseUnit); // Equivalent to (x * y) / baseUnit rounded up.\n }\n\n function fmulUp(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.\n }\n\n function fdiv(\n uint256 x,\n uint256 y,\n uint256 baseUnit\n ) internal pure returns (uint256) {\n return mulDivDown(x, baseUnit, y); // Equivalent to (x * baseUnit) / y rounded down.\n }\n\n function fdiv(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.\n }\n\n function fdivUp(\n uint256 x,\n uint256 y,\n uint256 baseUnit\n ) internal pure returns (uint256) {\n return mulDivUp(x, baseUnit, y); // Equivalent to (x * baseUnit) / y rounded up.\n }\n\n function fdivUp(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.\n }\n\n function mulDivDown(\n uint256 x,\n uint256 y,\n uint256 denominator\n ) internal pure returns (uint256 z) {\n assembly {\n // Store x * y in z for now.\n z := mul(x, y)\n\n // Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y))\n if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) {\n revert(0, 0)\n }\n\n // Divide z by the denominator.\n z := div(z, denominator)\n }\n }\n\n function mulDivUp(\n uint256 x,\n uint256 y,\n uint256 denominator\n ) internal pure returns (uint256 z) {\n assembly {\n // Store x * y in z for now.\n z := mul(x, y)\n\n // Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y))\n if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) {\n revert(0, 0)\n }\n\n // First, divide z - 1 by the denominator and add 1.\n // We allow z - 1 to underflow if z is 0, because we multiply the\n // end result by 0 if z is zero, ensuring we return 0 if z is zero.\n z := mul(iszero(iszero(z)), add(div(sub(z, 1), denominator), 1))\n }\n }\n}\n"
|
|
},
|
|
"@sense-finance/v1-utils/src/libs/Levels.sol": {
|
|
"content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.7.0;\n\nlibrary Levels {\n uint256 private constant _INIT_BIT = 0x1;\n uint256 private constant _ISSUE_BIT = 0x2;\n uint256 private constant _COMBINE_BIT = 0x4;\n uint256 private constant _COLLECT_BIT = 0x8;\n uint256 private constant _REDEEM_BIT = 0x10;\n uint256 private constant _REDEEM_HOOK_BIT = 0x20;\n\n function initRestricted(uint256 level) internal pure returns (bool) {\n return level & _INIT_BIT != _INIT_BIT;\n }\n\n function issueRestricted(uint256 level) internal pure returns (bool) {\n return level & _ISSUE_BIT != _ISSUE_BIT;\n }\n\n function combineRestricted(uint256 level) internal pure returns (bool) {\n return level & _COMBINE_BIT != _COMBINE_BIT;\n }\n\n function collectDisabled(uint256 level) internal pure returns (bool) {\n return level & _COLLECT_BIT != _COLLECT_BIT;\n }\n\n function redeemRestricted(uint256 level) internal pure returns (bool) {\n return level & _REDEEM_BIT != _REDEEM_BIT;\n }\n\n function redeemHookDisabled(uint256 level) internal pure returns (bool) {\n return level & _REDEEM_HOOK_BIT != _REDEEM_HOOK_BIT;\n }\n}\n"
|
|
},
|
|
"@sense-finance/v1-core/src/tokens/YT.sol": {
|
|
"content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity 0.8.11;\n\n// Internal references\nimport { Divider } from \"../Divider.sol\";\nimport { Token } from \"./Token.sol\";\n\n/// @title Yield Token\n/// @notice Strips off excess before every transfer\ncontract YT is Token {\n address public immutable adapter;\n address public immutable divider;\n uint256 public immutable maturity;\n\n constructor(\n address _adapter,\n uint256 _maturity,\n string memory _name,\n string memory _symbol,\n uint8 _decimals,\n address _divider\n ) Token(_name, _symbol, _decimals, _divider) {\n adapter = _adapter;\n maturity = _maturity;\n divider = _divider;\n }\n\n function collect() external returns (uint256 _collected) {\n return Divider(divider).collect(msg.sender, adapter, maturity, 0, address(0));\n }\n\n function transfer(address to, uint256 value) public override returns (bool) {\n Divider(divider).collect(msg.sender, adapter, maturity, value, to);\n return super.transfer(to, value);\n }\n\n function transferFrom(\n address from,\n address to,\n uint256 value\n ) public override returns (bool) {\n if (value > 0) Divider(divider).collect(from, adapter, maturity, value, to);\n return super.transferFrom(from, to, value);\n }\n}\n"
|
|
},
|
|
"@sense-finance/v1-core/src/tokens/Token.sol": {
|
|
"content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity 0.8.11;\n\n// External references\nimport { ERC20 } from \"@rari-capital/solmate/src/tokens/ERC20.sol\";\n\n// Internal references\nimport { Trust } from \"@sense-finance/v1-utils/src/Trust.sol\";\n\n/// @title Base Token\ncontract Token is ERC20, Trust {\n constructor(\n string memory _name,\n string memory _symbol,\n uint8 _decimals,\n address _trusted\n ) ERC20(_name, _symbol, _decimals) Trust(_trusted) {}\n\n /// @param usr The address to send the minted tokens\n /// @param amount The amount to be minted\n function mint(address usr, uint256 amount) public requiresTrust {\n _mint(usr, amount);\n }\n\n /// @param usr The address from where to burn tokens from\n /// @param amount The amount to be burned\n function burn(address usr, uint256 amount) public requiresTrust {\n _burn(usr, amount);\n }\n}\n"
|
|
},
|
|
"@openzeppelin/contracts/utils/Context.sol": {
|
|
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n}\n"
|
|
},
|
|
"@sense-finance/v1-core/src/external/flashloan/IERC3156FlashLender.sol": {
|
|
"content": "pragma solidity ^0.8.0;\nimport \"./IERC3156FlashBorrower.sol\";\n\ninterface IERC3156FlashLender {\n /// @dev The amount of currency available to be lent.\n /// @param token The loan currency.\n /// @return The amount of `token` that can be borrowed.\n function maxFlashLoan(address token) external view returns (uint256);\n\n /// @dev The fee to be charged for a given loan.\n /// @param token The loan currency.\n /// @param amount The amount of tokens lent.\n /// @return The amount of `token` to be charged for the loan, on top of the returned principal.\n function flashFee(address token, uint256 amount) external view returns (uint256);\n\n /// @dev Initiate a flash loan.\n /// @param receiver The receiver of the tokens in the loan, and the receiver of the callback.\n /// @param token The loan currency.\n /// @param amount The amount of tokens lent.\n /// @param data Arbitrary data structure, intended to contain user-defined parameters.\n function flashLoan(\n IERC3156FlashBorrower receiver,\n address token,\n uint256 amount,\n bytes calldata data\n ) external returns (bool);\n}\n"
|
|
},
|
|
"@sense-finance/v1-core/src/external/flashloan/IERC3156FlashBorrower.sol": {
|
|
"content": "pragma solidity ^0.8.0;\n\ninterface IERC3156FlashBorrower {\n /// @dev Receive a flash loan.\n /// @param initiator The initiator of the loan.\n /// @param token The loan currency.\n /// @param amount The amount of tokens lent.\n /// @param fee The additional amount of tokens to repay.\n /// @param data Arbitrary data structure, intended to contain user-defined parameters.\n /// @return The keccak256 hash of \"ERC3156FlashBorrower.onFlashLoan\"\n function onFlashLoan(\n address initiator,\n address token,\n uint256 amount,\n uint256 fee,\n bytes calldata data\n ) external returns (bytes32);\n}\n"
|
|
},
|
|
"@sense-finance/v1-core/src/adapters/abstract/extensions/Crop.sol": {
|
|
"content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity 0.8.11;\n\n// External references\nimport { ERC20 } from \"@rari-capital/solmate/src/tokens/ERC20.sol\";\nimport { SafeTransferLib } from \"@rari-capital/solmate/src/utils/SafeTransferLib.sol\";\n\n// Internal references\nimport { Divider } from \"../../../Divider.sol\";\nimport { BaseAdapter } from \"../BaseAdapter.sol\";\nimport { IClaimer } from \"../IClaimer.sol\";\nimport { FixedMath } from \"../../../external/FixedMath.sol\";\nimport { Trust } from \"@sense-finance/v1-utils/src/Trust.sol\";\nimport { Errors } from \"@sense-finance/v1-utils/src/libs/Errors.sol\";\n\n/// @notice This is meant to be used with BaseAdapter.sol\nabstract contract Crop is Trust {\n using SafeTransferLib for ERC20;\n using FixedMath for uint256;\n\n /// @notice Program state\n address public claimer; // claimer address\n address public reward;\n uint256 public share; // accumulated reward token per collected target\n uint256 public rewardBal; // last recorded balance of reward token\n uint256 public totalTarget; // total target accumulated by all users\n mapping(address => uint256) public tBalance; // target balance per user\n mapping(address => uint256) public rewarded; // reward token per user\n mapping(address => uint256) public reconciledAmt; // reconciled target amount per user\n mapping(address => mapping(uint256 => bool)) public reconciled; // whether a user has been reconciled for a given maturity\n\n event Distributed(address indexed usr, address indexed token, uint256 amount);\n\n constructor(address _divider, address _reward) {\n setIsTrusted(_divider, true);\n reward = _reward;\n }\n\n /// @notice Distribute the rewards tokens to the user according to their share\n /// @dev The reconcile amount allows us to prevent diluting other users' rewards\n function notify(\n address _usr,\n uint256 amt,\n bool join\n ) public virtual requiresTrust {\n _distribute(_usr);\n if (amt > 0) {\n if (join) {\n totalTarget += amt;\n tBalance[_usr] += amt;\n } else {\n uint256 uReconciledAmt = reconciledAmt[_usr];\n if (uReconciledAmt > 0) {\n if (amt < uReconciledAmt) {\n unchecked {\n uReconciledAmt -= amt;\n }\n amt = 0;\n } else {\n unchecked {\n amt -= uReconciledAmt;\n }\n uReconciledAmt = 0;\n }\n reconciledAmt[_usr] = uReconciledAmt;\n }\n if (amt > 0) {\n totalTarget -= amt;\n tBalance[_usr] -= amt;\n }\n }\n }\n rewarded[_usr] = tBalance[_usr].fmulUp(share, FixedMath.RAY);\n }\n\n /// @notice Reconciles users target balances to zero by distributing rewards on their holdings,\n /// to avoid dilution of next Series' YT holders.\n /// This function should be called right after a Series matures and will save the user's YT balance\n /// (in target terms) on reconciledAmt[usr]. When `notify()` is triggered, we take that amount and\n /// subtract it from the user's target balance (`tBalance`) which will fix (or reconcile)\n /// his position to prevent dilution.\n /// @param _usrs Users to reconcile\n /// @param _maturities Maturities of the series that we want to reconcile users on.\n function reconcile(address[] calldata _usrs, uint256[] calldata _maturities) public {\n Divider divider = Divider(BaseAdapter(address(this)).divider());\n for (uint256 j = 0; j < _maturities.length; j++) {\n for (uint256 i = 0; i < _usrs.length; i++) {\n address usr = _usrs[i];\n uint256 ytBal = ERC20(divider.yt(address(this), _maturities[j])).balanceOf(usr);\n // We don't want to reconcile users if maturity has not been reached or if they have already been reconciled\n if (_maturities[j] <= block.timestamp && ytBal > 0 && !reconciled[usr][_maturities[j]]) {\n _distribute(usr);\n uint256 tBal = ytBal.fdiv(divider.lscales(address(this), _maturities[j], usr));\n totalTarget -= tBal;\n tBalance[usr] -= tBal;\n reconciledAmt[usr] += tBal; // We increase reconciledAmt with the user's YT balance in target terms\n reconciled[usr][_maturities[j]] = true;\n emit Reconciled(usr, tBal, _maturities[j]);\n }\n }\n }\n }\n\n /// @notice Distributes rewarded tokens to users proportionally based on their `tBalance`\n /// @param _usr User to distribute reward tokens to\n function _distribute(address _usr) internal {\n _claimReward();\n\n uint256 crop = ERC20(reward).balanceOf(address(this)) - rewardBal;\n if (totalTarget > 0) share += (crop.fdiv(totalTarget, FixedMath.RAY));\n\n uint256 last = rewarded[_usr];\n uint256 curr = tBalance[_usr].fmul(share, FixedMath.RAY);\n if (curr > last) {\n unchecked {\n ERC20(reward).safeTransfer(_usr, curr - last);\n }\n }\n rewardBal = ERC20(reward).balanceOf(address(this));\n emit Distributed(_usr, reward, curr > last ? curr - last : 0);\n }\n\n /// @notice Some protocols don't airdrop reward tokens, instead users must claim them.\n /// This method may be overriden by child contracts to claim a protocol's rewards\n function _claimReward() internal virtual {\n if (claimer != address(0)) {\n ERC20 target = ERC20(BaseAdapter(address(this)).target());\n uint256 tBal = ERC20(target).balanceOf(address(this));\n\n if (tBal > 0) {\n // We send all the target balance to the claimer contract to it can claim rewards\n ERC20(target).transfer(claimer, tBal);\n\n // Make claimer to claim rewards\n IClaimer(claimer).claim();\n\n // Get the target back\n if (ERC20(target).balanceOf(address(this)) < tBal) revert Errors.BadContractInteration();\n }\n }\n }\n\n /// @notice Overrides the rewardToken address.\n /// @param _reward New reward token address\n function setRewardToken(address _reward) public requiresTrust {\n _claimReward();\n reward = _reward;\n emit RewardTokenChanged(reward);\n }\n\n /// @notice Sets `claimer`.\n /// @param _claimer New claimer contract address\n function setClaimer(address _claimer) public requiresTrust {\n claimer = _claimer;\n emit ClaimerChanged(claimer);\n }\n\n /* ========== LOGS ========== */\n\n event Reconciled(address indexed usr, uint256 tBal, uint256 maturity);\n event RewardTokenChanged(address indexed reward);\n event ClaimerChanged(address indexed claimer);\n}\n"
|
|
},
|
|
"@sense-finance/v1-core/src/adapters/abstract/extensions/Crops.sol": {
|
|
"content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity 0.8.11;\n\n// External references\nimport { ERC20 } from \"@rari-capital/solmate/src/tokens/ERC20.sol\";\nimport { SafeTransferLib } from \"@rari-capital/solmate/src/utils/SafeTransferLib.sol\";\n\n// Internal references\nimport { Divider } from \"../../../Divider.sol\";\nimport { BaseAdapter } from \"../BaseAdapter.sol\";\nimport { IClaimer } from \"../IClaimer.sol\";\nimport { FixedMath } from \"../../../external/FixedMath.sol\";\nimport { Errors } from \"@sense-finance/v1-utils/src/libs/Errors.sol\";\nimport { Trust } from \"@sense-finance/v1-utils/src/Trust.sol\";\n\n/// @notice This is meant to be used with BaseAdapter.sol\nabstract contract Crops is Trust {\n using SafeTransferLib for ERC20;\n using FixedMath for uint256;\n\n /// @notice Program state\n address public claimer; // claimer address\n uint256 public totalTarget; // total target accumulated by all users\n mapping(address => uint256) public tBalance; // target balance per user\n mapping(address => uint256) public reconciledAmt; // reconciled target amount per user\n mapping(address => mapping(uint256 => bool)) public reconciled; // whether a user has been reconciled for a given maturity\n\n address[] public rewardTokens; // reward tokens addresses\n mapping(address => Crop) public data;\n\n struct Crop {\n // Accumulated reward token per collected target\n uint256 shares;\n // Last recorded balance of this contract per reward token\n uint256 rewardedBalances;\n // Rewarded token per token per user\n mapping(address => uint256) rewarded;\n }\n\n constructor(address _divider, address[] memory _rewardTokens) {\n setIsTrusted(_divider, true);\n rewardTokens = _rewardTokens;\n }\n\n function notify(\n address _usr,\n uint256 amt,\n bool join\n ) public virtual requiresTrust {\n _distribute(_usr);\n if (amt > 0) {\n if (join) {\n totalTarget += amt;\n tBalance[_usr] += amt;\n } else {\n uint256 uReconciledAmt = reconciledAmt[_usr];\n if (uReconciledAmt > 0) {\n if (amt < uReconciledAmt) {\n unchecked {\n uReconciledAmt -= amt;\n }\n amt = 0;\n } else {\n unchecked {\n amt -= uReconciledAmt;\n }\n uReconciledAmt = 0;\n }\n reconciledAmt[_usr] = uReconciledAmt;\n }\n if (amt > 0) {\n totalTarget -= amt;\n tBalance[_usr] -= amt;\n }\n }\n }\n for (uint256 i = 0; i < rewardTokens.length; i++) {\n data[rewardTokens[i]].rewarded[_usr] = tBalance[_usr].fmulUp(data[rewardTokens[i]].shares, FixedMath.RAY);\n }\n }\n\n /// @notice Reconciles users target balances to zero by distributing rewards on their holdings,\n /// to avoid dilution of next Series' YT holders.\n /// This function should be called right after a Series matures and will save the user's YT balance\n /// (in target terms) on reconciledAmt[usr]. When `notify()` is triggered for on a new Series, we will\n /// take that amount and subtract it from the user's target balance (`tBalance`) which will fix (or reconcile)\n /// his position to prevent dilution.\n /// @param _usrs Users to reconcile\n /// @param _maturities Maturities of the series that we want to reconcile users on.\n function reconcile(address[] calldata _usrs, uint256[] calldata _maturities) public {\n Divider divider = Divider(BaseAdapter(address(this)).divider());\n for (uint256 j = 0; j < _maturities.length; j++) {\n for (uint256 i = 0; i < _usrs.length; i++) {\n address usr = _usrs[i];\n uint256 ytBal = ERC20(divider.yt(address(this), _maturities[j])).balanceOf(usr);\n // We don't want to reconcile users if maturity has not been reached or if they have already been reconciled\n if (_maturities[j] <= block.timestamp && ytBal > 0 && !reconciled[usr][_maturities[j]]) {\n _distribute(usr);\n uint256 tBal = ytBal.fdiv(divider.lscales(address(this), _maturities[j], usr));\n totalTarget -= tBal;\n tBalance[usr] -= tBal;\n reconciledAmt[usr] += tBal; // We increase reconciledAmt with the user's YT balance in target terms\n reconciled[usr][_maturities[j]] = true;\n emit Reconciled(usr, tBal, _maturities[j]);\n }\n }\n }\n }\n\n /// @notice Distributes rewarded tokens to users proportionally based on their `tBalance`\n /// @param _usr User to distribute reward tokens to\n function _distribute(address _usr) internal {\n _claimRewards();\n\n for (uint256 i = 0; i < rewardTokens.length; i++) {\n uint256 crop = ERC20(rewardTokens[i]).balanceOf(address(this)) - data[rewardTokens[i]].rewardedBalances;\n if (totalTarget > 0) data[rewardTokens[i]].shares += (crop.fdiv(totalTarget, FixedMath.RAY));\n\n uint256 last = data[rewardTokens[i]].rewarded[_usr];\n uint256 curr = tBalance[_usr].fmul(data[rewardTokens[i]].shares, FixedMath.RAY);\n if (curr > last) {\n unchecked {\n ERC20(rewardTokens[i]).safeTransfer(_usr, curr - last);\n }\n }\n data[rewardTokens[i]].rewardedBalances = ERC20(rewardTokens[i]).balanceOf(address(this));\n emit Distributed(_usr, rewardTokens[i], curr > last ? curr - last : 0);\n }\n }\n\n /// @notice Some protocols don't airdrop reward tokens, instead users must claim them.\n /// This method may be overriden by child contracts to claim a protocol's rewards\n function _claimRewards() internal virtual {\n if (claimer != address(0)) {\n ERC20 target = ERC20(BaseAdapter(address(this)).target());\n uint256 tBal = ERC20(target).balanceOf(address(this));\n\n if (tBal > 0) {\n // We send all the target balance to the claimer contract to it can claim rewards\n ERC20(target).transfer(claimer, tBal);\n\n // Make claimer to claim rewards\n IClaimer(claimer).claim();\n\n // Get the target back\n if (ERC20(target).balanceOf(address(this)) < tBal) revert Errors.BadContractInteration();\n }\n }\n }\n\n /// @notice Overrides the rewardTokens array with a new one.\n /// @dev Calls _claimRewards() in case the new array contains less reward tokens than the old one.\n /// @param _rewardTokens New reward tokens array\n function setRewardTokens(address[] memory _rewardTokens) public requiresTrust {\n _claimRewards();\n rewardTokens = _rewardTokens;\n emit RewardTokensChanged(rewardTokens);\n }\n\n /// @notice Sets `claimer`.\n /// @param _claimer New claimer contract address\n function setClaimer(address _claimer) public requiresTrust {\n claimer = _claimer;\n emit ClaimerChanged(claimer);\n }\n\n /* ========== LOGS ========== */\n\n event Distributed(address indexed usr, address indexed token, uint256 amount);\n event RewardTokensChanged(address[] indexed rewardTokens);\n event Reconciled(address indexed usr, uint256 tBal, uint256 maturity);\n event ClaimerChanged(address indexed claimer);\n}\n"
|
|
},
|
|
"@sense-finance/v1-core/src/adapters/abstract/IClaimer.sol": {
|
|
"content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity 0.8.11;\n\ninterface IClaimer {\n /// @dev Claims rewards on protocol.\n function claim() external;\n}\n"
|
|
},
|
|
"@sense-finance/v1-core/src/adapters/abstract/erc4626/ERC4626Adapter.sol": {
|
|
"content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity 0.8.11;\n\n// External references\nimport { ERC20 } from \"@rari-capital/solmate/src/tokens/ERC20.sol\";\nimport { SafeTransferLib } from \"@rari-capital/solmate/src/utils/SafeTransferLib.sol\";\nimport { ERC4626 } from \"@rari-capital/solmate/src/mixins/ERC4626.sol\";\nimport { Errors } from \"@sense-finance/v1-utils/src/libs/Errors.sol\";\n\n// Internal references\nimport { MasterPriceOracle } from \"../../implementations/oracles/MasterPriceOracle.sol\";\nimport { FixedMath } from \"../../../external/FixedMath.sol\";\nimport { BaseAdapter } from \"../BaseAdapter.sol\";\n\n/// @notice Adapter contract for ERC4626 Vaults\ncontract ERC4626Adapter is BaseAdapter {\n using SafeTransferLib for ERC20;\n using FixedMath for uint256;\n\n address public constant RARI_MASTER_ORACLE = 0x1887118E49e0F4A78Bd71B792a49dE03504A764D;\n\n uint256 public immutable BASE_UINT;\n uint256 public immutable SCALE_FACTOR;\n\n constructor(\n address _divider,\n address _target,\n address _rewardsRecipient,\n uint128 _ifee,\n AdapterParams memory _adapterParams\n ) BaseAdapter(_divider, _target, address(ERC4626(_target).asset()), _rewardsRecipient, _ifee, _adapterParams) {\n uint256 tDecimals = ERC4626(target).decimals();\n BASE_UINT = 10**tDecimals;\n SCALE_FACTOR = 10**(18 - tDecimals); // we assume targets decimals <= 18\n ERC20(underlying).safeApprove(target, type(uint256).max);\n }\n\n function scale() external override returns (uint256) {\n return ERC4626(target).convertToAssets(BASE_UINT) * SCALE_FACTOR;\n }\n\n function scaleStored() external view override returns (uint256) {\n return ERC4626(target).convertToAssets(BASE_UINT) * SCALE_FACTOR;\n }\n\n function getUnderlyingPrice() external view override returns (uint256 price) {\n price = MasterPriceOracle(adapterParams.oracle).price(underlying);\n if (price == 0) {\n revert Errors.InvalidPrice();\n }\n }\n\n function wrapUnderlying(uint256 assets) external override returns (uint256 _shares) {\n ERC20(underlying).safeTransferFrom(msg.sender, address(this), assets);\n _shares = ERC4626(target).deposit(assets, msg.sender);\n }\n\n function unwrapTarget(uint256 shares) external override returns (uint256 _assets) {\n _assets = ERC4626(target).redeem(shares, msg.sender, msg.sender);\n }\n\n function extractToken(address token) external virtual override {\n // Check that token is neither the target nor the stake\n if (token == target || token == adapterParams.stake) revert Errors.TokenNotSupported();\n ERC20 t = ERC20(token);\n uint256 tBal = t.balanceOf(address(this));\n t.safeTransfer(rewardsRecipient, tBal);\n emit RewardsClaimed(token, rewardsRecipient, tBal);\n }\n}\n"
|
|
},
|
|
"@rari-capital/solmate/src/mixins/ERC4626.sol": {
|
|
"content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\nimport {ERC20} from \"../tokens/ERC20.sol\";\nimport {SafeTransferLib} from \"../utils/SafeTransferLib.sol\";\nimport {FixedPointMathLib} from \"../utils/FixedPointMathLib.sol\";\n\n/// @notice Minimal ERC4626 tokenized Vault implementation.\n/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/mixins/ERC4626.sol)\nabstract contract ERC4626 is ERC20 {\n using SafeTransferLib for ERC20;\n using FixedPointMathLib for uint256;\n\n /*//////////////////////////////////////////////////////////////\n EVENTS\n //////////////////////////////////////////////////////////////*/\n\n event Deposit(address indexed caller, address indexed owner, uint256 assets, uint256 shares);\n\n event Withdraw(\n address indexed caller,\n address indexed receiver,\n address indexed owner,\n uint256 assets,\n uint256 shares\n );\n\n /*//////////////////////////////////////////////////////////////\n IMMUTABLES\n //////////////////////////////////////////////////////////////*/\n\n ERC20 public immutable asset;\n\n constructor(\n ERC20 _asset,\n string memory _name,\n string memory _symbol\n ) ERC20(_name, _symbol, _asset.decimals()) {\n asset = _asset;\n }\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function deposit(uint256 assets, address receiver) public virtual returns (uint256 shares) {\n // Check for rounding error since we round down in previewDeposit.\n require((shares = previewDeposit(assets)) != 0, \"ZERO_SHARES\");\n\n // Need to transfer before minting or ERC777s could reenter.\n asset.safeTransferFrom(msg.sender, address(this), assets);\n\n _mint(receiver, shares);\n\n emit Deposit(msg.sender, receiver, assets, shares);\n\n afterDeposit(assets, shares);\n }\n\n function mint(uint256 shares, address receiver) public virtual returns (uint256 assets) {\n assets = previewMint(shares); // No need to check for rounding error, previewMint rounds up.\n\n // Need to transfer before minting or ERC777s could reenter.\n asset.safeTransferFrom(msg.sender, address(this), assets);\n\n _mint(receiver, shares);\n\n emit Deposit(msg.sender, receiver, assets, shares);\n\n afterDeposit(assets, shares);\n }\n\n function withdraw(\n uint256 assets,\n address receiver,\n address owner\n ) public virtual returns (uint256 shares) {\n shares = previewWithdraw(assets); // No need to check for rounding error, previewWithdraw rounds up.\n\n if (msg.sender != owner) {\n uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.\n\n if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;\n }\n\n beforeWithdraw(assets, shares);\n\n _burn(owner, shares);\n\n emit Withdraw(msg.sender, receiver, owner, assets, shares);\n\n asset.safeTransfer(receiver, assets);\n }\n\n function redeem(\n uint256 shares,\n address receiver,\n address owner\n ) public virtual returns (uint256 assets) {\n if (msg.sender != owner) {\n uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.\n\n if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;\n }\n\n // Check for rounding error since we round down in previewRedeem.\n require((assets = previewRedeem(shares)) != 0, \"ZERO_ASSETS\");\n\n beforeWithdraw(assets, shares);\n\n _burn(owner, shares);\n\n emit Withdraw(msg.sender, receiver, owner, assets, shares);\n\n asset.safeTransfer(receiver, assets);\n }\n\n /*//////////////////////////////////////////////////////////////\n ACCOUNTING LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function totalAssets() public view virtual returns (uint256);\n\n function convertToShares(uint256 assets) public view virtual returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? assets : assets.mulDivDown(supply, totalAssets());\n }\n\n function convertToAssets(uint256 shares) public view virtual returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? shares : shares.mulDivDown(totalAssets(), supply);\n }\n\n function previewDeposit(uint256 assets) public view virtual returns (uint256) {\n return convertToShares(assets);\n }\n\n function previewMint(uint256 shares) public view virtual returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? shares : shares.mulDivUp(totalAssets(), supply);\n }\n\n function previewWithdraw(uint256 assets) public view virtual returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? assets : assets.mulDivUp(supply, totalAssets());\n }\n\n function previewRedeem(uint256 shares) public view virtual returns (uint256) {\n return convertToAssets(shares);\n }\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LIMIT LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function maxDeposit(address) public view virtual returns (uint256) {\n return type(uint256).max;\n }\n\n function maxMint(address) public view virtual returns (uint256) {\n return type(uint256).max;\n }\n\n function maxWithdraw(address owner) public view virtual returns (uint256) {\n return convertToAssets(balanceOf[owner]);\n }\n\n function maxRedeem(address owner) public view virtual returns (uint256) {\n return balanceOf[owner];\n }\n\n /*//////////////////////////////////////////////////////////////\n INTERNAL HOOKS LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function beforeWithdraw(uint256 assets, uint256 shares) internal virtual {}\n\n function afterDeposit(uint256 assets, uint256 shares) internal virtual {}\n}\n"
|
|
},
|
|
"@sense-finance/v1-core/src/adapters/implementations/oracles/MasterPriceOracle.sol": {
|
|
"content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity 0.8.11;\n\nimport { Trust } from \"@sense-finance/v1-utils/src/Trust.sol\";\nimport { Errors } from \"@sense-finance/v1-utils/src/libs/Errors.sol\";\nimport { IPriceFeed } from \"../../abstract/IPriceFeed.sol\";\n\n/// @notice This contract gets prices from an available oracle address which must implement IPriceFeed.sol\n/// If there's no oracle set, it will try getting the price from Chainlink's Oracle.\n/// @author Inspired by: https://github.com/Rari-Capital/fuse-v1/blob/development/src/oracles/MasterPriceOracle.sol\ncontract MasterPriceOracle is IPriceFeed, Trust {\n address public senseChainlinkPriceOracle;\n\n /// @dev Maps underlying token addresses to oracle addresses.\n mapping(address => address) public oracles;\n\n /// @dev Constructor to initialize state variables.\n /// @param _chainlinkOracle The underlying ERC20 token addresses to link to `_oracles`.\n /// @param _underlyings The underlying ERC20 token addresses to link to `_oracles`.\n /// @param _oracles The `PriceOracle` contracts to be assigned to `underlyings`.\n constructor(\n address _chainlinkOracle,\n address[] memory _underlyings,\n address[] memory _oracles\n ) public Trust(msg.sender) {\n senseChainlinkPriceOracle = _chainlinkOracle;\n\n // Input validation\n if (_underlyings.length != _oracles.length) revert Errors.InvalidParam();\n\n // Initialize state variables\n for (uint256 i = 0; i < _underlyings.length; i++) oracles[_underlyings[i]] = _oracles[i];\n }\n\n /// @dev Sets `_oracles` for `underlyings`.\n /// Caller of this function must make sure that the oracles being added return non-stale, greater than 0\n /// prices for all underlying tokens.\n function add(address[] calldata _underlyings, address[] calldata _oracles) external requiresTrust {\n if (_underlyings.length <= 0 || _underlyings.length != _oracles.length) revert Errors.InvalidParam();\n\n for (uint256 i = 0; i < _underlyings.length; i++) {\n oracles[_underlyings[i]] = _oracles[i];\n }\n }\n\n /// @dev Attempts to return the price in ETH of `underlying` (implements `BasePriceOracle`).\n function price(address underlying) external view override returns (uint256) {\n if (underlying == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) return 1e18; // Return 1e18 for WETH\n\n address oracle = oracles[underlying];\n if (oracle != address(0)) {\n return IPriceFeed(oracle).price(underlying);\n } else {\n // Try token/ETH from Sense's Chainlink Oracle\n try IPriceFeed(senseChainlinkPriceOracle).price(underlying) returns (uint256 price) {\n return price;\n } catch {\n revert Errors.PriceOracleNotFound();\n }\n }\n }\n\n /// @dev Sets the `senseChainlinkPriceOracle`.\n function setSenseChainlinkPriceOracle(address _senseChainlinkPriceOracle) public requiresTrust {\n senseChainlinkPriceOracle = _senseChainlinkPriceOracle;\n emit SenseChainlinkPriceOracleChanged(senseChainlinkPriceOracle);\n }\n\n /* ========== LOGS ========== */\n event SenseChainlinkPriceOracleChanged(address indexed senseChainlinkPriceOracle);\n}\n"
|
|
},
|
|
"@rari-capital/solmate/src/utils/FixedPointMathLib.sol": {
|
|
"content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\n/// @notice Arithmetic library with operations for fixed-point numbers.\n/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/FixedPointMathLib.sol)\n/// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)\nlibrary FixedPointMathLib {\n /*//////////////////////////////////////////////////////////////\n SIMPLIFIED FIXED POINT OPERATIONS\n //////////////////////////////////////////////////////////////*/\n\n uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s.\n\n function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.\n }\n\n function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.\n }\n\n function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.\n }\n\n function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.\n }\n\n /*//////////////////////////////////////////////////////////////\n LOW LEVEL FIXED POINT OPERATIONS\n //////////////////////////////////////////////////////////////*/\n\n function mulDivDown(\n uint256 x,\n uint256 y,\n uint256 denominator\n ) internal pure returns (uint256 z) {\n assembly {\n // Store x * y in z for now.\n z := mul(x, y)\n\n // Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y))\n if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) {\n revert(0, 0)\n }\n\n // Divide z by the denominator.\n z := div(z, denominator)\n }\n }\n\n function mulDivUp(\n uint256 x,\n uint256 y,\n uint256 denominator\n ) internal pure returns (uint256 z) {\n assembly {\n // Store x * y in z for now.\n z := mul(x, y)\n\n // Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y))\n if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) {\n revert(0, 0)\n }\n\n // First, divide z - 1 by the denominator and add 1.\n // We allow z - 1 to underflow if z is 0, because we multiply the\n // end result by 0 if z is zero, ensuring we return 0 if z is zero.\n z := mul(iszero(iszero(z)), add(div(sub(z, 1), denominator), 1))\n }\n }\n\n function rpow(\n uint256 x,\n uint256 n,\n uint256 scalar\n ) internal pure returns (uint256 z) {\n assembly {\n switch x\n case 0 {\n switch n\n case 0 {\n // 0 ** 0 = 1\n z := scalar\n }\n default {\n // 0 ** n = 0\n z := 0\n }\n }\n default {\n switch mod(n, 2)\n case 0 {\n // If n is even, store scalar in z for now.\n z := scalar\n }\n default {\n // If n is odd, store x in z for now.\n z := x\n }\n\n // Shifting right by 1 is like dividing by 2.\n let half := shr(1, scalar)\n\n for {\n // Shift n right by 1 before looping to halve it.\n n := shr(1, n)\n } n {\n // Shift n right by 1 each iteration to halve it.\n n := shr(1, n)\n } {\n // Revert immediately if x ** 2 would overflow.\n // Equivalent to iszero(eq(div(xx, x), x)) here.\n if shr(128, x) {\n revert(0, 0)\n }\n\n // Store x squared.\n let xx := mul(x, x)\n\n // Round to the nearest number.\n let xxRound := add(xx, half)\n\n // Revert if xx + half overflowed.\n if lt(xxRound, xx) {\n revert(0, 0)\n }\n\n // Set x to scaled xxRound.\n x := div(xxRound, scalar)\n\n // If n is even:\n if mod(n, 2) {\n // Compute z * x.\n let zx := mul(z, x)\n\n // If z * x overflowed:\n if iszero(eq(div(zx, x), z)) {\n // Revert if x is non-zero.\n if iszero(iszero(x)) {\n revert(0, 0)\n }\n }\n\n // Round to the nearest number.\n let zxRound := add(zx, half)\n\n // Revert if zx + half overflowed.\n if lt(zxRound, zx) {\n revert(0, 0)\n }\n\n // Return properly scaled zxRound.\n z := div(zxRound, scalar)\n }\n }\n }\n }\n }\n\n /*//////////////////////////////////////////////////////////////\n GENERAL NUMBER UTILITIES\n //////////////////////////////////////////////////////////////*/\n\n function sqrt(uint256 x) internal pure returns (uint256 z) {\n assembly {\n // Start off with z at 1.\n z := 1\n\n // Used below to help find a nearby power of 2.\n let y := x\n\n // Find the lowest power of 2 that is at least sqrt(x).\n if iszero(lt(y, 0x100000000000000000000000000000000)) {\n y := shr(128, y) // Like dividing by 2 ** 128.\n z := shl(64, z) // Like multiplying by 2 ** 64.\n }\n if iszero(lt(y, 0x10000000000000000)) {\n y := shr(64, y) // Like dividing by 2 ** 64.\n z := shl(32, z) // Like multiplying by 2 ** 32.\n }\n if iszero(lt(y, 0x100000000)) {\n y := shr(32, y) // Like dividing by 2 ** 32.\n z := shl(16, z) // Like multiplying by 2 ** 16.\n }\n if iszero(lt(y, 0x10000)) {\n y := shr(16, y) // Like dividing by 2 ** 16.\n z := shl(8, z) // Like multiplying by 2 ** 8.\n }\n if iszero(lt(y, 0x100)) {\n y := shr(8, y) // Like dividing by 2 ** 8.\n z := shl(4, z) // Like multiplying by 2 ** 4.\n }\n if iszero(lt(y, 0x10)) {\n y := shr(4, y) // Like dividing by 2 ** 4.\n z := shl(2, z) // Like multiplying by 2 ** 2.\n }\n if iszero(lt(y, 0x8)) {\n // Equivalent to 2 ** z.\n z := shl(1, z)\n }\n\n // Shifting right by 1 is like dividing by 2.\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n\n // Compute a rounded down version of z.\n let zRoundDown := div(x, z)\n\n // If zRoundDown is smaller, use it.\n if lt(zRoundDown, z) {\n z := zRoundDown\n }\n }\n }\n}\n"
|
|
},
|
|
"@sense-finance/v1-core/src/adapters/abstract/IPriceFeed.sol": {
|
|
"content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity 0.8.11;\n\n/// @title IPriceFeed\n/// @notice Returns prices of underlying tokens\n/// @author Taken from: https://github.com/Rari-Capital/fuse-v1/blob/development/src/oracles/BasePriceOracle.sol\ninterface IPriceFeed {\n /// @notice Get the price of an underlying asset.\n /// @param underlying The underlying asset to get the price of.\n /// @return price The underlying asset price in ETH as a mantissa (scaled by 1e18).\n /// Zero means the price is unavailable.\n function price(address underlying) external view returns (uint256 price);\n}\n"
|
|
}
|
|
},
|
|
"settings": {
|
|
"optimizer": {
|
|
"enabled": true,
|
|
"runs": 15000
|
|
},
|
|
"outputSelection": {
|
|
"*": {
|
|
"*": [
|
|
"evm.bytecode",
|
|
"evm.deployedBytecode",
|
|
"devdoc",
|
|
"userdoc",
|
|
"metadata",
|
|
"abi"
|
|
]
|
|
}
|
|
},
|
|
"metadata": {
|
|
"useLiteralContent": true
|
|
},
|
|
"libraries": {}
|
|
}
|
|
} |