Description:
Multi-signature wallet contract requiring multiple confirmations for transaction execution.
Blockchain: Ethereum
Source Code: View Code On The Blockchain
Solidity Source Code:
{{
"language": "Solidity",
"sources": {
"src/ERC20VaultImplementation.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "./UpgradeableBaseVault.sol";
import "./IVaultInitializer.sol";
contract ERC20VaultImplementation is UpgradeableBaseVault, IVaultInitializer {
using SafeERC20 for IERC20;
bool private initialized;
function initialize(
VaultConfig calldata cfg,
address _underlying,
string calldata _name,
string calldata _symbol,
address _owner,
address _principal,
uint256 _initialAmount,
address _creator
) external payable override {
if (initialized) revert ALREADY_INITIALIZED();
initialized = true;
name = _name;
symbol = _symbol;
_status = _NOT_ENTERED;
_paused = false;
underlying = _underlying;
isEtherPool = false;
principal = _principal;
poolCreator = _creator;
depositFeeBps = cfg.depositFeeBps;
withdrawalFeeBps = cfg.withdrawalFeeBps;
projectFeeBps = cfg.projectFeeBps;
reserveRatioBps = cfg.reserveRatioBps;
lossCapBps = cfg.lossCapBps;
maxDepositPercentageBps = cfg.maxDepositPercentageBps;
bootstrapLock = cfg.bootstrapLock;
discountTierCount = cfg.discountTierCount;
for (uint8 i = 0; i < 4; i++) {
discountDurations[i] = cfg.discountDurations[i];
discountBps[i] = cfg.discountBps[i];
}
tvlFirstElbow = cfg.tvlFirstElbow;
tvlSecondElbow = cfg.tvlSecondElbow;
slope1Bps = cfg.slope1Bps;
maxFeeBps = cfg.maxFeeBps;
withdrawCooldown = cfg.withdrawCooldown;
maxWithdrawPenaltyBps = cfg.maxWithdrawPenaltyBps;
fastExitWindow = cfg.fastExitWindow;
fastExitFloorBps = cfg.fastExitFloorBps;
vaultStart = block.timestamp;
depositsStopped = false;
_transferOwnership(_owner);
seeder = _owner;
// Bootstrap with initial amount - mint shares based on actual assets
uint256 initialAssets = _totalAssets();
if (initialAssets > 0) {
_mint(_owner, initialAssets);
lastExchangeRate = SCALE;
}
}
function deposit(uint256 amount, address receiver, uint256 minShares)
external
payable
nonReentrant
whenNotPaused
whenDepositsAllowed
override
{
if (receiver != msg.sender) revert TRANSFERS_DISABLED();
if (msg.value != 0) revert UNEXPECTED_ETH();
if (amount == 0) revert ZERO_AMOUNT();
uint256 before = IERC20(underlying).balanceOf(address(this));
IERC20(underlying).safeTransferFrom(msg.sender, address(this), amount);
uint256 afterBal = IERC20(underlying).balanceOf(address(this));
uint256 received = afterBal - before;
// Allow first deposit even if cap is configured
if (maxDepositPercentageBps > 0 && before > 0) {
if (received > (before * maxDepositPercentageBps) / BPS) {
revert EXCEEDS_MAX_DEPOSIT();
}
}
uint16 effFeeBps = _feeBpsAtTVL(afterBal); // ✅ after-deposit TVL
uint256 net = received - (received * effFeeBps) / BPS;
uint256 shares = totalSupply() == 0 ? net : (net * totalSupply()) / before;
if (shares < minShares) revert SLIPPAGE_EXCEEDED();
_mint(receiver, shares);
lastDepositTimestamp[receiver] = block.timestamp;
_updateExchangeRate();
}
function withdraw(uint256 shares, address receiver) external override nonReentrant whenNotPaused {
if (msg.sender == seeder && block.timestamp < vaultStart + bootstrapLock) {
revert SEEDER_LOCKED();
}
if (shares == 0) revert ZERO_SHARES();
if (receiver == address(0)) revert("ERC20: transfer to the zero address");
uint256 assetsBefore = _totalAssets();
uint256 gross = shares * assetsBefore / totalSupply();
uint256 fee = gross * withdrawalFeeBps / BPS;
uint256 proj = gross * projectFeeBps / BPS;
// Use new effective penalty calculation
VaultConfig memory cfg = VaultConfig({
depositFeeBps: depositFeeBps,
withdrawalFeeBps: withdrawalFeeBps,
projectFeeBps: projectFeeBps,
reserveRatioBps: reserveRatioBps,
lossCapBps: lossCapBps,
maxDepositPercentageBps: maxDepositPercentageBps,
bootstrapLock: bootstrapLock,
discountTierCount: discountTierCount,
discountDurations: discountDurations,
discountBps: discountBps,
tvlFirstElbow: tvlFirstElbow,
tvlSecondElbow: tvlSecondElbow,
slope1Bps: slope1Bps,
maxFeeBps: maxFeeBps,
withdrawCooldown: withdrawCooldown,
maxWithdrawPenaltyBps: maxWithdrawPenaltyBps,
fastExitWindow: fastExitWindow,
fastExitFloorBps: fastExitFloorBps
});
uint256 penaltyBps = _effectivePenaltyBps(cfg, msg.sender);
uint256 penaltyAmount = gross * penaltyBps / BPS;
uint256 net = gross - fee - proj - penaltyAmount;
uint256 afterAssets = assetsBefore - net - proj;
if (afterAssets * BPS < reserveRatioBps * assetsBefore) revert RESERVE_TOO_LOW();
_burn(msg.sender, shares);
_send(receiver, net);
if (proj > 0) {
uint256 creatorShare = proj / 2;
uint256 projectShare = proj - creatorShare; // Handles odd amounts
// Send to project address first (more trusted)
_send(PROJECT_FEE_ADDRESS, projectShare);
// Send to creator second (potentially untrusted)
// This already uses nonReentrant modifier, but be extra careful
_send(poolCreator, creatorShare);
}
_updateExchangeRate();
}
}"
},
"src/UpgradeableBaseVault.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol";
import "lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol";
import "./VaultConfig.sol";
import "./Errors.sol";
/**
* @title UpgradeableBaseVault
* @dev Base vault implementation for EIP-1167 proxy pattern
* This implements ERC20 functionality manually to allow initialization after deployment
*/
abstract contract UpgradeableBaseVault {
using SafeERC20 for IERC20;
// ERC20 Storage
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string public name;
string public symbol;
uint8 public constant decimals = 18;
// Ownable Storage
address private _owner;
// Seeder tracking for bootstrap lock
address public seeder;
// ReentrancyGuard Storage
uint256 internal constant _NOT_ENTERED = 1;
uint256 internal constant _ENTERED = 2;
uint256 internal _status;
// Pausable Storage
bool internal _paused;
// Vault specific storage
address public constant PROJECT_FEE_ADDRESS = 0xB88276aB75113Eb8191B0e0A5D48f36B05AE6eD4;
address public underlying;
address public principal;
address public poolCreator;
bool public isEtherPool;
bool public depositsStopped;
uint16 public depositFeeBps;
uint16 public withdrawalFeeBps;
uint16 public projectFeeBps;
uint16 public reserveRatioBps;
uint16 public lossCapBps;
uint16 public maxDepositPercentageBps;
uint32 public bootstrapLock;
uint8 public discountTierCount;
uint32[4] public discountDurations;
uint16[4] public discountBps;
uint256 public tvlFirstElbow;
uint256 public tvlSecondElbow;
uint16 public slope1Bps;
uint16 public maxFeeBps;
uint32 public withdrawCooldown;
uint16 public maxWithdrawPenaltyBps;
uint32 public fastExitWindow;
uint16 public fastExitFloorBps;
uint256 public vaultStart;
uint256 public lastExchangeRate;
mapping(address => uint256) public lastDepositTimestamp;
// Events
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event Paused(address account);
event Unpaused(address account);
event Donated(address indexed caller, uint256 amount);
event DepositsStopped(address indexed principal);
event DepositsResumed(address indexed principal);
event PoolUnpaused(address indexed principal);
// Modifiers
modifier onlyOwner() {
if (owner() != msg.sender) revert NOT_OWNER();
_;
}
modifier nonReentrant() {
if (_status == _ENTERED) revert REENTRANT_CALL();
_status = _ENTERED;
_;
_status = _NOT_ENTERED;
}
modifier whenNotPaused() {
if (paused()) revert PAUSED();
_;
}
modifier whenPaused() {
if (!paused()) revert NOT_PAUSED();
_;
}
modifier onlyPrincipal() {
if (msg.sender != principal) revert NOT_PRINCIPAL();
_;
}
modifier whenDepositsAllowed() {
if (depositsStopped) revert DEPOSITS_STOPPED();
_;
}
// ERC20 Functions
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
function transfer(address to, uint256 amount) public returns (bool) {
address tokenOwner = msg.sender;
_transfer(tokenOwner, to, amount);
return true;
}
function allowance(address tokenOwner, address spender) public view returns (uint256) {
return _allowances[tokenOwner][spender];
}
function approve(address spender, uint256 amount) public returns (bool) {
address tokenOwner = msg.sender;
_approve(tokenOwner, spender, amount);
return true;
}
function transferFrom(address from, address to, uint256 amount) public returns (bool) {
address spender = msg.sender;
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
// Ownable Functions
function owner() public view returns (address) {
return _owner;
}
function renounceOwnership() public onlyOwner {
_transferOwnership(address(0));
}
function transferOwnership(address newOwner) public onlyOwner {
if (newOwner == address(0)) revert ZERO_ADDRESS_OWNER();
_transferOwnership(newOwner);
}
// Pausable Functions
function paused() public view returns (bool) {
return _paused;
}
// Internal functions
function _transfer(address from, address to, uint256 amount) internal {
if (from == address(0)) revert ZERO_ADDRESS_FROM();
if (to == address(0)) revert ZERO_ADDRESS_TO();
// Custom restriction: no transfers except mint/burn
if (!(from == address(0) || to == address(0))) revert TRANSFERS_DISABLED();
uint256 fromBalance = _balances[from];
if (fromBalance < amount) revert INSUFFICIENT_BALANCE();
unchecked {
_balances[from] = fromBalance - amount;
_balances[to] += amount;
}
emit Transfer(from, to, amount);
}
function _mint(address account, uint256 amount) internal {
if (account == address(0)) revert ZERO_ADDRESS_MINT();
_totalSupply += amount;
unchecked {
_balances[account] += amount;
}
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint256 amount) internal {
if (account == address(0)) revert ZERO_ADDRESS_BURN();
uint256 accountBalance = _balances[account];
if (accountBalance < amount) revert BURN_EXCEEDS_BALANCE();
unchecked {
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
}
emit Transfer(account, address(0), amount);
}
function _approve(address tokenOwner, address spender, uint256 amount) internal {
if (tokenOwner == address(0)) revert ZERO_ADDRESS_APPROVE_FROM();
if (spender == address(0)) revert ZERO_ADDRESS_APPROVE_TO();
_allowances[tokenOwner][spender] = amount;
emit Approval(tokenOwner, spender, amount);
}
function _spendAllowance(address tokenOwner, address spender, uint256 amount) internal {
uint256 currentAllowance = allowance(tokenOwner, spender);
if (currentAllowance != type(uint256).max) {
if (currentAllowance < amount) revert INSUFFICIENT_ALLOWANCE();
unchecked {
_approve(tokenOwner, spender, currentAllowance - amount);
}
}
}
function _transferOwnership(address newOwner) internal {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
function _pause() internal whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
function _unpause() internal whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
// Vault specific functions
function _totalAssets() internal view returns (uint256) {
return isEtherPool ? address(this).balance : IERC20(underlying).balanceOf(address(this));
}
function _send(address to, uint256 amount) internal {
if (isEtherPool) {
(bool ok,) = to.call{value: amount}("");
if (!ok) revert ETH_TRANSFER_FAIL();
} else {
IERC20(underlying).safeTransfer(to, amount);
}
}
function _updateExchangeRate() internal {
uint256 supply = totalSupply();
if (supply == 0) {
// No LPs → nothing to protect; let next deposit establish a fresh baseline.
lastExchangeRate = 0;
return;
}
uint256 newRate = (_totalAssets() * SCALE) / supply;
// Enforce loss cap only when LPs exist
if (
lastExchangeRate > 0 &&
newRate < lastExchangeRate &&
((lastExchangeRate - newRate) * BPS) / lastExchangeRate >= lossCapBps
) {
_pause();
}
lastExchangeRate = newRate;
}
function _currentDiscountBps() internal view returns (uint16) {
uint256 elapsed = block.timestamp - vaultStart;
for (uint8 i = 0; i < discountTierCount; i++) {
if (elapsed <= discountDurations[i]) return discountBps[i];
}
return 0;
}
function _feeBpsAtTVL(uint256 tvl) internal view returns (uint16) {
uint16 disc = _currentDiscountBps();
uint16 baseAfter = depositFeeBps > disc ? depositFeeBps - disc : 0;
return _calculateDynamicFee(tvl, baseAfter);
}
function _effectiveDepositFeeBps() internal view returns (uint16) {
uint256 currentTVL = _totalAssets();
return _feeBpsAtTVL(currentTVL);
}
function _calculateDynamicFee(uint256 tvl, uint16 baseFee) internal view returns (uint16) {
if (tvl < tvlFirstElbow) {
return baseFee;
}
if (tvl < tvlSecondElbow) {
uint256 tvlProgress = tvl - tvlFirstElbow;
uint256 tvlRange = tvlSecondElbow - tvlFirstElbow;
uint256 additionalFee = (slope1Bps * tvlProgress) / tvlRange;
uint256 totalFee = baseFee + additionalFee;
return totalFee > maxFeeBps ? maxFeeBps : uint16(totalFee);
}
uint256 cappedFee = baseFee + slope1Bps;
return cappedFee > maxFeeBps ? maxFeeBps : uint16(cappedFee);
}
// Withdrawal penalty helper functions
function _linearPenaltyBps(VaultConfig memory c, uint256 t) internal pure returns (uint256) {
if (t >= c.withdrawCooldown || c.withdrawCooldown == 0) return 0;
return uint256(c.maxWithdrawPenaltyBps) * (c.withdrawCooldown - t) / c.withdrawCooldown;
}
function _fastExitFloorBps(VaultConfig memory c, uint256 t) internal pure returns (uint256) {
return (t < c.fastExitWindow) ? c.fastExitFloorBps : 0;
}
function _effectivePenaltyBps(VaultConfig memory c, address user) internal view returns (uint256) {
uint256 t = block.timestamp - lastDepositTimestamp[user];
uint256 linear = _linearPenaltyBps(c, t);
uint256 floor = _fastExitFloorBps(c, t);
return linear > floor ? linear : floor; // pick the harsher, not both
}
function previewDepositFee(uint256 depositAmount) external view returns (uint256 feeAmount, uint16 feeBps) {
uint256 tvlAfter = _totalAssets() + depositAmount;
feeBps = _feeBpsAtTVL(tvlAfter);
feeAmount = (depositAmount * feeBps) / BPS;
}
function getCurrentFeeTier()
external
view
returns (
string memory tierName,
uint256 currentTVL,
uint16 currentFeeBps,
uint256 nextTierThreshold,
uint16 nextTierFeeBps
)
{
currentTVL = _totalAssets();
// What the depositor actually pays *today* (includes discount, dynamic elbow logic)
currentFeeBps = _effectiveDepositFeeBps();
// Derive baseAfter (depositFee minus current discount) to preview next tier consistently
uint16 disc = _currentDiscountBps();
uint16 baseAfter = depositFeeBps > disc ? depositFeeBps - disc : 0;
if (currentTVL < tvlFirstElbow) {
tierName = "Tier A (Early Stage)";
nextTierThreshold = tvlFirstElbow;
nextTierFeeBps = _calculateDynamicFee(nextTierThreshold, baseAfter);
} else if (currentTVL < tvlSecondElbow) {
tierName = "Tier B (Growth Stage)";
nextTierThreshold = tvlSecondElbow;
nextTierFeeBps = _calculateDynamicFee(nextTierThreshold, baseAfter);
} else {
tierName = "Tier C (Mature Stage)";
nextTierThreshold = type(uint256).max;
nextTierFeeBps = _calculateDynamicFee(nextTierThreshold, baseAfter);
}
}
// Public functions
function donate(uint256 amount) external payable nonReentrant whenDepositsAllowed {
if (isEtherPool) {
if (!(msg.value == amount && amount > 0)) revert BAD_ETH_AMT();
} else {
if (amount == 0) revert BAD_TOKEN_AMT();
IERC20(underlying).safeTransferFrom(msg.sender, address(this), amount);
}
_updateExchangeRate();
emit Donated(msg.sender, amount);
}
function stopPool() external onlyPrincipal {
if (depositsStopped) revert ALREADY_STOPPED();
depositsStopped = true;
emit DepositsStopped(principal);
}
function resumePool() external onlyPrincipal {
if (!depositsStopped) revert NOT_STOPPED();
depositsStopped = false;
emit DepositsResumed(principal);
}
function unpause() external onlyPrincipal {
_unpause();
emit PoolUnpaused(principal);
}
function deposit(uint256 amount, address receiver, uint256 minShares) external payable virtual;
function withdraw(uint256 shares, address receiver) external virtual;
}"
},
"src/IVaultInitializer.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "./VaultConfig.sol";
interface IVaultInitializer {
function initialize(
VaultConfig calldata cfg,
address underlying,
string calldata name,
string calldata symbol,
address owner,
address principal,
uint256 initialAmount,
address creator
) external payable;
}"
},
"lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 amount) external returns (bool);
}
"
},
"lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../extensions/IERC20Permit.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
* Revert on invalid signature.
*/
function safePermit(
IERC20Permit token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return
success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
}
}
"
},
"src/VaultConfig.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
uint256 constant BPS = 10_000;
uint256 constant SCALE = 1e18;
struct VaultConfig {
uint16 depositFeeBps;
uint16 withdrawalFeeBps;
uint16 projectFeeBps;
uint16 reserveRatioBps;
uint16 lossCapBps;
uint16 maxDepositPercentageBps;
uint32 bootstrapLock;
uint8 discountTierCount;
uint32[4] discountDurations;
uint16[4] discountBps;
uint256 tvlFirstElbow;
uint256 tvlSecondElbow;
uint16 slope1Bps;
uint16 maxFeeBps;
uint32 withdrawCooldown;
uint16 maxWithdrawPenaltyBps;
uint32 fastExitWindow;
uint16 fastExitFloorBps;
}"
},
"src/Errors.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
// Common custom errors for gas savings
error NOT_PRINCIPAL();
error DEPOSITS_STOPPED();
error ZERO_PRINCIPAL();
error ETH_TRANSFER_FAIL();
error BAD_ETH_AMT();
error BAD_TOKEN_AMT();
error ALREADY_STOPPED();
error NOT_STOPPED();
error TRANSFERS_DISABLED();
error UNEXPECTED_ETH();
error ZERO_AMOUNT();
error EXCEEDS_MAX_DEPOSIT();
error SLIPPAGE_EXCEEDED();
error ZERO_SHARES();
error RESERVE_TOO_LOW();
error INIT_ZERO();
error ZERO_TOKEN();
error INVALID_POOL_COUNT();
error PROTOCOL_FEE_TOO_LOW();
error PROTOCOL_FEE_TOO_HIGH();
error TRADING_FEE_TOO_LOW();
error TRADING_FEE_TOO_HIGH();
error INVALID_POOL();
error POOL_NOT_ETH();
error POOL_TOKEN_MISMATCH();
error MUST_SUM_TO_10000();
error STRATEGY_INACTIVE();
error SLIPPAGE_TOO_HIGH();
error BAD_MINSHARES_LEN();
error POOL_DEPOSITS_STOPPED();
error POOL_PAUSED();
error NO_POSITION();
error INVALID_PERCENTAGE();
error NO_TOKENS_RECEIVED();
error NO_TOKENS_RECEIVED_FOR_SWAP();
error ETH_FEE_TRANSFER_FAILED();
error ETH_TRANSFER_FAILED();
error MAX_FEE_TOO_HIGH();
error SLOPE_TOO_STEEP();
error INV_DEP_FEE();
error INV_WD_FEE();
error INV_PROJ_FEE();
error INV_RES_RATIO();
error INV_LOSS_CAP();
error INV_MAX_DEP_PCT();
error INV_COOLDOWN();
error INV_PENALTY();
error INV_FAST_EXIT_WINDOW();
error INV_FAST_EXIT_FLOOR();
error INV_TIER_CNT();
error INV_DUR_0();
error INV_DUR_SEQ();
error INV_DISC_BPS();
error INV_TVL_ELBOW_1();
error INV_TVL_ELBOW_2();
error INV_MAX_FEE();
error ZERO_ETH_AMOUNT();
error SEEDER_LOCKED();
error STRATEGY_FEE_TOO_LOW();
// Additional errors for require statement replacements
error ALREADY_INITIALIZED();
error FACTORY_ALREADY_SET();
error FACTORY_ZERO_ADDRESS();
error INVALID_ETHER_VAULT_IMPL();
error INVALID_ERC20_VAULT_IMPL();
error CLONE_FAILED();
error CLONE2_FAILED();
error NOT_OWNER();
error REENTRANT_CALL();
error PAUSED();
error NOT_PAUSED();
error ZERO_ADDRESS_OWNER();
error ZERO_ADDRESS_FROM();
error ZERO_ADDRESS_TO();
error INSUFFICIENT_BALANCE();
error ZERO_ADDRESS_MINT();
error ZERO_ADDRESS_BURN();
error BURN_EXCEEDS_BALANCE();
error ZERO_ADDRESS_APPROVE_FROM();
error ZERO_ADDRESS_APPROVE_TO();
error INSUFFICIENT_ALLOWANCE();
error TICK_OUT_OF_RANGE();
error ZERO_DENOMINATOR();
error MATH_OVERFLOW();
"
},
"lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
"
},
"lib/openzeppelin-contracts/contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
"
}
},
"settings": {
"remappings": [
"ds-test/=lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"forge-std/=lib/forge-std/src/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/",
"openzeppelin/=lib/openzeppelin-contracts/contracts/",
"v3-core/=lib/v3-core/",
"v3-periphery/=lib/v3-periphery/contracts/"
],
"optimizer": {
"enabled": true,
"runs": 200
},
"metadata": {
"useLiteralContent": false,
"bytecodeHash": "ipfs",
"appendCBOR": true
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"evmVersion": "cancun",
"viaIR": true
}
}}
Submitted on: 2025-10-16 17:42:13
Comments
Log in to comment.
No comments yet.