Description:
Proxy contract enabling upgradeable smart contract patterns. Delegates calls to an implementation contract.
Blockchain: Ethereum
Source Code: View Code On The Blockchain
Solidity Source Code:
{{
"language": "Solidity",
"sources": {
"contracts/oracle/libraries/VaultAdapter.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;
import { Access } from "../../access/Access.sol";
import { IVault } from "../../interfaces/IVault.sol";
import { IVaultAdapter } from "../../interfaces/IVaultAdapter.sol";
import { VaultAdapterStorageUtils } from "../../storage/VaultAdapterStorageUtils.sol";
import { UUPSUpgradeable } from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
/// @title Vault Adapter
/// @author kexley, Cap Labs
/// @notice Market rates are sourced from the Vault
contract VaultAdapter is IVaultAdapter, UUPSUpgradeable, Access, VaultAdapterStorageUtils {
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
/// @inheritdoc IVaultAdapter
function initialize(address _accessControl) external initializer {
__Access_init(_accessControl);
__UUPSUpgradeable_init();
}
/// @inheritdoc IVaultAdapter
function rate(address _vault, address _asset) external returns (uint256 latestAnswer) {
UtilizationData storage utilizationData = getVaultAdapterStorage().utilizationData[_vault][_asset];
uint256 elapsed;
uint256 utilization;
if (block.timestamp > utilizationData.lastUpdate) {
uint256 index = IVault(_vault).currentUtilizationIndex(_asset);
elapsed = block.timestamp - utilizationData.lastUpdate;
/// Use average utilization except on the first rate update
if (elapsed != block.timestamp) {
utilization = (index - utilizationData.index) / elapsed;
} else {
utilization = IVault(_vault).utilization(_asset);
}
utilizationData.index = index;
utilizationData.lastUpdate = block.timestamp;
} else {
utilization = IVault(_vault).utilization(_asset);
}
latestAnswer = _applySlopes(_vault, _asset, utilization, elapsed);
}
/// @inheritdoc IVaultAdapter
function slopes(address _asset) external view returns (SlopeData memory) {
return getVaultAdapterStorage().slopeData[_asset];
}
/// @inheritdoc IVaultAdapter
function maxMultiplier() external view returns (uint256) {
return getVaultAdapterStorage().maxMultiplier;
}
/// @inheritdoc IVaultAdapter
function minMultiplier() external view returns (uint256) {
return getVaultAdapterStorage().minMultiplier;
}
/// @inheritdoc IVaultAdapter
function multiplierRate() external view returns (uint256) {
return getVaultAdapterStorage().rate;
}
/// @inheritdoc IVaultAdapter
function setSlopes(address _asset, SlopeData memory _slopes) external checkAccess(this.setSlopes.selector) {
if (_slopes.kink >= 1e27 || _slopes.kink == 0) revert InvalidKink();
getVaultAdapterStorage().slopeData[_asset] = _slopes;
emit SetSlopes(_asset, _slopes);
}
/// @inheritdoc IVaultAdapter
function setLimits(uint256 _maxMultiplier, uint256 _minMultiplier, uint256 _rate)
external
checkAccess(this.setLimits.selector)
{
VaultAdapterStorage storage $ = getVaultAdapterStorage();
$.maxMultiplier = _maxMultiplier;
$.minMultiplier = _minMultiplier;
$.rate = _rate;
emit SetLimits(_maxMultiplier, _minMultiplier, _rate);
}
/// @dev Interest is applied according to where on the slope the current utilization is and the
/// multiplier depends on the duration and distance the utilization is from the kink point.
/// All utilization values, kinks, and multipliers are in ray (1e27)
/// @param _vault Vault address
/// @param _asset Asset address
/// @param _utilization Utilization ratio in ray (1e27)
/// @param _elapsed Length of time at the utilization
/// @return interestRate Interest rate in ray (1e27)
function _applySlopes(address _vault, address _asset, uint256 _utilization, uint256 _elapsed)
internal
returns (uint256 interestRate)
{
VaultAdapterStorage storage $ = getVaultAdapterStorage();
UtilizationData storage utilizationData = $.utilizationData[_vault][_asset];
SlopeData memory _slopes = $.slopeData[_asset];
if (_utilization > _slopes.kink) {
uint256 excess = _utilization - _slopes.kink;
utilizationData.multiplier = utilizationData.multiplier
* (1e27 + (1e27 * excess / (1e27 - _slopes.kink)) * _elapsed * $.rate / 1e27) / 1e27;
if (utilizationData.multiplier > $.maxMultiplier) {
utilizationData.multiplier = $.maxMultiplier;
}
interestRate = (_slopes.slope0 + (_slopes.slope1 * excess / 1e27)) * utilizationData.multiplier / 1e27;
} else {
utilizationData.multiplier = utilizationData.multiplier * 1e27
/ (1e27 + (1e27 * (_slopes.kink - _utilization) / _slopes.kink) * _elapsed * $.rate / 1e27);
if (utilizationData.multiplier < $.minMultiplier) {
utilizationData.multiplier = $.minMultiplier;
}
interestRate = (_slopes.slope0 * _utilization / _slopes.kink) * utilizationData.multiplier / 1e27;
}
}
/// @inheritdoc UUPSUpgradeable
function _authorizeUpgrade(address) internal view override checkAccess(bytes4(0)) { }
}
"
},
"contracts/access/Access.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;
import { IAccess } from "../interfaces/IAccess.sol";
import { IAccessControl } from "../interfaces/IAccessControl.sol";
import { AccessStorageUtils } from "../storage/AccessStorageUtils.sol";
import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
/// @title Access
/// @author kexley, Cap Labs
/// @notice Inheritable access
abstract contract Access is IAccess, Initializable, AccessStorageUtils {
/// @dev Check caller has permissions for a function, revert if call is not allowed
/// @param _selector Function selector
modifier checkAccess(bytes4 _selector) {
_checkAccess(_selector);
_;
}
/// @dev Initialize the access control address
/// @param _accessControl Access control address
function __Access_init(address _accessControl) internal onlyInitializing {
__Access_init_unchained(_accessControl);
}
/// @dev Initialize unchained
/// @param _accessControl Access control address
function __Access_init_unchained(address _accessControl) internal onlyInitializing {
getAccessStorage().accessControl = _accessControl;
}
/// @dev Check caller has access to a function, revert overwise
/// @param _selector Function selector
function _checkAccess(bytes4 _selector) internal view {
bool hasAccess =
IAccessControl(getAccessStorage().accessControl).checkAccess(_selector, address(this), msg.sender);
if (!hasAccess) revert AccessDenied();
}
}
"
},
"contracts/interfaces/IVault.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;
import { EnumerableSet } from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
/// @title Vault interface for storing the backing for cTokens
/// @author kexley, Cap Labs
/// @notice Interface for the Vault contract which handles supplies, borrows and utilization tracking
interface IVault {
/// @dev Storage for the vault
/// @param assets List of assets
/// @param totalSupplies Total supplies of an asset
/// @param totalBorrows Total borrows of an asset
/// @param utilizationIndex Utilization index of an asset
/// @param lastUpdate Last update time of an asset
/// @param paused Pause state of an asset
/// @param insuranceFund Insurance fund address
struct VaultStorage {
EnumerableSet.AddressSet assets;
mapping(address => uint256) totalSupplies;
mapping(address => uint256) totalBorrows;
mapping(address => uint256) utilizationIndex;
mapping(address => uint256) lastUpdate;
mapping(address => bool) paused;
address insuranceFund;
}
/// @dev Parameters for minting or burning
/// @param asset Asset to mint or burn
/// @param amountIn Amount of asset to use in the minting or burning
/// @param amountOut Amount of cap token to mint or burn
/// @param minAmountOut Minimum amount to mint or burn
/// @param receiver Receiver of the minting or burning
/// @param deadline Deadline of the tx
/// @param fee Fee paid to the insurance fund
struct MintBurnParams {
address asset;
uint256 amountIn;
uint256 amountOut;
uint256 minAmountOut;
address receiver;
uint256 deadline;
uint256 fee;
}
/// @dev Parameters for redeeming
/// @param amountIn Amount of cap token to burn
/// @param amountsOut Amounts of assets to withdraw
/// @param minAmountsOut Minimum amounts of assets to withdraw
/// @param receiver Receiver of the withdrawal
/// @param deadline Deadline of the tx
/// @param fees Fees paid to the insurance fund
struct RedeemParams {
uint256 amountIn;
uint256[] amountsOut;
uint256[] minAmountsOut;
address receiver;
uint256 deadline;
uint256[] fees;
}
/// @dev Parameters for borrowing
/// @param asset Asset to borrow
/// @param amount Amount of asset to borrow
/// @param receiver Receiver of the borrow
struct BorrowParams {
address asset;
uint256 amount;
address receiver;
}
/// @dev Parameters for repaying
/// @param asset Asset to repay
/// @param amount Amount of asset to repay
struct RepayParams {
address asset;
uint256 amount;
}
/// @notice Mint the cap token using an asset
/// @dev This contract must have approval to move asset from msg.sender
/// @param _asset Whitelisted asset to deposit
/// @param _amountIn Amount of asset to use in the minting
/// @param _minAmountOut Minimum amount to mint
/// @param _receiver Receiver of the minting
/// @param _deadline Deadline of the tx
function mint(address _asset, uint256 _amountIn, uint256 _minAmountOut, address _receiver, uint256 _deadline)
external
returns (uint256 amountOut);
/// @notice Burn the cap token for an asset
/// @dev Asset is withdrawn from the reserve or divested from the underlying vault
/// @param _asset Asset to withdraw
/// @param _amountIn Amount of cap token to burn
/// @param _minAmountOut Minimum amount out to receive
/// @param _receiver Receiver of the withdrawal
/// @param _deadline Deadline of the tx
function burn(address _asset, uint256 _amountIn, uint256 _minAmountOut, address _receiver, uint256 _deadline)
external
returns (uint256 amountOut);
/// @notice Redeem the Cap token for a bundle of assets
/// @dev Assets are withdrawn from the reserve or divested from the underlying vault
/// @param _amountIn Amount of Cap token to burn
/// @param _minAmountsOut Minimum amounts of assets to withdraw
/// @param _receiver Receiver of the withdrawal
/// @param _deadline Deadline of the tx
/// @return amountsOut Amount of assets withdrawn
function redeem(uint256 _amountIn, uint256[] calldata _minAmountsOut, address _receiver, uint256 _deadline)
external
returns (uint256[] memory amountsOut);
/// @notice Borrow an asset
/// @dev Whitelisted agents can borrow any amount, LTV is handled by Agent contracts
/// @param _asset Asset to borrow
/// @param _amount Amount of asset to borrow
/// @param _receiver Receiver of the borrow
function borrow(address _asset, uint256 _amount, address _receiver) external;
/// @notice Repay an asset
/// @param _asset Asset to repay
/// @param _amount Amount of asset to repay
function repay(address _asset, uint256 _amount) external;
/// @notice Add an asset to the vault list
/// @param _asset Asset address
function addAsset(address _asset) external;
/// @notice Remove an asset from the vault list
/// @param _asset Asset address
function removeAsset(address _asset) external;
/// @notice Pause an asset
/// @param _asset Asset address
function pauseAsset(address _asset) external;
/// @notice Unpause an asset
/// @param _asset Asset address
function unpauseAsset(address _asset) external;
/// @notice Pause all protocol operations
function pauseProtocol() external;
/// @notice Unpause all protocol operations
function unpauseProtocol() external;
/// @notice Set the insurance fund
/// @param _insuranceFund Insurance fund address
function setInsuranceFund(address _insuranceFund) external;
/// @notice Rescue an unsupported asset
/// @param _asset Asset to rescue
/// @param _receiver Receiver of the rescue
function rescueERC20(address _asset, address _receiver) external;
/// @notice Get the list of assets supported by the vault
/// @return assetList List of assets
function assets() external view returns (address[] memory assetList);
/// @notice Get the total supplies of an asset
/// @param _asset Asset address
/// @return totalSupply Total supply
function totalSupplies(address _asset) external view returns (uint256 totalSupply);
/// @notice Get the total borrows of an asset
/// @param _asset Asset address
/// @return totalBorrow Total borrow
function totalBorrows(address _asset) external view returns (uint256 totalBorrow);
/// @notice Get the pause state of an asset
/// @param _asset Asset address
/// @return isPaused Pause state
function paused(address _asset) external view returns (bool isPaused);
/// @notice Available balance to borrow
/// @param _asset Asset to borrow
/// @return amount Amount available
function availableBalance(address _asset) external view returns (uint256 amount);
/// @notice Utilization rate of an asset
/// @dev Utilization scaled by 1e27
/// @param _asset Utilized asset
/// @return ratio Utilization ratio
function utilization(address _asset) external view returns (uint256 ratio);
/// @notice Up to date cumulative utilization index of an asset
/// @dev Utilization scaled by 1e27
/// @param _asset Utilized asset
/// @return index Utilization ratio index
function currentUtilizationIndex(address _asset) external view returns (uint256 index);
/// @notice Get the insurance fund
/// @return insuranceFund Insurance fund
function insuranceFund() external view returns (address);
}
"
},
"contracts/interfaces/IVaultAdapter.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;
/// @title Vault Adapter
/// @author kexley, Cap Labs
/// @notice Utilization rates are sourced from the Vault
interface IVaultAdapter {
/// @dev Storage for the vault adapter
/// @param slopeData Slope data for an asset
/// @param utilizationData Utilization data for an asset
/// @param maxMultiplier Maximum slope multiplier
/// @param minMultiplier Minimum slope multiplier
/// @param rate Rate at which the multiplier shifts
struct VaultAdapterStorage {
mapping(address => SlopeData) slopeData;
mapping(address => mapping(address => UtilizationData)) utilizationData;
uint256 maxMultiplier;
uint256 minMultiplier;
uint256 rate;
}
/// @dev Slope data for an asset
/// @param kink Kink point
/// @param slope0 Slope before kink
/// @param slope1 Slope after kink
struct SlopeData {
uint256 kink;
uint256 slope0;
uint256 slope1;
}
/// @dev Slope data for an asset
/// @param multiplier Multiplier for the asset
/// @param index Index of the asset
/// @param lastUpdate Last updated timestamp
struct UtilizationData {
uint256 multiplier;
uint256 index;
uint256 lastUpdate;
}
/// @notice Emitted when slopes are set
/// @param _asset Asset address
/// @param _slopes Slope data
event SetSlopes(address indexed _asset, SlopeData _slopes);
/// @notice Emitted when limits are set
/// @param _maxMultiplier Maximum slope multiplier
/// @param _minMultiplier Minimum slope multiplier
/// @param _rate Rate at which the multiplier shifts
event SetLimits(uint256 _maxMultiplier, uint256 _minMultiplier, uint256 _rate);
/// @dev Invalid kink
error InvalidKink();
/// @notice Initialize the vault adapter
/// @param _accessControl Access control
function initialize(address _accessControl) external;
/// @notice Fetch borrow rate for an asset from the Vault
/// @param _vault Vault address
/// @param _asset Asset to fetch rate for
/// @return latestAnswer Borrow rate
function rate(address _vault, address _asset) external returns (uint256 latestAnswer);
/// @notice Fetch slopes for an asset
/// @param _asset Asset to fetch slopes for
/// @return slopes Slope data
function slopes(address _asset) external view returns (SlopeData memory slopes);
/// @notice Fetch maximum multiplier
/// @return maxMultiplier Maximum multiplier
function maxMultiplier() external view returns (uint256 maxMultiplier);
/// @notice Fetch minimum multiplier
/// @return minMultiplier Minimum multiplier
function minMultiplier() external view returns (uint256 minMultiplier);
/// @notice Fetch the rate at which the multiplier shifts
/// @return multiplierRate Multiplier rate
function multiplierRate() external view returns (uint256 multiplierRate);
/// @notice Set utilization slopes for an asset
/// @param _asset Asset address
/// @param _slopes Slope data
function setSlopes(address _asset, SlopeData memory _slopes) external;
/// @notice Set limits for the utilization multiplier
/// @param _maxMultiplier Maximum slope multiplier
/// @param _minMultiplier Minimum slope multiplier
/// @param _rate Rate at which the multiplier shifts
function setLimits(uint256 _maxMultiplier, uint256 _minMultiplier, uint256 _rate) external;
}
"
},
"contracts/storage/VaultAdapterStorageUtils.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;
import { IVaultAdapter } from "../interfaces/IVaultAdapter.sol";
/// @title VaultAdapterStorageUtils
/// @author kexley, Cap Labs
/// @notice Storage utilities for VaultAdapter contract
abstract contract VaultAdapterStorageUtils {
/// @dev keccak256(abi.encode(uint256(keccak256("cap.storage.VaultAdapter")) - 1)) & ~bytes32(uint256(0xff))
bytes32 constant VaultAdapterStorageLocation = 0x2b1d5d801322d1007f654ac87d8072a5f5ca4203517edc869ef2aa54addad600;
/// @notice Get vault adapter storage
/// @return $ Storage pointer
function getVaultAdapterStorage() internal pure returns (IVaultAdapter.VaultAdapterStorage storage $) {
assembly {
$.slot := VaultAdapterStorageLocation
}
}
}
"
},
"node_modules/@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.22;
import {IERC1822Proxiable} from "@openzeppelin/contracts/interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol";
import {Initializable} from "./Initializable.sol";
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*/
abstract contract UUPSUpgradeable is Initializable, IERC1822Proxiable {
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
address private immutable __self = address(this);
/**
* @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
* and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
* while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
* If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must
* be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
* during an upgrade.
*/
string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";
/**
* @dev The call is from an unauthorized context.
*/
error UUPSUnauthorizedCallContext();
/**
* @dev The storage `slot` is unsupported as a UUID.
*/
error UUPSUnsupportedProxiableUUID(bytes32 slot);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC-1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC-1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
_checkProxy();
_;
}
/**
* @dev Check that the execution is not being performed through a delegate call. This allows a function to be
* callable on the implementing contract but not through proxies.
*/
modifier notDelegated() {
_checkNotDelegated();
_;
}
function __UUPSUpgradeable_init() internal onlyInitializing {
}
function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
}
/**
* @dev Implementation of the ERC-1822 {proxiableUUID} function. This returns the storage slot used by the
* implementation. It is used to validate the implementation's compatibility when performing an upgrade.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
*/
function proxiableUUID() external view virtual notDelegated returns (bytes32) {
return ERC1967Utils.IMPLEMENTATION_SLOT;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*
* @custom:oz-upgrades-unsafe-allow-reachable delegatecall
*/
function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, data);
}
/**
* @dev Reverts if the execution is not performed via delegatecall or the execution
* context is not of a proxy with an ERC-1967 compliant implementation pointing to self.
* See {_onlyProxy}.
*/
function _checkProxy() internal view virtual {
if (
address(this) == __self || // Must be called through delegatecall
ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
) {
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Reverts if the execution is performed via delegatecall.
* See {notDelegated}.
*/
function _checkNotDelegated() internal view virtual {
if (address(this) != __self) {
// Must not be called through delegatecall
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
/**
* @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
*
* As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
* is expected to be the implementation slot in ERC-1967.
*
* Emits an {IERC1967-Upgraded} event.
*/
function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
revert UUPSUnsupportedProxiableUUID(slot);
}
ERC1967Utils.upgradeToAndCall(newImplementation, data);
} catch {
// The implementation is not UUPS
revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
}
}
}
"
},
"contracts/interfaces/IAccess.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;
/// @title IAccess
/// @author kexley, Cap Labs
/// @notice Interface for Access contract
interface IAccess {
/// @dev Access storage
/// @param accessControl Access control address
struct AccessStorage {
address accessControl;
}
/// @notice Access is denied for the caller
error AccessDenied();
}
"
},
"contracts/interfaces/IAccessControl.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;
/// @title IAccessControl
/// @author kexley, Cap Labs
/// @notice Interface for granular access control system that manages permissions for specific function selectors on contracts
interface IAccessControl {
/// @notice Error thrown when trying to revoke own revocation role
error CannotRevokeSelf();
/// @notice Initialize the access control system with a default admin
/// @param _admin Address to be granted the default admin role and initial access management permissions
function initialize(address _admin) external;
/// @notice Grant access to a specific method on a contract
/// @param _selector Function selector (4-byte identifier) of the method to grant access to
/// @param _contract Address of the contract containing the method
/// @param _address Address to grant access to
function grantAccess(bytes4 _selector, address _contract, address _address) external;
/// @notice Revoke access to a specific method on a contract
/// @param _selector Function selector (4-byte identifier) of the method to revoke access from
/// @param _contract Address of the contract containing the method
/// @param _address Address to revoke access from
function revokeAccess(bytes4 _selector, address _contract, address _address) external;
/// @notice Check if a specific method access is granted to an address
/// @param _selector Function selector (4-byte identifier) of the method to check
/// @param _contract Address of the contract containing the method
/// @param _caller Address to check permissions for
/// @return hasAccess True if access is granted, false otherwise
function checkAccess(bytes4 _selector, address _contract, address _caller) external view returns (bool hasAccess);
/// @notice Get the role identifier for a specific function selector on a contract
/// @dev The role identifier is a unique identifier derived packing the selector and contract address
/// @param _selector Function selector (4-byte identifier) of the method
/// @param _contract Address of the contract containing the method
/// @return roleId Unique role identifier derived from the selector and contract address
function role(bytes4 _selector, address _contract) external pure returns (bytes32 roleId);
}
"
},
"contracts/storage/AccessStorageUtils.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;
import { IAccess } from "../interfaces/IAccess.sol";
/// @title Access Storage Utils
/// @author kexley, Cap Labs
/// @notice Storage utilities for access control
abstract contract AccessStorageUtils {
/// @dev keccak256(abi.encode(uint256(keccak256("cap.storage.Access")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant AccessStorageLocation = 0xb413d65cb88f23816c329284a0d3eb15a99df7963ab7402ade4c5da22bff6b00;
/// @dev Get access storage
/// @return $ Storage pointer
function getAccessStorage() internal pure returns (IAccess.AccessStorage storage $) {
assembly {
$.slot := AccessStorageLocation
}
}
}
"
},
"node_modules/@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.20;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Storage of the initializable contract.
*
* It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
* when using with upgradeable contracts.
*
* @custom:storage-location erc7201:openzeppelin.storage.Initializable
*/
struct InitializableStorage {
/**
* @dev Indicates that the contract has been initialized.
*/
uint64 _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool _initializing;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;
/**
* @dev The contract is already initialized.
*/
error InvalidInitialization();
/**
* @dev The contract is not initializing.
*/
error NotInitializing();
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint64 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
* number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
* production.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
// Cache values to avoid duplicated sloads
bool isTopLevelCall = !$._initializing;
uint64 initialized = $._initialized;
// Allowed calls:
// - initialSetup: the contract is not in the initializing state and no previous version was
// initialized
// - construction: the contract is initialized at version 1 (no reininitialization) and the
// current contract is just being deployed
bool initialSetup = initialized == 0 && isTopLevelCall;
bool construction = initialized == 1 && address(this).code.length == 0;
if (!initialSetup && !construction) {
revert InvalidInitialization();
}
$._initialized = 1;
if (isTopLevelCall) {
$._initializing = true;
}
_;
if (isTopLevelCall) {
$._initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint64 version) {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing || $._initialized >= version) {
revert InvalidInitialization();
}
$._initialized = version;
$._initializing = true;
_;
$._initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
_checkInitializing();
_;
}
/**
* @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
*/
function _checkInitializing() internal view virtual {
if (!_isInitializing()) {
revert NotInitializing();
}
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing) {
revert InvalidInitialization();
}
if ($._initialized != type(uint64).max) {
$._initialized = type(uint64).max;
emit Initialized(type(uint64).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint64) {
return _getInitializableStorage()._initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _getInitializableStorage()._initializing;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
assembly {
$.slot := INITIALIZABLE_STORAGE
}
}
}
"
},
"node_modules/@openzeppelin/contracts/utils/structs/EnumerableSet.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
pragma solidity ^0.8.20;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```solidity
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*
* [WARNING]
* ====
* Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
* unusable.
* See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
*
* In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
* array of EnumerableSet.
* ====
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position is the index of the value in the `values` array plus 1.
// Position 0 is used to mean a value is not in the set.
mapping(bytes32 value => uint256) _positions;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._positions[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We cache the value's position to prevent multiple reads from the same storage slot
uint256 position = set._positions[value];
if (position != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 valueIndex = position - 1;
uint256 lastIndex = set._values.length - 1;
if (valueIndex != lastIndex) {
bytes32 lastValue = set._values[lastIndex];
// Move the lastValue to the index where the value to delete is
set._values[valueIndex] = lastValue;
// Update the tracked position of the lastValue (that was just moved)
set._positions[lastValue] = position;
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the tracked position for the deleted slot
delete set._positions[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._positions[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
bytes32[] memory store = _values(set._inner);
bytes32[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
}
"
},
"node_modules/@openzeppelin/contracts/interfaces/draft-IERC1822.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/draft-IERC1822.sol)
pragma solidity ^0.8.20;
/**
* @dev ERC-1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
* proxy whose upgrades are fully controlled by the current implementation.
*/
interface IERC1822Proxiable {
/**
* @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
* address.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy.
*/
function proxiableUUID() external view returns (bytes32);
}
"
},
"node_modules/@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (proxy/ERC1967/ERC1967Utils.sol)
pragma solidity ^0.8.22;
import {IBeacon} from "../beacon/IBeacon.sol";
import {IERC1967} from "../../interfaces/IERC1967.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";
/**
* @dev This library provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots.
*/
library ERC1967Utils {
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev The `implementation` of the proxy is invalid.
*/
error ERC1967InvalidImplementation(address implementation);
/**
* @dev The `admin` of the proxy is invalid.
*/
error ERC1967InvalidAdmin(address admin);
/**
* @dev The `beacon` of the proxy is invalid.
*/
error ERC1967InvalidBeacon(address beacon);
/**
* @dev An upgrade function sees `msg.value > 0` that may be lost.
*/
error ERC1967NonPayable();
/**
* @dev Returns the current implementation address.
*/
function getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the ERC-1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
if (newImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(newImplementation);
}
StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Performs implementation upgrade with additional setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) internal {
_setImplementation(newImplementation);
emit IERC1967.Upgraded(newImplementation);
if (data.length > 0) {
Address.functionDelegateCall(newImplementation, data);
} else {
_checkNonPayable();
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Returns the current admin.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using
* the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
*/
function getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the ERC-1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
if (newAdmin == address(0)) {
revert ERC1967InvalidAdmin(address(0));
}
StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {IERC1967-AdminChanged} event.
*/
function changeAdmin(address newAdmin) internal {
emit IERC1967.AdminChanged(getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Returns the current beacon.
*/
function getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the ERC-1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
if (newBeacon.code.length == 0) {
revert ERC1967InvalidBeacon(newBeacon);
}
StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;
address beaconImplementation = IBeacon(newBeacon).implementation();
if (beaconImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(beaconImplementation);
}
}
/**
* @dev Change the beacon and trigger a setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-BeaconUpgraded} event.
*
* CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
* it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
* efficiency.
*/
function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
_setBeacon(newBeacon);
emit IERC1967.BeaconUpgraded(newBeacon);
if (data.length > 0) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
} else {
_checkNonPayable();
}
}
/**
* @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
* if an upgrade doesn't perform an initialization call.
*/
function _checkNonPayable() private {
if (msg.value > 0) {
revert ERC1967NonPayable();
}
}
}
"
},
"node_modules/@openzeppelin/contracts/proxy/beacon/IBeacon.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.20;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeacon {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {UpgradeableBeacon} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
"
},
"node_modules/@openzeppelin/contracts/interfaces/IERC1967.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC1967.sol)
pragma solidity ^0.8.20;
/**
* @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
*/
interface IERC1967 {
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Emitted when the beacon is changed.
*/
event BeaconUpgraded(address indexed beacon);
}
"
},
"node_modules/@openzeppelin/contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (utils/Address.sol)
pragma solidity ^0.8.20;
import {Errors} from "./Errors.sol";
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @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.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert Errors.InsufficientBalance(address(this).balance, amount);
}
(bool success, bytes memory returndata) = recipient.call{value: amount}("");
if (!success) {
_revert(returndata);
}
}
/**
* @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 or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {Errors.FailedCall} error.
*
* 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.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @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`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert Errors.I
Submitted on: 2025-09-24 16:19:57
Comments
Log in to comment.
No comments yet.