Overview
BERA Balance
BERA Value
$0.00More Info
Private Name Tags
ContractCreator
Loading...
Loading
This contract may be a proxy contract. Click on More Options and select Is this a proxy? to confirm and enable the "Read as Proxy" & "Write as Proxy" tabs.
Contract Source Code Verified (Exact Match)
Contract Name:
BBHub
Compiler Version
v0.8.26+commit.8a97fa7a
Optimization Enabled:
Yes with 200 runs
Other Settings:
cancun EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.26; import {ERC20Upgradeable, IERC20, IERC20Metadata} from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import {Multicallable} from "solady/src/utils/Multicallable.sol"; import {RewardVault} from "@berachain/pol/rewards/RewardVault.sol"; import {RewardVaultFactory} from "@berachain/pol/rewards/RewardVaultFactory.sol"; import {Utils} from "./libraries/Utils.sol"; /// @title Bera Baddies Hub /// @author The Baddies /// @dev Refer to the docs: contract BBHub is ERC20Upgradeable, OwnableUpgradeable, Multicallable { using Utils for bytes4; /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* CONSTANTS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @notice name of the token to comply with ERC20. string private constant NAME = "Bera Baddies Points"; /// @notice symbol of the token to comply with ERC20. string private constant SYMBOL = "BBP"; /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* ERROR/EVENTS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ error InvariantCheckFailed(); error ZeroAddress(); error ZeroStake(); error EmissionFailed(); error UnauthorizedTransfer(); event PointsAssigned(address indexed to, uint256 amount); event PointsRevoked(address indexed from, uint256 amount); /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* STORAGE */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @notice immutable variable denoting the `InfraredVault` for the BBPoints. RewardVault public vault; /// @notice Initializes the BBHub contract. function initialize(address _owner, address _factory) external initializer { if (_owner == address(0) || _factory == address(0)) revert ZeroAddress(); __Ownable_init(_owner); __ERC20_init(NAME, SYMBOL); /// @notice creates the vault if it does not exist, if already exists returns the address. vault = RewardVault( RewardVaultFactory(_factory).createRewardVault(address(this)) ); _approve(address(this), address(vault), type(uint256).max); } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* ACCESS CONTROL */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @notice Throws if the invariant of the contract is broken. modifier invariantCheck() { /// @dev The BB soul bound token only lives inside reward vaults. if (balanceOf(address(vault)) != totalSupply()) revert InvariantCheckFailed(); /// Run the method. _; } /// @notice Throws if caller is not the vault modifier onlyVault() { if (msg.sender != address(vault)) revert UnauthorizedTransfer(); _; } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* ADMIN */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @notice Add points to the `to` address and delegates on their behalf. /// @param to address The account being assigned the delegate stake. /// @param amount uint256 The amount being assigned. function assign( address to, uint256 amount ) external onlyOwner invariantCheck { if (to == address(0)) revert ZeroAddress(); if (amount == 0) revert ZeroStake(); super._mint(address(this), amount); vault.delegateStake(to, amount); emit PointsAssigned(to, amount); } /// @notice Removes points from the `from` address and burns the tokens. /// @dev The `from` address can still claim unclaimed rewards from the reward vault. /// @dev If the amount is 0, the contract will revoke all the delegated stake. /// @param from address The account we are revoking the points from. /// @param amount uint256 The amount of tokens we are removing from the delegated stake. function revoke( address from, uint256 amount ) external onlyOwner invariantCheck { if (from == address(0)) revert ZeroAddress(); /// @dev if amount is set to 0, remove all stake. if (amount == 0) { amount = vault.getDelegateStake(from, address(this)); } /// @dev returns the tokens back to the delegator, which is address(this). vault.delegateWithdraw(from, amount); /// @dev burn the tokens to adhere to the invariant. super._burn(address(this), amount); emit PointsRevoked(from, amount); } /// @notice Overrides the default ERC20 transfer function to allow only transfers to the vault function transfer( address to, uint256 amount ) public virtual override onlyVault returns (bool) { return super.transfer(to, amount); } /// @notice Overrides the default ERC20 transferFrom function to allow only transfer to the vault function transferFrom( address from, address to, uint256 amount ) public virtual override onlyVault returns (bool) { return super.transferFrom(from, to, amount); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.2.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.20; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import {ContextUpgradeable} from "../../utils/ContextUpgradeable.sol"; import {IERC20Errors} from "@openzeppelin/contracts/interfaces/draft-IERC6093.sol"; import {Initializable} from "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * * TIP: For a detailed writeup see our guide * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * The default value of {decimals} is 18. To change this, you should override * this function so it returns a different value. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC-20 * applications. */ abstract contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20, IERC20Metadata, IERC20Errors { /// @custom:storage-location erc7201:openzeppelin.storage.ERC20 struct ERC20Storage { mapping(address account => uint256) _balances; mapping(address account => mapping(address spender => uint256)) _allowances; uint256 _totalSupply; string _name; string _symbol; } // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ERC20")) - 1)) & ~bytes32(uint256(0xff)) bytes32 private constant ERC20StorageLocation = 0x52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace00; function _getERC20Storage() private pure returns (ERC20Storage storage $) { assembly { $.slot := ERC20StorageLocation } } /** * @dev Sets the values for {name} and {symbol}. * * All two of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing { __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { ERC20Storage storage $ = _getERC20Storage(); $._name = name_; $._symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { ERC20Storage storage $ = _getERC20Storage(); return $._name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { ERC20Storage storage $ = _getERC20Storage(); return $._symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the default value returned by this function, unless * it's overridden. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual returns (uint256) { ERC20Storage storage $ = _getERC20Storage(); return $._totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual returns (uint256) { ERC20Storage storage $ = _getERC20Storage(); return $._balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `value`. */ function transfer(address to, uint256 value) public virtual returns (bool) { address owner = _msgSender(); _transfer(owner, to, value); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual returns (uint256) { ERC20Storage storage $ = _getERC20Storage(); return $._allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, value); return true; } /** * @dev See {IERC20-transferFrom}. * * Skips emitting an {Approval} event indicating an allowance update. This is not * required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve]. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `value`. * - the caller must have allowance for ``from``'s tokens of at least * `value`. */ function transferFrom(address from, address to, uint256 value) public virtual returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, value); _transfer(from, to, value); return true; } /** * @dev Moves a `value` amount of tokens from `from` to `to`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * NOTE: This function is not virtual, {_update} should be overridden instead. */ function _transfer(address from, address to, uint256 value) internal { if (from == address(0)) { revert ERC20InvalidSender(address(0)); } if (to == address(0)) { revert ERC20InvalidReceiver(address(0)); } _update(from, to, value); } /** * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from` * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding * this function. * * Emits a {Transfer} event. */ function _update(address from, address to, uint256 value) internal virtual { ERC20Storage storage $ = _getERC20Storage(); if (from == address(0)) { // Overflow check required: The rest of the code assumes that totalSupply never overflows $._totalSupply += value; } else { uint256 fromBalance = $._balances[from]; if (fromBalance < value) { revert ERC20InsufficientBalance(from, fromBalance, value); } unchecked { // Overflow not possible: value <= fromBalance <= totalSupply. $._balances[from] = fromBalance - value; } } if (to == address(0)) { unchecked { // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply. $._totalSupply -= value; } } else { unchecked { // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256. $._balances[to] += value; } } emit Transfer(from, to, value); } /** * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0). * Relies on the `_update` mechanism * * Emits a {Transfer} event with `from` set to the zero address. * * NOTE: This function is not virtual, {_update} should be overridden instead. */ function _mint(address account, uint256 value) internal { if (account == address(0)) { revert ERC20InvalidReceiver(address(0)); } _update(address(0), account, value); } /** * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply. * Relies on the `_update` mechanism. * * Emits a {Transfer} event with `to` set to the zero address. * * NOTE: This function is not virtual, {_update} should be overridden instead */ function _burn(address account, uint256 value) internal { if (account == address(0)) { revert ERC20InvalidSender(address(0)); } _update(account, address(0), value); } /** * @dev Sets `value` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. * * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument. */ function _approve(address owner, address spender, uint256 value) internal { _approve(owner, spender, value, true); } /** * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event. * * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any * `Approval` event during `transferFrom` operations. * * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to * true using the following override: * * ```solidity * function _approve(address owner, address spender, uint256 value, bool) internal virtual override { * super._approve(owner, spender, value, true); * } * ``` * * Requirements are the same as {_approve}. */ function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual { ERC20Storage storage $ = _getERC20Storage(); if (owner == address(0)) { revert ERC20InvalidApprover(address(0)); } if (spender == address(0)) { revert ERC20InvalidSpender(address(0)); } $._allowances[owner][spender] = value; if (emitEvent) { emit Approval(owner, spender, value); } } /** * @dev Updates `owner` s allowance for `spender` based on spent `value`. * * Does not update the allowance value in case of infinite allowance. * Revert if not enough allowance is available. * * Does not emit an {Approval} event. */ function _spendAllowance(address owner, address spender, uint256 value) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance < type(uint256).max) { if (currentAllowance < value) { revert ERC20InsufficientAllowance(spender, currentAllowance, value); } unchecked { _approve(owner, spender, currentAllowance - value, false); } } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol) pragma solidity ^0.8.20; import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol"; import {Initializable} from "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * The initial owner is set to the address provided by the deployer. This can * later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { /// @custom:storage-location erc7201:openzeppelin.storage.Ownable struct OwnableStorage { address _owner; } // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Ownable")) - 1)) & ~bytes32(uint256(0xff)) bytes32 private constant OwnableStorageLocation = 0x9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300; function _getOwnableStorage() private pure returns (OwnableStorage storage $) { assembly { $.slot := OwnableStorageLocation } } /** * @dev The caller account is not authorized to perform an operation. */ error OwnableUnauthorizedAccount(address account); /** * @dev The owner is not a valid owner account. (eg. `address(0)`) */ error OwnableInvalidOwner(address owner); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the address provided by the deployer as the initial owner. */ function __Ownable_init(address initialOwner) internal onlyInitializing { __Ownable_init_unchained(initialOwner); } function __Ownable_init_unchained(address initialOwner) internal onlyInitializing { if (initialOwner == address(0)) { revert OwnableInvalidOwner(address(0)); } _transferOwnership(initialOwner); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { _checkOwner(); _; } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { OwnableStorage storage $ = _getOwnableStorage(); return $._owner; } /** * @dev Throws if the sender is not the owner. */ function _checkOwner() internal view virtual { if (owner() != _msgSender()) { revert OwnableUnauthorizedAccount(_msgSender()); } } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby disabling any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { if (newOwner == address(0)) { revert OwnableInvalidOwner(address(0)); } _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { OwnableStorage storage $ = _getOwnableStorage(); address oldOwner = $._owner; $._owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /// @notice Contract that enables a single call to call multiple methods on itself. /// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/Multicallable.sol) /// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/Multicallable.sol) /// /// WARNING: /// This implementation is NOT to be used with ERC2771 out-of-the-box. /// https://blog.openzeppelin.com/arbitrary-address-spoofing-vulnerability-erc2771context-multicall-public-disclosure /// This also applies to potentially other ERCs / patterns appending to the back of calldata. /// /// We do NOT have a check for ERC2771, as we do not inherit from OpenZeppelin's context. /// Moreover, it is infeasible and inefficient for us to add checks and mitigations /// for all possible ERC / patterns appending to the back of calldata. /// /// We would highly recommend using an alternative pattern such as /// https://github.com/Vectorized/multicaller /// which is more flexible, futureproof, and safer by default. abstract contract Multicallable { /// @dev Apply `delegatecall` with the current contract to each calldata in `data`, /// and store the `abi.encode` formatted results of each `delegatecall` into `results`. /// If any of the `delegatecall`s reverts, the entire context is reverted, /// and the error is bubbled up. /// /// By default, this function directly returns the results and terminates the call context. /// If you need to add before and after actions to the multicall, please override this function. function multicall(bytes[] calldata data) public payable virtual returns (bytes[] memory) { // Revert if `msg.value` is non-zero by default to guard against double-spending. // (See: https://www.paradigm.xyz/2021/08/two-rights-might-make-a-wrong) // // If you really need to pass in a `msg.value`, then you will have to // override this function and add in any relevant before and after checks. if (msg.value != 0) revert(); // `_multicallDirectReturn` returns the results directly and terminates the call context. _multicallDirectReturn(_multicall(data)); } /// @dev The inner logic of `multicall`. /// This function is included so that you can override `multicall` /// to add before and after actions, and use the `_multicallDirectReturn` function. function _multicall(bytes[] calldata data) internal virtual returns (bytes32 results) { /// @solidity memory-safe-assembly assembly { results := mload(0x40) mstore(results, 0x20) mstore(add(0x20, results), data.length) let c := add(0x40, results) let s := c let end := shl(5, data.length) calldatacopy(c, data.offset, end) end := add(c, end) let m := end if data.length { for {} 1 {} { let o := add(data.offset, mload(c)) calldatacopy(m, add(o, 0x20), calldataload(o)) // forgefmt: disable-next-item if iszero(delegatecall(gas(), address(), m, calldataload(o), codesize(), 0x00)) { // Bubble up the revert if the delegatecall reverts. returndatacopy(results, 0x00, returndatasize()) revert(results, returndatasize()) } mstore(c, sub(m, s)) c := add(0x20, c) // Append the `returndatasize()`, and the return data. mstore(m, returndatasize()) let b := add(m, 0x20) returndatacopy(b, 0x00, returndatasize()) // Advance `m` by `returndatasize() + 0x20`, // rounded up to the next multiple of 32. m := and(add(add(b, returndatasize()), 0x1f), 0xffffffffffffffe0) mstore(add(b, returndatasize()), 0) // Zeroize the slot after the returndata. if iszero(lt(c, end)) { break } } } mstore(0x40, m) // Allocate memory. results := or(shl(64, sub(m, results)), results) // Pack the bytes length into `results`. } } /// @dev Decodes the `results` into an array of bytes. /// This can be useful if you need to access the results or re-encode it. function _multicallResultsToBytesArray(bytes32 results) internal pure virtual returns (bytes[] memory decoded) { /// @solidity memory-safe-assembly assembly { decoded := mload(0x40) let c := and(0xffffffffffffffff, results) // Extract the offset. mstore(decoded, mload(add(c, 0x20))) // Store the length. let o := add(decoded, 0x20) // Start of elements in `decoded`. let end := add(o, shl(5, mload(decoded))) mstore(0x40, end) // Allocate memory. let s := add(c, 0x40) // Start of elements in `results`. let d := sub(s, o) // Difference between input and output pointers. for {} iszero(eq(o, end)) { o := add(o, 0x20) } { mstore(o, add(mload(add(d, o)), s)) } } } /// @dev Directly returns the `results` and terminates the current call context. /// `results` must be from `_multicall`, else behavior is undefined. function _multicallDirectReturn(bytes32 results) internal pure virtual { /// @solidity memory-safe-assembly assembly { return(and(0xffffffffffffffff, results), shr(64, results)) } } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.26; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import { PausableUpgradeable } from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; import { ReentrancyGuardUpgradeable } from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import { FixedPointMathLib } from "solady/src/utils/FixedPointMathLib.sol"; import { Utils } from "../../libraries/Utils.sol"; import { IBeaconDeposit } from "../interfaces/IBeaconDeposit.sol"; import { IRewardVault } from "../interfaces/IRewardVault.sol"; import { FactoryOwnable } from "../../base/FactoryOwnable.sol"; import { StakingRewards } from "../../base/StakingRewards.sol"; /// @title Rewards Vault /// @author Berachain Team /// @notice This contract is the vault for the Berachain rewards, it handles the staking and rewards accounting of BGT. /// @dev This contract is taken from the stable and tested: /// https://github.com/Synthetixio/synthetix/blob/develop/contracts/StakingRewards.sol /// We are using this model instead of 4626 because we want to incentivize staying in the vault for x period of time to /// to be considered a 'miner' and not a 'trader'. contract RewardVault is PausableUpgradeable, ReentrancyGuardUpgradeable, FactoryOwnable, StakingRewards, IRewardVault { using Utils for bytes4; using SafeERC20 for IERC20; using Utils for address; /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* STRUCTS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @notice Struct to hold delegate stake data. /// @param delegateTotalStaked The total amount staked by delegates. /// @param stakedByDelegate The mapping of the amount staked by each delegate. struct DelegateStake { uint256 delegateTotalStaked; mapping(address delegate => uint256 amount) stakedByDelegate; } /// @notice Struct to hold an incentive data. /// @param minIncentiveRate The minimum amount of the token to incentivize per BGT emission. /// @param incentiveRate The amount of the token to incentivize per BGT emission. /// @param amountRemaining The amount of the token remaining to incentivize. /// @param manager The address of the manager that can addIncentive for this incentive token. struct Incentive { uint256 minIncentiveRate; uint256 incentiveRate; uint256 amountRemaining; address manager; } uint256 private constant MAX_INCENTIVE_RATE = 1e36; // for 18 decimal token, this will mean 1e18 incentiveTokens // per BGT emission. /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* STORAGE */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @notice The maximum count of incentive tokens that can be stored. uint8 public maxIncentiveTokensCount; /// @notice The address of the distributor contract. address public distributor; /// @notice The BeaconDeposit contract. IBeaconDeposit public beaconDepositContract; mapping(address account => DelegateStake) internal _delegateStake; /// @notice The mapping of accounts to their operators. mapping(address account => address operator) internal _operators; /// @notice the mapping of incentive token to its incentive data. mapping(address token => Incentive) public incentives; /// @notice The list of whitelisted tokens. address[] public whitelistedTokens; /// @custom:oz-upgrades-unsafe-allow constructor constructor() { _disableInitializers(); } /// @inheritdoc IRewardVault function initialize( address _beaconDepositContract, address _bgt, address _distributor, address _stakingToken ) external initializer { __FactoryOwnable_init(msg.sender); __Pausable_init(); __ReentrancyGuard_init(); __StakingRewards_init(_stakingToken, _bgt, 7 days); maxIncentiveTokensCount = 2; // slither-disable-next-line missing-zero-check distributor = _distributor; beaconDepositContract = IBeaconDeposit(_beaconDepositContract); emit DistributorSet(_distributor); emit MaxIncentiveTokensCountUpdated(2); } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* MODIFIERS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ modifier onlyDistributor() { if (msg.sender != distributor) NotDistributor.selector.revertWith(); _; } modifier onlyOperatorOrUser(address account) { if (msg.sender != account) { if (msg.sender != _operators[account]) NotOperator.selector.revertWith(); } _; } modifier checkSelfStakedBalance(address account, uint256 amount) { _checkSelfStakedBalance(account, amount); _; } modifier onlyWhitelistedToken(address token) { if (incentives[token].minIncentiveRate == 0) TokenNotWhitelisted.selector.revertWith(); _; } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* ADMIN FUNCTIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @inheritdoc IRewardVault function setDistributor(address _rewardDistribution) external onlyFactoryOwner { if (_rewardDistribution == address(0)) ZeroAddress.selector.revertWith(); distributor = _rewardDistribution; emit DistributorSet(_rewardDistribution); } /// @inheritdoc IRewardVault function notifyRewardAmount(bytes calldata pubkey, uint256 reward) external onlyDistributor { _notifyRewardAmount(reward); _processIncentives(pubkey, reward); } /// @inheritdoc IRewardVault function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyFactoryOwner { if (tokenAddress == address(stakeToken)) CannotRecoverStakingToken.selector.revertWith(); if (incentives[tokenAddress].minIncentiveRate != 0) CannotRecoverIncentiveToken.selector.revertWith(); IERC20(tokenAddress).safeTransfer(msg.sender, tokenAmount); emit Recovered(tokenAddress, tokenAmount); } /// @inheritdoc IRewardVault function setRewardsDuration(uint256 _rewardsDuration) external onlyFactoryOwner { _setRewardsDuration(_rewardsDuration); } /// @inheritdoc IRewardVault function whitelistIncentiveToken( address token, uint256 minIncentiveRate, address manager ) external onlyFactoryOwner { // validate `minIncentiveRate` value if (minIncentiveRate == 0) MinIncentiveRateIsZero.selector.revertWith(); if (minIncentiveRate > MAX_INCENTIVE_RATE) IncentiveRateTooHigh.selector.revertWith(); // validate token and manager address if (token == address(0) || manager == address(0)) ZeroAddress.selector.revertWith(); Incentive storage incentive = incentives[token]; if (whitelistedTokens.length == maxIncentiveTokensCount || incentive.minIncentiveRate != 0) { TokenAlreadyWhitelistedOrLimitReached.selector.revertWith(); } whitelistedTokens.push(token); //set the incentive rate to the minIncentiveRate. incentive.incentiveRate = minIncentiveRate; incentive.minIncentiveRate = minIncentiveRate; // set the manager incentive.manager = manager; emit IncentiveTokenWhitelisted(token, minIncentiveRate, manager); } /// @inheritdoc IRewardVault function removeIncentiveToken(address token) external onlyFactoryVaultManager onlyWhitelistedToken(token) { delete incentives[token]; // delete the token from the list. _deleteWhitelistedTokenFromList(token); emit IncentiveTokenRemoved(token); } /// @inheritdoc IRewardVault function updateIncentiveManager( address token, address newManager ) external onlyFactoryOwner onlyWhitelistedToken(token) { if (newManager == address(0)) ZeroAddress.selector.revertWith(); Incentive storage incentive = incentives[token]; // cache the current manager address currentManager = incentive.manager; incentive.manager = newManager; emit IncentiveManagerChanged(token, newManager, currentManager); } /// @inheritdoc IRewardVault function setMaxIncentiveTokensCount(uint8 _maxIncentiveTokensCount) external onlyFactoryOwner { if (_maxIncentiveTokensCount < whitelistedTokens.length) { InvalidMaxIncentiveTokensCount.selector.revertWith(); } maxIncentiveTokensCount = _maxIncentiveTokensCount; emit MaxIncentiveTokensCountUpdated(_maxIncentiveTokensCount); } /// @inheritdoc IRewardVault function pause() external onlyFactoryVaultPauser { _pause(); } /// @inheritdoc IRewardVault function unpause() external onlyFactoryVaultManager { _unpause(); } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* GETTERS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @inheritdoc IRewardVault function operator(address account) external view returns (address) { return _operators[account]; } /// @inheritdoc IRewardVault function getWhitelistedTokensCount() external view returns (uint256) { return whitelistedTokens.length; } /// @inheritdoc IRewardVault function getWhitelistedTokens() public view returns (address[] memory) { return whitelistedTokens; } /// @inheritdoc IRewardVault function getTotalDelegateStaked(address account) external view returns (uint256) { return _delegateStake[account].delegateTotalStaked; } /// @inheritdoc IRewardVault function getDelegateStake(address account, address delegate) external view returns (uint256) { return _delegateStake[account].stakedByDelegate[delegate]; } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* WRITES */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @inheritdoc IRewardVault function stake(uint256 amount) external nonReentrant whenNotPaused { _stake(msg.sender, amount); } /// @inheritdoc IRewardVault function delegateStake(address account, uint256 amount) external nonReentrant whenNotPaused { if (msg.sender == account) NotDelegate.selector.revertWith(); _stake(account, amount); unchecked { DelegateStake storage info = _delegateStake[account]; // Overflow is not possible for `delegateTotalStaked` as it is bounded by the `totalSupply` which has // been incremented in `_stake`. info.delegateTotalStaked += amount; // If the total staked by all delegates does not overflow, this increment is safe. info.stakedByDelegate[msg.sender] += amount; } emit DelegateStaked(account, msg.sender, amount); } /// @inheritdoc IRewardVault function withdraw(uint256 amount) external nonReentrant checkSelfStakedBalance(msg.sender, amount) { _withdraw(msg.sender, amount); } /// @inheritdoc IRewardVault function delegateWithdraw(address account, uint256 amount) external nonReentrant { if (msg.sender == account) NotDelegate.selector.revertWith(); unchecked { DelegateStake storage info = _delegateStake[account]; uint256 stakedByDelegate = info.stakedByDelegate[msg.sender]; if (stakedByDelegate < amount) InsufficientDelegateStake.selector.revertWith(); info.stakedByDelegate[msg.sender] = stakedByDelegate - amount; // underflow is impossible because `info.delegateTotalStaked` >= `stakedByDelegate` >= `amount` info.delegateTotalStaked -= amount; } _withdraw(account, amount); emit DelegateWithdrawn(account, msg.sender, amount); } /// @inheritdoc IRewardVault function getReward( address account, address recipient ) external nonReentrant onlyOperatorOrUser(account) returns (uint256) { return _getReward(account, recipient); } /// @inheritdoc IRewardVault function exit(address recipient) external nonReentrant { // self-staked amount uint256 amount = _accountInfo[msg.sender].balance - _delegateStake[msg.sender].delegateTotalStaked; _withdraw(msg.sender, amount); _getReward(msg.sender, recipient); } /// @inheritdoc IRewardVault function setOperator(address _operator) external { _operators[msg.sender] = _operator; emit OperatorSet(msg.sender, _operator); } /// @inheritdoc IRewardVault function addIncentive( address token, uint256 amount, uint256 incentiveRate ) external nonReentrant onlyWhitelistedToken(token) { if (incentiveRate > MAX_INCENTIVE_RATE) IncentiveRateTooHigh.selector.revertWith(); Incentive storage incentive = incentives[token]; (uint256 minIncentiveRate, uint256 incentiveRateStored, uint256 amountRemainingBefore, address manager) = (incentive.minIncentiveRate, incentive.incentiveRate, incentive.amountRemaining, incentive.manager); // Only allow the incentive token manager to add incentive. if (msg.sender != manager) NotIncentiveManager.selector.revertWith(); // The incentive amount should be equal to or greater than the `minIncentiveRate` to avoid spamming. // If the `minIncentiveRate` is 100 USDC/BGT, the amount should be at least 100 USDC. if (amount < minIncentiveRate) AmountLessThanMinIncentiveRate.selector.revertWith(); IERC20(token).safeTransferFrom(msg.sender, address(this), amount); incentive.amountRemaining = amountRemainingBefore + amount; // Allows updating the incentive rate if the remaining incentive amount is 0 and // the `incentiveRate` is greater than or equal to the `minIncentiveRate`. if (amountRemainingBefore == 0 && incentiveRate >= minIncentiveRate) { incentive.incentiveRate = incentiveRate; } // Allows increasing the incentive rate, provided the `amount` suffices to incentivize the same amount of BGT. // If the current rate is 100 USDC/BGT and the amount remaining is 50 USDC, incentivizing 0.5 BGT, // then for a new rate of 150 USDC/BGT, the input amount should be at least 0.5 * (150 - 100) = 25 USDC, // ensuring that it will still incentivize 0.5 BGT. else if (incentiveRate > incentiveRateStored) { uint256 rateDelta; unchecked { rateDelta = incentiveRate - incentiveRateStored; } if (amount >= FixedPointMathLib.mulDiv(amountRemainingBefore, rateDelta, incentiveRateStored)) { incentive.incentiveRate = incentiveRate; } } emit IncentiveAdded(token, msg.sender, amount, incentive.incentiveRate); } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* INTERNAL FUNCTIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Check if the account has enough self-staked balance. /// @param account The account to check the self-staked balance for. /// @param amount The amount being withdrawn. function _checkSelfStakedBalance(address account, uint256 amount) internal view { unchecked { uint256 selfStaked = _accountInfo[account].balance - _delegateStake[account].delegateTotalStaked; if (selfStaked < amount) InsufficientSelfStake.selector.revertWith(); } } /// @dev The Distributor grants this contract the allowance to transfer the BGT in its balance. function _safeTransferRewardToken(address to, uint256 amount) internal override { rewardToken.safeTransferFrom(distributor, to, amount); } // Ensure the provided reward amount is not more than the balance in the contract. // This keeps the reward rate in the right range, preventing overflows due to // very high values of rewardRate in the earned and rewardsPerToken functions; // Reward + leftover must be less than 2^256 / 10^18 to avoid overflow. function _checkRewardSolvency() internal view override { uint256 allowance = rewardToken.allowance(distributor, address(this)); if (undistributedRewards / PRECISION > allowance) InsolventReward.selector.revertWith(); } /// @notice process the incentives for a validator. /// @notice If a token transfer consumes more than 500k gas units, the transfer alone will fail. /// @param pubkey The pubkey of the validator to process the incentives for. /// @param bgtEmitted The amount of BGT emitted by the validator. function _processIncentives(bytes calldata pubkey, uint256 bgtEmitted) internal { // Validator's operator corresponding to the pubkey receives the incentives. // The pubkey -> operator relationship is maintained by the BeaconDeposit contract. address _operator = beaconDepositContract.getOperator(pubkey); uint256 whitelistedTokensCount = whitelistedTokens.length; unchecked { for (uint256 i; i < whitelistedTokensCount; ++i) { address token = whitelistedTokens[i]; Incentive storage incentive = incentives[token]; uint256 amount = FixedPointMathLib.mulDiv(bgtEmitted, incentive.incentiveRate, PRECISION); uint256 amountRemaining = incentive.amountRemaining; amount = FixedPointMathLib.min(amount, amountRemaining); if (amount > 0) { // Transfer the incentive to the operator. // slither-disable-next-line arbitrary-send-erc20 bool success = token.trySafeTransfer(_operator, amount); if (success) { // Update the remaining amount only if tokens were transfered. incentive.amountRemaining = amountRemaining - amount; emit IncentivesProcessed(pubkey, token, bgtEmitted, amount); } else { emit IncentivesProcessFailed(pubkey, token, bgtEmitted, amount); } } } } } function _deleteWhitelistedTokenFromList(address token) internal { uint256 activeTokens = whitelistedTokens.length; // The length of `whitelistedTokens` cannot be 0 because the `onlyWhitelistedToken` check has already been // performed. unchecked { for (uint256 i; i < activeTokens; ++i) { if (token == whitelistedTokens[i]) { whitelistedTokens[i] = whitelistedTokens[activeTokens - 1]; whitelistedTokens.pop(); return; } } } } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.26; import { AccessControlUpgradeable } from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import { UUPSUpgradeable } from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import { LibClone } from "solady/src/utils/LibClone.sol"; import { UpgradeableBeacon } from "solady/src/utils/UpgradeableBeacon.sol"; import { Utils } from "../../libraries/Utils.sol"; import { IRewardVaultFactory } from "../interfaces/IRewardVaultFactory.sol"; import { RewardVault } from "./RewardVault.sol"; /// @title RewardVaultFactory /// @author Berachain Team /// @notice Factory contract for creating RewardVaults and keeping track of them. contract RewardVaultFactory is IRewardVaultFactory, AccessControlUpgradeable, UUPSUpgradeable { using Utils for bytes4; /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* STORAGE */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @notice The VAULT MANAGER role. bytes32 public constant VAULT_MANAGER_ROLE = keccak256("VAULT_MANAGER_ROLE"); /// @notice The VAULT PAUSER role. bytes32 public constant VAULT_PAUSER_ROLE = keccak256("VAULT_PAUSER_ROLE"); /// @notice The beacon address. address public beacon; /// @notice The BGT token address. address public bgt; /// @notice The distributor address. address public distributor; /// @notice The BeaconDeposit contract address. address public beaconDepositContract; /// @notice Mapping of staking token to vault address. mapping(address stakingToken => address vault) public getVault; /// @notice Array of all vaults that have been created. address[] public allVaults; /// @custom:oz-upgrades-unsafe-allow constructor constructor() { _disableInitializers(); } function initialize( address _bgt, address _distributor, address _beaconDepositContract, address _governance, address _vaultImpl ) external initializer { __AccessControl_init(); __UUPSUpgradeable_init(); _grantRole(DEFAULT_ADMIN_ROLE, _governance); // Allow the vault manager to manage the vault pauser role. // vault manager can grant and revoke the access for the vault pauser role. _setRoleAdmin(VAULT_PAUSER_ROLE, VAULT_MANAGER_ROLE); // slither-disable-next-line missing-zero-check bgt = _bgt; // slither-disable-next-line missing-zero-check distributor = _distributor; // slither-disable-next-line missing-zero-check beaconDepositContract = _beaconDepositContract; beacon = address(new UpgradeableBeacon(_governance, _vaultImpl)); } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* ADMIN */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ function _authorizeUpgrade(address newImplementation) internal override onlyRole(DEFAULT_ADMIN_ROLE) { } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* VAULT CREATION */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @inheritdoc IRewardVaultFactory function createRewardVault(address stakingToken) external returns (address) { address cachedAddress = getVault[stakingToken]; if (cachedAddress != address(0)) return cachedAddress; // Check the code size of the staking token. if (stakingToken.code.length == 0) NotAContract.selector.revertWith(); // Use solady library to deploy deterministic clone of vaultImpl. bytes32 salt; assembly ("memory-safe") { mstore(0, stakingToken) salt := keccak256(0, 0x20) } address vault = LibClone.deployDeterministicERC1967BeaconProxy(beacon, salt); // Store the vault in the mapping and array. getVault[stakingToken] = vault; allVaults.push(vault); emit VaultCreated(stakingToken, vault); // Initialize the vault. RewardVault(vault).initialize(beaconDepositContract, bgt, distributor, stakingToken); return vault; } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* READS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @inheritdoc IRewardVaultFactory function predictRewardVaultAddress(address stakingToken) external view returns (address) { bytes32 salt; assembly ("memory-safe") { mstore(0, stakingToken) salt := keccak256(0, 0x20) } return LibClone.predictDeterministicAddressERC1967BeaconProxy(beacon, salt, address(this)); } /// @inheritdoc IRewardVaultFactory function allVaultsLength() external view returns (uint256) { return allVaults.length; } }
// SPDX-License-Identifier: BUSL-1.1 // solhint-disable-next-line compiler-version pragma solidity 0.8.26; import { SafeTransferLib } from "solady/src/utils/SafeTransferLib.sol"; library Utils { using SafeTransferLib for address; /// @notice The gas limit for a transfer, used to prevent malicious token griefing. uint32 constant TRANSFER_GAS_LIMIT = 500_000; /// @notice Error for overflow when increasing allowance error IncreaseAllowanceOverflow(); /// @dev Reverts with the selector of a custom error in the scratch space. function revertWith(bytes4 selector) internal pure { assembly ("memory-safe") { mstore(0, selector) revert(0, 0x04) } } /// @dev Reverts for the reason encoding a silent revert, Error(string), or a custom error. function revertFor(bytes memory reason) internal pure { assembly ("memory-safe") { revert(add(reason, 0x20), mload(reason)) } } function revertWith(bytes4 selector, address addr) internal pure { assembly ("memory-safe") { mstore(0, selector) mstore(0x04, addr) revert(0, 0x24) // 4 (selector) + 32 (addr) } } function revertWith(bytes4 selector, uint256 amount) internal pure { assembly ("memory-safe") { mstore(0, selector) mstore(0x04, amount) revert(0, 0x24) // 4 (selector) + 32 (amount) } } function revertWith(bytes4 selector, uint256 amount1, uint256 amount2) internal pure { assembly ("memory-safe") { mstore(0, selector) mstore(0x04, amount1) mstore(0x24, amount2) revert(0, 0x44) // 4 (selector) + 32 (amount1) + 32 (amount2) } } function revertWith(bytes4 selector, address addr1, address addr2) internal pure { assembly ("memory-safe") { mstore(0, selector) mstore(0x04, addr1) mstore(0x24, addr2) revert(0, 0x44) // 4 (selector) + 32 (addr1) + 32 (addr2) } } /// @dev Increase the calling contract's allowance toward `spender` by `amount`. /// @dev Does not check if token exists. function safeIncreaseAllowance(address token, address spender, uint256 amount) internal { unchecked { uint256 oldAllowance = allowance(token, address(this), spender); uint256 newAllowance = oldAllowance + amount; if (newAllowance < oldAllowance) revertWith(IncreaseAllowanceOverflow.selector); token.safeApprove(spender, newAllowance); } } /// @dev Returns the amount of ERC20 `token` that `owner` has allowed `spender` to use. /// Returns zero if the `token` does not exist. function allowance(address token, address owner, address spender) internal view returns (uint256 amount) { assembly ("memory-safe") { mstore(0, 0xdd62ed3e00000000000000000000000000000000000000000000000000000000) // Store function selector of // `allowance(address,address)`. mstore(0x04, owner) // Store the `owner` argument. mstore(0x24, spender) // Store the `spender` argument. amount := mul( // The arguments of `mul` are evaluated from right to left. mload(0), and( // The arguments of `and` are evaluated from right to left. gt(returndatasize(), 0x1f), // At least 32 bytes returned. staticcall(gas(), token, 0, 0x44, 0, 0x20) ) ) mstore(0x24, 0) // clear the upper bits of free memory pointer. } } /// @dev Sends `amount` of ERC20 `token` from the current contract to `to`. /// Doesn't revert upon failure. function trySafeTransfer(address token, address to, uint256 amount) internal returns (bool success) { assembly ("memory-safe") { mstore(0x14, to) // Store the `to` argument. mstore(0x34, amount) // Store the `amount` argument. mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)` function selector. // Perform the transfer, returning success status. success := and( or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing. call(TRANSFER_GAS_LIMIT, token, 0, 0x10, 0x44, 0x00, 0x20) ) mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten. } } function changeDecimals(uint256 amount, uint8 from, uint8 to) internal pure returns (uint256) { if (from == to) { return amount; } if (from > to) { return amount / (10 ** (from - to)); } else { return amount * (10 ** (to - from)); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.20; /** * @dev Interface of the ERC-20 standard as defined in the ERC. */ 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 value of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the value of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves a `value` amount of 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 value) 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 a `value` amount of tokens 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 value) external returns (bool); /** * @dev Moves a `value` amount of tokens from `from` to `to` using the * allowance mechanism. `value` 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 value) external returns (bool); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.20; import {IERC20} from "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC-20 standard. */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol) pragma solidity ^0.8.20; import {Initializable} from "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } function _contextSuffixLength() internal view virtual returns (uint256) { return 0; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (interfaces/draft-IERC6093.sol) pragma solidity ^0.8.20; /** * @dev Standard ERC-20 Errors * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens. */ interface IERC20Errors { /** * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers. * @param sender Address whose tokens are being transferred. * @param balance Current balance for the interacting account. * @param needed Minimum amount required to perform a transfer. */ error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed); /** * @dev Indicates a failure with the token `sender`. Used in transfers. * @param sender Address whose tokens are being transferred. */ error ERC20InvalidSender(address sender); /** * @dev Indicates a failure with the token `receiver`. Used in transfers. * @param receiver Address to which tokens are being transferred. */ error ERC20InvalidReceiver(address receiver); /** * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers. * @param spender Address that may be allowed to operate on tokens without being their owner. * @param allowance Amount of tokens a `spender` is allowed to operate with. * @param needed Minimum amount required to perform a transfer. */ error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed); /** * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals. * @param approver Address initiating an approval operation. */ error ERC20InvalidApprover(address approver); /** * @dev Indicates a failure with the `spender` to be approved. Used in approvals. * @param spender Address that may be allowed to operate on tokens without being their owner. */ error ERC20InvalidSpender(address spender); } /** * @dev Standard ERC-721 Errors * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens. */ interface IERC721Errors { /** * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-20. * Used in balance queries. * @param owner Address of the current owner of a token. */ error ERC721InvalidOwner(address owner); /** * @dev Indicates a `tokenId` whose `owner` is the zero address. * @param tokenId Identifier number of a token. */ error ERC721NonexistentToken(uint256 tokenId); /** * @dev Indicates an error related to the ownership over a particular token. Used in transfers. * @param sender Address whose tokens are being transferred. * @param tokenId Identifier number of a token. * @param owner Address of the current owner of a token. */ error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner); /** * @dev Indicates a failure with the token `sender`. Used in transfers. * @param sender Address whose tokens are being transferred. */ error ERC721InvalidSender(address sender); /** * @dev Indicates a failure with the token `receiver`. Used in transfers. * @param receiver Address to which tokens are being transferred. */ error ERC721InvalidReceiver(address receiver); /** * @dev Indicates a failure with the `operator`’s approval. Used in transfers. * @param operator Address that may be allowed to operate on tokens without being their owner. * @param tokenId Identifier number of a token. */ error ERC721InsufficientApproval(address operator, uint256 tokenId); /** * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals. * @param approver Address initiating an approval operation. */ error ERC721InvalidApprover(address approver); /** * @dev Indicates a failure with the `operator` to be approved. Used in approvals. * @param operator Address that may be allowed to operate on tokens without being their owner. */ error ERC721InvalidOperator(address operator); } /** * @dev Standard ERC-1155 Errors * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens. */ interface IERC1155Errors { /** * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers. * @param sender Address whose tokens are being transferred. * @param balance Current balance for the interacting account. * @param needed Minimum amount required to perform a transfer. * @param tokenId Identifier number of a token. */ error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId); /** * @dev Indicates a failure with the token `sender`. Used in transfers. * @param sender Address whose tokens are being transferred. */ error ERC1155InvalidSender(address sender); /** * @dev Indicates a failure with the token `receiver`. Used in transfers. * @param receiver Address to which tokens are being transferred. */ error ERC1155InvalidReceiver(address receiver); /** * @dev Indicates a failure with the `operator`’s approval. Used in transfers. * @param operator Address that may be allowed to operate on tokens without being their owner. * @param owner Address of the current owner of a token. */ error ERC1155MissingApprovalForAll(address operator, address owner); /** * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals. * @param approver Address initiating an approval operation. */ error ERC1155InvalidApprover(address approver); /** * @dev Indicates a failure with the `operator` to be approved. Used in approvals. * @param operator Address that may be allowed to operate on tokens without being their owner. */ error ERC1155InvalidOperator(address operator); /** * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation. * Used in batch transfers. * @param idsLength Length of the array of token identifiers * @param valuesLength Length of the array of token amounts */ error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength); }
// 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 } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.2.0) (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.20; import {IERC20} from "../IERC20.sol"; import {IERC1363} from "../../../interfaces/IERC1363.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC-20 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 { /** * @dev An operation with an ERC-20 token failed. */ error SafeERC20FailedOperation(address token); /** * @dev Indicates a failed `decreaseAllowance` request. */ error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease); /** * @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.encodeCall(token.transfer, (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.encodeCall(token.transferFrom, (from, to, 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. * * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client" * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior. */ function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 oldAllowance = token.allowance(address(this), spender); forceApprove(token, spender, oldAllowance + value); } /** * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no * value, non-reverting calls are assumed to be successful. * * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client" * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior. */ function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal { unchecked { uint256 currentAllowance = token.allowance(address(this), spender); if (currentAllowance < requestedDecrease) { revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease); } forceApprove(token, spender, currentAllowance - requestedDecrease); } } /** * @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. * * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being * set here. */ function forceApprove(IERC20 token, address spender, uint256 value) internal { bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value)); if (!_callOptionalReturnBool(token, approvalCall)) { _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0))); _callOptionalReturn(token, approvalCall); } } /** * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when * targeting contracts. * * Reverts if the returned value is other than `true`. */ function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal { if (to.code.length == 0) { safeTransfer(token, to, value); } else if (!token.transferAndCall(to, value, data)) { revert SafeERC20FailedOperation(address(token)); } } /** * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when * targeting contracts. * * Reverts if the returned value is other than `true`. */ function transferFromAndCallRelaxed( IERC1363 token, address from, address to, uint256 value, bytes memory data ) internal { if (to.code.length == 0) { safeTransferFrom(token, from, to, value); } else if (!token.transferFromAndCall(from, to, value, data)) { revert SafeERC20FailedOperation(address(token)); } } /** * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when * targeting contracts. * * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}. * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall} * once without retrying, and relies on the returned value to be true. * * Reverts if the returned value is other than `true`. */ function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal { if (to.code.length == 0) { forceApprove(token, to, value); } else if (!token.approveAndCall(to, value, data)) { revert SafeERC20FailedOperation(address(token)); } } /** * @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 {_callOptionalReturnBool} that reverts if call fails to meet the requirements. */ function _callOptionalReturn(IERC20 token, bytes memory data) private { uint256 returnSize; uint256 returnValue; assembly ("memory-safe") { let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20) // bubble errors if iszero(success) { let ptr := mload(0x40) returndatacopy(ptr, 0, returndatasize()) revert(ptr, returndatasize()) } returnSize := returndatasize() returnValue := mload(0) } if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) { revert SafeERC20FailedOperation(address(token)); } } /** * @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 silently catches all reverts and returns a bool instead. */ function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) { bool success; uint256 returnSize; uint256 returnValue; assembly ("memory-safe") { success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20) returnSize := returndatasize() returnValue := mload(0) } return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/Pausable.sol) pragma solidity ^0.8.20; import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol"; import {Initializable} from "../proxy/utils/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /// @custom:storage-location erc7201:openzeppelin.storage.Pausable struct PausableStorage { bool _paused; } // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Pausable")) - 1)) & ~bytes32(uint256(0xff)) bytes32 private constant PausableStorageLocation = 0xcd5ed15c6e187e77e9aee88184c21f4f2182ab5827cb3b7e07fbedcd63f03300; function _getPausableStorage() private pure returns (PausableStorage storage $) { assembly { $.slot := PausableStorageLocation } } /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); /** * @dev The operation failed because the contract is paused. */ error EnforcedPause(); /** * @dev The operation failed because the contract is not paused. */ error ExpectedPause(); /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal onlyInitializing { __Pausable_init_unchained(); } function __Pausable_init_unchained() internal onlyInitializing { PausableStorage storage $ = _getPausableStorage(); $._paused = false; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { _requireNotPaused(); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { _requirePaused(); _; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { PausableStorage storage $ = _getPausableStorage(); return $._paused; } /** * @dev Throws if the contract is paused. */ function _requireNotPaused() internal view virtual { if (paused()) { revert EnforcedPause(); } } /** * @dev Throws if the contract is not paused. */ function _requirePaused() internal view virtual { if (!paused()) { revert ExpectedPause(); } } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { PausableStorage storage $ = _getPausableStorage(); $._paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { PausableStorage storage $ = _getPausableStorage(); $._paused = false; emit Unpaused(_msgSender()); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol) pragma solidity ^0.8.20; import {Initializable} from "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at, * consider using {ReentrancyGuardTransient} instead. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant NOT_ENTERED = 1; uint256 private constant ENTERED = 2; /// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard struct ReentrancyGuardStorage { uint256 _status; } // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff)) bytes32 private constant ReentrancyGuardStorageLocation = 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00; function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) { assembly { $.slot := ReentrancyGuardStorageLocation } } /** * @dev Unauthorized reentrant call. */ error ReentrancyGuardReentrantCall(); function __ReentrancyGuard_init() internal onlyInitializing { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal onlyInitializing { ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage(); $._status = NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { _nonReentrantBefore(); _; _nonReentrantAfter(); } function _nonReentrantBefore() private { ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage(); // On the first call to nonReentrant, _status will be NOT_ENTERED if ($._status == ENTERED) { revert ReentrancyGuardReentrantCall(); } // Any calls to nonReentrant after this point will fail $._status = ENTERED; } function _nonReentrantAfter() private { ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage(); // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) $._status = NOT_ENTERED; } /** * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a * `nonReentrant` function in the call stack. */ function _reentrancyGuardEntered() internal view returns (bool) { ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage(); return $._status == ENTERED; } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /// @notice Arithmetic library with operations for fixed-point numbers. /// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/FixedPointMathLib.sol) /// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol) library FixedPointMathLib { /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* CUSTOM ERRORS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev The operation failed, as the output exceeds the maximum value of uint256. error ExpOverflow(); /// @dev The operation failed, as the output exceeds the maximum value of uint256. error FactorialOverflow(); /// @dev The operation failed, due to an overflow. error RPowOverflow(); /// @dev The mantissa is too big to fit. error MantissaOverflow(); /// @dev The operation failed, due to an multiplication overflow. error MulWadFailed(); /// @dev The operation failed, due to an multiplication overflow. error SMulWadFailed(); /// @dev The operation failed, either due to a multiplication overflow, or a division by a zero. error DivWadFailed(); /// @dev The operation failed, either due to a multiplication overflow, or a division by a zero. error SDivWadFailed(); /// @dev The operation failed, either due to a multiplication overflow, or a division by a zero. error MulDivFailed(); /// @dev The division failed, as the denominator is zero. error DivFailed(); /// @dev The full precision multiply-divide operation failed, either due /// to the result being larger than 256 bits, or a division by a zero. error FullMulDivFailed(); /// @dev The output is undefined, as the input is less-than-or-equal to zero. error LnWadUndefined(); /// @dev The input outside the acceptable domain. error OutOfDomain(); /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* CONSTANTS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev The scalar of ETH and most ERC20s. uint256 internal constant WAD = 1e18; /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* SIMPLIFIED FIXED POINT OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Equivalent to `(x * y) / WAD` rounded down. function mulWad(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { // Equivalent to `require(y == 0 || x <= type(uint256).max / y)`. if gt(x, div(not(0), y)) { if y { mstore(0x00, 0xbac65e5b) // `MulWadFailed()`. revert(0x1c, 0x04) } } z := div(mul(x, y), WAD) } } /// @dev Equivalent to `(x * y) / WAD` rounded down. function sMulWad(int256 x, int256 y) internal pure returns (int256 z) { /// @solidity memory-safe-assembly assembly { z := mul(x, y) // Equivalent to `require((x == 0 || z / x == y) && !(x == -1 && y == type(int256).min))`. if iszero(gt(or(iszero(x), eq(sdiv(z, x), y)), lt(not(x), eq(y, shl(255, 1))))) { mstore(0x00, 0xedcd4dd4) // `SMulWadFailed()`. revert(0x1c, 0x04) } z := sdiv(z, WAD) } } /// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks. function rawMulWad(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := div(mul(x, y), WAD) } } /// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks. function rawSMulWad(int256 x, int256 y) internal pure returns (int256 z) { /// @solidity memory-safe-assembly assembly { z := sdiv(mul(x, y), WAD) } } /// @dev Equivalent to `(x * y) / WAD` rounded up. function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := mul(x, y) // Equivalent to `require(y == 0 || x <= type(uint256).max / y)`. if iszero(eq(div(z, y), x)) { if y { mstore(0x00, 0xbac65e5b) // `MulWadFailed()`. revert(0x1c, 0x04) } } z := add(iszero(iszero(mod(z, WAD))), div(z, WAD)) } } /// @dev Equivalent to `(x * y) / WAD` rounded up, but without overflow checks. function rawMulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := add(iszero(iszero(mod(mul(x, y), WAD))), div(mul(x, y), WAD)) } } /// @dev Equivalent to `(x * WAD) / y` rounded down. function divWad(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { // Equivalent to `require(y != 0 && x <= type(uint256).max / WAD)`. if iszero(mul(y, lt(x, add(1, div(not(0), WAD))))) { mstore(0x00, 0x7c5f487d) // `DivWadFailed()`. revert(0x1c, 0x04) } z := div(mul(x, WAD), y) } } /// @dev Equivalent to `(x * WAD) / y` rounded down. function sDivWad(int256 x, int256 y) internal pure returns (int256 z) { /// @solidity memory-safe-assembly assembly { z := mul(x, WAD) // Equivalent to `require(y != 0 && ((x * WAD) / WAD == x))`. if iszero(mul(y, eq(sdiv(z, WAD), x))) { mstore(0x00, 0x5c43740d) // `SDivWadFailed()`. revert(0x1c, 0x04) } z := sdiv(z, y) } } /// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks. function rawDivWad(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := div(mul(x, WAD), y) } } /// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks. function rawSDivWad(int256 x, int256 y) internal pure returns (int256 z) { /// @solidity memory-safe-assembly assembly { z := sdiv(mul(x, WAD), y) } } /// @dev Equivalent to `(x * WAD) / y` rounded up. function divWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { // Equivalent to `require(y != 0 && x <= type(uint256).max / WAD)`. if iszero(mul(y, lt(x, add(1, div(not(0), WAD))))) { mstore(0x00, 0x7c5f487d) // `DivWadFailed()`. revert(0x1c, 0x04) } z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y)) } } /// @dev Equivalent to `(x * WAD) / y` rounded up, but without overflow and divide by zero checks. function rawDivWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y)) } } /// @dev Equivalent to `x` to the power of `y`. /// because `x ** y = (e ** ln(x)) ** y = e ** (ln(x) * y)`. /// Note: This function is an approximation. function powWad(int256 x, int256 y) internal pure returns (int256) { // Using `ln(x)` means `x` must be greater than 0. return expWad((lnWad(x) * y) / int256(WAD)); } /// @dev Returns `exp(x)`, denominated in `WAD`. /// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln /// Note: This function is an approximation. Monotonically increasing. function expWad(int256 x) internal pure returns (int256 r) { unchecked { // When the result is less than 0.5 we return zero. // This happens when `x <= (log(1e-18) * 1e18) ~ -4.15e19`. if (x <= -41446531673892822313) return r; /// @solidity memory-safe-assembly assembly { // When the result is greater than `(2**255 - 1) / 1e18` we can not represent it as // an int. This happens when `x >= floor(log((2**255 - 1) / 1e18) * 1e18) ≈ 135`. if iszero(slt(x, 135305999368893231589)) { mstore(0x00, 0xa37bfec9) // `ExpOverflow()`. revert(0x1c, 0x04) } } // `x` is now in the range `(-42, 136) * 1e18`. Convert to `(-42, 136) * 2**96` // for more intermediate precision and a binary basis. This base conversion // is a multiplication by 1e18 / 2**96 = 5**18 / 2**78. x = (x << 78) / 5 ** 18; // Reduce range of x to (-½ ln 2, ½ ln 2) * 2**96 by factoring out powers // of two such that exp(x) = exp(x') * 2**k, where k is an integer. // Solving this gives k = round(x / log(2)) and x' = x - k * log(2). int256 k = ((x << 96) / 54916777467707473351141471128 + 2 ** 95) >> 96; x = x - k * 54916777467707473351141471128; // `k` is in the range `[-61, 195]`. // Evaluate using a (6, 7)-term rational approximation. // `p` is made monic, we'll multiply by a scale factor later. int256 y = x + 1346386616545796478920950773328; y = ((y * x) >> 96) + 57155421227552351082224309758442; int256 p = y + x - 94201549194550492254356042504812; p = ((p * y) >> 96) + 28719021644029726153956944680412240; p = p * x + (4385272521454847904659076985693276 << 96); // We leave `p` in `2**192` basis so we don't need to scale it back up for the division. int256 q = x - 2855989394907223263936484059900; q = ((q * x) >> 96) + 50020603652535783019961831881945; q = ((q * x) >> 96) - 533845033583426703283633433725380; q = ((q * x) >> 96) + 3604857256930695427073651918091429; q = ((q * x) >> 96) - 14423608567350463180887372962807573; q = ((q * x) >> 96) + 26449188498355588339934803723976023; /// @solidity memory-safe-assembly assembly { // Div in assembly because solidity adds a zero check despite the unchecked. // The q polynomial won't have zeros in the domain as all its roots are complex. // No scaling is necessary because p is already `2**96` too large. r := sdiv(p, q) } // r should be in the range `(0.09, 0.25) * 2**96`. // We now need to multiply r by: // - The scale factor `s ≈ 6.031367120`. // - The `2**k` factor from the range reduction. // - The `1e18 / 2**96` factor for base conversion. // We do this all at once, with an intermediate result in `2**213` // basis, so the final right shift is always by a positive amount. r = int256( (uint256(r) * 3822833074963236453042738258902158003155416615667) >> uint256(195 - k) ); } } /// @dev Returns `ln(x)`, denominated in `WAD`. /// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln /// Note: This function is an approximation. Monotonically increasing. function lnWad(int256 x) internal pure returns (int256 r) { /// @solidity memory-safe-assembly assembly { // We want to convert `x` from `10**18` fixed point to `2**96` fixed point. // We do this by multiplying by `2**96 / 10**18`. But since // `ln(x * C) = ln(x) + ln(C)`, we can simply do nothing here // and add `ln(2**96 / 10**18)` at the end. // Compute `k = log2(x) - 96`, `r = 159 - k = 255 - log2(x) = 255 ^ log2(x)`. r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x)) r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x)))) r := or(r, shl(5, lt(0xffffffff, shr(r, x)))) r := or(r, shl(4, lt(0xffff, shr(r, x)))) r := or(r, shl(3, lt(0xff, shr(r, x)))) // We place the check here for more optimal stack operations. if iszero(sgt(x, 0)) { mstore(0x00, 0x1615e638) // `LnWadUndefined()`. revert(0x1c, 0x04) } // forgefmt: disable-next-item r := xor(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)), 0xf8f9f9faf9fdfafbf9fdfcfdfafbfcfef9fafdfafcfcfbfefafafcfbffffffff)) // Reduce range of x to (1, 2) * 2**96 // ln(2^k * x) = k * ln(2) + ln(x) x := shr(159, shl(r, x)) // Evaluate using a (8, 8)-term rational approximation. // `p` is made monic, we will multiply by a scale factor later. // forgefmt: disable-next-item let p := sub( // This heavily nested expression is to avoid stack-too-deep for via-ir. sar(96, mul(add(43456485725739037958740375743393, sar(96, mul(add(24828157081833163892658089445524, sar(96, mul(add(3273285459638523848632254066296, x), x))), x))), x)), 11111509109440967052023855526967) p := sub(sar(96, mul(p, x)), 45023709667254063763336534515857) p := sub(sar(96, mul(p, x)), 14706773417378608786704636184526) p := sub(mul(p, x), shl(96, 795164235651350426258249787498)) // We leave `p` in `2**192` basis so we don't need to scale it back up for the division. // `q` is monic by convention. let q := add(5573035233440673466300451813936, x) q := add(71694874799317883764090561454958, sar(96, mul(x, q))) q := add(283447036172924575727196451306956, sar(96, mul(x, q))) q := add(401686690394027663651624208769553, sar(96, mul(x, q))) q := add(204048457590392012362485061816622, sar(96, mul(x, q))) q := add(31853899698501571402653359427138, sar(96, mul(x, q))) q := add(909429971244387300277376558375, sar(96, mul(x, q))) // `p / q` is in the range `(0, 0.125) * 2**96`. // Finalization, we need to: // - Multiply by the scale factor `s = 5.549…`. // - Add `ln(2**96 / 10**18)`. // - Add `k * ln(2)`. // - Multiply by `10**18 / 2**96 = 5**18 >> 78`. // The q polynomial is known not to have zeros in the domain. // No scaling required because p is already `2**96` too large. p := sdiv(p, q) // Multiply by the scaling factor: `s * 5**18 * 2**96`, base is now `5**18 * 2**192`. p := mul(1677202110996718588342820967067443963516166, p) // Add `ln(2) * k * 5**18 * 2**192`. // forgefmt: disable-next-item p := add(mul(16597577552685614221487285958193947469193820559219878177908093499208371, sub(159, r)), p) // Add `ln(2**96 / 10**18) * 5**18 * 2**192`. p := add(600920179829731861736702779321621459595472258049074101567377883020018308, p) // Base conversion: mul `2**18 / 2**192`. r := sar(174, p) } } /// @dev Returns `W_0(x)`, denominated in `WAD`. /// See: https://en.wikipedia.org/wiki/Lambert_W_function /// a.k.a. Product log function. This is an approximation of the principal branch. /// Note: This function is an approximation. Monotonically increasing. function lambertW0Wad(int256 x) internal pure returns (int256 w) { // forgefmt: disable-next-item unchecked { if ((w = x) <= -367879441171442322) revert OutOfDomain(); // `x` less than `-1/e`. (int256 wad, int256 p) = (int256(WAD), x); uint256 c; // Whether we need to avoid catastrophic cancellation. uint256 i = 4; // Number of iterations. if (w <= 0x1ffffffffffff) { if (-0x4000000000000 <= w) { i = 1; // Inputs near zero only take one step to converge. } else if (w <= -0x3ffffffffffffff) { i = 32; // Inputs near `-1/e` take very long to converge. } } else if (uint256(w >> 63) == uint256(0)) { /// @solidity memory-safe-assembly assembly { // Inline log2 for more performance, since the range is small. let v := shr(49, w) let l := shl(3, lt(0xff, v)) l := add(or(l, byte(and(0x1f, shr(shr(l, v), 0x8421084210842108cc6318c6db6d54be)), 0x0706060506020504060203020504030106050205030304010505030400000000)), 49) w := sdiv(shl(l, 7), byte(sub(l, 31), 0x0303030303030303040506080c13)) c := gt(l, 60) i := add(2, add(gt(l, 53), c)) } } else { int256 ll = lnWad(w = lnWad(w)); /// @solidity memory-safe-assembly assembly { // `w = ln(x) - ln(ln(x)) + b * ln(ln(x)) / ln(x)`. w := add(sdiv(mul(ll, 1023715080943847266), w), sub(w, ll)) i := add(3, iszero(shr(68, x))) c := iszero(shr(143, x)) } if (c == uint256(0)) { do { // If `x` is big, use Newton's so that intermediate values won't overflow. int256 e = expWad(w); /// @solidity memory-safe-assembly assembly { let t := mul(w, div(e, wad)) w := sub(w, sdiv(sub(t, x), div(add(e, t), wad))) } if (p <= w) break; p = w; } while (--i != uint256(0)); /// @solidity memory-safe-assembly assembly { w := sub(w, sgt(w, 2)) } return w; } } do { // Otherwise, use Halley's for faster convergence. int256 e = expWad(w); /// @solidity memory-safe-assembly assembly { let t := add(w, wad) let s := sub(mul(w, e), mul(x, wad)) w := sub(w, sdiv(mul(s, wad), sub(mul(e, t), sdiv(mul(add(t, wad), s), add(t, t))))) } if (p <= w) break; p = w; } while (--i != c); /// @solidity memory-safe-assembly assembly { w := sub(w, sgt(w, 2)) } // For certain ranges of `x`, we'll use the quadratic-rate recursive formula of // R. Iacono and J.P. Boyd for the last iteration, to avoid catastrophic cancellation. if (c == uint256(0)) return w; int256 t = w | 1; /// @solidity memory-safe-assembly assembly { x := sdiv(mul(x, wad), t) } x = (t * (wad + lnWad(x))); /// @solidity memory-safe-assembly assembly { w := sdiv(x, add(wad, t)) } } } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* GENERAL NUMBER UTILITIES */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Returns `a * b == x * y`, with full precision. function fullMulEq(uint256 a, uint256 b, uint256 x, uint256 y) internal pure returns (bool result) { /// @solidity memory-safe-assembly assembly { result := and(eq(mul(a, b), mul(x, y)), eq(mulmod(x, y, not(0)), mulmod(a, b, not(0)))) } } /// @dev Calculates `floor(x * y / d)` with full precision. /// Throws if result overflows a uint256 or when `d` is zero. /// Credit to Remco Bloemen under MIT license: https://2π.com/21/muldiv function fullMulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { // 512-bit multiply `[p1 p0] = x * y`. // Compute the product mod `2**256` and mod `2**256 - 1` // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that `product = p1 * 2**256 + p0`. // Temporarily use `z` as `p0` to save gas. z := mul(x, y) // Lower 256 bits of `x * y`. for {} 1 {} { // If overflows. if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) { let mm := mulmod(x, y, not(0)) let p1 := sub(mm, add(z, lt(mm, z))) // Upper 256 bits of `x * y`. /*------------------- 512 by 256 division --------------------*/ // Make division exact by subtracting the remainder from `[p1 p0]`. let r := mulmod(x, y, d) // Compute remainder using mulmod. let t := and(d, sub(0, d)) // The least significant bit of `d`. `t >= 1`. // Make sure `z` is less than `2**256`. Also prevents `d == 0`. // Placing the check here seems to give more optimal stack operations. if iszero(gt(d, p1)) { mstore(0x00, 0xae47f702) // `FullMulDivFailed()`. revert(0x1c, 0x04) } d := div(d, t) // Divide `d` by `t`, which is a power of two. // Invert `d mod 2**256` // Now that `d` is an odd number, it has an inverse // modulo `2**256` such that `d * inv = 1 mod 2**256`. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, `d * inv = 1 mod 2**4`. let inv := xor(2, mul(3, d)) // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**8 inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**16 inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**32 inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**64 inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**128 z := mul( // Divide [p1 p0] by the factors of two. // Shift in bits from `p1` into `p0`. For this we need // to flip `t` such that it is `2**256 / t`. or(mul(sub(p1, gt(r, z)), add(div(sub(0, t), t), 1)), div(sub(z, r), t)), mul(sub(2, mul(d, inv)), inv) // inverse mod 2**256 ) break } z := div(z, d) break } } } /// @dev Calculates `floor(x * y / d)` with full precision. /// Behavior is undefined if `d` is zero or the final result cannot fit in 256 bits. /// Performs the full 512 bit calculation regardless. function fullMulDivUnchecked(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := mul(x, y) let mm := mulmod(x, y, not(0)) let p1 := sub(mm, add(z, lt(mm, z))) let t := and(d, sub(0, d)) let r := mulmod(x, y, d) d := div(d, t) let inv := xor(2, mul(3, d)) inv := mul(inv, sub(2, mul(d, inv))) inv := mul(inv, sub(2, mul(d, inv))) inv := mul(inv, sub(2, mul(d, inv))) inv := mul(inv, sub(2, mul(d, inv))) inv := mul(inv, sub(2, mul(d, inv))) z := mul( or(mul(sub(p1, gt(r, z)), add(div(sub(0, t), t), 1)), div(sub(z, r), t)), mul(sub(2, mul(d, inv)), inv) ) } } /// @dev Calculates `floor(x * y / d)` with full precision, rounded up. /// Throws if result overflows a uint256 or when `d` is zero. /// Credit to Uniswap-v3-core under MIT license: /// https://github.com/Uniswap/v3-core/blob/main/contracts/libraries/FullMath.sol function fullMulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) { z = fullMulDiv(x, y, d); /// @solidity memory-safe-assembly assembly { if mulmod(x, y, d) { z := add(z, 1) if iszero(z) { mstore(0x00, 0xae47f702) // `FullMulDivFailed()`. revert(0x1c, 0x04) } } } } /// @dev Calculates `floor(x * y / 2 ** n)` with full precision. /// Throws if result overflows a uint256. /// Credit to Philogy under MIT license: /// https://github.com/SorellaLabs/angstrom/blob/main/contracts/src/libraries/X128MathLib.sol function fullMulDivN(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { // Temporarily use `z` as `p0` to save gas. z := mul(x, y) // Lower 256 bits of `x * y`. We'll call this `z`. for {} 1 {} { if iszero(or(iszero(x), eq(div(z, x), y))) { let k := and(n, 0xff) // `n`, cleaned. let mm := mulmod(x, y, not(0)) let p1 := sub(mm, add(z, lt(mm, z))) // Upper 256 bits of `x * y`. // | p1 | z | // Before: | p1_0 ¦ p1_1 | z_0 ¦ z_1 | // Final: | 0 ¦ p1_0 | p1_1 ¦ z_0 | // Check that final `z` doesn't overflow by checking that p1_0 = 0. if iszero(shr(k, p1)) { z := add(shl(sub(256, k), p1), shr(k, z)) break } mstore(0x00, 0xae47f702) // `FullMulDivFailed()`. revert(0x1c, 0x04) } z := shr(and(n, 0xff), z) break } } } /// @dev Returns `floor(x * y / d)`. /// Reverts if `x * y` overflows, or `d` is zero. function mulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := mul(x, y) // Equivalent to `require(d != 0 && (y == 0 || x <= type(uint256).max / y))`. if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) { mstore(0x00, 0xad251c27) // `MulDivFailed()`. revert(0x1c, 0x04) } z := div(z, d) } } /// @dev Returns `ceil(x * y / d)`. /// Reverts if `x * y` overflows, or `d` is zero. function mulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := mul(x, y) // Equivalent to `require(d != 0 && (y == 0 || x <= type(uint256).max / y))`. if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) { mstore(0x00, 0xad251c27) // `MulDivFailed()`. revert(0x1c, 0x04) } z := add(iszero(iszero(mod(z, d))), div(z, d)) } } /// @dev Returns `x`, the modular multiplicative inverse of `a`, such that `(a * x) % n == 1`. function invMod(uint256 a, uint256 n) internal pure returns (uint256 x) { /// @solidity memory-safe-assembly assembly { let g := n let r := mod(a, n) for { let y := 1 } 1 {} { let q := div(g, r) let t := g g := r r := sub(t, mul(r, q)) let u := x x := y y := sub(u, mul(y, q)) if iszero(r) { break } } x := mul(eq(g, 1), add(x, mul(slt(x, 0), n))) } } /// @dev Returns `ceil(x / d)`. /// Reverts if `d` is zero. function divUp(uint256 x, uint256 d) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { if iszero(d) { mstore(0x00, 0x65244e4e) // `DivFailed()`. revert(0x1c, 0x04) } z := add(iszero(iszero(mod(x, d))), div(x, d)) } } /// @dev Returns `max(0, x - y)`. Alias for `saturatingSub`. function zeroFloorSub(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := mul(gt(x, y), sub(x, y)) } } /// @dev Returns `max(0, x - y)`. function saturatingSub(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := mul(gt(x, y), sub(x, y)) } } /// @dev Returns `min(2 ** 256 - 1, x + y)`. function saturatingAdd(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := or(sub(0, lt(add(x, y), x)), add(x, y)) } } /// @dev Returns `min(2 ** 256 - 1, x * y)`. function saturatingMul(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := or(sub(or(iszero(x), eq(div(mul(x, y), x), y)), 1), mul(x, y)) } } /// @dev Returns `condition ? x : y`, without branching. function ternary(bool condition, uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := xor(x, mul(xor(x, y), iszero(condition))) } } /// @dev Returns `condition ? x : y`, without branching. function ternary(bool condition, bytes32 x, bytes32 y) internal pure returns (bytes32 z) { /// @solidity memory-safe-assembly assembly { z := xor(x, mul(xor(x, y), iszero(condition))) } } /// @dev Returns `condition ? x : y`, without branching. function ternary(bool condition, address x, address y) internal pure returns (address z) { /// @solidity memory-safe-assembly assembly { z := xor(x, mul(xor(x, y), iszero(condition))) } } /// @dev Returns `x != 0 ? x : y`, without branching. function coalesce(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := or(x, mul(y, iszero(x))) } } /// @dev Returns `x != bytes32(0) ? x : y`, without branching. function coalesce(bytes32 x, bytes32 y) internal pure returns (bytes32 z) { /// @solidity memory-safe-assembly assembly { z := or(x, mul(y, iszero(x))) } } /// @dev Returns `x != address(0) ? x : y`, without branching. function coalesce(address x, address y) internal pure returns (address z) { /// @solidity memory-safe-assembly assembly { z := or(x, mul(y, iszero(shl(96, x)))) } } /// @dev Exponentiate `x` to `y` by squaring, denominated in base `b`. /// Reverts if the computation overflows. function rpow(uint256 x, uint256 y, uint256 b) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := mul(b, iszero(y)) // `0 ** 0 = 1`. Otherwise, `0 ** n = 0`. if x { z := xor(b, mul(xor(b, x), and(y, 1))) // `z = isEven(y) ? scale : x` let half := shr(1, b) // Divide `b` by 2. // Divide `y` by 2 every iteration. for { y := shr(1, y) } y { y := shr(1, y) } { let xx := mul(x, x) // Store x squared. let xxRound := add(xx, half) // Round to the nearest number. // Revert if `xx + half` overflowed, or if `x ** 2` overflows. if or(lt(xxRound, xx), shr(128, x)) { mstore(0x00, 0x49f7642b) // `RPowOverflow()`. revert(0x1c, 0x04) } x := div(xxRound, b) // Set `x` to scaled `xxRound`. // If `y` is odd: if and(y, 1) { let zx := mul(z, x) // Compute `z * x`. let zxRound := add(zx, half) // Round to the nearest number. // If `z * x` overflowed or `zx + half` overflowed: if or(xor(div(zx, x), z), lt(zxRound, zx)) { // Revert if `x` is non-zero. if x { mstore(0x00, 0x49f7642b) // `RPowOverflow()`. revert(0x1c, 0x04) } } z := div(zxRound, b) // Return properly scaled `zxRound`. } } } } } /// @dev Returns the square root of `x`, rounded down. function sqrt(uint256 x) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { // `floor(sqrt(2**15)) = 181`. `sqrt(2**15) - 181 = 2.84`. z := 181 // The "correct" value is 1, but this saves a multiplication later. // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically. // Let `y = x / 2**r`. We check `y >= 2**(k + 8)` // but shift right by `k` bits to ensure that if `x >= 256`, then `y >= 256`. let r := shl(7, lt(0xffffffffffffffffffffffffffffffffff, x)) r := or(r, shl(6, lt(0xffffffffffffffffff, shr(r, x)))) r := or(r, shl(5, lt(0xffffffffff, shr(r, x)))) r := or(r, shl(4, lt(0xffffff, shr(r, x)))) z := shl(shr(1, r), z) // Goal was to get `z*z*y` within a small factor of `x`. More iterations could // get y in a tighter range. Currently, we will have y in `[256, 256*(2**16))`. // We ensured `y >= 256` so that the relative difference between `y` and `y+1` is small. // That's not possible if `x < 256` but we can just verify those cases exhaustively. // Now, `z*z*y <= x < z*z*(y+1)`, and `y <= 2**(16+8)`, and either `y >= 256`, or `x < 256`. // Correctness can be checked exhaustively for `x < 256`, so we assume `y >= 256`. // Then `z*sqrt(y)` is within `sqrt(257)/sqrt(256)` of `sqrt(x)`, or about 20bps. // For `s` in the range `[1/256, 256]`, the estimate `f(s) = (181/1024) * (s+1)` // is in the range `(1/2.84 * sqrt(s), 2.84 * sqrt(s))`, // with largest error when `s = 1` and when `s = 256` or `1/256`. // Since `y` is in `[256, 256*(2**16))`, let `a = y/65536`, so that `a` is in `[1/256, 256)`. // Then we can estimate `sqrt(y)` using // `sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2**18`. // There is no overflow risk here since `y < 2**136` after the first branch above. z := shr(18, mul(z, add(shr(r, x), 65536))) // A `mul()` is saved from starting `z` at 181. // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough. z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) // If `x+1` is a perfect square, the Babylonian method cycles between // `floor(sqrt(x))` and `ceil(sqrt(x))`. This statement ensures we return floor. // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division z := sub(z, lt(div(x, z), z)) } } /// @dev Returns the cube root of `x`, rounded down. /// Credit to bout3fiddy and pcaversaccio under AGPLv3 license: /// https://github.com/pcaversaccio/snekmate/blob/main/src/utils/Math.vy /// Formally verified by xuwinnie: /// https://github.com/vectorized/solady/blob/main/audits/xuwinnie-solady-cbrt-proof.pdf function cbrt(uint256 x) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { let r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x)) r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x)))) r := or(r, shl(5, lt(0xffffffff, shr(r, x)))) r := or(r, shl(4, lt(0xffff, shr(r, x)))) r := or(r, shl(3, lt(0xff, shr(r, x)))) // Makeshift lookup table to nudge the approximate log2 result. z := div(shl(div(r, 3), shl(lt(0xf, shr(r, x)), 0xf)), xor(7, mod(r, 3))) // Newton-Raphson's. z := div(add(add(div(x, mul(z, z)), z), z), 3) z := div(add(add(div(x, mul(z, z)), z), z), 3) z := div(add(add(div(x, mul(z, z)), z), z), 3) z := div(add(add(div(x, mul(z, z)), z), z), 3) z := div(add(add(div(x, mul(z, z)), z), z), 3) z := div(add(add(div(x, mul(z, z)), z), z), 3) z := div(add(add(div(x, mul(z, z)), z), z), 3) // Round down. z := sub(z, lt(div(x, mul(z, z)), z)) } } /// @dev Returns the square root of `x`, denominated in `WAD`, rounded down. function sqrtWad(uint256 x) internal pure returns (uint256 z) { unchecked { if (x <= type(uint256).max / 10 ** 18) return sqrt(x * 10 ** 18); z = (1 + sqrt(x)) * 10 ** 9; z = (fullMulDivUnchecked(x, 10 ** 18, z) + z) >> 1; } /// @solidity memory-safe-assembly assembly { z := sub(z, gt(999999999999999999, sub(mulmod(z, z, x), 1))) // Round down. } } /// @dev Returns the cube root of `x`, denominated in `WAD`, rounded down. /// Formally verified by xuwinnie: /// https://github.com/vectorized/solady/blob/main/audits/xuwinnie-solady-cbrt-proof.pdf function cbrtWad(uint256 x) internal pure returns (uint256 z) { unchecked { if (x <= type(uint256).max / 10 ** 36) return cbrt(x * 10 ** 36); z = (1 + cbrt(x)) * 10 ** 12; z = (fullMulDivUnchecked(x, 10 ** 36, z * z) + z + z) / 3; } /// @solidity memory-safe-assembly assembly { let p := x for {} 1 {} { if iszero(shr(229, p)) { if iszero(shr(199, p)) { p := mul(p, 100000000000000000) // 10 ** 17. break } p := mul(p, 100000000) // 10 ** 8. break } if iszero(shr(249, p)) { p := mul(p, 100) } break } let t := mulmod(mul(z, z), z, p) z := sub(z, gt(lt(t, shr(1, p)), iszero(t))) // Round down. } } /// @dev Returns the factorial of `x`. function factorial(uint256 x) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := 1 if iszero(lt(x, 58)) { mstore(0x00, 0xaba0f2a2) // `FactorialOverflow()`. revert(0x1c, 0x04) } for {} x { x := sub(x, 1) } { z := mul(z, x) } } } /// @dev Returns the log2 of `x`. /// Equivalent to computing the index of the most significant bit (MSB) of `x`. /// Returns 0 if `x` is zero. function log2(uint256 x) internal pure returns (uint256 r) { /// @solidity memory-safe-assembly assembly { r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x)) r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x)))) r := or(r, shl(5, lt(0xffffffff, shr(r, x)))) r := or(r, shl(4, lt(0xffff, shr(r, x)))) r := or(r, shl(3, lt(0xff, shr(r, x)))) // forgefmt: disable-next-item r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)), 0x0706060506020504060203020504030106050205030304010505030400000000)) } } /// @dev Returns the log2 of `x`, rounded up. /// Returns 0 if `x` is zero. function log2Up(uint256 x) internal pure returns (uint256 r) { r = log2(x); /// @solidity memory-safe-assembly assembly { r := add(r, lt(shl(r, 1), x)) } } /// @dev Returns the log10 of `x`. /// Returns 0 if `x` is zero. function log10(uint256 x) internal pure returns (uint256 r) { /// @solidity memory-safe-assembly assembly { if iszero(lt(x, 100000000000000000000000000000000000000)) { x := div(x, 100000000000000000000000000000000000000) r := 38 } if iszero(lt(x, 100000000000000000000)) { x := div(x, 100000000000000000000) r := add(r, 20) } if iszero(lt(x, 10000000000)) { x := div(x, 10000000000) r := add(r, 10) } if iszero(lt(x, 100000)) { x := div(x, 100000) r := add(r, 5) } r := add(r, add(gt(x, 9), add(gt(x, 99), add(gt(x, 999), gt(x, 9999))))) } } /// @dev Returns the log10 of `x`, rounded up. /// Returns 0 if `x` is zero. function log10Up(uint256 x) internal pure returns (uint256 r) { r = log10(x); /// @solidity memory-safe-assembly assembly { r := add(r, lt(exp(10, r), x)) } } /// @dev Returns the log256 of `x`. /// Returns 0 if `x` is zero. function log256(uint256 x) internal pure returns (uint256 r) { /// @solidity memory-safe-assembly assembly { r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x)) r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x)))) r := or(r, shl(5, lt(0xffffffff, shr(r, x)))) r := or(r, shl(4, lt(0xffff, shr(r, x)))) r := or(shr(3, r), lt(0xff, shr(r, x))) } } /// @dev Returns the log256 of `x`, rounded up. /// Returns 0 if `x` is zero. function log256Up(uint256 x) internal pure returns (uint256 r) { r = log256(x); /// @solidity memory-safe-assembly assembly { r := add(r, lt(shl(shl(3, r), 1), x)) } } /// @dev Returns the scientific notation format `mantissa * 10 ** exponent` of `x`. /// Useful for compressing prices (e.g. using 25 bit mantissa and 7 bit exponent). function sci(uint256 x) internal pure returns (uint256 mantissa, uint256 exponent) { /// @solidity memory-safe-assembly assembly { mantissa := x if mantissa { if iszero(mod(mantissa, 1000000000000000000000000000000000)) { mantissa := div(mantissa, 1000000000000000000000000000000000) exponent := 33 } if iszero(mod(mantissa, 10000000000000000000)) { mantissa := div(mantissa, 10000000000000000000) exponent := add(exponent, 19) } if iszero(mod(mantissa, 1000000000000)) { mantissa := div(mantissa, 1000000000000) exponent := add(exponent, 12) } if iszero(mod(mantissa, 1000000)) { mantissa := div(mantissa, 1000000) exponent := add(exponent, 6) } if iszero(mod(mantissa, 10000)) { mantissa := div(mantissa, 10000) exponent := add(exponent, 4) } if iszero(mod(mantissa, 100)) { mantissa := div(mantissa, 100) exponent := add(exponent, 2) } if iszero(mod(mantissa, 10)) { mantissa := div(mantissa, 10) exponent := add(exponent, 1) } } } } /// @dev Convenience function for packing `x` into a smaller number using `sci`. /// The `mantissa` will be in bits [7..255] (the upper 249 bits). /// The `exponent` will be in bits [0..6] (the lower 7 bits). /// Use `SafeCastLib` to safely ensure that the `packed` number is small /// enough to fit in the desired unsigned integer type: /// ``` /// uint32 packed = SafeCastLib.toUint32(FixedPointMathLib.packSci(777 ether)); /// ``` function packSci(uint256 x) internal pure returns (uint256 packed) { (x, packed) = sci(x); // Reuse for `mantissa` and `exponent`. /// @solidity memory-safe-assembly assembly { if shr(249, x) { mstore(0x00, 0xce30380c) // `MantissaOverflow()`. revert(0x1c, 0x04) } packed := or(shl(7, x), packed) } } /// @dev Convenience function for unpacking a packed number from `packSci`. function unpackSci(uint256 packed) internal pure returns (uint256 unpacked) { unchecked { unpacked = (packed >> 7) * 10 ** (packed & 0x7f); } } /// @dev Returns the average of `x` and `y`. Rounds towards zero. function avg(uint256 x, uint256 y) internal pure returns (uint256 z) { unchecked { z = (x & y) + ((x ^ y) >> 1); } } /// @dev Returns the average of `x` and `y`. Rounds towards negative infinity. function avg(int256 x, int256 y) internal pure returns (int256 z) { unchecked { z = (x >> 1) + (y >> 1) + (x & y & 1); } } /// @dev Returns the absolute value of `x`. function abs(int256 x) internal pure returns (uint256 z) { unchecked { z = (uint256(x) + uint256(x >> 255)) ^ uint256(x >> 255); } } /// @dev Returns the absolute distance between `x` and `y`. function dist(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := add(xor(sub(0, gt(x, y)), sub(y, x)), gt(x, y)) } } /// @dev Returns the absolute distance between `x` and `y`. function dist(int256 x, int256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := add(xor(sub(0, sgt(x, y)), sub(y, x)), sgt(x, y)) } } /// @dev Returns the minimum of `x` and `y`. function min(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := xor(x, mul(xor(x, y), lt(y, x))) } } /// @dev Returns the minimum of `x` and `y`. function min(int256 x, int256 y) internal pure returns (int256 z) { /// @solidity memory-safe-assembly assembly { z := xor(x, mul(xor(x, y), slt(y, x))) } } /// @dev Returns the maximum of `x` and `y`. function max(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := xor(x, mul(xor(x, y), gt(y, x))) } } /// @dev Returns the maximum of `x` and `y`. function max(int256 x, int256 y) internal pure returns (int256 z) { /// @solidity memory-safe-assembly assembly { z := xor(x, mul(xor(x, y), sgt(y, x))) } } /// @dev Returns `x`, bounded to `minValue` and `maxValue`. function clamp(uint256 x, uint256 minValue, uint256 maxValue) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := xor(x, mul(xor(x, minValue), gt(minValue, x))) z := xor(z, mul(xor(z, maxValue), lt(maxValue, z))) } } /// @dev Returns `x`, bounded to `minValue` and `maxValue`. function clamp(int256 x, int256 minValue, int256 maxValue) internal pure returns (int256 z) { /// @solidity memory-safe-assembly assembly { z := xor(x, mul(xor(x, minValue), sgt(minValue, x))) z := xor(z, mul(xor(z, maxValue), slt(maxValue, z))) } } /// @dev Returns greatest common divisor of `x` and `y`. function gcd(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { for { z := x } y {} { let t := y y := mod(z, y) z := t } } } /// @dev Returns `a + (b - a) * (t - begin) / (end - begin)`, /// with `t` clamped between `begin` and `end` (inclusive). /// Agnostic to the order of (`a`, `b`) and (`end`, `begin`). /// If `begins == end`, returns `t <= begin ? a : b`. function lerp(uint256 a, uint256 b, uint256 t, uint256 begin, uint256 end) internal pure returns (uint256) { if (begin > end) (t, begin, end) = (~t, ~begin, ~end); if (t <= begin) return a; if (t >= end) return b; unchecked { if (b >= a) return a + fullMulDiv(b - a, t - begin, end - begin); return a - fullMulDiv(a - b, t - begin, end - begin); } } /// @dev Returns `a + (b - a) * (t - begin) / (end - begin)`. /// with `t` clamped between `begin` and `end` (inclusive). /// Agnostic to the order of (`a`, `b`) and (`end`, `begin`). /// If `begins == end`, returns `t <= begin ? a : b`. function lerp(int256 a, int256 b, int256 t, int256 begin, int256 end) internal pure returns (int256) { if (begin > end) (t, begin, end) = (~t, ~begin, ~end); if (t <= begin) return a; if (t >= end) return b; // forgefmt: disable-next-item unchecked { if (b >= a) return int256(uint256(a) + fullMulDiv(uint256(b - a), uint256(t - begin), uint256(end - begin))); return int256(uint256(a) - fullMulDiv(uint256(a - b), uint256(t - begin), uint256(end - begin))); } } /// @dev Returns if `x` is an even number. Some people may need this. function isEven(uint256 x) internal pure returns (bool) { return x & uint256(1) == uint256(0); } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* RAW NUMBER OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Returns `x + y`, without checking for overflow. function rawAdd(uint256 x, uint256 y) internal pure returns (uint256 z) { unchecked { z = x + y; } } /// @dev Returns `x + y`, without checking for overflow. function rawAdd(int256 x, int256 y) internal pure returns (int256 z) { unchecked { z = x + y; } } /// @dev Returns `x - y`, without checking for underflow. function rawSub(uint256 x, uint256 y) internal pure returns (uint256 z) { unchecked { z = x - y; } } /// @dev Returns `x - y`, without checking for underflow. function rawSub(int256 x, int256 y) internal pure returns (int256 z) { unchecked { z = x - y; } } /// @dev Returns `x * y`, without checking for overflow. function rawMul(uint256 x, uint256 y) internal pure returns (uint256 z) { unchecked { z = x * y; } } /// @dev Returns `x * y`, without checking for overflow. function rawMul(int256 x, int256 y) internal pure returns (int256 z) { unchecked { z = x * y; } } /// @dev Returns `x / y`, returning 0 if `y` is zero. function rawDiv(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := div(x, y) } } /// @dev Returns `x / y`, returning 0 if `y` is zero. function rawSDiv(int256 x, int256 y) internal pure returns (int256 z) { /// @solidity memory-safe-assembly assembly { z := sdiv(x, y) } } /// @dev Returns `x % y`, returning 0 if `y` is zero. function rawMod(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := mod(x, y) } } /// @dev Returns `x % y`, returning 0 if `y` is zero. function rawSMod(int256 x, int256 y) internal pure returns (int256 z) { /// @solidity memory-safe-assembly assembly { z := smod(x, y) } } /// @dev Returns `(x + y) % d`, return 0 if `d` if zero. function rawAddMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := addmod(x, y, d) } } /// @dev Returns `(x * y) % d`, return 0 if `d` if zero. function rawMulMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := mulmod(x, y, d) } } }
// SPDX-License-Identifier: BUSL-1.1 // solhint-disable-next-line compiler-version pragma solidity 0.8.26; import { SafeTransferLib } from "solady/src/utils/SafeTransferLib.sol"; library Utils { using SafeTransferLib for address; /// @notice The gas limit for a transfer, used to prevent malicious token griefing. uint32 constant TRANSFER_GAS_LIMIT = 500_000; /// @notice Error for overflow when increasing allowance error IncreaseAllowanceOverflow(); /// @dev Reverts with the selector of a custom error in the scratch space. function revertWith(bytes4 selector) internal pure { assembly ("memory-safe") { mstore(0, selector) revert(0, 0x04) } } /// @dev Reverts for the reason encoding a silent revert, Error(string), or a custom error. function revertFor(bytes memory reason) internal pure { assembly ("memory-safe") { revert(add(reason, 0x20), mload(reason)) } } function revertWith(bytes4 selector, address addr) internal pure { assembly ("memory-safe") { mstore(0, selector) mstore(0x04, addr) revert(0, 0x24) // 4 (selector) + 32 (addr) } } function revertWith(bytes4 selector, uint256 amount) internal pure { assembly ("memory-safe") { mstore(0, selector) mstore(0x04, amount) revert(0, 0x24) // 4 (selector) + 32 (amount) } } function revertWith(bytes4 selector, uint256 amount1, uint256 amount2) internal pure { assembly ("memory-safe") { mstore(0, selector) mstore(0x04, amount1) mstore(0x24, amount2) revert(0, 0x44) // 4 (selector) + 32 (amount1) + 32 (amount2) } } function revertWith(bytes4 selector, address addr1, address addr2) internal pure { assembly ("memory-safe") { mstore(0, selector) mstore(0x04, addr1) mstore(0x24, addr2) revert(0, 0x44) // 4 (selector) + 32 (addr1) + 32 (addr2) } } /// @dev Increase the calling contract's allowance toward `spender` by `amount`. /// @dev Does not check if token exists. function safeIncreaseAllowance(address token, address spender, uint256 amount) internal { unchecked { uint256 oldAllowance = allowance(token, address(this), spender); uint256 newAllowance = oldAllowance + amount; if (newAllowance < oldAllowance) revertWith(IncreaseAllowanceOverflow.selector); token.safeApprove(spender, newAllowance); } } /// @dev Returns the amount of ERC20 `token` that `owner` has allowed `spender` to use. /// Returns zero if the `token` does not exist. function allowance(address token, address owner, address spender) internal view returns (uint256 amount) { assembly ("memory-safe") { mstore(0, 0xdd62ed3e00000000000000000000000000000000000000000000000000000000) // Store function selector of // `allowance(address,address)`. mstore(0x04, owner) // Store the `owner` argument. mstore(0x24, spender) // Store the `spender` argument. amount := mul( // The arguments of `mul` are evaluated from right to left. mload(0), and( // The arguments of `and` are evaluated from right to left. gt(returndatasize(), 0x1f), // At least 32 bytes returned. staticcall(gas(), token, 0, 0x44, 0, 0x20) ) ) mstore(0x24, 0) // clear the upper bits of free memory pointer. } } /// @dev Sends `amount` of ERC20 `token` from the current contract to `to`. /// Doesn't revert upon failure. function trySafeTransfer(address token, address to, uint256 amount) internal returns (bool success) { assembly ("memory-safe") { mstore(0x14, to) // Store the `to` argument. mstore(0x34, amount) // Store the `amount` argument. mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)` function selector. // Perform the transfer, returning success status. success := and( or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing. call(TRANSFER_GAS_LIMIT, token, 0, 0x10, 0x44, 0x00, 0x20) ) mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten. } } function changeDecimals(uint256 amount, uint8 from, uint8 to) internal pure returns (uint256) { if (from == to) { return amount; } if (from > to) { return amount / (10 ** (from - to)); } else { return amount * (10 ** (to - from)); } } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.26; import { IPOLErrors } from "./IPOLErrors.sol"; /// @title IBeaconDeposit /// @author Berachain Team. interface IBeaconDeposit is IPOLErrors { /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* EVENTS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /** * @dev Emitted when a deposit is made, which could mean a new validator or a top up of an existing one. * @param pubkey the public key of the validator. * @param credentials is the withdrawal credentials of the validator. * @param amount the amount of stake being deposited, in Gwei. * @param signature the signature of the deposit message. * @param index the index of the deposit. */ event Deposit(bytes pubkey, bytes credentials, uint64 amount, bytes signature, uint64 index); /** * @notice Emitted when the operator change of a validator is queued. * @param pubkey The pubkey of the validator. * @param queuedOperator The new queued operator address. * @param currentOperator The current operator address. * @param queuedTimestamp The timestamp when the change was queued. */ event OperatorChangeQueued( bytes indexed pubkey, address queuedOperator, address currentOperator, uint256 queuedTimestamp ); /** * @notice Emitted when the operator change of a validator is cancelled. * @param pubkey The pubkey of the validator. */ event OperatorChangeCancelled(bytes indexed pubkey); /** * @notice Emitted when the operator of a validator is updated. * @param pubkey The pubkey of the validator. * @param newOperator The new operator address. * @param previousOperator The previous operator address. */ event OperatorUpdated(bytes indexed pubkey, address newOperator, address previousOperator); /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* VIEWS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /** * @notice Get the operator address for a given pubkey. * @dev Returns zero address if the pubkey is not registered. * @param pubkey The pubkey of the validator. * @return The operator address for the given pubkey. */ function getOperator(bytes calldata pubkey) external view returns (address); /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* WRITES */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /** * @notice Submit a deposit message to the Beaconchain. * @notice This will be used to create a new validator or to top up an existing one, increasing stake. * @param pubkey is the consensus public key of the validator. * @param credentials is the withdrawal credentials of the validator. * @param signature is the signature used only on the first deposit. * @param operator is the address of the operator used for `POL` mechanics. * @dev emits the Deposit event upon successful deposit. * @dev Reverts if the operator is already set and caller passed non-zero operator. */ function deposit( bytes calldata pubkey, bytes calldata credentials, bytes calldata signature, address operator ) external payable; /** * @notice Request to change the operator of a validator. * @dev Only the current operator can request a change. * @param pubkey The pubkey of the validator. * @param newOperator The new operator address. */ function requestOperatorChange(bytes calldata pubkey, address newOperator) external; /** * @notice Cancel the operator change of a validator. * @dev Only the current operator can cancel the change. * @param pubkey The pubkey of the validator. */ function cancelOperatorChange(bytes calldata pubkey) external; /** * @notice Accept the operator change of a validator. * @dev Only the new operator can accept the change. * @dev Reverts if the queue delay has not passed. * @param pubkey The pubkey of the validator. */ function acceptOperatorChange(bytes calldata pubkey) external; }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.26; import { IPOLErrors } from "./IPOLErrors.sol"; import { IStakingRewards } from "../../base/IStakingRewards.sol"; interface IRewardVault is IPOLErrors, IStakingRewards { /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* EVENTS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @notice Emitted when a delegate has staked on behalf of an account. /// @param account The account whose delegate has staked. /// @param delegate The delegate that has staked. /// @param amount The amount of staked tokens. event DelegateStaked(address indexed account, address indexed delegate, uint256 amount); /// @notice Emitted when a delegate has withdrawn on behalf of an account. /// @param account The account whose delegate has withdrawn. /// @param delegate The delegate that has withdrawn. /// @param amount The amount of withdrawn tokens. event DelegateWithdrawn(address indexed account, address indexed delegate, uint256 amount); /// @notice Emitted when a token has been recovered. /// @param token The token that has been recovered. /// @param amount The amount of token recovered. event Recovered(address token, uint256 amount); /// @notice Emitted when the msg.sender has set an operator to handle its rewards. /// @param account The account that has set the operator. /// @param operator The operator that has been set. event OperatorSet(address account, address operator); /// @notice Emitted when the distributor is set. /// @param distributor The address of the distributor. event DistributorSet(address indexed distributor); /// @notice Emitted when the manager of an incentive token is changed. /// @param token The address of the incentive token. /// @param newManager The new manager of the incentive token. /// @param oldManager The old manager of the incentive token. event IncentiveManagerChanged(address indexed token, address newManager, address oldManager); /// @notice Emitted when an incentive token is whitelisted. /// @param token The address of the token that has been whitelisted. /// @param minIncentiveRate The minimum amount of the token to incentivize per BGT emission. /// @param manager The address of the manager that can addIncentive for this incentive token. event IncentiveTokenWhitelisted(address indexed token, uint256 minIncentiveRate, address manager); /// @notice Emitted when an incentive token is removed. /// @param token The address of the token that has been removed. event IncentiveTokenRemoved(address indexed token); /// @notice Emitted when maxIncentiveTokensCount is updated. /// @param maxIncentiveTokensCount The max count of incentive tokens. event MaxIncentiveTokensCountUpdated(uint8 maxIncentiveTokensCount); /// @notice Emitted when incentives are processed for the operator of a validator. event IncentivesProcessed(bytes indexed pubkey, address indexed token, uint256 bgtEmitted, uint256 amount); /// @notice Emitted when incentives fail to be processed for the operator of a validator. event IncentivesProcessFailed(bytes indexed pubkey, address indexed token, uint256 bgtEmitted, uint256 amount); /// @notice Emitted when incentives are added to the vault. /// @param token The incentive token. /// @param sender The address that added the incentive. /// @param amount The amount of the incentive. /// @param incentiveRate The amount of the token to incentivize per BGT emission. event IncentiveAdded(address indexed token, address sender, uint256 amount, uint256 incentiveRate); /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* GETTERS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @notice Get the address that is allowed to distribute rewards. /// @return The address that is allowed to distribute rewards. function distributor() external view returns (address); /// @notice Get the operator for an account. /// @param account The account to get the operator for. /// @return The operator for the account. function operator(address account) external view returns (address); /// @notice Get the count of active incentive tokens. /// @return The count of active incentive tokens. function getWhitelistedTokensCount() external view returns (uint256); /// @notice Get the list of whitelisted tokens. /// @return The list of whitelisted tokens. function getWhitelistedTokens() external view returns (address[] memory); /// @notice Get the total amount staked by delegates. /// @return The total amount staked by delegates. function getTotalDelegateStaked(address account) external view returns (uint256); /// @notice Get the amount staked by a delegate on behalf of an account. /// @return The amount staked by a delegate. function getDelegateStake(address account, address delegate) external view returns (uint256); /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* ADMIN */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /** * @notice Initialize the vault, this is only callable once and by the factory since its the deployer. * @param _berachef The address of the berachef. * @param _bgt The address of the BGT token. * @param _distributor The address of the distributor. * @param _stakingToken The address of the staking token. */ function initialize(address _berachef, address _bgt, address _distributor, address _stakingToken) external; /// @notice Allows the factory owner to set the contract that is allowed to distribute rewards. /// @param _rewardDistribution The address that is allowed to distribute rewards. function setDistributor(address _rewardDistribution) external; /// @notice Allows the distributor to notify the reward amount. /// @param pubkey The pubkey of the validator. /// @param reward The amount of reward to notify. function notifyRewardAmount(bytes calldata pubkey, uint256 reward) external; /// @notice Allows the factory owner to recover any ERC20 token from the vault. /// @param tokenAddress The address of the token to recover. /// @param tokenAmount The amount of token to recover. function recoverERC20(address tokenAddress, uint256 tokenAmount) external; /// @notice Allows the factory owner to update the duration of the rewards. /// @param _rewardsDuration The new duration of the rewards. function setRewardsDuration(uint256 _rewardsDuration) external; /// @notice Allows the factory owner to whitelist a token to incentivize with. /// @param token The address of the token to whitelist. /// @param minIncentiveRate The minimum amount of the token to incentivize per BGT emission. /// @param manager The address of the manager that can addIncentive for this token. function whitelistIncentiveToken(address token, uint256 minIncentiveRate, address manager) external; /// @notice Allows the factory vault manager to remove a whitelisted incentive token. /// @param token The address of the token to remove. function removeIncentiveToken(address token) external; /// @notice Allows the factory owner to update the maxIncentiveTokensCount. /// @param _maxIncentiveTokensCount The new maxIncentiveTokens count. function setMaxIncentiveTokensCount(uint8 _maxIncentiveTokensCount) external; /// @notice Allows the factory vault pauser to pause the vault. function pause() external; /// @notice Allows the factory vault manager to unpause the vault. function unpause() external; /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* MUTATIVE */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @notice Exit the vault with the staked tokens and claim the reward. /// @dev Only the account holder can call this function, not the operator. /// @dev Clears out the user self-staked balance and rewards. /// @param recipient The address to send the 'BGT' reward to. function exit(address recipient) external; /// @notice Claim the reward. /// @dev The operator only handles BGT, not STAKING_TOKEN. /// @dev Callable by the operator or the account holder. /// @param account The account to get the reward for. /// @param recipient The address to send the reward to. /// @return The amount of the reward claimed. function getReward(address account, address recipient) external returns (uint256); /// @notice Stake tokens in the vault. /// @param amount The amount of tokens to stake. function stake(uint256 amount) external; /// @notice Stake tokens on behalf of another account. /// @param account The account to stake for. /// @param amount The amount of tokens to stake. function delegateStake(address account, uint256 amount) external; /// @notice Withdraw the staked tokens from the vault. /// @param amount The amount of tokens to withdraw. function withdraw(uint256 amount) external; /// @notice Withdraw tokens staked on behalf of another account by the delegate (msg.sender). /// @param account The account to withdraw for. /// @param amount The amount of tokens to withdraw. function delegateWithdraw(address account, uint256 amount) external; /// @notice Allows msg.sender to set another address to claim and manage their rewards. /// @param _operator The address that will be allowed to claim and manage rewards. function setOperator(address _operator) external; /// @notice Update the manager of an incentive token. /// @dev Permissioned function, only allow factory owner to update the manager. /// @param token The address of the incentive token. /// @param newManager The new manager of the incentive token. function updateIncentiveManager(address token, address newManager) external; /// @notice Add an incentive token to the vault. /// @notice The incentive token's transfer should not exceed a gas usage of 500k units. /// In case the transfer exceeds 500k gas units, your incentive will fail to be transferred to the validator and /// its delegates. /// @param token The address of the token to add as an incentive. /// @param amount The amount of the token to add as an incentive. /// @param incentiveRate The amount of the token to incentivize per BGT emission. /// @dev Permissioned function, only callable by incentive token manager. function addIncentive(address token, uint256 amount, uint256 incentiveRate) external; }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.26; import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import { AccessControlUpgradeable } from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import { IRewardVaultFactory } from "../pol/interfaces/IRewardVaultFactory.sol"; import { Utils } from "../libraries/Utils.sol"; /// @title FactoryOwnable /// @author Berachain Team /// @notice Contract module which provides a modifier for restricting access to the factory owner. abstract contract FactoryOwnable is Initializable { using Utils for bytes4; /// @notice Throws if sender is not the owner of factory contract. /// @param account The address of the sender. error OwnableUnauthorizedAccount(address account); /// @custom:storage-location erc7201:berachain.storage.factoryOwnable struct FactoryOwnableStorage { address _factory; } // keccak256(abi.encode(uint256(keccak256("berachain.storage.factoryOwnable")) - 1)) & ~bytes32(uint256(0xff)) bytes32 private constant FactoryOwnableStorageLocation = 0x4e32a932fdd4658a66f9586d8955a0d0a795a01bd8251335b4fae29d972acc00; /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* INITIALIZER */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Must be called by the initializer of the inheriting contract. /// @param factoryAddr The address of the ownable factory contract. function __FactoryOwnable_init(address factoryAddr) internal onlyInitializing { _setFactory(factoryAddr); } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* MODIFIERS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Throws if called by any account other than the factory owner. modifier onlyFactoryOwner() { _checkFactoryOwner(); _; } /// @dev Throws if called by any account other than the factory vault manager. modifier onlyFactoryVaultManager() { _checkFactoryVaultManager(); _; } /// @dev Throws if called by any account other than the factory vault pauser. modifier onlyFactoryVaultPauser() { _checkFactoryVaultPauser(); _; } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* GETTERS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @notice Returns the address of the factory contract. function factory() public view virtual returns (address) { FactoryOwnableStorage storage $ = _getFactoryOwnableStorage(); return $._factory; } /// @notice Returns if the user is a owner of the factory contract. function isFactoryOwner(address user) public view virtual returns (bool) { FactoryOwnableStorage storage $ = _getFactoryOwnableStorage(); return AccessControlUpgradeable($._factory).hasRole(_getAdminRole(), user); } /// @notice Returns if the account is a vault manager of the factory contract. function isFactoryVaultManager(address user) public view virtual returns (bool) { FactoryOwnableStorage storage $ = _getFactoryOwnableStorage(); return AccessControlUpgradeable($._factory).hasRole(_getVaultManagerRole(), user); } /// @notice Returns if the account is a vault pauser of the factory contract. function isFactoryVaultPauser(address user) public view virtual returns (bool) { FactoryOwnableStorage storage $ = _getFactoryOwnableStorage(); return AccessControlUpgradeable($._factory).hasRole(_getVaultPauserRole(), user); } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* INTERNALS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Returns the DEFAULT_ADMIN_ROLE of the factory contract. function _getAdminRole() internal view returns (bytes32) { FactoryOwnableStorage storage $ = _getFactoryOwnableStorage(); return AccessControlUpgradeable($._factory).DEFAULT_ADMIN_ROLE(); } /// @dev Returns the VAULT_MANAGER_ROLE of the factory contract. function _getVaultManagerRole() internal view returns (bytes32) { FactoryOwnableStorage storage $ = _getFactoryOwnableStorage(); return IRewardVaultFactory($._factory).VAULT_MANAGER_ROLE(); } /// @dev Returns the VAULT_PAUSER_ROLE of the factory contract. function _getVaultPauserRole() internal view returns (bytes32) { FactoryOwnableStorage storage $ = _getFactoryOwnableStorage(); return IRewardVaultFactory($._factory).VAULT_PAUSER_ROLE(); } /// @dev Returns the storage struct of the factory ownable contract. function _getFactoryOwnableStorage() internal pure returns (FactoryOwnableStorage storage $) { assembly { $.slot := FactoryOwnableStorageLocation } } /// @dev Sets the address of the factory contract. function _setFactory(address factoryAddr) internal { FactoryOwnableStorage storage $ = _getFactoryOwnableStorage(); $._factory = factoryAddr; } /// @dev Checks if the sender is a admin of the factory contract. function _checkFactoryOwner() internal view { if (!isFactoryOwner(msg.sender)) OwnableUnauthorizedAccount.selector.revertWith(msg.sender); } /// @dev Check if the sender is a vault manager of the factory contract. function _checkFactoryVaultManager() internal view { if (!isFactoryVaultManager(msg.sender)) OwnableUnauthorizedAccount.selector.revertWith(msg.sender); } /// @dev Check if the sender is a vault pauser of the factory contract. function _checkFactoryVaultPauser() internal view { if (!isFactoryVaultPauser(msg.sender)) OwnableUnauthorizedAccount.selector.revertWith(msg.sender); } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.26; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import { FixedPointMathLib } from "solady/src/utils/FixedPointMathLib.sol"; import { Utils } from "../libraries/Utils.sol"; import { IStakingRewards } from "./IStakingRewards.sol"; /// @title StakingRewards /// @author Berachain Team /// @notice This is a minimal implementation of staking rewards logic to be inherited. /// @dev This contract is modified and abstracted from the stable and tested: /// https://github.com/Synthetixio/synthetix/blob/develop/contracts/StakingRewards.sol abstract contract StakingRewards is Initializable, IStakingRewards { using Utils for bytes4; using SafeERC20 for IERC20; /// @notice Struct to hold account data. /// @param balance The balance of the staked tokens. /// @param unclaimedReward The amount of unclaimed rewards. /// @param rewardsPerTokenPaid The amount of rewards per token paid, scaled by PRECISION. struct Info { uint256 balance; uint256 unclaimedReward; uint256 rewardsPerTokenPaid; } uint256 internal constant PRECISION = 1e18; /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* STORAGE */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @notice ERC20 token which users stake to earn rewards. IERC20 public stakeToken; /// @notice ERC20 token in which rewards are denominated and distributed. IERC20 public rewardToken; /// @notice The reward rate for the current reward period scaled by PRECISION. uint256 public rewardRate; /// @notice The amount of undistributed rewards scaled by PRECISION. uint256 public undistributedRewards; /// @notice The last updated reward per token scaled by PRECISION. uint256 public rewardPerTokenStored; /// @notice The total supply of the staked tokens. uint256 public totalSupply; /// @notice The end of the current reward period, where we need to start a new one. uint256 public periodFinish; /// @notice The time over which the rewards will be distributed. Current default is 7 days. uint256 public rewardsDuration; /// @notice The last time the rewards were updated. uint256 public lastUpdateTime; /// @notice The mapping of accounts to their data. mapping(address account => Info) internal _accountInfo; /// @dev This gap is used to prevent storage collisions. uint256[50] private __gap; /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* INITIALIZER */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Must be called by the initializer of the inheriting contract. /// @param _stakingToken The address of the token that users will stake. /// @param _rewardToken The address of the token that will be distributed as rewards. /// @param _rewardsDuration The duration of the rewards cycle. function __StakingRewards_init( address _stakingToken, address _rewardToken, uint256 _rewardsDuration ) internal onlyInitializing { stakeToken = IERC20(_stakingToken); rewardToken = IERC20(_rewardToken); rewardsDuration = _rewardsDuration; } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* MODIFIERS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ modifier updateReward(address account) { _updateReward(account); _; } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* STATE MUTATING FUNCTIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @notice Notifies the staking contract of a new reward transfer. /// @param reward The quantity of reward tokens being notified. /// @dev Only authorized notifiers should call this method to avoid griefing or false notifications. function _notifyRewardAmount(uint256 reward) internal virtual updateReward(address(0)) { reward = reward * PRECISION; if (totalSupply != 0 && block.timestamp < periodFinish) { reward += _computeLeftOverReward(); } undistributedRewards += reward; _checkRewardSolvency(); if (totalSupply != 0) { _setRewardRate(); lastUpdateTime = block.timestamp; } emit RewardAdded(reward); } /// @notice Check if the rewards are solvent. /// @dev Inherited contracts may override this function to implement custom solvency checks. function _checkRewardSolvency() internal view virtual { if (undistributedRewards / PRECISION > rewardToken.balanceOf(address(this))) { InsolventReward.selector.revertWith(); } } /// @notice Claims the reward for a specified account and transfers it to the specified recipient. /// @param account The account to claim the reward for. /// @param recipient The account to receive the reward. /// @return The amount of the reward claimed. function _getReward(address account, address recipient) internal virtual updateReward(account) returns (uint256) { Info storage info = _accountInfo[account]; uint256 reward = info.unclaimedReward; // get the rewards owed to the account if (reward != 0) { info.unclaimedReward = 0; _safeTransferRewardToken(recipient, reward); emit RewardPaid(account, recipient, reward); } return reward; } /// @notice Safely transfers the reward tokens to the specified recipient. /// @dev Inherited contracts may override this function to implement custom transfer logic. /// @param to The recipient address. /// @param amount The amount of reward tokens to transfer. function _safeTransferRewardToken(address to, uint256 amount) internal virtual { rewardToken.safeTransfer(to, amount); } /// @notice Stakes tokens in the vault for a specified account. /// @param account The account to stake the tokens for. /// @param amount The amount of tokens to stake. function _stake(address account, uint256 amount) internal virtual { if (amount == 0) StakeAmountIsZero.selector.revertWith(); // set the reward rate after the first stake if there are undistributed rewards if (totalSupply == 0 && undistributedRewards > 0) { _setRewardRate(); } // update the rewards for the account after `rewardRate` is updated _updateReward(account); unchecked { uint256 totalSupplyBefore = totalSupply; // cache storage read uint256 totalSupplyAfter = totalSupplyBefore + amount; // `<=` and `<` are equivalent here but the former is cheaper if (totalSupplyAfter <= totalSupplyBefore) TotalSupplyOverflow.selector.revertWith(); totalSupply = totalSupplyAfter; // `totalSupply` would have overflowed first because `totalSupplyBefore` >= `_accountInfo[account].balance` _accountInfo[account].balance += amount; } _safeTransferFromStakeToken(msg.sender, amount); emit Staked(account, amount); } /// @notice Safely transfers staking tokens from the sender to the contract. /// @dev Inherited contracts may override this function to implement custom transfer logic. /// @param from The address to transfer the tokens from. /// @param amount The amount of tokens to transfer. function _safeTransferFromStakeToken(address from, uint256 amount) internal virtual { stakeToken.safeTransferFrom(from, address(this), amount); } /// @notice Withdraws staked tokens from the vault for a specified account. /// @param account The account to withdraw the tokens for. /// @param amount The amount of tokens to withdraw. function _withdraw(address account, uint256 amount) internal virtual { if (amount == 0) WithdrawAmountIsZero.selector.revertWith(); // update the rewards for the account before the balance is updated _updateReward(account); unchecked { Info storage info = _accountInfo[account]; uint256 balanceBefore = info.balance; // cache storage read if (balanceBefore < amount) InsufficientStake.selector.revertWith(); info.balance = balanceBefore - amount; // underflow not possible because `totalSupply` >= `balanceBefore` >= `amount` totalSupply -= amount; } if (totalSupply == 0 && block.timestamp < periodFinish) { undistributedRewards += _computeLeftOverReward(); } _safeTransferStakeToken(msg.sender, amount); emit Withdrawn(account, amount); } /// @notice Safely transfers staking tokens to the specified recipient. /// @param to The recipient address. /// @param amount The amount of tokens to transfer. function _safeTransferStakeToken(address to, uint256 amount) internal virtual { stakeToken.safeTransfer(to, amount); } function _setRewardRate() internal virtual { uint256 _rewardsDuration = rewardsDuration; // cache storage read uint256 _rewardRate = undistributedRewards / _rewardsDuration; rewardRate = _rewardRate; periodFinish = block.timestamp + _rewardsDuration; undistributedRewards -= _rewardRate * _rewardsDuration; } function _updateReward(address account) internal virtual { uint256 _rewardPerToken = rewardPerToken(); // cache result rewardPerTokenStored = _rewardPerToken; // record the last time the rewards were updated lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { Info storage info = _accountInfo[account]; (info.unclaimedReward, info.rewardsPerTokenPaid) = (earned(account), _rewardPerToken); } } /// @dev Allows to change `rewardsDuration` during the reward cycle, not affecting `rewardRate` which /// will be updated upon next `_notifyRewardAmount()` call. function _setRewardsDuration(uint256 _rewardsDuration) internal virtual { if (_rewardsDuration == 0) RewardsDurationIsZero.selector.revertWith(); rewardsDuration = _rewardsDuration; emit RewardsDurationUpdated(_rewardsDuration); } /// @notice Returns the left over amount scaled by PRECISION. function _computeLeftOverReward() internal view returns (uint256 leftOver) { uint256 remainingTime; unchecked { remainingTime = periodFinish - block.timestamp; } leftOver = rewardRate * remainingTime; } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* GETTERS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ function balanceOf(address account) public view virtual returns (uint256) { return _accountInfo[account].balance; } function rewards(address account) public view virtual returns (uint256) { return _accountInfo[account].unclaimedReward; } function userRewardPerTokenPaid(address account) public view virtual returns (uint256) { return _accountInfo[account].rewardsPerTokenPaid; } function lastTimeRewardApplicable() public view virtual returns (uint256) { return FixedPointMathLib.min(block.timestamp, periodFinish); } /// @dev Gives current reward per token, result is scaled by PRECISION. function rewardPerToken() public view virtual returns (uint256) { uint256 _totalSupply = totalSupply; // cache storage read if (_totalSupply == 0) return rewardPerTokenStored; uint256 timeDelta; unchecked { timeDelta = lastTimeRewardApplicable() - lastUpdateTime; } // computes reward per token by rounding it down to avoid reverting '_getReward' with insufficient rewards uint256 _newRewardPerToken = FixedPointMathLib.fullMulDiv(rewardRate, timeDelta, _totalSupply); return rewardPerTokenStored + _newRewardPerToken; } function earned(address account) public view virtual returns (uint256) { Info storage info = _accountInfo[account]; (uint256 balance, uint256 unclaimedReward, uint256 rewardsPerTokenPaid) = (info.balance, info.unclaimedReward, info.rewardsPerTokenPaid); uint256 rewardPerTokenDelta; unchecked { rewardPerTokenDelta = rewardPerToken() - rewardsPerTokenPaid; } return unclaimedReward + FixedPointMathLib.fullMulDiv(balance, rewardPerTokenDelta, PRECISION); } function getRewardForDuration() public view virtual returns (uint256) { return FixedPointMathLib.fullMulDiv(rewardRate, rewardsDuration, PRECISION); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (access/AccessControl.sol) pragma solidity ^0.8.20; import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol"; import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol"; import {ERC165Upgradeable} from "../utils/introspection/ERC165Upgradeable.sol"; import {Initializable} from "../proxy/utils/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ```solidity * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ```solidity * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules} * to enforce additional security measures for this role. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControl, ERC165Upgradeable { struct RoleData { mapping(address account => bool) hasRole; bytes32 adminRole; } bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /// @custom:storage-location erc7201:openzeppelin.storage.AccessControl struct AccessControlStorage { mapping(bytes32 role => RoleData) _roles; } // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessControl")) - 1)) & ~bytes32(uint256(0xff)) bytes32 private constant AccessControlStorageLocation = 0x02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800; function _getAccessControlStorage() private pure returns (AccessControlStorage storage $) { assembly { $.slot := AccessControlStorageLocation } } /** * @dev Modifier that checks that an account has a specific role. Reverts * with an {AccessControlUnauthorizedAccount} error including the required role. */ modifier onlyRole(bytes32 role) { _checkRole(role); _; } function __AccessControl_init() internal onlyInitializing { } function __AccessControl_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view virtual returns (bool) { AccessControlStorage storage $ = _getAccessControlStorage(); return $._roles[role].hasRole[account]; } /** * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()` * is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier. */ function _checkRole(bytes32 role) internal view virtual { _checkRole(role, _msgSender()); } /** * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account` * is missing `role`. */ function _checkRole(bytes32 role, address account) internal view virtual { if (!hasRole(role, account)) { revert AccessControlUnauthorizedAccount(account, role); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) { AccessControlStorage storage $ = _getAccessControlStorage(); return $._roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. * * May emit a {RoleGranted} event. */ function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. * * May emit a {RoleRevoked} event. */ function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `callerConfirmation`. * * May emit a {RoleRevoked} event. */ function renounceRole(bytes32 role, address callerConfirmation) public virtual { if (callerConfirmation != _msgSender()) { revert AccessControlBadConfirmation(); } _revokeRole(role, callerConfirmation); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { AccessControlStorage storage $ = _getAccessControlStorage(); bytes32 previousAdminRole = getRoleAdmin(role); $._roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted. * * Internal function without access restriction. * * May emit a {RoleGranted} event. */ function _grantRole(bytes32 role, address account) internal virtual returns (bool) { AccessControlStorage storage $ = _getAccessControlStorage(); if (!hasRole(role, account)) { $._roles[role].hasRole[account] = true; emit RoleGranted(role, account, _msgSender()); return true; } else { return false; } } /** * @dev Attempts to revoke `role` to `account` and returns a boolean indicating if `role` was revoked. * * Internal function without access restriction. * * May emit a {RoleRevoked} event. */ function _revokeRole(bytes32 role, address account) internal virtual returns (bool) { AccessControlStorage storage $ = _getAccessControlStorage(); if (hasRole(role, account)) { $._roles[role].hasRole[account] = false; emit RoleRevoked(role, account, _msgSender()); return true; } else { return false; } } }
// 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); } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /// @notice Minimal proxy library. /// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/LibClone.sol) /// @author Minimal proxy by 0age (https://github.com/0age) /// @author Clones with immutable args by wighawag, zefram.eth, Saw-mon & Natalie /// (https://github.com/Saw-mon-and-Natalie/clones-with-immutable-args) /// @author Minimal ERC1967 proxy by jtriley-eth (https://github.com/jtriley-eth/minimum-viable-proxy) /// /// @dev Minimal proxy: /// Although the sw0nt pattern saves 5 gas over the ERC1167 pattern during runtime, /// it is not supported out-of-the-box on Etherscan. Hence, we choose to use the 0age pattern, /// which saves 4 gas over the ERC1167 pattern during runtime, and has the smallest bytecode. /// - Automatically verified on Etherscan. /// /// @dev Minimal proxy (PUSH0 variant): /// This is a new minimal proxy that uses the PUSH0 opcode introduced during Shanghai. /// It is optimized first for minimal runtime gas, then for minimal bytecode. /// The PUSH0 clone functions are intentionally postfixed with a jarring "_PUSH0" as /// many EVM chains may not support the PUSH0 opcode in the early months after Shanghai. /// Please use with caution. /// - Automatically verified on Etherscan. /// /// @dev Clones with immutable args (CWIA): /// The implementation of CWIA here is does NOT append the immutable args into the calldata /// passed into delegatecall. It is simply an ERC1167 minimal proxy with the immutable arguments /// appended to the back of the runtime bytecode. /// - Uses the identity precompile (0x4) to copy args during deployment. /// /// @dev Minimal ERC1967 proxy: /// An minimal ERC1967 proxy, intended to be upgraded with UUPS. /// This is NOT the same as ERC1967Factory's transparent proxy, which includes admin logic. /// - Automatically verified on Etherscan. /// /// @dev Minimal ERC1967 proxy with immutable args: /// - Uses the identity precompile (0x4) to copy args during deployment. /// - Automatically verified on Etherscan. /// /// @dev ERC1967I proxy: /// An variant of the minimal ERC1967 proxy, with a special code path that activates /// if `calldatasize() == 1`. This code path skips the delegatecall and directly returns the /// `implementation` address. The returned implementation is guaranteed to be valid if the /// keccak256 of the proxy's code is equal to `ERC1967I_CODE_HASH`. /// /// @dev ERC1967I proxy with immutable args: /// An variant of the minimal ERC1967 proxy, with a special code path that activates /// if `calldatasize() == 1`. This code path skips the delegatecall and directly returns the /// - Uses the identity precompile (0x4) to copy args during deployment. /// /// @dev Minimal ERC1967 beacon proxy: /// A minimal beacon proxy, intended to be upgraded with an upgradable beacon. /// - Automatically verified on Etherscan. /// /// @dev Minimal ERC1967 beacon proxy with immutable args: /// - Uses the identity precompile (0x4) to copy args during deployment. /// - Automatically verified on Etherscan. /// /// @dev ERC1967I beacon proxy: /// An variant of the minimal ERC1967 beacon proxy, with a special code path that activates /// if `calldatasize() == 1`. This code path skips the delegatecall and directly returns the /// `implementation` address. The returned implementation is guaranteed to be valid if the /// keccak256 of the proxy's code is equal to `ERC1967I_CODE_HASH`. /// /// @dev ERC1967I proxy with immutable args: /// An variant of the minimal ERC1967 beacon proxy, with a special code path that activates /// if `calldatasize() == 1`. This code path skips the delegatecall and directly returns the /// - Uses the identity precompile (0x4) to copy args during deployment. library LibClone { /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* CONSTANTS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev The keccak256 of deployed code for the clone proxy, /// with the implementation set to `address(0)`. bytes32 internal constant CLONE_CODE_HASH = 0x48db2cfdb2853fce0b464f1f93a1996469459df3ab6c812106074c4106a1eb1f; /// @dev The keccak256 of deployed code for the PUSH0 proxy, /// with the implementation set to `address(0)`. bytes32 internal constant PUSH0_CLONE_CODE_HASH = 0x67bc6bde1b84d66e267c718ba44cf3928a615d29885537955cb43d44b3e789dc; /// @dev The keccak256 of deployed code for the ERC-1167 CWIA proxy, /// with the implementation set to `address(0)`. bytes32 internal constant CWIA_CODE_HASH = 0x3cf92464268225a4513da40a34d967354684c32cd0edd67b5f668dfe3550e940; /// @dev The keccak256 of the deployed code for the ERC1967 proxy. bytes32 internal constant ERC1967_CODE_HASH = 0xaaa52c8cc8a0e3fd27ce756cc6b4e70c51423e9b597b11f32d3e49f8b1fc890d; /// @dev The keccak256 of the deployed code for the ERC1967I proxy. bytes32 internal constant ERC1967I_CODE_HASH = 0xce700223c0d4cea4583409accfc45adac4a093b3519998a9cbbe1504dadba6f7; /// @dev The keccak256 of the deployed code for the ERC1967 beacon proxy. bytes32 internal constant ERC1967_BEACON_PROXY_CODE_HASH = 0x14044459af17bc4f0f5aa2f658cb692add77d1302c29fe2aebab005eea9d1162; /// @dev The keccak256 of the deployed code for the ERC1967 beacon proxy. bytes32 internal constant ERC1967I_BEACON_PROXY_CODE_HASH = 0xf8c46d2793d5aa984eb827aeaba4b63aedcab80119212fce827309788735519a; /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* CUSTOM ERRORS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Unable to deploy the clone. error DeploymentFailed(); /// @dev The salt must start with either the zero address or `by`. error SaltDoesNotStartWith(); /// @dev The ETH transfer has failed. error ETHTransferFailed(); /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* MINIMAL PROXY OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Deploys a clone of `implementation`. function clone(address implementation) internal returns (address instance) { instance = clone(0, implementation); } /// @dev Deploys a clone of `implementation`. /// Deposits `value` ETH during deployment. function clone(uint256 value, address implementation) internal returns (address instance) { /// @solidity memory-safe-assembly assembly { /** * --------------------------------------------------------------------------+ * CREATION (9 bytes) | * --------------------------------------------------------------------------| * Opcode | Mnemonic | Stack | Memory | * --------------------------------------------------------------------------| * 60 runSize | PUSH1 runSize | r | | * 3d | RETURNDATASIZE | 0 r | | * 81 | DUP2 | r 0 r | | * 60 offset | PUSH1 offset | o r 0 r | | * 3d | RETURNDATASIZE | 0 o r 0 r | | * 39 | CODECOPY | 0 r | [0..runSize): runtime code | * f3 | RETURN | | [0..runSize): runtime code | * --------------------------------------------------------------------------| * RUNTIME (44 bytes) | * --------------------------------------------------------------------------| * Opcode | Mnemonic | Stack | Memory | * --------------------------------------------------------------------------| * | * ::: keep some values in stack ::::::::::::::::::::::::::::::::::::::::::: | * 3d | RETURNDATASIZE | 0 | | * 3d | RETURNDATASIZE | 0 0 | | * 3d | RETURNDATASIZE | 0 0 0 | | * 3d | RETURNDATASIZE | 0 0 0 0 | | * | * ::: copy calldata to memory ::::::::::::::::::::::::::::::::::::::::::::: | * 36 | CALLDATASIZE | cds 0 0 0 0 | | * 3d | RETURNDATASIZE | 0 cds 0 0 0 0 | | * 3d | RETURNDATASIZE | 0 0 cds 0 0 0 0 | | * 37 | CALLDATACOPY | 0 0 0 0 | [0..cds): calldata | * | * ::: delegate call to the implementation contract :::::::::::::::::::::::: | * 36 | CALLDATASIZE | cds 0 0 0 0 | [0..cds): calldata | * 3d | RETURNDATASIZE | 0 cds 0 0 0 0 | [0..cds): calldata | * 73 addr | PUSH20 addr | addr 0 cds 0 0 0 0 | [0..cds): calldata | * 5a | GAS | gas addr 0 cds 0 0 0 0 | [0..cds): calldata | * f4 | DELEGATECALL | success 0 0 | [0..cds): calldata | * | * ::: copy return data to memory :::::::::::::::::::::::::::::::::::::::::: | * 3d | RETURNDATASIZE | rds success 0 0 | [0..cds): calldata | * 3d | RETURNDATASIZE | rds rds success 0 0 | [0..cds): calldata | * 93 | SWAP4 | 0 rds success 0 rds | [0..cds): calldata | * 80 | DUP1 | 0 0 rds success 0 rds | [0..cds): calldata | * 3e | RETURNDATACOPY | success 0 rds | [0..rds): returndata | * | * 60 0x2a | PUSH1 0x2a | 0x2a success 0 rds | [0..rds): returndata | * 57 | JUMPI | 0 rds | [0..rds): returndata | * | * ::: revert :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: | * fd | REVERT | | [0..rds): returndata | * | * ::: return :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: | * 5b | JUMPDEST | 0 rds | [0..rds): returndata | * f3 | RETURN | | [0..rds): returndata | * --------------------------------------------------------------------------+ */ mstore(0x21, 0x5af43d3d93803e602a57fd5bf3) mstore(0x14, implementation) mstore(0x00, 0x602c3d8160093d39f33d3d3d3d363d3d37363d73) instance := create(value, 0x0c, 0x35) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } mstore(0x21, 0) // Restore the overwritten part of the free memory pointer. } } /// @dev Deploys a deterministic clone of `implementation` with `salt`. function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) { instance = cloneDeterministic(0, implementation, salt); } /// @dev Deploys a deterministic clone of `implementation` with `salt`. /// Deposits `value` ETH during deployment. function cloneDeterministic(uint256 value, address implementation, bytes32 salt) internal returns (address instance) { /// @solidity memory-safe-assembly assembly { mstore(0x21, 0x5af43d3d93803e602a57fd5bf3) mstore(0x14, implementation) mstore(0x00, 0x602c3d8160093d39f33d3d3d3d363d3d37363d73) instance := create2(value, 0x0c, 0x35, salt) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } mstore(0x21, 0) // Restore the overwritten part of the free memory pointer. } } /// @dev Returns the initialization code of the clone of `implementation`. function initCode(address implementation) internal pure returns (bytes memory c) { /// @solidity memory-safe-assembly assembly { c := mload(0x40) mstore(add(c, 0x40), 0x5af43d3d93803e602a57fd5bf30000000000000000000000) mstore(add(c, 0x28), implementation) mstore(add(c, 0x14), 0x602c3d8160093d39f33d3d3d3d363d3d37363d73) mstore(c, 0x35) // Store the length. mstore(0x40, add(c, 0x60)) // Allocate memory. } } /// @dev Returns the initialization code hash of the clone of `implementation`. function initCodeHash(address implementation) internal pure returns (bytes32 hash) { /// @solidity memory-safe-assembly assembly { mstore(0x21, 0x5af43d3d93803e602a57fd5bf3) mstore(0x14, implementation) mstore(0x00, 0x602c3d8160093d39f33d3d3d3d363d3d37363d73) hash := keccak256(0x0c, 0x35) mstore(0x21, 0) // Restore the overwritten part of the free memory pointer. } } /// @dev Returns the address of the clone of `implementation`, with `salt` by `deployer`. /// Note: The returned result has dirty upper 96 bits. Please clean if used in assembly. function predictDeterministicAddress(address implementation, bytes32 salt, address deployer) internal pure returns (address predicted) { bytes32 hash = initCodeHash(implementation); predicted = predictDeterministicAddress(hash, salt, deployer); } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* MINIMAL PROXY OPERATIONS (PUSH0 VARIANT) */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Deploys a PUSH0 clone of `implementation`. function clone_PUSH0(address implementation) internal returns (address instance) { instance = clone_PUSH0(0, implementation); } /// @dev Deploys a PUSH0 clone of `implementation`. /// Deposits `value` ETH during deployment. function clone_PUSH0(uint256 value, address implementation) internal returns (address instance) { /// @solidity memory-safe-assembly assembly { /** * --------------------------------------------------------------------------+ * CREATION (9 bytes) | * --------------------------------------------------------------------------| * Opcode | Mnemonic | Stack | Memory | * --------------------------------------------------------------------------| * 60 runSize | PUSH1 runSize | r | | * 5f | PUSH0 | 0 r | | * 81 | DUP2 | r 0 r | | * 60 offset | PUSH1 offset | o r 0 r | | * 5f | PUSH0 | 0 o r 0 r | | * 39 | CODECOPY | 0 r | [0..runSize): runtime code | * f3 | RETURN | | [0..runSize): runtime code | * --------------------------------------------------------------------------| * RUNTIME (45 bytes) | * --------------------------------------------------------------------------| * Opcode | Mnemonic | Stack | Memory | * --------------------------------------------------------------------------| * | * ::: keep some values in stack ::::::::::::::::::::::::::::::::::::::::::: | * 5f | PUSH0 | 0 | | * 5f | PUSH0 | 0 0 | | * | * ::: copy calldata to memory ::::::::::::::::::::::::::::::::::::::::::::: | * 36 | CALLDATASIZE | cds 0 0 | | * 5f | PUSH0 | 0 cds 0 0 | | * 5f | PUSH0 | 0 0 cds 0 0 | | * 37 | CALLDATACOPY | 0 0 | [0..cds): calldata | * | * ::: delegate call to the implementation contract :::::::::::::::::::::::: | * 36 | CALLDATASIZE | cds 0 0 | [0..cds): calldata | * 5f | PUSH0 | 0 cds 0 0 | [0..cds): calldata | * 73 addr | PUSH20 addr | addr 0 cds 0 0 | [0..cds): calldata | * 5a | GAS | gas addr 0 cds 0 0 | [0..cds): calldata | * f4 | DELEGATECALL | success | [0..cds): calldata | * | * ::: copy return data to memory :::::::::::::::::::::::::::::::::::::::::: | * 3d | RETURNDATASIZE | rds success | [0..cds): calldata | * 5f | PUSH0 | 0 rds success | [0..cds): calldata | * 5f | PUSH0 | 0 0 rds success | [0..cds): calldata | * 3e | RETURNDATACOPY | success | [0..rds): returndata | * | * 60 0x29 | PUSH1 0x29 | 0x29 success | [0..rds): returndata | * 57 | JUMPI | | [0..rds): returndata | * | * ::: revert :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: | * 3d | RETURNDATASIZE | rds | [0..rds): returndata | * 5f | PUSH0 | 0 rds | [0..rds): returndata | * fd | REVERT | | [0..rds): returndata | * | * ::: return :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: | * 5b | JUMPDEST | | [0..rds): returndata | * 3d | RETURNDATASIZE | rds | [0..rds): returndata | * 5f | PUSH0 | 0 rds | [0..rds): returndata | * f3 | RETURN | | [0..rds): returndata | * --------------------------------------------------------------------------+ */ mstore(0x24, 0x5af43d5f5f3e6029573d5ffd5b3d5ff3) // 16 mstore(0x14, implementation) // 20 mstore(0x00, 0x602d5f8160095f39f35f5f365f5f37365f73) // 9 + 9 instance := create(value, 0x0e, 0x36) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } mstore(0x24, 0) // Restore the overwritten part of the free memory pointer. } } /// @dev Deploys a deterministic PUSH0 clone of `implementation` with `salt`. function cloneDeterministic_PUSH0(address implementation, bytes32 salt) internal returns (address instance) { instance = cloneDeterministic_PUSH0(0, implementation, salt); } /// @dev Deploys a deterministic PUSH0 clone of `implementation` with `salt`. /// Deposits `value` ETH during deployment. function cloneDeterministic_PUSH0(uint256 value, address implementation, bytes32 salt) internal returns (address instance) { /// @solidity memory-safe-assembly assembly { mstore(0x24, 0x5af43d5f5f3e6029573d5ffd5b3d5ff3) // 16 mstore(0x14, implementation) // 20 mstore(0x00, 0x602d5f8160095f39f35f5f365f5f37365f73) // 9 + 9 instance := create2(value, 0x0e, 0x36, salt) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } mstore(0x24, 0) // Restore the overwritten part of the free memory pointer. } } /// @dev Returns the initialization code of the PUSH0 clone of `implementation`. function initCode_PUSH0(address implementation) internal pure returns (bytes memory c) { /// @solidity memory-safe-assembly assembly { c := mload(0x40) mstore(add(c, 0x40), 0x5af43d5f5f3e6029573d5ffd5b3d5ff300000000000000000000) // 16 mstore(add(c, 0x26), implementation) // 20 mstore(add(c, 0x12), 0x602d5f8160095f39f35f5f365f5f37365f73) // 9 + 9 mstore(c, 0x36) // Store the length. mstore(0x40, add(c, 0x60)) // Allocate memory. } } /// @dev Returns the initialization code hash of the PUSH0 clone of `implementation`. function initCodeHash_PUSH0(address implementation) internal pure returns (bytes32 hash) { /// @solidity memory-safe-assembly assembly { mstore(0x24, 0x5af43d5f5f3e6029573d5ffd5b3d5ff3) // 16 mstore(0x14, implementation) // 20 mstore(0x00, 0x602d5f8160095f39f35f5f365f5f37365f73) // 9 + 9 hash := keccak256(0x0e, 0x36) mstore(0x24, 0) // Restore the overwritten part of the free memory pointer. } } /// @dev Returns the address of the PUSH0 clone of `implementation`, with `salt` by `deployer`. /// Note: The returned result has dirty upper 96 bits. Please clean if used in assembly. function predictDeterministicAddress_PUSH0( address implementation, bytes32 salt, address deployer ) internal pure returns (address predicted) { bytes32 hash = initCodeHash_PUSH0(implementation); predicted = predictDeterministicAddress(hash, salt, deployer); } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* CLONES WITH IMMUTABLE ARGS OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Deploys a clone of `implementation` with immutable arguments encoded in `args`. function clone(address implementation, bytes memory args) internal returns (address instance) { instance = clone(0, implementation, args); } /// @dev Deploys a clone of `implementation` with immutable arguments encoded in `args`. /// Deposits `value` ETH during deployment. function clone(uint256 value, address implementation, bytes memory args) internal returns (address instance) { /// @solidity memory-safe-assembly assembly { /** * ---------------------------------------------------------------------------+ * CREATION (10 bytes) | * ---------------------------------------------------------------------------| * Opcode | Mnemonic | Stack | Memory | * ---------------------------------------------------------------------------| * 61 runSize | PUSH2 runSize | r | | * 3d | RETURNDATASIZE | 0 r | | * 81 | DUP2 | r 0 r | | * 60 offset | PUSH1 offset | o r 0 r | | * 3d | RETURNDATASIZE | 0 o r 0 r | | * 39 | CODECOPY | 0 r | [0..runSize): runtime code | * f3 | RETURN | | [0..runSize): runtime code | * ---------------------------------------------------------------------------| * RUNTIME (45 bytes + extraLength) | * ---------------------------------------------------------------------------| * Opcode | Mnemonic | Stack | Memory | * ---------------------------------------------------------------------------| * | * ::: copy calldata to memory :::::::::::::::::::::::::::::::::::::::::::::: | * 36 | CALLDATASIZE | cds | | * 3d | RETURNDATASIZE | 0 cds | | * 3d | RETURNDATASIZE | 0 0 cds | | * 37 | CALLDATACOPY | | [0..cds): calldata | * | * ::: delegate call to the implementation contract ::::::::::::::::::::::::: | * 3d | RETURNDATASIZE | 0 | [0..cds): calldata | * 3d | RETURNDATASIZE | 0 0 | [0..cds): calldata | * 3d | RETURNDATASIZE | 0 0 0 | [0..cds): calldata | * 36 | CALLDATASIZE | cds 0 0 0 | [0..cds): calldata | * 3d | RETURNDATASIZE | 0 cds 0 0 0 0 | [0..cds): calldata | * 73 addr | PUSH20 addr | addr 0 cds 0 0 0 0 | [0..cds): calldata | * 5a | GAS | gas addr 0 cds 0 0 0 0 | [0..cds): calldata | * f4 | DELEGATECALL | success 0 0 | [0..cds): calldata | * | * ::: copy return data to memory ::::::::::::::::::::::::::::::::::::::::::: | * 3d | RETURNDATASIZE | rds success 0 | [0..cds): calldata | * 82 | DUP3 | 0 rds success 0 | [0..cds): calldata | * 80 | DUP1 | 0 0 rds success 0 | [0..cds): calldata | * 3e | RETURNDATACOPY | success 0 | [0..rds): returndata | * 90 | SWAP1 | 0 success | [0..rds): returndata | * 3d | RETURNDATASIZE | rds 0 success | [0..rds): returndata | * 91 | SWAP2 | success 0 rds | [0..rds): returndata | * | * 60 0x2b | PUSH1 0x2b | 0x2b success 0 rds | [0..rds): returndata | * 57 | JUMPI | 0 rds | [0..rds): returndata | * | * ::: revert ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: | * fd | REVERT | | [0..rds): returndata | * | * ::: return ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: | * 5b | JUMPDEST | 0 rds | [0..rds): returndata | * f3 | RETURN | | [0..rds): returndata | * ---------------------------------------------------------------------------+ */ let m := mload(0x40) let n := mload(args) pop(staticcall(gas(), 4, add(args, 0x20), n, add(m, 0x43), n)) mstore(add(m, 0x23), 0x5af43d82803e903d91602b57fd5bf3) mstore(add(m, 0x14), implementation) mstore(m, add(0xfe61002d3d81600a3d39f3363d3d373d3d3d363d73, shl(136, n))) // Do a out-of-gas revert if `n` is greater than `0xffff - 0x2d = 0xffd2`. instance := create(value, add(m, add(0x0b, lt(n, 0xffd3))), add(n, 0x37)) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } } } /// @dev Deploys a deterministic clone of `implementation` /// with immutable arguments encoded in `args` and `salt`. function cloneDeterministic(address implementation, bytes memory args, bytes32 salt) internal returns (address instance) { instance = cloneDeterministic(0, implementation, args, salt); } /// @dev Deploys a deterministic clone of `implementation` /// with immutable arguments encoded in `args` and `salt`. function cloneDeterministic( uint256 value, address implementation, bytes memory args, bytes32 salt ) internal returns (address instance) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) let n := mload(args) pop(staticcall(gas(), 4, add(args, 0x20), n, add(m, 0x43), n)) mstore(add(m, 0x23), 0x5af43d82803e903d91602b57fd5bf3) mstore(add(m, 0x14), implementation) mstore(m, add(0xfe61002d3d81600a3d39f3363d3d373d3d3d363d73, shl(136, n))) // Do a out-of-gas revert if `n` is greater than `0xffff - 0x2d = 0xffd2`. instance := create2(value, add(m, add(0x0b, lt(n, 0xffd3))), add(n, 0x37), salt) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } } } /// @dev Deploys a deterministic clone of `implementation` /// with immutable arguments encoded in `args` and `salt`. /// This method does not revert if the clone has already been deployed. function createDeterministicClone(address implementation, bytes memory args, bytes32 salt) internal returns (bool alreadyDeployed, address instance) { return createDeterministicClone(0, implementation, args, salt); } /// @dev Deploys a deterministic clone of `implementation` /// with immutable arguments encoded in `args` and `salt`. /// This method does not revert if the clone has already been deployed. function createDeterministicClone( uint256 value, address implementation, bytes memory args, bytes32 salt ) internal returns (bool alreadyDeployed, address instance) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) let n := mload(args) pop(staticcall(gas(), 4, add(args, 0x20), n, add(m, 0x43), n)) mstore(add(m, 0x23), 0x5af43d82803e903d91602b57fd5bf3) mstore(add(m, 0x14), implementation) // Do a out-of-gas revert if `n` is greater than `0xffff - 0x2d = 0xffd2`. // forgefmt: disable-next-item mstore(add(m, gt(n, 0xffd2)), add(0xfe61002d3d81600a3d39f3363d3d373d3d3d363d73, shl(136, n))) // Compute and store the bytecode hash. mstore8(0x00, 0xff) // Write the prefix. mstore(0x35, keccak256(add(m, 0x0c), add(n, 0x37))) mstore(0x01, shl(96, address())) mstore(0x15, salt) instance := keccak256(0x00, 0x55) for {} 1 {} { if iszero(extcodesize(instance)) { instance := create2(value, add(m, 0x0c), add(n, 0x37), salt) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } break } alreadyDeployed := 1 if iszero(value) { break } if iszero(call(gas(), instance, value, codesize(), 0x00, codesize(), 0x00)) { mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`. revert(0x1c, 0x04) } break } mstore(0x35, 0) // Restore the overwritten part of the free memory pointer. } } /// @dev Returns the initialization code of the clone of `implementation` /// using immutable arguments encoded in `args`. function initCode(address implementation, bytes memory args) internal pure returns (bytes memory c) { /// @solidity memory-safe-assembly assembly { c := mload(0x40) let n := mload(args) // Do a out-of-gas revert if `n` is greater than `0xffff - 0x2d = 0xffd2`. returndatacopy(returndatasize(), returndatasize(), gt(n, 0xffd2)) for { let i := 0 } lt(i, n) { i := add(i, 0x20) } { mstore(add(add(c, 0x57), i), mload(add(add(args, 0x20), i))) } mstore(add(c, 0x37), 0x5af43d82803e903d91602b57fd5bf3) mstore(add(c, 0x28), implementation) mstore(add(c, 0x14), add(0x61002d3d81600a3d39f3363d3d373d3d3d363d73, shl(136, n))) mstore(c, add(0x37, n)) // Store the length. mstore(add(c, add(n, 0x57)), 0) // Zeroize the slot after the bytes. mstore(0x40, add(c, add(n, 0x77))) // Allocate memory. } } /// @dev Returns the initialization code hash of the clone of `implementation` /// using immutable arguments encoded in `args`. function initCodeHash(address implementation, bytes memory args) internal pure returns (bytes32 hash) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) let n := mload(args) // Do a out-of-gas revert if `n` is greater than `0xffff - 0x2d = 0xffd2`. returndatacopy(returndatasize(), returndatasize(), gt(n, 0xffd2)) for { let i := 0 } lt(i, n) { i := add(i, 0x20) } { mstore(add(add(m, 0x43), i), mload(add(add(args, 0x20), i))) } mstore(add(m, 0x23), 0x5af43d82803e903d91602b57fd5bf3) mstore(add(m, 0x14), implementation) mstore(m, add(0x61002d3d81600a3d39f3363d3d373d3d3d363d73, shl(136, n))) hash := keccak256(add(m, 0x0c), add(n, 0x37)) } } /// @dev Returns the address of the clone of /// `implementation` using immutable arguments encoded in `args`, with `salt`, by `deployer`. /// Note: The returned result has dirty upper 96 bits. Please clean if used in assembly. function predictDeterministicAddress( address implementation, bytes memory data, bytes32 salt, address deployer ) internal pure returns (address predicted) { bytes32 hash = initCodeHash(implementation, data); predicted = predictDeterministicAddress(hash, salt, deployer); } /// @dev Equivalent to `argsOnClone(instance, 0, 2 ** 256 - 1)`. function argsOnClone(address instance) internal view returns (bytes memory args) { /// @solidity memory-safe-assembly assembly { args := mload(0x40) mstore(args, and(0xffffffffff, sub(extcodesize(instance), 0x2d))) // Store the length. extcodecopy(instance, add(args, 0x20), 0x2d, add(mload(args), 0x20)) mstore(0x40, add(mload(args), add(args, 0x40))) // Allocate memory. } } /// @dev Equivalent to `argsOnClone(instance, start, 2 ** 256 - 1)`. function argsOnClone(address instance, uint256 start) internal view returns (bytes memory args) { /// @solidity memory-safe-assembly assembly { args := mload(0x40) let n := and(0xffffffffff, sub(extcodesize(instance), 0x2d)) let l := sub(n, and(0xffffff, mul(lt(start, n), start))) extcodecopy(instance, args, add(start, 0x0d), add(l, 0x40)) mstore(args, mul(sub(n, start), lt(start, n))) // Store the length. mstore(0x40, add(args, add(0x40, mload(args)))) // Allocate memory. } } /// @dev Returns a slice of the immutable arguments on `instance` from `start` to `end`. /// `start` and `end` will be clamped to the range `[0, args.length]`. /// The `instance` MUST be deployed via the clone with immutable args functions. /// Otherwise, the behavior is undefined. /// Out-of-gas reverts if `instance` does not have any code. function argsOnClone(address instance, uint256 start, uint256 end) internal view returns (bytes memory args) { /// @solidity memory-safe-assembly assembly { args := mload(0x40) if iszero(lt(end, 0xffff)) { end := 0xffff } let d := mul(sub(end, start), lt(start, end)) extcodecopy(instance, args, add(start, 0x0d), add(d, 0x20)) if iszero(and(0xff, mload(add(args, d)))) { let n := sub(extcodesize(instance), 0x2d) returndatacopy(returndatasize(), returndatasize(), shr(40, n)) d := mul(gt(n, start), sub(d, mul(gt(end, n), sub(end, n)))) } mstore(args, d) // Store the length. mstore(add(add(args, 0x20), d), 0) // Zeroize the slot after the bytes. mstore(0x40, add(add(args, 0x40), d)) // Allocate memory. } } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* MINIMAL ERC1967 PROXY OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ // Note: The ERC1967 proxy here is intended to be upgraded with UUPS. // This is NOT the same as ERC1967Factory's transparent proxy, which includes admin logic. /// @dev Deploys a minimal ERC1967 proxy with `implementation`. function deployERC1967(address implementation) internal returns (address instance) { instance = deployERC1967(0, implementation); } /// @dev Deploys a minimal ERC1967 proxy with `implementation`. /// Deposits `value` ETH during deployment. function deployERC1967(uint256 value, address implementation) internal returns (address instance) { /// @solidity memory-safe-assembly assembly { /** * ---------------------------------------------------------------------------------+ * CREATION (34 bytes) | * ---------------------------------------------------------------------------------| * Opcode | Mnemonic | Stack | Memory | * ---------------------------------------------------------------------------------| * 60 runSize | PUSH1 runSize | r | | * 3d | RETURNDATASIZE | 0 r | | * 81 | DUP2 | r 0 r | | * 60 offset | PUSH1 offset | o r 0 r | | * 3d | RETURNDATASIZE | 0 o r 0 r | | * 39 | CODECOPY | 0 r | [0..runSize): runtime code | * 73 impl | PUSH20 impl | impl 0 r | [0..runSize): runtime code | * 60 slotPos | PUSH1 slotPos | slotPos impl 0 r | [0..runSize): runtime code | * 51 | MLOAD | slot impl 0 r | [0..runSize): runtime code | * 55 | SSTORE | 0 r | [0..runSize): runtime code | * f3 | RETURN | | [0..runSize): runtime code | * ---------------------------------------------------------------------------------| * RUNTIME (61 bytes) | * ---------------------------------------------------------------------------------| * Opcode | Mnemonic | Stack | Memory | * ---------------------------------------------------------------------------------| * | * ::: copy calldata to memory :::::::::::::::::::::::::::::::::::::::::::::::::::: | * 36 | CALLDATASIZE | cds | | * 3d | RETURNDATASIZE | 0 cds | | * 3d | RETURNDATASIZE | 0 0 cds | | * 37 | CALLDATACOPY | | [0..calldatasize): calldata | * | * ::: delegatecall to implementation ::::::::::::::::::::::::::::::::::::::::::::: | * 3d | RETURNDATASIZE | 0 | | * 3d | RETURNDATASIZE | 0 0 | | * 36 | CALLDATASIZE | cds 0 0 | [0..calldatasize): calldata | * 3d | RETURNDATASIZE | 0 cds 0 0 | [0..calldatasize): calldata | * 7f slot | PUSH32 slot | s 0 cds 0 0 | [0..calldatasize): calldata | * 54 | SLOAD | i 0 cds 0 0 | [0..calldatasize): calldata | * 5a | GAS | g i 0 cds 0 0 | [0..calldatasize): calldata | * f4 | DELEGATECALL | succ | [0..calldatasize): calldata | * | * ::: copy returndata to memory :::::::::::::::::::::::::::::::::::::::::::::::::: | * 3d | RETURNDATASIZE | rds succ | [0..calldatasize): calldata | * 60 0x00 | PUSH1 0x00 | 0 rds succ | [0..calldatasize): calldata | * 80 | DUP1 | 0 0 rds succ | [0..calldatasize): calldata | * 3e | RETURNDATACOPY | succ | [0..returndatasize): returndata | * | * ::: branch on delegatecall status :::::::::::::::::::::::::::::::::::::::::::::: | * 60 0x38 | PUSH1 0x38 | dest succ | [0..returndatasize): returndata | * 57 | JUMPI | | [0..returndatasize): returndata | * | * ::: delegatecall failed, revert :::::::::::::::::::::::::::::::::::::::::::::::: | * 3d | RETURNDATASIZE | rds | [0..returndatasize): returndata | * 60 0x00 | PUSH1 0x00 | 0 rds | [0..returndatasize): returndata | * fd | REVERT | | [0..returndatasize): returndata | * | * ::: delegatecall succeeded, return ::::::::::::::::::::::::::::::::::::::::::::: | * 5b | JUMPDEST | | [0..returndatasize): returndata | * 3d | RETURNDATASIZE | rds | [0..returndatasize): returndata | * 60 0x00 | PUSH1 0x00 | 0 rds | [0..returndatasize): returndata | * f3 | RETURN | | [0..returndatasize): returndata | * ---------------------------------------------------------------------------------+ */ let m := mload(0x40) // Cache the free memory pointer. mstore(0x60, 0xcc3735a920a3ca505d382bbc545af43d6000803e6038573d6000fd5b3d6000f3) mstore(0x40, 0x5155f3363d3d373d3d363d7f360894a13ba1a3210667c828492db98dca3e2076) mstore(0x20, 0x6009) mstore(0x1e, implementation) mstore(0x0a, 0x603d3d8160223d3973) instance := create(value, 0x21, 0x5f) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } mstore(0x40, m) // Restore the free memory pointer. mstore(0x60, 0) // Restore the zero slot. } } /// @dev Deploys a deterministic minimal ERC1967 proxy with `implementation` and `salt`. function deployDeterministicERC1967(address implementation, bytes32 salt) internal returns (address instance) { instance = deployDeterministicERC1967(0, implementation, salt); } /// @dev Deploys a deterministic minimal ERC1967 proxy with `implementation` and `salt`. /// Deposits `value` ETH during deployment. function deployDeterministicERC1967(uint256 value, address implementation, bytes32 salt) internal returns (address instance) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) // Cache the free memory pointer. mstore(0x60, 0xcc3735a920a3ca505d382bbc545af43d6000803e6038573d6000fd5b3d6000f3) mstore(0x40, 0x5155f3363d3d373d3d363d7f360894a13ba1a3210667c828492db98dca3e2076) mstore(0x20, 0x6009) mstore(0x1e, implementation) mstore(0x0a, 0x603d3d8160223d3973) instance := create2(value, 0x21, 0x5f, salt) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } mstore(0x40, m) // Restore the free memory pointer. mstore(0x60, 0) // Restore the zero slot. } } /// @dev Creates a deterministic minimal ERC1967 proxy with `implementation` and `salt`. /// Note: This method is intended for use in ERC4337 factories, /// which are expected to NOT revert if the proxy is already deployed. function createDeterministicERC1967(address implementation, bytes32 salt) internal returns (bool alreadyDeployed, address instance) { return createDeterministicERC1967(0, implementation, salt); } /// @dev Creates a deterministic minimal ERC1967 proxy with `implementation` and `salt`. /// Deposits `value` ETH during deployment. /// Note: This method is intended for use in ERC4337 factories, /// which are expected to NOT revert if the proxy is already deployed. function createDeterministicERC1967(uint256 value, address implementation, bytes32 salt) internal returns (bool alreadyDeployed, address instance) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) // Cache the free memory pointer. mstore(0x60, 0xcc3735a920a3ca505d382bbc545af43d6000803e6038573d6000fd5b3d6000f3) mstore(0x40, 0x5155f3363d3d373d3d363d7f360894a13ba1a3210667c828492db98dca3e2076) mstore(0x20, 0x6009) mstore(0x1e, implementation) mstore(0x0a, 0x603d3d8160223d3973) // Compute and store the bytecode hash. mstore(add(m, 0x35), keccak256(0x21, 0x5f)) mstore(m, shl(88, address())) mstore8(m, 0xff) // Write the prefix. mstore(add(m, 0x15), salt) instance := keccak256(m, 0x55) for {} 1 {} { if iszero(extcodesize(instance)) { instance := create2(value, 0x21, 0x5f, salt) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } break } alreadyDeployed := 1 if iszero(value) { break } if iszero(call(gas(), instance, value, codesize(), 0x00, codesize(), 0x00)) { mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`. revert(0x1c, 0x04) } break } mstore(0x40, m) // Restore the free memory pointer. mstore(0x60, 0) // Restore the zero slot. } } /// @dev Returns the initialization code of the minimal ERC1967 proxy of `implementation`. function initCodeERC1967(address implementation) internal pure returns (bytes memory c) { /// @solidity memory-safe-assembly assembly { c := mload(0x40) mstore(add(c, 0x60), 0x3735a920a3ca505d382bbc545af43d6000803e6038573d6000fd5b3d6000f300) mstore(add(c, 0x40), 0x55f3363d3d373d3d363d7f360894a13ba1a3210667c828492db98dca3e2076cc) mstore(add(c, 0x20), or(shl(24, implementation), 0x600951)) mstore(add(c, 0x09), 0x603d3d8160223d3973) mstore(c, 0x5f) // Store the length. mstore(0x40, add(c, 0x80)) // Allocate memory. } } /// @dev Returns the initialization code hash of the minimal ERC1967 proxy of `implementation`. function initCodeHashERC1967(address implementation) internal pure returns (bytes32 hash) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) // Cache the free memory pointer. mstore(0x60, 0xcc3735a920a3ca505d382bbc545af43d6000803e6038573d6000fd5b3d6000f3) mstore(0x40, 0x5155f3363d3d373d3d363d7f360894a13ba1a3210667c828492db98dca3e2076) mstore(0x20, 0x6009) mstore(0x1e, implementation) mstore(0x0a, 0x603d3d8160223d3973) hash := keccak256(0x21, 0x5f) mstore(0x40, m) // Restore the free memory pointer. mstore(0x60, 0) // Restore the zero slot. } } /// @dev Returns the address of the ERC1967 proxy of `implementation`, with `salt` by `deployer`. /// Note: The returned result has dirty upper 96 bits. Please clean if used in assembly. function predictDeterministicAddressERC1967( address implementation, bytes32 salt, address deployer ) internal pure returns (address predicted) { bytes32 hash = initCodeHashERC1967(implementation); predicted = predictDeterministicAddress(hash, salt, deployer); } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* MINIMAL ERC1967 PROXY WITH IMMUTABLE ARGS OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Deploys a minimal ERC1967 proxy with `implementation` and `args`. function deployERC1967(address implementation, bytes memory args) internal returns (address instance) { instance = deployERC1967(0, implementation, args); } /// @dev Deploys a minimal ERC1967 proxy with `implementation` and `args`. /// Deposits `value` ETH during deployment. function deployERC1967(uint256 value, address implementation, bytes memory args) internal returns (address instance) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) let n := mload(args) pop(staticcall(gas(), 4, add(args, 0x20), n, add(m, 0x60), n)) mstore(add(m, 0x40), 0xcc3735a920a3ca505d382bbc545af43d6000803e6038573d6000fd5b3d6000f3) mstore(add(m, 0x20), 0x5155f3363d3d373d3d363d7f360894a13ba1a3210667c828492db98dca3e2076) mstore(0x16, 0x6009) mstore(0x14, implementation) // Do a out-of-gas revert if `n` is greater than `0xffff - 0x3d = 0xffc2`. mstore(gt(n, 0xffc2), add(0xfe61003d3d8160233d3973, shl(56, n))) mstore(m, mload(0x16)) instance := create(value, m, add(n, 0x60)) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } } } /// @dev Deploys a deterministic minimal ERC1967 proxy with `implementation`, `args` and `salt`. function deployDeterministicERC1967(address implementation, bytes memory args, bytes32 salt) internal returns (address instance) { instance = deployDeterministicERC1967(0, implementation, args, salt); } /// @dev Deploys a deterministic minimal ERC1967 proxy with `implementation`, `args` and `salt`. /// Deposits `value` ETH during deployment. function deployDeterministicERC1967( uint256 value, address implementation, bytes memory args, bytes32 salt ) internal returns (address instance) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) let n := mload(args) pop(staticcall(gas(), 4, add(args, 0x20), n, add(m, 0x60), n)) mstore(add(m, 0x40), 0xcc3735a920a3ca505d382bbc545af43d6000803e6038573d6000fd5b3d6000f3) mstore(add(m, 0x20), 0x5155f3363d3d373d3d363d7f360894a13ba1a3210667c828492db98dca3e2076) mstore(0x16, 0x6009) mstore(0x14, implementation) // Do a out-of-gas revert if `n` is greater than `0xffff - 0x3d = 0xffc2`. mstore(gt(n, 0xffc2), add(0xfe61003d3d8160233d3973, shl(56, n))) mstore(m, mload(0x16)) instance := create2(value, m, add(n, 0x60), salt) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } } } /// @dev Creates a deterministic minimal ERC1967 proxy with `implementation`, `args` and `salt`. /// Note: This method is intended for use in ERC4337 factories, /// which are expected to NOT revert if the proxy is already deployed. function createDeterministicERC1967(address implementation, bytes memory args, bytes32 salt) internal returns (bool alreadyDeployed, address instance) { return createDeterministicERC1967(0, implementation, args, salt); } /// @dev Creates a deterministic minimal ERC1967 proxy with `implementation`, `args` and `salt`. /// Deposits `value` ETH during deployment. /// Note: This method is intended for use in ERC4337 factories, /// which are expected to NOT revert if the proxy is already deployed. function createDeterministicERC1967( uint256 value, address implementation, bytes memory args, bytes32 salt ) internal returns (bool alreadyDeployed, address instance) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) let n := mload(args) pop(staticcall(gas(), 4, add(args, 0x20), n, add(m, 0x60), n)) mstore(add(m, 0x40), 0xcc3735a920a3ca505d382bbc545af43d6000803e6038573d6000fd5b3d6000f3) mstore(add(m, 0x20), 0x5155f3363d3d373d3d363d7f360894a13ba1a3210667c828492db98dca3e2076) mstore(0x16, 0x6009) mstore(0x14, implementation) // Do a out-of-gas revert if `n` is greater than `0xffff - 0x3d = 0xffc2`. mstore(gt(n, 0xffc2), add(0xfe61003d3d8160233d3973, shl(56, n))) mstore(m, mload(0x16)) // Compute and store the bytecode hash. mstore8(0x00, 0xff) // Write the prefix. mstore(0x35, keccak256(m, add(n, 0x60))) mstore(0x01, shl(96, address())) mstore(0x15, salt) instance := keccak256(0x00, 0x55) for {} 1 {} { if iszero(extcodesize(instance)) { instance := create2(value, m, add(n, 0x60), salt) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } break } alreadyDeployed := 1 if iszero(value) { break } if iszero(call(gas(), instance, value, codesize(), 0x00, codesize(), 0x00)) { mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`. revert(0x1c, 0x04) } break } mstore(0x35, 0) // Restore the overwritten part of the free memory pointer. } } /// @dev Returns the initialization code of the minimal ERC1967 proxy of `implementation` and `args`. function initCodeERC1967(address implementation, bytes memory args) internal pure returns (bytes memory c) { /// @solidity memory-safe-assembly assembly { c := mload(0x40) let n := mload(args) // Do a out-of-gas revert if `n` is greater than `0xffff - 0x3d = 0xffc2`. returndatacopy(returndatasize(), returndatasize(), gt(n, 0xffc2)) for { let i := 0 } lt(i, n) { i := add(i, 0x20) } { mstore(add(add(c, 0x80), i), mload(add(add(args, 0x20), i))) } mstore(add(c, 0x60), 0xcc3735a920a3ca505d382bbc545af43d6000803e6038573d6000fd5b3d6000f3) mstore(add(c, 0x40), 0x5155f3363d3d373d3d363d7f360894a13ba1a3210667c828492db98dca3e2076) mstore(add(c, 0x20), 0x6009) mstore(add(c, 0x1e), implementation) mstore(add(c, 0x0a), add(0x61003d3d8160233d3973, shl(56, n))) mstore(c, add(n, 0x60)) // Store the length. mstore(add(c, add(n, 0x80)), 0) // Zeroize the slot after the bytes. mstore(0x40, add(c, add(n, 0xa0))) // Allocate memory. } } /// @dev Returns the initialization code hash of the minimal ERC1967 proxy of `implementation` and `args`. function initCodeHashERC1967(address implementation, bytes memory args) internal pure returns (bytes32 hash) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) let n := mload(args) // Do a out-of-gas revert if `n` is greater than `0xffff - 0x3d = 0xffc2`. returndatacopy(returndatasize(), returndatasize(), gt(n, 0xffc2)) for { let i := 0 } lt(i, n) { i := add(i, 0x20) } { mstore(add(add(m, 0x60), i), mload(add(add(args, 0x20), i))) } mstore(add(m, 0x40), 0xcc3735a920a3ca505d382bbc545af43d6000803e6038573d6000fd5b3d6000f3) mstore(add(m, 0x20), 0x5155f3363d3d373d3d363d7f360894a13ba1a3210667c828492db98dca3e2076) mstore(0x16, 0x6009) mstore(0x14, implementation) mstore(0x00, add(0x61003d3d8160233d3973, shl(56, n))) mstore(m, mload(0x16)) hash := keccak256(m, add(n, 0x60)) } } /// @dev Returns the address of the ERC1967 proxy of `implementation`, `args`, with `salt` by `deployer`. /// Note: The returned result has dirty upper 96 bits. Please clean if used in assembly. function predictDeterministicAddressERC1967( address implementation, bytes memory args, bytes32 salt, address deployer ) internal pure returns (address predicted) { bytes32 hash = initCodeHashERC1967(implementation, args); predicted = predictDeterministicAddress(hash, salt, deployer); } /// @dev Equivalent to `argsOnERC1967(instance, start, 2 ** 256 - 1)`. function argsOnERC1967(address instance) internal view returns (bytes memory args) { /// @solidity memory-safe-assembly assembly { args := mload(0x40) mstore(args, and(0xffffffffff, sub(extcodesize(instance), 0x3d))) // Store the length. extcodecopy(instance, add(args, 0x20), 0x3d, add(mload(args), 0x20)) mstore(0x40, add(mload(args), add(args, 0x40))) // Allocate memory. } } /// @dev Equivalent to `argsOnERC1967(instance, start, 2 ** 256 - 1)`. function argsOnERC1967(address instance, uint256 start) internal view returns (bytes memory args) { /// @solidity memory-safe-assembly assembly { args := mload(0x40) let n := and(0xffffffffff, sub(extcodesize(instance), 0x3d)) let l := sub(n, and(0xffffff, mul(lt(start, n), start))) extcodecopy(instance, args, add(start, 0x1d), add(l, 0x40)) mstore(args, mul(sub(n, start), lt(start, n))) // Store the length. mstore(0x40, add(args, add(0x40, mload(args)))) // Allocate memory. } } /// @dev Returns a slice of the immutable arguments on `instance` from `start` to `end`. /// `start` and `end` will be clamped to the range `[0, args.length]`. /// The `instance` MUST be deployed via the ERC1967 with immutable args functions. /// Otherwise, the behavior is undefined. /// Out-of-gas reverts if `instance` does not have any code. function argsOnERC1967(address instance, uint256 start, uint256 end) internal view returns (bytes memory args) { /// @solidity memory-safe-assembly assembly { args := mload(0x40) if iszero(lt(end, 0xffff)) { end := 0xffff } let d := mul(sub(end, start), lt(start, end)) extcodecopy(instance, args, add(start, 0x1d), add(d, 0x20)) if iszero(and(0xff, mload(add(args, d)))) { let n := sub(extcodesize(instance), 0x3d) returndatacopy(returndatasize(), returndatasize(), shr(40, n)) d := mul(gt(n, start), sub(d, mul(gt(end, n), sub(end, n)))) } mstore(args, d) // Store the length. mstore(add(add(args, 0x20), d), 0) // Zeroize the slot after the bytes. mstore(0x40, add(add(args, 0x40), d)) // Allocate memory. } } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* ERC1967I PROXY OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ // Note: This proxy has a special code path that activates if `calldatasize() == 1`. // This code path skips the delegatecall and directly returns the `implementation` address. // The returned implementation is guaranteed to be valid if the keccak256 of the // proxy's code is equal to `ERC1967I_CODE_HASH`. /// @dev Deploys a ERC1967I proxy with `implementation`. function deployERC1967I(address implementation) internal returns (address instance) { instance = deployERC1967I(0, implementation); } /// @dev Deploys a ERC1967I proxy with `implementation`. /// Deposits `value` ETH during deployment. function deployERC1967I(uint256 value, address implementation) internal returns (address instance) { /// @solidity memory-safe-assembly assembly { /** * ---------------------------------------------------------------------------------+ * CREATION (34 bytes) | * ---------------------------------------------------------------------------------| * Opcode | Mnemonic | Stack | Memory | * ---------------------------------------------------------------------------------| * 60 runSize | PUSH1 runSize | r | | * 3d | RETURNDATASIZE | 0 r | | * 81 | DUP2 | r 0 r | | * 60 offset | PUSH1 offset | o r 0 r | | * 3d | RETURNDATASIZE | 0 o r 0 r | | * 39 | CODECOPY | 0 r | [0..runSize): runtime code | * 73 impl | PUSH20 impl | impl 0 r | [0..runSize): runtime code | * 60 slotPos | PUSH1 slotPos | slotPos impl 0 r | [0..runSize): runtime code | * 51 | MLOAD | slot impl 0 r | [0..runSize): runtime code | * 55 | SSTORE | 0 r | [0..runSize): runtime code | * f3 | RETURN | | [0..runSize): runtime code | * ---------------------------------------------------------------------------------| * RUNTIME (82 bytes) | * ---------------------------------------------------------------------------------| * Opcode | Mnemonic | Stack | Memory | * ---------------------------------------------------------------------------------| * | * ::: check calldatasize ::::::::::::::::::::::::::::::::::::::::::::::::::::::::: | * 36 | CALLDATASIZE | cds | | * 58 | PC | 1 cds | | * 14 | EQ | eqs | | * 60 0x43 | PUSH1 0x43 | dest eqs | | * 57 | JUMPI | | | * | * ::: copy calldata to memory :::::::::::::::::::::::::::::::::::::::::::::::::::: | * 36 | CALLDATASIZE | cds | | * 3d | RETURNDATASIZE | 0 cds | | * 3d | RETURNDATASIZE | 0 0 cds | | * 37 | CALLDATACOPY | | [0..calldatasize): calldata | * | * ::: delegatecall to implementation ::::::::::::::::::::::::::::::::::::::::::::: | * 3d | RETURNDATASIZE | 0 | | * 3d | RETURNDATASIZE | 0 0 | | * 36 | CALLDATASIZE | cds 0 0 | [0..calldatasize): calldata | * 3d | RETURNDATASIZE | 0 cds 0 0 | [0..calldatasize): calldata | * 7f slot | PUSH32 slot | s 0 cds 0 0 | [0..calldatasize): calldata | * 54 | SLOAD | i 0 cds 0 0 | [0..calldatasize): calldata | * 5a | GAS | g i 0 cds 0 0 | [0..calldatasize): calldata | * f4 | DELEGATECALL | succ | [0..calldatasize): calldata | * | * ::: copy returndata to memory :::::::::::::::::::::::::::::::::::::::::::::::::: | * 3d | RETURNDATASIZE | rds succ | [0..calldatasize): calldata | * 60 0x00 | PUSH1 0x00 | 0 rds succ | [0..calldatasize): calldata | * 80 | DUP1 | 0 0 rds succ | [0..calldatasize): calldata | * 3e | RETURNDATACOPY | succ | [0..returndatasize): returndata | * | * ::: branch on delegatecall status :::::::::::::::::::::::::::::::::::::::::::::: | * 60 0x3E | PUSH1 0x3E | dest succ | [0..returndatasize): returndata | * 57 | JUMPI | | [0..returndatasize): returndata | * | * ::: delegatecall failed, revert :::::::::::::::::::::::::::::::::::::::::::::::: | * 3d | RETURNDATASIZE | rds | [0..returndatasize): returndata | * 60 0x00 | PUSH1 0x00 | 0 rds | [0..returndatasize): returndata | * fd | REVERT | | [0..returndatasize): returndata | * | * ::: delegatecall succeeded, return ::::::::::::::::::::::::::::::::::::::::::::: | * 5b | JUMPDEST | | [0..returndatasize): returndata | * 3d | RETURNDATASIZE | rds | [0..returndatasize): returndata | * 60 0x00 | PUSH1 0x00 | 0 rds | [0..returndatasize): returndata | * f3 | RETURN | | [0..returndatasize): returndata | * | * ::: implementation , return :::::::::::::::::::::::::::::::::::::::::::::::::::: | * 5b | JUMPDEST | | | * 60 0x20 | PUSH1 0x20 | 32 | | * 60 0x0F | PUSH1 0x0F | o 32 | | * 3d | RETURNDATASIZE | 0 o 32 | | * 39 | CODECOPY | | [0..32): implementation slot | * 3d | RETURNDATASIZE | 0 | [0..32): implementation slot | * 51 | MLOAD | slot | [0..32): implementation slot | * 54 | SLOAD | impl | [0..32): implementation slot | * 3d | RETURNDATASIZE | 0 impl | [0..32): implementation slot | * 52 | MSTORE | | [0..32): implementation address | * 59 | MSIZE | 32 | [0..32): implementation address | * 3d | RETURNDATASIZE | 0 32 | [0..32): implementation address | * f3 | RETURN | | [0..32): implementation address | * ---------------------------------------------------------------------------------+ */ let m := mload(0x40) // Cache the free memory pointer. mstore(0x60, 0x3d6000803e603e573d6000fd5b3d6000f35b6020600f3d393d51543d52593df3) mstore(0x40, 0xa13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc545af4) mstore(0x20, 0x600f5155f3365814604357363d3d373d3d363d7f360894) mstore(0x09, or(shl(160, 0x60523d8160223d3973), shr(96, shl(96, implementation)))) instance := create(value, 0x0c, 0x74) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } mstore(0x40, m) // Restore the free memory pointer. mstore(0x60, 0) // Restore the zero slot. } } /// @dev Deploys a deterministic ERC1967I proxy with `implementation` and `salt`. function deployDeterministicERC1967I(address implementation, bytes32 salt) internal returns (address instance) { instance = deployDeterministicERC1967I(0, implementation, salt); } /// @dev Deploys a deterministic ERC1967I proxy with `implementation` and `salt`. /// Deposits `value` ETH during deployment. function deployDeterministicERC1967I(uint256 value, address implementation, bytes32 salt) internal returns (address instance) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) // Cache the free memory pointer. mstore(0x60, 0x3d6000803e603e573d6000fd5b3d6000f35b6020600f3d393d51543d52593df3) mstore(0x40, 0xa13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc545af4) mstore(0x20, 0x600f5155f3365814604357363d3d373d3d363d7f360894) mstore(0x09, or(shl(160, 0x60523d8160223d3973), shr(96, shl(96, implementation)))) instance := create2(value, 0x0c, 0x74, salt) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } mstore(0x40, m) // Restore the free memory pointer. mstore(0x60, 0) // Restore the zero slot. } } /// @dev Creates a deterministic ERC1967I proxy with `implementation` and `salt`. /// Note: This method is intended for use in ERC4337 factories, /// which are expected to NOT revert if the proxy is already deployed. function createDeterministicERC1967I(address implementation, bytes32 salt) internal returns (bool alreadyDeployed, address instance) { return createDeterministicERC1967I(0, implementation, salt); } /// @dev Creates a deterministic ERC1967I proxy with `implementation` and `salt`. /// Deposits `value` ETH during deployment. /// Note: This method is intended for use in ERC4337 factories, /// which are expected to NOT revert if the proxy is already deployed. function createDeterministicERC1967I(uint256 value, address implementation, bytes32 salt) internal returns (bool alreadyDeployed, address instance) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) // Cache the free memory pointer. mstore(0x60, 0x3d6000803e603e573d6000fd5b3d6000f35b6020600f3d393d51543d52593df3) mstore(0x40, 0xa13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc545af4) mstore(0x20, 0x600f5155f3365814604357363d3d373d3d363d7f360894) mstore(0x09, or(shl(160, 0x60523d8160223d3973), shr(96, shl(96, implementation)))) // Compute and store the bytecode hash. mstore(add(m, 0x35), keccak256(0x0c, 0x74)) mstore(m, shl(88, address())) mstore8(m, 0xff) // Write the prefix. mstore(add(m, 0x15), salt) instance := keccak256(m, 0x55) for {} 1 {} { if iszero(extcodesize(instance)) { instance := create2(value, 0x0c, 0x74, salt) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } break } alreadyDeployed := 1 if iszero(value) { break } if iszero(call(gas(), instance, value, codesize(), 0x00, codesize(), 0x00)) { mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`. revert(0x1c, 0x04) } break } mstore(0x40, m) // Restore the free memory pointer. mstore(0x60, 0) // Restore the zero slot. } } /// @dev Returns the initialization code of the ERC1967I proxy of `implementation`. function initCodeERC1967I(address implementation) internal pure returns (bytes memory c) { /// @solidity memory-safe-assembly assembly { c := mload(0x40) mstore(add(c, 0x74), 0x3d6000803e603e573d6000fd5b3d6000f35b6020600f3d393d51543d52593df3) mstore(add(c, 0x54), 0xa13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc545af4) mstore(add(c, 0x34), 0x600f5155f3365814604357363d3d373d3d363d7f360894) mstore(add(c, 0x1d), implementation) mstore(add(c, 0x09), 0x60523d8160223d3973) mstore(add(c, 0x94), 0) mstore(c, 0x74) // Store the length. mstore(0x40, add(c, 0xa0)) // Allocate memory. } } /// @dev Returns the initialization code hash of the ERC1967I proxy of `implementation`. function initCodeHashERC1967I(address implementation) internal pure returns (bytes32 hash) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) // Cache the free memory pointer. mstore(0x60, 0x3d6000803e603e573d6000fd5b3d6000f35b6020600f3d393d51543d52593df3) mstore(0x40, 0xa13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc545af4) mstore(0x20, 0x600f5155f3365814604357363d3d373d3d363d7f360894) mstore(0x09, or(shl(160, 0x60523d8160223d3973), shr(96, shl(96, implementation)))) hash := keccak256(0x0c, 0x74) mstore(0x40, m) // Restore the free memory pointer. mstore(0x60, 0) // Restore the zero slot. } } /// @dev Returns the address of the ERC1967I proxy of `implementation`, with `salt` by `deployer`. /// Note: The returned result has dirty upper 96 bits. Please clean if used in assembly. function predictDeterministicAddressERC1967I( address implementation, bytes32 salt, address deployer ) internal pure returns (address predicted) { bytes32 hash = initCodeHashERC1967I(implementation); predicted = predictDeterministicAddress(hash, salt, deployer); } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* ERC1967I PROXY WITH IMMUTABLE ARGS OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Deploys a minimal ERC1967I proxy with `implementation` and `args`. function deployERC1967I(address implementation, bytes memory args) internal returns (address) { return deployERC1967I(0, implementation, args); } /// @dev Deploys a minimal ERC1967I proxy with `implementation` and `args`. /// Deposits `value` ETH during deployment. function deployERC1967I(uint256 value, address implementation, bytes memory args) internal returns (address instance) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) let n := mload(args) pop(staticcall(gas(), 4, add(args, 0x20), n, add(m, 0x8b), n)) mstore(add(m, 0x6b), 0x3d6000803e603e573d6000fd5b3d6000f35b6020600f3d393d51543d52593df3) mstore(add(m, 0x4b), 0xa13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc545af4) mstore(add(m, 0x2b), 0x600f5155f3365814604357363d3d373d3d363d7f360894) mstore(add(m, 0x14), implementation) mstore(m, add(0xfe6100523d8160233d3973, shl(56, n))) // Do a out-of-gas revert if `n` is greater than `0xffff - 0x52 = 0xffad`. instance := create(value, add(m, add(0x15, lt(n, 0xffae))), add(0x75, n)) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } } } /// @dev Deploys a deterministic ERC1967I proxy with `implementation`, `args`, and `salt`. function deployDeterministicERC1967I(address implementation, bytes memory args, bytes32 salt) internal returns (address instance) { instance = deployDeterministicERC1967I(0, implementation, args, salt); } /// @dev Deploys a deterministic ERC1967I proxy with `implementation`, `args`, and `salt`. /// Deposits `value` ETH during deployment. function deployDeterministicERC1967I( uint256 value, address implementation, bytes memory args, bytes32 salt ) internal returns (address instance) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) let n := mload(args) pop(staticcall(gas(), 4, add(args, 0x20), n, add(m, 0x8b), n)) mstore(add(m, 0x6b), 0x3d6000803e603e573d6000fd5b3d6000f35b6020600f3d393d51543d52593df3) mstore(add(m, 0x4b), 0xa13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc545af4) mstore(add(m, 0x2b), 0x600f5155f3365814604357363d3d373d3d363d7f360894) mstore(add(m, 0x14), implementation) mstore(m, add(0xfe6100523d8160233d3973, shl(56, n))) // Do a out-of-gas revert if `n` is greater than `0xffff - 0x52 = 0xffad`. instance := create2(value, add(m, add(0x15, lt(n, 0xffae))), add(0x75, n), salt) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } } } /// @dev Creates a deterministic ERC1967I proxy with `implementation`, `args` and `salt`. /// Note: This method is intended for use in ERC4337 factories, /// which are expected to NOT revert if the proxy is already deployed. function createDeterministicERC1967I(address implementation, bytes memory args, bytes32 salt) internal returns (bool alreadyDeployed, address instance) { return createDeterministicERC1967I(0, implementation, args, salt); } /// @dev Creates a deterministic ERC1967I proxy with `implementation`, `args` and `salt`. /// Deposits `value` ETH during deployment. /// Note: This method is intended for use in ERC4337 factories, /// which are expected to NOT revert if the proxy is already deployed. function createDeterministicERC1967I( uint256 value, address implementation, bytes memory args, bytes32 salt ) internal returns (bool alreadyDeployed, address instance) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) let n := mload(args) pop(staticcall(gas(), 4, add(args, 0x20), n, add(m, 0x75), n)) mstore(add(m, 0x55), 0x3d6000803e603e573d6000fd5b3d6000f35b6020600f3d393d51543d52593df3) mstore(add(m, 0x35), 0xa13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc545af4) mstore(add(m, 0x15), 0x5155f3365814604357363d3d373d3d363d7f360894) mstore(0x16, 0x600f) mstore(0x14, implementation) // Do a out-of-gas revert if `n` is greater than `0xffff - 0x52 = 0xffad`. mstore(gt(n, 0xffad), add(0xfe6100523d8160233d3973, shl(56, n))) mstore(m, mload(0x16)) // Compute and store the bytecode hash. mstore8(0x00, 0xff) // Write the prefix. mstore(0x35, keccak256(m, add(n, 0x75))) mstore(0x01, shl(96, address())) mstore(0x15, salt) instance := keccak256(0x00, 0x55) for {} 1 {} { if iszero(extcodesize(instance)) { instance := create2(value, m, add(0x75, n), salt) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } break } alreadyDeployed := 1 if iszero(value) { break } if iszero(call(gas(), instance, value, codesize(), 0x00, codesize(), 0x00)) { mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`. revert(0x1c, 0x04) } break } mstore(0x35, 0) // Restore the overwritten part of the free memory pointer. } } /// @dev Returns the initialization code of the ERC1967I proxy of `implementation` and `args`. function initCodeERC1967I(address implementation, bytes memory args) internal pure returns (bytes memory c) { /// @solidity memory-safe-assembly assembly { c := mload(0x40) let n := mload(args) // Do a out-of-gas revert if `n` is greater than `0xffff - 0x52 = 0xffad`. returndatacopy(returndatasize(), returndatasize(), gt(n, 0xffad)) for { let i := 0 } lt(i, n) { i := add(i, 0x20) } { mstore(add(add(c, 0x95), i), mload(add(add(args, 0x20), i))) } mstore(add(c, 0x75), 0x3d6000803e603e573d6000fd5b3d6000f35b6020600f3d393d51543d52593df3) mstore(add(c, 0x55), 0xa13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc545af4) mstore(add(c, 0x35), 0x600f5155f3365814604357363d3d373d3d363d7f360894) mstore(add(c, 0x1e), implementation) mstore(add(c, 0x0a), add(0x6100523d8160233d3973, shl(56, n))) mstore(add(c, add(n, 0x95)), 0) mstore(c, add(0x75, n)) // Store the length. mstore(0x40, add(c, add(n, 0xb5))) // Allocate memory. } } /// @dev Returns the initialization code hash of the ERC1967I proxy of `implementation` and `args. function initCodeHashERC1967I(address implementation, bytes memory args) internal pure returns (bytes32 hash) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) // Cache the free memory pointer. let n := mload(args) // Do a out-of-gas revert if `n` is greater than `0xffff - 0x52 = 0xffad`. returndatacopy(returndatasize(), returndatasize(), gt(n, 0xffad)) for { let i := 0 } lt(i, n) { i := add(i, 0x20) } { mstore(add(add(m, 0x75), i), mload(add(add(args, 0x20), i))) } mstore(add(m, 0x55), 0x3d6000803e603e573d6000fd5b3d6000f35b6020600f3d393d51543d52593df3) mstore(add(m, 0x35), 0xa13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc545af4) mstore(add(m, 0x15), 0x5155f3365814604357363d3d373d3d363d7f360894) mstore(0x16, 0x600f) mstore(0x14, implementation) mstore(0x00, add(0x6100523d8160233d3973, shl(56, n))) mstore(m, mload(0x16)) hash := keccak256(m, add(0x75, n)) } } /// @dev Returns the address of the ERC1967I proxy of `implementation`, `args` with `salt` by `deployer`. /// Note: The returned result has dirty upper 96 bits. Please clean if used in assembly. function predictDeterministicAddressERC1967I( address implementation, bytes memory args, bytes32 salt, address deployer ) internal pure returns (address predicted) { bytes32 hash = initCodeHashERC1967I(implementation, args); predicted = predictDeterministicAddress(hash, salt, deployer); } /// @dev Equivalent to `argsOnERC1967I(instance, start, 2 ** 256 - 1)`. function argsOnERC1967I(address instance) internal view returns (bytes memory args) { /// @solidity memory-safe-assembly assembly { args := mload(0x40) mstore(args, and(0xffffffffff, sub(extcodesize(instance), 0x52))) // Store the length. extcodecopy(instance, add(args, 0x20), 0x52, add(mload(args), 0x20)) mstore(0x40, add(mload(args), add(args, 0x40))) // Allocate memory. } } /// @dev Equivalent to `argsOnERC1967I(instance, start, 2 ** 256 - 1)`. function argsOnERC1967I(address instance, uint256 start) internal view returns (bytes memory args) { /// @solidity memory-safe-assembly assembly { args := mload(0x40) let n := and(0xffffffffff, sub(extcodesize(instance), 0x52)) let l := sub(n, and(0xffffff, mul(lt(start, n), start))) extcodecopy(instance, args, add(start, 0x32), add(l, 0x40)) mstore(args, mul(sub(n, start), lt(start, n))) // Store the length. mstore(0x40, add(mload(args), add(args, 0x40))) // Allocate memory. } } /// @dev Returns a slice of the immutable arguments on `instance` from `start` to `end`. /// `start` and `end` will be clamped to the range `[0, args.length]`. /// The `instance` MUST be deployed via the ERC1967 with immutable args functions. /// Otherwise, the behavior is undefined. /// Out-of-gas reverts if `instance` does not have any code. function argsOnERC1967I(address instance, uint256 start, uint256 end) internal view returns (bytes memory args) { /// @solidity memory-safe-assembly assembly { args := mload(0x40) if iszero(lt(end, 0xffff)) { end := 0xffff } let d := mul(sub(end, start), lt(start, end)) extcodecopy(instance, args, add(start, 0x32), add(d, 0x20)) if iszero(and(0xff, mload(add(args, d)))) { let n := sub(extcodesize(instance), 0x52) returndatacopy(returndatasize(), returndatasize(), shr(40, n)) d := mul(gt(n, start), sub(d, mul(gt(end, n), sub(end, n)))) } mstore(args, d) // Store the length. mstore(add(add(args, 0x20), d), 0) // Zeroize the slot after the bytes. mstore(0x40, add(add(args, 0x40), d)) // Allocate memory. } } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* ERC1967 BOOTSTRAP OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ // A bootstrap is a minimal UUPS implementation that allows an ERC1967 proxy // pointing to it to be upgraded. The ERC1967 proxy can then be deployed to a // deterministic address independent of the implementation: // ``` // address bootstrap = LibClone.erc1967Bootstrap(); // address instance = LibClone.deployDeterministicERC1967(0, bootstrap, salt); // LibClone.bootstrapERC1967(bootstrap, implementation); // ``` /// @dev Deploys the ERC1967 bootstrap if it has not been deployed. function erc1967Bootstrap() internal returns (address) { return erc1967Bootstrap(address(this)); } /// @dev Deploys the ERC1967 bootstrap if it has not been deployed. function erc1967Bootstrap(address authorizedUpgrader) internal returns (address bootstrap) { bytes memory c = initCodeERC1967Bootstrap(authorizedUpgrader); bootstrap = predictDeterministicAddress(keccak256(c), bytes32(0), address(this)); /// @solidity memory-safe-assembly assembly { if iszero(extcodesize(bootstrap)) { if iszero(create2(0, add(c, 0x20), mload(c), 0)) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } } } } /// @dev Replaces the implementation at `instance`. function bootstrapERC1967(address instance, address implementation) internal { /// @solidity memory-safe-assembly assembly { mstore(0x00, implementation) if iszero(call(gas(), instance, 0, 0x0c, 0x14, codesize(), 0x00)) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } } } /// @dev Replaces the implementation at `instance`, and then call it with `data`. function bootstrapERC1967AndCall(address instance, address implementation, bytes memory data) internal { /// @solidity memory-safe-assembly assembly { let n := mload(data) mstore(data, implementation) if iszero(call(gas(), instance, 0, add(data, 0x0c), add(n, 0x14), codesize(), 0x00)) { if iszero(returndatasize()) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } returndatacopy(mload(0x40), 0x00, returndatasize()) revert(mload(0x40), returndatasize()) } mstore(data, n) // Restore the length of `data`. } } /// @dev Returns the implementation address of the ERC1967 bootstrap for this contract. function predictDeterministicAddressERC1967Bootstrap() internal view returns (address) { return predictDeterministicAddressERC1967Bootstrap(address(this), address(this)); } /// @dev Returns the implementation address of the ERC1967 bootstrap for this contract. function predictDeterministicAddressERC1967Bootstrap( address authorizedUpgrader, address deployer ) internal pure returns (address) { bytes32 hash = initCodeHashERC1967Bootstrap(authorizedUpgrader); return predictDeterministicAddress(hash, bytes32(0), deployer); } /// @dev Returns the initialization code of the ERC1967 bootstrap. function initCodeERC1967Bootstrap(address authorizedUpgrader) internal pure returns (bytes memory c) { /// @solidity memory-safe-assembly assembly { c := mload(0x40) mstore(add(c, 0x80), 0x3d3560601c5af46047573d6000383e3d38fd0000000000000000000000000000) mstore(add(c, 0x60), 0xa920a3ca505d382bbc55601436116049575b005b363d3d373d3d601436036014) mstore(add(c, 0x40), 0x0338573d3560601c7f360894a13ba1a3210667c828492db98dca3e2076cc3735) mstore(add(c, 0x20), authorizedUpgrader) mstore(add(c, 0x0c), 0x606880600a3d393df3fe3373) mstore(c, 0x72) mstore(0x40, add(c, 0xa0)) } } /// @dev Returns the initialization code hash of the ERC1967 bootstrap. function initCodeHashERC1967Bootstrap(address authorizedUpgrader) internal pure returns (bytes32) { return keccak256(initCodeERC1967Bootstrap(authorizedUpgrader)); } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* MINIMAL ERC1967 BEACON PROXY OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ // Note: If you use this proxy, you MUST make sure that the beacon is a // valid ERC1967 beacon. This means that the beacon must always return a valid // address upon a staticcall to `implementation()`, given sufficient gas. // For performance, the deployment operations and the proxy assumes that the // beacon is always valid and will NOT validate it. /// @dev Deploys a minimal ERC1967 beacon proxy. function deployERC1967BeaconProxy(address beacon) internal returns (address instance) { instance = deployERC1967BeaconProxy(0, beacon); } /// @dev Deploys a minimal ERC1967 beacon proxy. /// Deposits `value` ETH during deployment. function deployERC1967BeaconProxy(uint256 value, address beacon) internal returns (address instance) { /// @solidity memory-safe-assembly assembly { /** * ---------------------------------------------------------------------------------+ * CREATION (34 bytes) | * ---------------------------------------------------------------------------------| * Opcode | Mnemonic | Stack | Memory | * ---------------------------------------------------------------------------------| * 60 runSize | PUSH1 runSize | r | | * 3d | RETURNDATASIZE | 0 r | | * 81 | DUP2 | r 0 r | | * 60 offset | PUSH1 offset | o r 0 r | | * 3d | RETURNDATASIZE | 0 o r 0 r | | * 39 | CODECOPY | 0 r | [0..runSize): runtime code | * 73 beac | PUSH20 beac | beac 0 r | [0..runSize): runtime code | * 60 slotPos | PUSH1 slotPos | slotPos beac 0 r | [0..runSize): runtime code | * 51 | MLOAD | slot beac 0 r | [0..runSize): runtime code | * 55 | SSTORE | 0 r | [0..runSize): runtime code | * f3 | RETURN | | [0..runSize): runtime code | * ---------------------------------------------------------------------------------| * RUNTIME (82 bytes) | * ---------------------------------------------------------------------------------| * Opcode | Mnemonic | Stack | Memory | * ---------------------------------------------------------------------------------| * | * ::: copy calldata to memory :::::::::::::::::::::::::::::::::::::::::::::::::::: | * 36 | CALLDATASIZE | cds | | * 3d | RETURNDATASIZE | 0 cds | | * 3d | RETURNDATASIZE | 0 0 cds | | * 37 | CALLDATACOPY | | [0..calldatasize): calldata | * | * ::: delegatecall to implementation ::::::::::::::::::::::::::::::::::::::::::::: | * 3d | RETURNDATASIZE | 0 | | * 3d | RETURNDATASIZE | 0 0 | | * 36 | CALLDATASIZE | cds 0 0 | [0..calldatasize): calldata | * 3d | RETURNDATASIZE | 0 cds 0 0 | [0..calldatasize): calldata | * | * ~~~~~~~ beacon staticcall sub procedure ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | * 60 0x20 | PUSH1 0x20 | 32 | | * 36 | CALLDATASIZE | cds 32 | | * 60 0x04 | PUSH1 0x04 | 4 cds 32 | | * 36 | CALLDATASIZE | cds 4 cds 32 | | * 63 0x5c60da1b | PUSH4 0x5c60da1b | 0x5c60da1b cds 4 cds 32 | | * 60 0xe0 | PUSH1 0xe0 | 224 0x5c60da1b cds 4 cds 32 | | * 1b | SHL | sel cds 4 cds 32 | | * 36 | CALLDATASIZE | cds sel cds 4 cds 32 | | * 52 | MSTORE | cds 4 cds 32 | sel | * 7f slot | PUSH32 slot | s cds 4 cds 32 | sel | * 54 | SLOAD | beac cds 4 cds 32 | sel | * 5a | GAS | g beac cds 4 cds 32 | sel | * fa | STATICCALL | succ | impl | * 50 | POP | | impl | * 36 | CALLDATASIZE | cds | impl | * 51 | MLOAD | impl | impl | * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | * 5a | GAS | g impl 0 cds 0 0 | [0..calldatasize): calldata | * f4 | DELEGATECALL | succ | [0..calldatasize): calldata | * | * ::: copy returndata to memory :::::::::::::::::::::::::::::::::::::::::::::::::: | * 3d | RETURNDATASIZE | rds succ | [0..calldatasize): calldata | * 60 0x00 | PUSH1 0x00 | 0 rds succ | [0..calldatasize): calldata | * 80 | DUP1 | 0 0 rds succ | [0..calldatasize): calldata | * 3e | RETURNDATACOPY | succ | [0..returndatasize): returndata | * | * ::: branch on delegatecall status :::::::::::::::::::::::::::::::::::::::::::::: | * 60 0x4d | PUSH1 0x4d | dest succ | [0..returndatasize): returndata | * 57 | JUMPI | | [0..returndatasize): returndata | * | * ::: delegatecall failed, revert :::::::::::::::::::::::::::::::::::::::::::::::: | * 3d | RETURNDATASIZE | rds | [0..returndatasize): returndata | * 60 0x00 | PUSH1 0x00 | 0 rds | [0..returndatasize): returndata | * fd | REVERT | | [0..returndatasize): returndata | * | * ::: delegatecall succeeded, return ::::::::::::::::::::::::::::::::::::::::::::: | * 5b | JUMPDEST | | [0..returndatasize): returndata | * 3d | RETURNDATASIZE | rds | [0..returndatasize): returndata | * 60 0x00 | PUSH1 0x00 | 0 rds | [0..returndatasize): returndata | * f3 | RETURN | | [0..returndatasize): returndata | * ---------------------------------------------------------------------------------+ */ let m := mload(0x40) // Cache the free memory pointer. mstore(0x60, 0xb3582b35133d50545afa5036515af43d6000803e604d573d6000fd5b3d6000f3) mstore(0x40, 0x1b60e01b36527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6c) mstore(0x20, 0x60195155f3363d3d373d3d363d602036600436635c60da) mstore(0x09, or(shl(160, 0x60523d8160223d3973), shr(96, shl(96, beacon)))) instance := create(value, 0x0c, 0x74) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } mstore(0x40, m) // Restore the free memory pointer. mstore(0x60, 0) // Restore the zero slot. } } /// @dev Deploys a deterministic minimal ERC1967 beacon proxy with `salt`. function deployDeterministicERC1967BeaconProxy(address beacon, bytes32 salt) internal returns (address instance) { instance = deployDeterministicERC1967BeaconProxy(0, beacon, salt); } /// @dev Deploys a deterministic minimal ERC1967 beacon proxy with `salt`. /// Deposits `value` ETH during deployment. function deployDeterministicERC1967BeaconProxy(uint256 value, address beacon, bytes32 salt) internal returns (address instance) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) // Cache the free memory pointer. mstore(0x60, 0xb3582b35133d50545afa5036515af43d6000803e604d573d6000fd5b3d6000f3) mstore(0x40, 0x1b60e01b36527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6c) mstore(0x20, 0x60195155f3363d3d373d3d363d602036600436635c60da) mstore(0x09, or(shl(160, 0x60523d8160223d3973), shr(96, shl(96, beacon)))) instance := create2(value, 0x0c, 0x74, salt) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } mstore(0x40, m) // Restore the free memory pointer. mstore(0x60, 0) // Restore the zero slot. } } /// @dev Creates a deterministic minimal ERC1967 beacon proxy with `salt`. /// Note: This method is intended for use in ERC4337 factories, /// which are expected to NOT revert if the proxy is already deployed. function createDeterministicERC1967BeaconProxy(address beacon, bytes32 salt) internal returns (bool alreadyDeployed, address instance) { return createDeterministicERC1967BeaconProxy(0, beacon, salt); } /// @dev Creates a deterministic minimal ERC1967 beacon proxy with `salt`. /// Deposits `value` ETH during deployment. /// Note: This method is intended for use in ERC4337 factories, /// which are expected to NOT revert if the proxy is already deployed. function createDeterministicERC1967BeaconProxy(uint256 value, address beacon, bytes32 salt) internal returns (bool alreadyDeployed, address instance) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) // Cache the free memory pointer. mstore(0x60, 0xb3582b35133d50545afa5036515af43d6000803e604d573d6000fd5b3d6000f3) mstore(0x40, 0x1b60e01b36527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6c) mstore(0x20, 0x60195155f3363d3d373d3d363d602036600436635c60da) mstore(0x09, or(shl(160, 0x60523d8160223d3973), shr(96, shl(96, beacon)))) // Compute and store the bytecode hash. mstore(add(m, 0x35), keccak256(0x0c, 0x74)) mstore(m, shl(88, address())) mstore8(m, 0xff) // Write the prefix. mstore(add(m, 0x15), salt) instance := keccak256(m, 0x55) for {} 1 {} { if iszero(extcodesize(instance)) { instance := create2(value, 0x0c, 0x74, salt) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } break } alreadyDeployed := 1 if iszero(value) { break } if iszero(call(gas(), instance, value, codesize(), 0x00, codesize(), 0x00)) { mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`. revert(0x1c, 0x04) } break } mstore(0x40, m) // Restore the free memory pointer. mstore(0x60, 0) // Restore the zero slot. } } /// @dev Returns the initialization code of the minimal ERC1967 beacon proxy. function initCodeERC1967BeaconProxy(address beacon) internal pure returns (bytes memory c) { /// @solidity memory-safe-assembly assembly { c := mload(0x40) mstore(add(c, 0x74), 0xb3582b35133d50545afa5036515af43d6000803e604d573d6000fd5b3d6000f3) mstore(add(c, 0x54), 0x1b60e01b36527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6c) mstore(add(c, 0x34), 0x60195155f3363d3d373d3d363d602036600436635c60da) mstore(add(c, 0x1d), beacon) mstore(add(c, 0x09), 0x60523d8160223d3973) mstore(add(c, 0x94), 0) mstore(c, 0x74) // Store the length. mstore(0x40, add(c, 0xa0)) // Allocate memory. } } /// @dev Returns the initialization code hash of the minimal ERC1967 beacon proxy. function initCodeHashERC1967BeaconProxy(address beacon) internal pure returns (bytes32 hash) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) // Cache the free memory pointer. mstore(0x60, 0xb3582b35133d50545afa5036515af43d6000803e604d573d6000fd5b3d6000f3) mstore(0x40, 0x1b60e01b36527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6c) mstore(0x20, 0x60195155f3363d3d373d3d363d602036600436635c60da) mstore(0x09, or(shl(160, 0x60523d8160223d3973), shr(96, shl(96, beacon)))) hash := keccak256(0x0c, 0x74) mstore(0x40, m) // Restore the free memory pointer. mstore(0x60, 0) // Restore the zero slot. } } /// @dev Returns the address of the ERC1967 beacon proxy, with `salt` by `deployer`. /// Note: The returned result has dirty upper 96 bits. Please clean if used in assembly. function predictDeterministicAddressERC1967BeaconProxy( address beacon, bytes32 salt, address deployer ) internal pure returns (address predicted) { bytes32 hash = initCodeHashERC1967BeaconProxy(beacon); predicted = predictDeterministicAddress(hash, salt, deployer); } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* ERC1967 BEACON PROXY WITH IMMUTABLE ARGS OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Deploys a minimal ERC1967 beacon proxy with `args`. function deployERC1967BeaconProxy(address beacon, bytes memory args) internal returns (address instance) { instance = deployERC1967BeaconProxy(0, beacon, args); } /// @dev Deploys a minimal ERC1967 beacon proxy with `args`. /// Deposits `value` ETH during deployment. function deployERC1967BeaconProxy(uint256 value, address beacon, bytes memory args) internal returns (address instance) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) let n := mload(args) pop(staticcall(gas(), 4, add(args, 0x20), n, add(m, 0x8b), n)) mstore(add(m, 0x6b), 0xb3582b35133d50545afa5036515af43d6000803e604d573d6000fd5b3d6000f3) mstore(add(m, 0x4b), 0x1b60e01b36527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6c) mstore(add(m, 0x2b), 0x60195155f3363d3d373d3d363d602036600436635c60da) mstore(add(m, 0x14), beacon) // Do a out-of-gas revert if `n` is greater than `0xffff - 0x52 = 0xffad`. mstore(add(m, gt(n, 0xffad)), add(0xfe6100523d8160233d3973, shl(56, n))) instance := create(value, add(m, 0x16), add(n, 0x75)) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } } } /// @dev Deploys a deterministic minimal ERC1967 beacon proxy with `args` and `salt`. function deployDeterministicERC1967BeaconProxy(address beacon, bytes memory args, bytes32 salt) internal returns (address instance) { instance = deployDeterministicERC1967BeaconProxy(0, beacon, args, salt); } /// @dev Deploys a deterministic minimal ERC1967 beacon proxy with `args` and `salt`. /// Deposits `value` ETH during deployment. function deployDeterministicERC1967BeaconProxy( uint256 value, address beacon, bytes memory args, bytes32 salt ) internal returns (address instance) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) let n := mload(args) pop(staticcall(gas(), 4, add(args, 0x20), n, add(m, 0x8b), n)) mstore(add(m, 0x6b), 0xb3582b35133d50545afa5036515af43d6000803e604d573d6000fd5b3d6000f3) mstore(add(m, 0x4b), 0x1b60e01b36527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6c) mstore(add(m, 0x2b), 0x60195155f3363d3d373d3d363d602036600436635c60da) mstore(add(m, 0x14), beacon) // Do a out-of-gas revert if `n` is greater than `0xffff - 0x52 = 0xffad`. mstore(add(m, gt(n, 0xffad)), add(0xfe6100523d8160233d3973, shl(56, n))) instance := create2(value, add(m, 0x16), add(n, 0x75), salt) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } } } /// @dev Creates a deterministic minimal ERC1967 beacon proxy with `args` and `salt`. /// Note: This method is intended for use in ERC4337 factories, /// which are expected to NOT revert if the proxy is already deployed. function createDeterministicERC1967BeaconProxy(address beacon, bytes memory args, bytes32 salt) internal returns (bool alreadyDeployed, address instance) { return createDeterministicERC1967BeaconProxy(0, beacon, args, salt); } /// @dev Creates a deterministic minimal ERC1967 beacon proxy with `args` and `salt`. /// Deposits `value` ETH during deployment. /// Note: This method is intended for use in ERC4337 factories, /// which are expected to NOT revert if the proxy is already deployed. function createDeterministicERC1967BeaconProxy( uint256 value, address beacon, bytes memory args, bytes32 salt ) internal returns (bool alreadyDeployed, address instance) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) let n := mload(args) pop(staticcall(gas(), 4, add(args, 0x20), n, add(m, 0x8b), n)) mstore(add(m, 0x6b), 0xb3582b35133d50545afa5036515af43d6000803e604d573d6000fd5b3d6000f3) mstore(add(m, 0x4b), 0x1b60e01b36527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6c) mstore(add(m, 0x2b), 0x60195155f3363d3d373d3d363d602036600436635c60da) mstore(add(m, 0x14), beacon) // Do a out-of-gas revert if `n` is greater than `0xffff - 0x52 = 0xffad`. mstore(add(m, gt(n, 0xffad)), add(0xfe6100523d8160233d3973, shl(56, n))) // Compute and store the bytecode hash. mstore8(0x00, 0xff) // Write the prefix. mstore(0x35, keccak256(add(m, 0x16), add(n, 0x75))) mstore(0x01, shl(96, address())) mstore(0x15, salt) instance := keccak256(0x00, 0x55) for {} 1 {} { if iszero(extcodesize(instance)) { instance := create2(value, add(m, 0x16), add(n, 0x75), salt) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } break } alreadyDeployed := 1 if iszero(value) { break } if iszero(call(gas(), instance, value, codesize(), 0x00, codesize(), 0x00)) { mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`. revert(0x1c, 0x04) } break } mstore(0x35, 0) // Restore the overwritten part of the free memory pointer. } } /// @dev Returns the initialization code of the minimal ERC1967 beacon proxy. function initCodeERC1967BeaconProxy(address beacon, bytes memory args) internal pure returns (bytes memory c) { /// @solidity memory-safe-assembly assembly { c := mload(0x40) let n := mload(args) // Do a out-of-gas revert if `n` is greater than `0xffff - 0x52 = 0xffad`. returndatacopy(returndatasize(), returndatasize(), gt(n, 0xffad)) for { let i := 0 } lt(i, n) { i := add(i, 0x20) } { mstore(add(add(c, 0x95), i), mload(add(add(args, 0x20), i))) } mstore(add(c, 0x75), 0xb3582b35133d50545afa5036515af43d6000803e604d573d6000fd5b3d6000f3) mstore(add(c, 0x55), 0x1b60e01b36527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6c) mstore(add(c, 0x35), 0x60195155f3363d3d373d3d363d602036600436635c60da) mstore(add(c, 0x1e), beacon) mstore(add(c, 0x0a), add(0x6100523d8160233d3973, shl(56, n))) mstore(c, add(n, 0x75)) // Store the length. mstore(add(c, add(n, 0x95)), 0) // Zeroize the slot after the bytes. mstore(0x40, add(c, add(n, 0xb5))) // Allocate memory. } } /// @dev Returns the initialization code hash of the minimal ERC1967 beacon proxy with `args`. function initCodeHashERC1967BeaconProxy(address beacon, bytes memory args) internal pure returns (bytes32 hash) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) let n := mload(args) // Do a out-of-gas revert if `n` is greater than `0xffff - 0x52 = 0xffad`. returndatacopy(returndatasize(), returndatasize(), gt(n, 0xffad)) for { let i := 0 } lt(i, n) { i := add(i, 0x20) } { mstore(add(add(m, 0x8b), i), mload(add(add(args, 0x20), i))) } mstore(add(m, 0x6b), 0xb3582b35133d50545afa5036515af43d6000803e604d573d6000fd5b3d6000f3) mstore(add(m, 0x4b), 0x1b60e01b36527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6c) mstore(add(m, 0x2b), 0x60195155f3363d3d373d3d363d602036600436635c60da) mstore(add(m, 0x14), beacon) mstore(m, add(0x6100523d8160233d3973, shl(56, n))) hash := keccak256(add(m, 0x16), add(n, 0x75)) } } /// @dev Returns the address of the ERC1967 beacon proxy with `args`, with `salt` by `deployer`. /// Note: The returned result has dirty upper 96 bits. Please clean if used in assembly. function predictDeterministicAddressERC1967BeaconProxy( address beacon, bytes memory args, bytes32 salt, address deployer ) internal pure returns (address predicted) { bytes32 hash = initCodeHashERC1967BeaconProxy(beacon, args); predicted = predictDeterministicAddress(hash, salt, deployer); } /// @dev Equivalent to `argsOnERC1967BeaconProxy(instance, start, 2 ** 256 - 1)`. function argsOnERC1967BeaconProxy(address instance) internal view returns (bytes memory args) { /// @solidity memory-safe-assembly assembly { args := mload(0x40) mstore(args, and(0xffffffffff, sub(extcodesize(instance), 0x52))) // Store the length. extcodecopy(instance, add(args, 0x20), 0x52, add(mload(args), 0x20)) mstore(0x40, add(mload(args), add(args, 0x40))) // Allocate memory. } } /// @dev Equivalent to `argsOnERC1967BeaconProxy(instance, start, 2 ** 256 - 1)`. function argsOnERC1967BeaconProxy(address instance, uint256 start) internal view returns (bytes memory args) { /// @solidity memory-safe-assembly assembly { args := mload(0x40) let n := and(0xffffffffff, sub(extcodesize(instance), 0x52)) let l := sub(n, and(0xffffff, mul(lt(start, n), start))) extcodecopy(instance, args, add(start, 0x32), add(l, 0x40)) mstore(args, mul(sub(n, start), lt(start, n))) // Store the length. mstore(0x40, add(args, add(0x40, mload(args)))) // Allocate memory. } } /// @dev Returns a slice of the immutable arguments on `instance` from `start` to `end`. /// `start` and `end` will be clamped to the range `[0, args.length]`. /// The `instance` MUST be deployed via the ERC1967 beacon proxy with immutable args functions. /// Otherwise, the behavior is undefined. /// Out-of-gas reverts if `instance` does not have any code. function argsOnERC1967BeaconProxy(address instance, uint256 start, uint256 end) internal view returns (bytes memory args) { /// @solidity memory-safe-assembly assembly { args := mload(0x40) if iszero(lt(end, 0xffff)) { end := 0xffff } let d := mul(sub(end, start), lt(start, end)) extcodecopy(instance, args, add(start, 0x32), add(d, 0x20)) if iszero(and(0xff, mload(add(args, d)))) { let n := sub(extcodesize(instance), 0x52) returndatacopy(returndatasize(), returndatasize(), shr(40, n)) d := mul(gt(n, start), sub(d, mul(gt(end, n), sub(end, n)))) } mstore(args, d) // Store the length. mstore(add(add(args, 0x20), d), 0) // Zeroize the slot after the bytes. mstore(0x40, add(add(args, 0x40), d)) // Allocate memory. } } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* ERC1967I BEACON PROXY OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ // Note: This proxy has a special code path that activates if `calldatasize() == 1`. // This code path skips the delegatecall and directly returns the `implementation` address. // The returned implementation is guaranteed to be valid if the keccak256 of the // proxy's code is equal to `ERC1967_BEACON_PROXY_CODE_HASH`. // // If you use this proxy, you MUST make sure that the beacon is a // valid ERC1967 beacon. This means that the beacon must always return a valid // address upon a staticcall to `implementation()`, given sufficient gas. // For performance, the deployment operations and the proxy assumes that the // beacon is always valid and will NOT validate it. /// @dev Deploys a ERC1967I beacon proxy. function deployERC1967IBeaconProxy(address beacon) internal returns (address instance) { instance = deployERC1967IBeaconProxy(0, beacon); } /// @dev Deploys a ERC1967I beacon proxy. /// Deposits `value` ETH during deployment. function deployERC1967IBeaconProxy(uint256 value, address beacon) internal returns (address instance) { /// @solidity memory-safe-assembly assembly { /** * ---------------------------------------------------------------------------------+ * CREATION (34 bytes) | * ---------------------------------------------------------------------------------| * Opcode | Mnemonic | Stack | Memory | * ---------------------------------------------------------------------------------| * 60 runSize | PUSH1 runSize | r | | * 3d | RETURNDATASIZE | 0 r | | * 81 | DUP2 | r 0 r | | * 60 offset | PUSH1 offset | o r 0 r | | * 3d | RETURNDATASIZE | 0 o r 0 r | | * 39 | CODECOPY | 0 r | [0..runSize): runtime code | * 73 beac | PUSH20 beac | beac 0 r | [0..runSize): runtime code | * 60 slotPos | PUSH1 slotPos | slotPos beac 0 r | [0..runSize): runtime code | * 51 | MLOAD | slot beac 0 r | [0..runSize): runtime code | * 55 | SSTORE | 0 r | [0..runSize): runtime code | * f3 | RETURN | | [0..runSize): runtime code | * ---------------------------------------------------------------------------------| * RUNTIME (87 bytes) | * ---------------------------------------------------------------------------------| * Opcode | Mnemonic | Stack | Memory | * ---------------------------------------------------------------------------------| * | * ::: copy calldata to memory :::::::::::::::::::::::::::::::::::::::::::::::::::: | * 36 | CALLDATASIZE | cds | | * 3d | RETURNDATASIZE | 0 cds | | * 3d | RETURNDATASIZE | 0 0 cds | | * 37 | CALLDATACOPY | | [0..calldatasize): calldata | * | * ::: delegatecall to implementation ::::::::::::::::::::::::::::::::::::::::::::: | * 3d | RETURNDATASIZE | 0 | | * 3d | RETURNDATASIZE | 0 0 | | * 36 | CALLDATASIZE | cds 0 0 | [0..calldatasize): calldata | * 3d | RETURNDATASIZE | 0 cds 0 0 | [0..calldatasize): calldata | * | * ~~~~~~~ beacon staticcall sub procedure ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | * 60 0x20 | PUSH1 0x20 | 32 | | * 36 | CALLDATASIZE | cds 32 | | * 60 0x04 | PUSH1 0x04 | 4 cds 32 | | * 36 | CALLDATASIZE | cds 4 cds 32 | | * 63 0x5c60da1b | PUSH4 0x5c60da1b | 0x5c60da1b cds 4 cds 32 | | * 60 0xe0 | PUSH1 0xe0 | 224 0x5c60da1b cds 4 cds 32 | | * 1b | SHL | sel cds 4 cds 32 | | * 36 | CALLDATASIZE | cds sel cds 4 cds 32 | | * 52 | MSTORE | cds 4 cds 32 | sel | * 7f slot | PUSH32 slot | s cds 4 cds 32 | sel | * 54 | SLOAD | beac cds 4 cds 32 | sel | * 5a | GAS | g beac cds 4 cds 32 | sel | * fa | STATICCALL | succ | impl | * ~~~~~~ check calldatasize ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | * 36 | CALLDATASIZE | cds succ | | * 14 | EQ | | impl | * 60 0x52 | PUSH1 0x52 | | impl | * 57 | JUMPI | | impl | * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | * 36 | CALLDATASIZE | cds | impl | * 51 | MLOAD | impl | impl | * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | * 5a | GAS | g impl 0 cds 0 0 | [0..calldatasize): calldata | * f4 | DELEGATECALL | succ | [0..calldatasize): calldata | * | * ::: copy returndata to memory :::::::::::::::::::::::::::::::::::::::::::::::::: | * 3d | RETURNDATASIZE | rds succ | [0..calldatasize): calldata | * 60 0x00 | PUSH1 0x00 | 0 rds succ | [0..calldatasize): calldata | * 60 0x01 | PUSH1 0x01 | 1 0 rds succ | [0..calldatasize): calldata | * 3e | RETURNDATACOPY | succ | [1..returndatasize): returndata | * | * ::: branch on delegatecall status :::::::::::::::::::::::::::::::::::::::::::::: | * 60 0x52 | PUSH1 0x52 | dest succ | [1..returndatasize): returndata | * 57 | JUMPI | | [1..returndatasize): returndata | * | * ::: delegatecall failed, revert :::::::::::::::::::::::::::::::::::::::::::::::: | * 3d | RETURNDATASIZE | rds | [1..returndatasize): returndata | * 60 0x01 | PUSH1 0x01 | 1 rds | [1..returndatasize): returndata | * fd | REVERT | | [1..returndatasize): returndata | * | * ::: delegatecall succeeded, return ::::::::::::::::::::::::::::::::::::::::::::: | * 5b | JUMPDEST | | [1..returndatasize): returndata | * 3d | RETURNDATASIZE | rds | [1..returndatasize): returndata | * 60 0x01 | PUSH1 0x01 | 1 rds | [1..returndatasize): returndata | * f3 | RETURN | | [1..returndatasize): returndata | * ---------------------------------------------------------------------------------+ */ let m := mload(0x40) // Cache the free memory pointer. mstore(0x60, 0x3d50545afa361460525736515af43d600060013e6052573d6001fd5b3d6001f3) mstore(0x40, 0x527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b3513) mstore(0x20, 0x60195155f3363d3d373d3d363d602036600436635c60da1b60e01b36) mstore(0x04, or(shl(160, 0x60573d8160223d3973), shr(96, shl(96, beacon)))) instance := create(value, 0x07, 0x79) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } mstore(0x40, m) // Restore the free memory pointer. mstore(0x60, 0) // Restore the zero slot. } } /// @dev Deploys a deterministic ERC1967I beacon proxy with `salt`. function deployDeterministicERC1967IBeaconProxy(address beacon, bytes32 salt) internal returns (address instance) { instance = deployDeterministicERC1967IBeaconProxy(0, beacon, salt); } /// @dev Deploys a deterministic ERC1967I beacon proxy with `salt`. /// Deposits `value` ETH during deployment. function deployDeterministicERC1967IBeaconProxy(uint256 value, address beacon, bytes32 salt) internal returns (address instance) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) // Cache the free memory pointer. mstore(0x60, 0x3d50545afa361460525736515af43d600060013e6052573d6001fd5b3d6001f3) mstore(0x40, 0x527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b3513) mstore(0x20, 0x60195155f3363d3d373d3d363d602036600436635c60da1b60e01b36) mstore(0x04, or(shl(160, 0x60573d8160223d3973), shr(96, shl(96, beacon)))) instance := create2(value, 0x07, 0x79, salt) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } mstore(0x40, m) // Restore the free memory pointer. mstore(0x60, 0) // Restore the zero slot. } } /// @dev Creates a deterministic ERC1967I beacon proxy with `salt`. /// Note: This method is intended for use in ERC4337 factories, /// which are expected to NOT revert if the proxy is already deployed. function createDeterministicERC1967IBeaconProxy(address beacon, bytes32 salt) internal returns (bool alreadyDeployed, address instance) { return createDeterministicERC1967IBeaconProxy(0, beacon, salt); } /// @dev Creates a deterministic ERC1967I beacon proxy with `salt`. /// Deposits `value` ETH during deployment. /// Note: This method is intended for use in ERC4337 factories, /// which are expected to NOT revert if the proxy is already deployed. function createDeterministicERC1967IBeaconProxy(uint256 value, address beacon, bytes32 salt) internal returns (bool alreadyDeployed, address instance) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) // Cache the free memory pointer. mstore(0x60, 0x3d50545afa361460525736515af43d600060013e6052573d6001fd5b3d6001f3) mstore(0x40, 0x527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b3513) mstore(0x20, 0x60195155f3363d3d373d3d363d602036600436635c60da1b60e01b36) mstore(0x04, or(shl(160, 0x60573d8160223d3973), shr(96, shl(96, beacon)))) // Compute and store the bytecode hash. mstore(add(m, 0x35), keccak256(0x07, 0x79)) mstore(m, shl(88, address())) mstore8(m, 0xff) // Write the prefix. mstore(add(m, 0x15), salt) instance := keccak256(m, 0x55) for {} 1 {} { if iszero(extcodesize(instance)) { instance := create2(value, 0x07, 0x79, salt) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } break } alreadyDeployed := 1 if iszero(value) { break } if iszero(call(gas(), instance, value, codesize(), 0x00, codesize(), 0x00)) { mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`. revert(0x1c, 0x04) } break } mstore(0x40, m) // Restore the free memory pointer. mstore(0x60, 0) // Restore the zero slot. } } /// @dev Returns the initialization code of the ERC1967I beacon proxy. function initCodeERC1967IBeaconProxy(address beacon) internal pure returns (bytes memory c) { /// @solidity memory-safe-assembly assembly { c := mload(0x40) mstore(add(c, 0x79), 0x3d50545afa361460525736515af43d600060013e6052573d6001fd5b3d6001f3) mstore(add(c, 0x59), 0x527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b3513) mstore(add(c, 0x39), 0x60195155f3363d3d373d3d363d602036600436635c60da1b60e01b36) mstore(add(c, 0x1d), beacon) mstore(add(c, 0x09), 0x60573d8160223d3973) mstore(add(c, 0x99), 0) mstore(c, 0x79) // Store the length. mstore(0x40, add(c, 0xa0)) // Allocate memory. } } /// @dev Returns the initialization code hash of the ERC1967I beacon proxy. function initCodeHashERC1967IBeaconProxy(address beacon) internal pure returns (bytes32 hash) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) // Cache the free memory pointer. mstore(0x60, 0x3d50545afa361460525736515af43d600060013e6052573d6001fd5b3d6001f3) mstore(0x40, 0x527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b3513) mstore(0x20, 0x60195155f3363d3d373d3d363d602036600436635c60da1b60e01b36) mstore(0x04, or(shl(160, 0x60573d8160223d3973), shr(96, shl(96, beacon)))) hash := keccak256(0x07, 0x79) mstore(0x40, m) // Restore the free memory pointer. mstore(0x60, 0) // Restore the zero slot. } } /// @dev Returns the address of the ERC1967I beacon proxy, with `salt` by `deployer`. /// Note: The returned result has dirty upper 96 bits. Please clean if used in assembly. function predictDeterministicAddressERC1967IBeaconProxy( address beacon, bytes32 salt, address deployer ) internal pure returns (address predicted) { bytes32 hash = initCodeHashERC1967IBeaconProxy(beacon); predicted = predictDeterministicAddress(hash, salt, deployer); } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* ERC1967I BEACON PROXY WITH IMMUTABLE ARGS OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Deploys a ERC1967I beacon proxy with `args. function deployERC1967IBeaconProxy(address beacon, bytes memory args) internal returns (address instance) { instance = deployERC1967IBeaconProxy(0, beacon, args); } /// @dev Deploys a ERC1967I beacon proxy with `args. /// Deposits `value` ETH during deployment. function deployERC1967IBeaconProxy(uint256 value, address beacon, bytes memory args) internal returns (address instance) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) // Cache the free memory pointer. let n := mload(args) pop(staticcall(gas(), 4, add(args, 0x20), n, add(m, 0x90), n)) mstore(add(m, 0x70), 0x3d50545afa361460525736515af43d600060013e6052573d6001fd5b3d6001f3) mstore(add(m, 0x50), 0x527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b3513) mstore(add(m, 0x30), 0x60195155f3363d3d373d3d363d602036600436635c60da1b60e01b36) mstore(add(m, 0x14), beacon) // Do a out-of-gas revert if `n` is greater than `0xffff - 0x57 = 0xffa8`. mstore(add(m, gt(n, 0xffa8)), add(0xfe6100573d8160233d3973, shl(56, n))) instance := create(value, add(m, 0x16), add(n, 0x7a)) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } } } /// @dev Deploys a deterministic ERC1967I beacon proxy with `args` and `salt`. function deployDeterministicERC1967IBeaconProxy(address beacon, bytes memory args, bytes32 salt) internal returns (address instance) { instance = deployDeterministicERC1967IBeaconProxy(0, beacon, args, salt); } /// @dev Deploys a deterministic ERC1967I beacon proxy with `args` and `salt`. /// Deposits `value` ETH during deployment. function deployDeterministicERC1967IBeaconProxy( uint256 value, address beacon, bytes memory args, bytes32 salt ) internal returns (address instance) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) // Cache the free memory pointer. let n := mload(args) pop(staticcall(gas(), 4, add(args, 0x20), n, add(m, 0x90), n)) mstore(add(m, 0x70), 0x3d50545afa361460525736515af43d600060013e6052573d6001fd5b3d6001f3) mstore(add(m, 0x50), 0x527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b3513) mstore(add(m, 0x30), 0x60195155f3363d3d373d3d363d602036600436635c60da1b60e01b36) mstore(add(m, 0x14), beacon) // Do a out-of-gas revert if `n` is greater than `0xffff - 0x57 = 0xffa8`. mstore(add(m, gt(n, 0xffa8)), add(0xfe6100573d8160233d3973, shl(56, n))) instance := create2(value, add(m, 0x16), add(n, 0x7a), salt) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } } } /// @dev Creates a deterministic ERC1967I beacon proxy with `args` and `salt`. /// Note: This method is intended for use in ERC4337 factories, /// which are expected to NOT revert if the proxy is already deployed. function createDeterministicERC1967IBeaconProxy(address beacon, bytes memory args, bytes32 salt) internal returns (bool alreadyDeployed, address instance) { return createDeterministicERC1967IBeaconProxy(0, beacon, args, salt); } /// @dev Creates a deterministic ERC1967I beacon proxy with `args` and `salt`. /// Deposits `value` ETH during deployment. /// Note: This method is intended for use in ERC4337 factories, /// which are expected to NOT revert if the proxy is already deployed. function createDeterministicERC1967IBeaconProxy( uint256 value, address beacon, bytes memory args, bytes32 salt ) internal returns (bool alreadyDeployed, address instance) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) let n := mload(args) pop(staticcall(gas(), 4, add(args, 0x20), n, add(m, 0x90), n)) mstore(add(m, 0x70), 0x3d50545afa361460525736515af43d600060013e6052573d6001fd5b3d6001f3) mstore(add(m, 0x50), 0x527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b3513) mstore(add(m, 0x30), 0x60195155f3363d3d373d3d363d602036600436635c60da1b60e01b36) mstore(add(m, 0x14), beacon) // Do a out-of-gas revert if `n` is greater than `0xffff - 0x57 = 0xffa8`. mstore(add(m, gt(n, 0xffa8)), add(0xfe6100573d8160233d3973, shl(56, n))) // Compute and store the bytecode hash. mstore8(0x00, 0xff) // Write the prefix. mstore(0x35, keccak256(add(m, 0x16), add(n, 0x7a))) mstore(0x01, shl(96, address())) mstore(0x15, salt) instance := keccak256(0x00, 0x55) for {} 1 {} { if iszero(extcodesize(instance)) { instance := create2(value, add(m, 0x16), add(n, 0x7a), salt) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } break } alreadyDeployed := 1 if iszero(value) { break } if iszero(call(gas(), instance, value, codesize(), 0x00, codesize(), 0x00)) { mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`. revert(0x1c, 0x04) } break } mstore(0x35, 0) // Restore the overwritten part of the free memory pointer. } } /// @dev Returns the initialization code of the ERC1967I beacon proxy with `args`. function initCodeERC1967IBeaconProxy(address beacon, bytes memory args) internal pure returns (bytes memory c) { /// @solidity memory-safe-assembly assembly { c := mload(0x40) let n := mload(args) // Do a out-of-gas revert if `n` is greater than `0xffff - 0x57 = 0xffa8`. returndatacopy(returndatasize(), returndatasize(), gt(n, 0xffa8)) for { let i := 0 } lt(i, n) { i := add(i, 0x20) } { mstore(add(add(c, 0x9a), i), mload(add(add(args, 0x20), i))) } mstore(add(c, 0x7a), 0x3d50545afa361460525736515af43d600060013e6052573d6001fd5b3d6001f3) mstore(add(c, 0x5a), 0x527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b3513) mstore(add(c, 0x3a), 0x60195155f3363d3d373d3d363d602036600436635c60da1b60e01b36) mstore(add(c, 0x1e), beacon) mstore(add(c, 0x0a), add(0x6100573d8160233d3973, shl(56, n))) mstore(add(c, add(n, 0x9a)), 0) mstore(c, add(n, 0x7a)) // Store the length. mstore(0x40, add(c, add(n, 0xba))) // Allocate memory. } } /// @dev Returns the initialization code hash of the ERC1967I beacon proxy with `args`. function initCodeHashERC1967IBeaconProxy(address beacon, bytes memory args) internal pure returns (bytes32 hash) { /// @solidity memory-safe-assembly assembly { let c := mload(0x40) // Cache the free memory pointer. let n := mload(args) // Do a out-of-gas revert if `n` is greater than `0xffff - 0x57 = 0xffa8`. returndatacopy(returndatasize(), returndatasize(), gt(n, 0xffa8)) for { let i := 0 } lt(i, n) { i := add(i, 0x20) } { mstore(add(add(c, 0x90), i), mload(add(add(args, 0x20), i))) } mstore(add(c, 0x70), 0x3d50545afa361460525736515af43d600060013e6052573d6001fd5b3d6001f3) mstore(add(c, 0x50), 0x527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b3513) mstore(add(c, 0x30), 0x60195155f3363d3d373d3d363d602036600436635c60da1b60e01b36) mstore(add(c, 0x14), beacon) mstore(c, add(0x6100573d8160233d3973, shl(56, n))) hash := keccak256(add(c, 0x16), add(n, 0x7a)) } } /// @dev Returns the address of the ERC1967I beacon proxy, with `args` and salt` by `deployer`. /// Note: The returned result has dirty upper 96 bits. Please clean if used in assembly. function predictDeterministicAddressERC1967IBeaconProxy( address beacon, bytes memory args, bytes32 salt, address deployer ) internal pure returns (address predicted) { bytes32 hash = initCodeHashERC1967IBeaconProxy(beacon, args); predicted = predictDeterministicAddress(hash, salt, deployer); } /// @dev Equivalent to `argsOnERC1967IBeaconProxy(instance, start, 2 ** 256 - 1)`. function argsOnERC1967IBeaconProxy(address instance) internal view returns (bytes memory args) { /// @solidity memory-safe-assembly assembly { args := mload(0x40) mstore(args, and(0xffffffffff, sub(extcodesize(instance), 0x57))) // Store the length. extcodecopy(instance, add(args, 0x20), 0x57, add(mload(args), 0x20)) mstore(0x40, add(mload(args), add(args, 0x40))) // Allocate memory. } } /// @dev Equivalent to `argsOnERC1967IBeaconProxy(instance, start, 2 ** 256 - 1)`. function argsOnERC1967IBeaconProxy(address instance, uint256 start) internal view returns (bytes memory args) { /// @solidity memory-safe-assembly assembly { args := mload(0x40) let n := and(0xffffffffff, sub(extcodesize(instance), 0x57)) let l := sub(n, and(0xffffff, mul(lt(start, n), start))) extcodecopy(instance, args, add(start, 0x37), add(l, 0x40)) mstore(args, mul(sub(n, start), lt(start, n))) // Store the length. mstore(0x40, add(args, add(0x40, mload(args)))) // Allocate memory. } } /// @dev Returns a slice of the immutable arguments on `instance` from `start` to `end`. /// `start` and `end` will be clamped to the range `[0, args.length]`. /// The `instance` MUST be deployed via the ERC1967I beacon proxy with immutable args functions. /// Otherwise, the behavior is undefined. /// Out-of-gas reverts if `instance` does not have any code. function argsOnERC1967IBeaconProxy(address instance, uint256 start, uint256 end) internal view returns (bytes memory args) { /// @solidity memory-safe-assembly assembly { args := mload(0x40) if iszero(lt(end, 0xffff)) { end := 0xffff } let d := mul(sub(end, start), lt(start, end)) extcodecopy(instance, args, add(start, 0x37), add(d, 0x20)) if iszero(and(0xff, mload(add(args, d)))) { let n := sub(extcodesize(instance), 0x57) returndatacopy(returndatasize(), returndatasize(), shr(40, n)) d := mul(gt(n, start), sub(d, mul(gt(end, n), sub(end, n)))) } mstore(args, d) // Store the length. mstore(add(add(args, 0x20), d), 0) // Zeroize the slot after the bytes. mstore(0x40, add(add(args, 0x40), d)) // Allocate memory. } } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* OTHER OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Returns `address(0)` if the implementation address cannot be determined. function implementationOf(address instance) internal view returns (address result) { /// @solidity memory-safe-assembly assembly { for { extcodecopy(instance, 0x00, 0x00, 0x57) } 1 {} { if mload(0x2d) { // ERC1967I and ERC1967IBeaconProxy detection. if or( eq(keccak256(0x00, 0x52), ERC1967I_CODE_HASH), eq(keccak256(0x00, 0x57), ERC1967I_BEACON_PROXY_CODE_HASH) ) { pop(staticcall(gas(), instance, 0x00, 0x01, 0x00, 0x20)) result := mload(0x0c) break } } // 0age clone detection. result := mload(0x0b) codecopy(0x0b, codesize(), 0x14) // Zeroize the 20 bytes for the address. if iszero(xor(keccak256(0x00, 0x2c), CLONE_CODE_HASH)) { break } mstore(0x0b, result) // Restore the zeroized memory. // CWIA detection. result := mload(0x0a) codecopy(0x0a, codesize(), 0x14) // Zeroize the 20 bytes for the address. if iszero(xor(keccak256(0x00, 0x2d), CWIA_CODE_HASH)) { break } mstore(0x0a, result) // Restore the zeroized memory. // PUSH0 clone detection. result := mload(0x09) codecopy(0x09, codesize(), 0x14) // Zeroize the 20 bytes for the address. result := shr(xor(keccak256(0x00, 0x2d), PUSH0_CLONE_CODE_HASH), result) break } result := shr(96, result) mstore(0x37, 0) // Restore the overwritten part of the free memory pointer. } } /// @dev Returns the address when a contract with initialization code hash, /// `hash`, is deployed with `salt`, by `deployer`. /// Note: The returned result has dirty upper 96 bits. Please clean if used in assembly. function predictDeterministicAddress(bytes32 hash, bytes32 salt, address deployer) internal pure returns (address predicted) { /// @solidity memory-safe-assembly assembly { // Compute and store the bytecode hash. mstore8(0x00, 0xff) // Write the prefix. mstore(0x35, hash) mstore(0x01, shl(96, deployer)) mstore(0x15, salt) predicted := keccak256(0x00, 0x55) mstore(0x35, 0) // Restore the overwritten part of the free memory pointer. } } /// @dev Requires that `salt` starts with either the zero address or `by`. function checkStartsWith(bytes32 salt, address by) internal pure { /// @solidity memory-safe-assembly assembly { // If the salt does not start with the zero address or `by`. if iszero(or(iszero(shr(96, salt)), eq(shr(96, shl(96, by)), shr(96, salt)))) { mstore(0x00, 0x0c4549ef) // `SaltDoesNotStartWith()`. revert(0x1c, 0x04) } } } /// @dev Returns the `bytes32` at `offset` in `args`, without any bounds checks. /// To load an address, you can use `address(bytes20(argLoad(args, offset)))`. function argLoad(bytes memory args, uint256 offset) internal pure returns (bytes32 result) { /// @solidity memory-safe-assembly assembly { result := mload(add(add(args, 0x20), offset)) } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /// @notice Upgradeable beacon for ERC1967 beacon proxies. /// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/UpgradeableBeacon.sol) /// @author Modified from OpenZeppelin /// (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/proxy/beacon/UpgradeableBeacon.sol) /// /// @dev Note: /// - The implementation is intended to be used with ERC1967 beacon proxies. /// See: `LibClone.deployERC1967BeaconProxy` and related functions. /// - For gas efficiency, the ownership functionality is baked into this contract. /// /// Optimized creation code (hex-encoded): /// `60406101c73d393d5160205180821760a01c3d3d3e803b1560875781684343a0dc92ed22dbfc558068911c5a209f08d5ec5e557fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b3d38a23d7f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e03d38a3610132806100953d393df35b636d3e283b3d526004601cfdfe3d3560e01c635c60da1b14610120573d3560e01c80638da5cb5b1461010e5780633659cfe61460021b8163f2fde38b1460011b179063715018a6141780153d3d3e684343a0dc92ed22dbfc805490813303610101573d9260068116610089575b508290557f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e03d38a3005b925060048035938460a01c60243610173d3d3e146100ba5782156100ad573861005f565b637448fbae3d526004601cfd5b82803b156100f4578068911c5a209f08d5ec5e557fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b3d38a2005b636d3e283b3d526004601cfd5b6382b429003d526004601cfd5b684343a0dc92ed22dbfc543d5260203df35b68911c5a209f08d5ec5e543d5260203df3`. /// See: https://gist.github.com/Vectorized/365bd7f6e9a848010f00adb9e50a2516 /// /// To get the initialization code: /// `abi.encodePacked(creationCode, abi.encode(initialOwner, initialImplementation))` /// /// This optimized bytecode is compiled via Yul and is not verifiable via Etherscan /// at the time of writing. For best gas efficiency, deploy the Yul version. /// The Solidity version is provided as an interface / reference. contract UpgradeableBeacon { /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* CUSTOM ERRORS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev The new implementation is not a deployed contract. error NewImplementationHasNoCode(); /// @dev The caller is not authorized to perform the operation. error Unauthorized(); /// @dev The `newOwner` cannot be the zero address. error NewOwnerIsZeroAddress(); /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* EVENTS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Emitted when the proxy's implementation is upgraded. event Upgraded(address indexed implementation); /// @dev The ownership is transferred from `oldOwner` to `newOwner`. /// This event is intentionally kept the same as OpenZeppelin's Ownable to be /// compatible with indexers and [EIP-173](https://eips.ethereum.org/EIPS/eip-173), /// despite it not being as lightweight as a single argument event. event OwnershipTransferred(address indexed oldOwner, address indexed newOwner); /// @dev `keccak256(bytes("Upgraded(address)"))`. uint256 private constant _UPGRADED_EVENT_SIGNATURE = 0xbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b; /// @dev `keccak256(bytes("OwnershipTransferred(address,address)"))`. uint256 private constant _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE = 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0; /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* STORAGE */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev The storage slot for the implementation address. /// `uint72(bytes9(keccak256("_UPGRADEABLE_BEACON_IMPLEMENTATION_SLOT")))`. uint256 internal constant _UPGRADEABLE_BEACON_IMPLEMENTATION_SLOT = 0x911c5a209f08d5ec5e; /// @dev The storage slot for the owner address. /// `uint72(bytes9(keccak256("_UPGRADEABLE_BEACON_OWNER_SLOT")))`. uint256 internal constant _UPGRADEABLE_BEACON_OWNER_SLOT = 0x4343a0dc92ed22dbfc; /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* CONSTRUCTOR */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ constructor(address initialOwner, address initialImplementation) payable { _constructUpgradeableBeacon(initialOwner, initialImplementation); } /// @dev Called in the constructor. Override as required. function _constructUpgradeableBeacon(address initialOwner, address initialImplementation) internal virtual { _initializeUpgradeableBeacon(initialOwner, initialImplementation); } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* UPGRADEABLE BEACON OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Required to be called in the constructor or initializer. /// This function does not guard against double-initialization. function _initializeUpgradeableBeacon(address initialOwner, address initialImplementation) internal virtual { // We don't need to check if `initialOwner` is the zero address here, // as some use cases may not want the beacon to be owned. _setOwner(initialOwner); _setImplementation(initialImplementation); } /// @dev Sets the implementation directly without authorization guard. function _setImplementation(address newImplementation) internal virtual { /// @solidity memory-safe-assembly assembly { newImplementation := shr(96, shl(96, newImplementation)) // Clean the upper 96 bits. if iszero(extcodesize(newImplementation)) { mstore(0x00, 0x6d3e283b) // `NewImplementationHasNoCode()`. revert(0x1c, 0x04) } sstore(_UPGRADEABLE_BEACON_IMPLEMENTATION_SLOT, newImplementation) // Store the implementation. // Emit the {Upgraded} event. log2(codesize(), 0x00, _UPGRADED_EVENT_SIGNATURE, newImplementation) } } /// @dev Sets the owner directly without authorization guard. function _setOwner(address newOwner) internal virtual { /// @solidity memory-safe-assembly assembly { newOwner := shr(96, shl(96, newOwner)) // Clean the upper 96 bits. let oldOwner := sload(_UPGRADEABLE_BEACON_OWNER_SLOT) sstore(_UPGRADEABLE_BEACON_OWNER_SLOT, newOwner) // Store the owner. // Emit the {OwnershipTransferred} event. log3(codesize(), 0x00, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, oldOwner, newOwner) } } /// @dev Returns the implementation stored in the beacon. /// See: https://eips.ethereum.org/EIPS/eip-1967#beacon-contract-address function implementation() public view returns (address result) { /// @solidity memory-safe-assembly assembly { result := sload(_UPGRADEABLE_BEACON_IMPLEMENTATION_SLOT) } } /// @dev Returns the owner of the beacon. function owner() public view returns (address result) { /// @solidity memory-safe-assembly assembly { result := sload(_UPGRADEABLE_BEACON_OWNER_SLOT) } } /// @dev Allows the owner to upgrade the implementation. function upgradeTo(address newImplementation) public virtual onlyOwner { _setImplementation(newImplementation); } /// @dev Allows the owner to transfer the ownership to `newOwner`. function transferOwnership(address newOwner) public virtual onlyOwner { /// @solidity memory-safe-assembly assembly { if iszero(shl(96, newOwner)) { mstore(0x00, 0x7448fbae) // `NewOwnerIsZeroAddress()`. revert(0x1c, 0x04) } } _setOwner(newOwner); } /// @dev Allows the owner to renounce their ownership. function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /// @dev Throws if the sender is not the owner. function _checkOwner() internal view virtual { /// @solidity memory-safe-assembly assembly { // If the caller is not the stored owner, revert. if iszero(eq(caller(), sload(_UPGRADEABLE_BEACON_OWNER_SLOT))) { mstore(0x00, 0x82b42900) // `Unauthorized()`. revert(0x1c, 0x04) } } } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* MODIFIERS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Marks a function as only callable by the owner. modifier onlyOwner() virtual { _checkOwner(); _; } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.26; import { IPOLErrors } from "../interfaces/IPOLErrors.sol"; interface IRewardVaultFactory is IPOLErrors { /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* EVENTS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /** * @notice Emitted when a new vault is created. * @param stakingToken The address of the staking token. * @param vault The address of the vault. */ event VaultCreated(address indexed stakingToken, address indexed vault); /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* VAULT CREATION */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /** * @notice Creates a new reward vault vault for the given staking token. * @dev Reverts if the staking token is not a contract. * @param stakingToken The address of the staking token. * @return The address of the new vault. */ function createRewardVault(address stakingToken) external returns (address); /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* READS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /** * @notice Gets the VAULT_MANAGER_ROLE. * @return The VAULT_MANAGER_ROLE. */ function VAULT_MANAGER_ROLE() external view returns (bytes32); /** * @notice Gets the VAULT_PAUSER_ROLE. * @return The VAULT_PAUSER_ROLE. */ function VAULT_PAUSER_ROLE() external view returns (bytes32); /** * @notice Gets the vault for the given staking token. * @param stakingToken The address of the staking token. * @return The address of the vault. */ function getVault(address stakingToken) external view returns (address); /** * @notice Gets the number of vaults that have been created. * @return The number of vaults. */ function allVaultsLength() external view returns (uint256); /** * @notice Predicts the address of the reward vault for the given staking token. * @param stakingToken The address of the staking token. * @return The address of the reward vault. */ function predictRewardVaultAddress(address stakingToken) external view returns (address); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values. /// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SafeTransferLib.sol) /// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol) /// @author Permit2 operations from (https://github.com/Uniswap/permit2/blob/main/src/libraries/Permit2Lib.sol) /// /// @dev Note: /// - For ETH transfers, please use `forceSafeTransferETH` for DoS protection. library SafeTransferLib { /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* CUSTOM ERRORS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev The ETH transfer has failed. error ETHTransferFailed(); /// @dev The ERC20 `transferFrom` has failed. error TransferFromFailed(); /// @dev The ERC20 `transfer` has failed. error TransferFailed(); /// @dev The ERC20 `approve` has failed. error ApproveFailed(); /// @dev The ERC20 `totalSupply` query has failed. error TotalSupplyQueryFailed(); /// @dev The Permit2 operation has failed. error Permit2Failed(); /// @dev The Permit2 amount must be less than `2**160 - 1`. error Permit2AmountOverflow(); /// @dev The Permit2 approve operation has failed. error Permit2ApproveFailed(); /// @dev The Permit2 lockdown operation has failed. error Permit2LockdownFailed(); /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* CONSTANTS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Suggested gas stipend for contract receiving ETH that disallows any storage writes. uint256 internal constant GAS_STIPEND_NO_STORAGE_WRITES = 2300; /// @dev Suggested gas stipend for contract receiving ETH to perform a few /// storage reads and writes, but low enough to prevent griefing. uint256 internal constant GAS_STIPEND_NO_GRIEF = 100000; /// @dev The unique EIP-712 domain domain separator for the DAI token contract. bytes32 internal constant DAI_DOMAIN_SEPARATOR = 0xdbb8cf42e1ecb028be3f3dbc922e1d878b963f411dc388ced501601c60f7c6f7; /// @dev The address for the WETH9 contract on Ethereum mainnet. address internal constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; /// @dev The canonical Permit2 address. /// [Github](https://github.com/Uniswap/permit2) /// [Etherscan](https://etherscan.io/address/0x000000000022D473030F116dDEE9F6B43aC78BA3) address internal constant PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3; /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* ETH OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ // If the ETH transfer MUST succeed with a reasonable gas budget, use the force variants. // // The regular variants: // - Forwards all remaining gas to the target. // - Reverts if the target reverts. // - Reverts if the current contract has insufficient balance. // // The force variants: // - Forwards with an optional gas stipend // (defaults to `GAS_STIPEND_NO_GRIEF`, which is sufficient for most cases). // - If the target reverts, or if the gas stipend is exhausted, // creates a temporary contract to force send the ETH via `SELFDESTRUCT`. // Future compatible with `SENDALL`: https://eips.ethereum.org/EIPS/eip-4758. // - Reverts if the current contract has insufficient balance. // // The try variants: // - Forwards with a mandatory gas stipend. // - Instead of reverting, returns whether the transfer succeeded. /// @dev Sends `amount` (in wei) ETH to `to`. function safeTransferETH(address to, uint256 amount) internal { /// @solidity memory-safe-assembly assembly { if iszero(call(gas(), to, amount, codesize(), 0x00, codesize(), 0x00)) { mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`. revert(0x1c, 0x04) } } } /// @dev Sends all the ETH in the current contract to `to`. function safeTransferAllETH(address to) internal { /// @solidity memory-safe-assembly assembly { // Transfer all the ETH and check if it succeeded or not. if iszero(call(gas(), to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) { mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`. revert(0x1c, 0x04) } } } /// @dev Force sends `amount` (in wei) ETH to `to`, with a `gasStipend`. function forceSafeTransferETH(address to, uint256 amount, uint256 gasStipend) internal { /// @solidity memory-safe-assembly assembly { if lt(selfbalance(), amount) { mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`. revert(0x1c, 0x04) } if iszero(call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)) { mstore(0x00, to) // Store the address in scratch space. mstore8(0x0b, 0x73) // Opcode `PUSH20`. mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`. if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation. } } } /// @dev Force sends all the ETH in the current contract to `to`, with a `gasStipend`. function forceSafeTransferAllETH(address to, uint256 gasStipend) internal { /// @solidity memory-safe-assembly assembly { if iszero(call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) { mstore(0x00, to) // Store the address in scratch space. mstore8(0x0b, 0x73) // Opcode `PUSH20`. mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`. if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation. } } } /// @dev Force sends `amount` (in wei) ETH to `to`, with `GAS_STIPEND_NO_GRIEF`. function forceSafeTransferETH(address to, uint256 amount) internal { /// @solidity memory-safe-assembly assembly { if lt(selfbalance(), amount) { mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`. revert(0x1c, 0x04) } if iszero(call(GAS_STIPEND_NO_GRIEF, to, amount, codesize(), 0x00, codesize(), 0x00)) { mstore(0x00, to) // Store the address in scratch space. mstore8(0x0b, 0x73) // Opcode `PUSH20`. mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`. if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation. } } } /// @dev Force sends all the ETH in the current contract to `to`, with `GAS_STIPEND_NO_GRIEF`. function forceSafeTransferAllETH(address to) internal { /// @solidity memory-safe-assembly assembly { // forgefmt: disable-next-item if iszero(call(GAS_STIPEND_NO_GRIEF, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) { mstore(0x00, to) // Store the address in scratch space. mstore8(0x0b, 0x73) // Opcode `PUSH20`. mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`. if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation. } } } /// @dev Sends `amount` (in wei) ETH to `to`, with a `gasStipend`. function trySafeTransferETH(address to, uint256 amount, uint256 gasStipend) internal returns (bool success) { /// @solidity memory-safe-assembly assembly { success := call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00) } } /// @dev Sends all the ETH in the current contract to `to`, with a `gasStipend`. function trySafeTransferAllETH(address to, uint256 gasStipend) internal returns (bool success) { /// @solidity memory-safe-assembly assembly { success := call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00) } } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* ERC20 OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Sends `amount` of ERC20 `token` from `from` to `to`. /// Reverts upon failure. /// /// The `from` account must have at least `amount` approved for /// the current contract to manage. function safeTransferFrom(address token, address from, address to, uint256 amount) internal { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) // Cache the free memory pointer. mstore(0x60, amount) // Store the `amount` argument. mstore(0x40, to) // Store the `to` argument. mstore(0x2c, shl(96, from)) // Store the `from` argument. mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`. let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20) if iszero(and(eq(mload(0x00), 1), success)) { if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) { mstore(0x00, 0x7939f424) // `TransferFromFailed()`. revert(0x1c, 0x04) } } mstore(0x60, 0) // Restore the zero slot to zero. mstore(0x40, m) // Restore the free memory pointer. } } /// @dev Sends `amount` of ERC20 `token` from `from` to `to`. /// /// The `from` account must have at least `amount` approved for the current contract to manage. function trySafeTransferFrom(address token, address from, address to, uint256 amount) internal returns (bool success) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) // Cache the free memory pointer. mstore(0x60, amount) // Store the `amount` argument. mstore(0x40, to) // Store the `to` argument. mstore(0x2c, shl(96, from)) // Store the `from` argument. mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`. success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20) if iszero(and(eq(mload(0x00), 1), success)) { success := lt(or(iszero(extcodesize(token)), returndatasize()), success) } mstore(0x60, 0) // Restore the zero slot to zero. mstore(0x40, m) // Restore the free memory pointer. } } /// @dev Sends all of ERC20 `token` from `from` to `to`. /// Reverts upon failure. /// /// The `from` account must have their entire balance approved for the current contract to manage. function safeTransferAllFrom(address token, address from, address to) internal returns (uint256 amount) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) // Cache the free memory pointer. mstore(0x40, to) // Store the `to` argument. mstore(0x2c, shl(96, from)) // Store the `from` argument. mstore(0x0c, 0x70a08231000000000000000000000000) // `balanceOf(address)`. // Read the balance, reverting upon failure. if iszero( and( // The arguments of `and` are evaluated from right to left. gt(returndatasize(), 0x1f), // At least 32 bytes returned. staticcall(gas(), token, 0x1c, 0x24, 0x60, 0x20) ) ) { mstore(0x00, 0x7939f424) // `TransferFromFailed()`. revert(0x1c, 0x04) } mstore(0x00, 0x23b872dd) // `transferFrom(address,address,uint256)`. amount := mload(0x60) // The `amount` is already at 0x60. We'll need to return it. // Perform the transfer, reverting upon failure. let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20) if iszero(and(eq(mload(0x00), 1), success)) { if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) { mstore(0x00, 0x7939f424) // `TransferFromFailed()`. revert(0x1c, 0x04) } } mstore(0x60, 0) // Restore the zero slot to zero. mstore(0x40, m) // Restore the free memory pointer. } } /// @dev Sends `amount` of ERC20 `token` from the current contract to `to`. /// Reverts upon failure. function safeTransfer(address token, address to, uint256 amount) internal { /// @solidity memory-safe-assembly assembly { mstore(0x14, to) // Store the `to` argument. mstore(0x34, amount) // Store the `amount` argument. mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`. // Perform the transfer, reverting upon failure. let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20) if iszero(and(eq(mload(0x00), 1), success)) { if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) { mstore(0x00, 0x90b8ec18) // `TransferFailed()`. revert(0x1c, 0x04) } } mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten. } } /// @dev Sends all of ERC20 `token` from the current contract to `to`. /// Reverts upon failure. function safeTransferAll(address token, address to) internal returns (uint256 amount) { /// @solidity memory-safe-assembly assembly { mstore(0x00, 0x70a08231) // Store the function selector of `balanceOf(address)`. mstore(0x20, address()) // Store the address of the current contract. // Read the balance, reverting upon failure. if iszero( and( // The arguments of `and` are evaluated from right to left. gt(returndatasize(), 0x1f), // At least 32 bytes returned. staticcall(gas(), token, 0x1c, 0x24, 0x34, 0x20) ) ) { mstore(0x00, 0x90b8ec18) // `TransferFailed()`. revert(0x1c, 0x04) } mstore(0x14, to) // Store the `to` argument. amount := mload(0x34) // The `amount` is already at 0x34. We'll need to return it. mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`. // Perform the transfer, reverting upon failure. let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20) if iszero(and(eq(mload(0x00), 1), success)) { if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) { mstore(0x00, 0x90b8ec18) // `TransferFailed()`. revert(0x1c, 0x04) } } mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten. } } /// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract. /// Reverts upon failure. function safeApprove(address token, address to, uint256 amount) internal { /// @solidity memory-safe-assembly assembly { mstore(0x14, to) // Store the `to` argument. mstore(0x34, amount) // Store the `amount` argument. mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`. let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20) if iszero(and(eq(mload(0x00), 1), success)) { if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) { mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`. revert(0x1c, 0x04) } } mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten. } } /// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract. /// If the initial attempt to approve fails, attempts to reset the approved amount to zero, /// then retries the approval again (some tokens, e.g. USDT, requires this). /// Reverts upon failure. function safeApproveWithRetry(address token, address to, uint256 amount) internal { /// @solidity memory-safe-assembly assembly { mstore(0x14, to) // Store the `to` argument. mstore(0x34, amount) // Store the `amount` argument. mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`. // Perform the approval, retrying upon failure. let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20) if iszero(and(eq(mload(0x00), 1), success)) { if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) { mstore(0x34, 0) // Store 0 for the `amount`. mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`. pop(call(gas(), token, 0, 0x10, 0x44, codesize(), 0x00)) // Reset the approval. mstore(0x34, amount) // Store back the original `amount`. // Retry the approval, reverting upon failure. success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20) if iszero(and(eq(mload(0x00), 1), success)) { // Check the `extcodesize` again just in case the token selfdestructs lol. if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) { mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`. revert(0x1c, 0x04) } } } } mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten. } } /// @dev Returns the amount of ERC20 `token` owned by `account`. /// Returns zero if the `token` does not exist. function balanceOf(address token, address account) internal view returns (uint256 amount) { /// @solidity memory-safe-assembly assembly { mstore(0x14, account) // Store the `account` argument. mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`. amount := mul( // The arguments of `mul` are evaluated from right to left. mload(0x20), and( // The arguments of `and` are evaluated from right to left. gt(returndatasize(), 0x1f), // At least 32 bytes returned. staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20) ) ) } } /// @dev Returns the total supply of the `token`. /// Reverts if the token does not exist or does not implement `totalSupply()`. function totalSupply(address token) internal view returns (uint256 result) { /// @solidity memory-safe-assembly assembly { mstore(0x00, 0x18160ddd) // `totalSupply()`. if iszero( and(gt(returndatasize(), 0x1f), staticcall(gas(), token, 0x1c, 0x04, 0x00, 0x20)) ) { mstore(0x00, 0x54cd9435) // `TotalSupplyQueryFailed()`. revert(0x1c, 0x04) } result := mload(0x00) } } /// @dev Sends `amount` of ERC20 `token` from `from` to `to`. /// If the initial attempt fails, try to use Permit2 to transfer the token. /// Reverts upon failure. /// /// The `from` account must have at least `amount` approved for the current contract to manage. function safeTransferFrom2(address token, address from, address to, uint256 amount) internal { if (!trySafeTransferFrom(token, from, to, amount)) { permit2TransferFrom(token, from, to, amount); } } /// @dev Sends `amount` of ERC20 `token` from `from` to `to` via Permit2. /// Reverts upon failure. function permit2TransferFrom(address token, address from, address to, uint256 amount) internal { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) mstore(add(m, 0x74), shr(96, shl(96, token))) mstore(add(m, 0x54), amount) mstore(add(m, 0x34), to) mstore(add(m, 0x20), shl(96, from)) // `transferFrom(address,address,uint160,address)`. mstore(m, 0x36c78516000000000000000000000000) let p := PERMIT2 let exists := eq(chainid(), 1) if iszero(exists) { exists := iszero(iszero(extcodesize(p))) } if iszero( and( call(gas(), p, 0, add(m, 0x10), 0x84, codesize(), 0x00), lt(iszero(extcodesize(token)), exists) // Token has code and Permit2 exists. ) ) { mstore(0x00, 0x7939f4248757f0fd) // `TransferFromFailed()` or `Permit2AmountOverflow()`. revert(add(0x18, shl(2, iszero(iszero(shr(160, amount))))), 0x04) } } } /// @dev Permit a user to spend a given amount of /// another user's tokens via native EIP-2612 permit if possible, falling /// back to Permit2 if native permit fails or is not implemented on the token. function permit2( address token, address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) internal { bool success; /// @solidity memory-safe-assembly assembly { for {} shl(96, xor(token, WETH9)) {} { mstore(0x00, 0x3644e515) // `DOMAIN_SEPARATOR()`. if iszero( and( // The arguments of `and` are evaluated from right to left. lt(iszero(mload(0x00)), eq(returndatasize(), 0x20)), // Returns 1 non-zero word. // Gas stipend to limit gas burn for tokens that don't refund gas when // an non-existing function is called. 5K should be enough for a SLOAD. staticcall(5000, token, 0x1c, 0x04, 0x00, 0x20) ) ) { break } // After here, we can be sure that token is a contract. let m := mload(0x40) mstore(add(m, 0x34), spender) mstore(add(m, 0x20), shl(96, owner)) mstore(add(m, 0x74), deadline) if eq(mload(0x00), DAI_DOMAIN_SEPARATOR) { mstore(0x14, owner) mstore(0x00, 0x7ecebe00000000000000000000000000) // `nonces(address)`. mstore( add(m, 0x94), lt(iszero(amount), staticcall(gas(), token, 0x10, 0x24, add(m, 0x54), 0x20)) ) mstore(m, 0x8fcbaf0c000000000000000000000000) // `IDAIPermit.permit`. // `nonces` is already at `add(m, 0x54)`. // `amount != 0` is already stored at `add(m, 0x94)`. mstore(add(m, 0xb4), and(0xff, v)) mstore(add(m, 0xd4), r) mstore(add(m, 0xf4), s) success := call(gas(), token, 0, add(m, 0x10), 0x104, codesize(), 0x00) break } mstore(m, 0xd505accf000000000000000000000000) // `IERC20Permit.permit`. mstore(add(m, 0x54), amount) mstore(add(m, 0x94), and(0xff, v)) mstore(add(m, 0xb4), r) mstore(add(m, 0xd4), s) success := call(gas(), token, 0, add(m, 0x10), 0xe4, codesize(), 0x00) break } } if (!success) simplePermit2(token, owner, spender, amount, deadline, v, r, s); } /// @dev Simple permit on the Permit2 contract. function simplePermit2( address token, address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) internal { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) mstore(m, 0x927da105) // `allowance(address,address,address)`. { let addressMask := shr(96, not(0)) mstore(add(m, 0x20), and(addressMask, owner)) mstore(add(m, 0x40), and(addressMask, token)) mstore(add(m, 0x60), and(addressMask, spender)) mstore(add(m, 0xc0), and(addressMask, spender)) } let p := mul(PERMIT2, iszero(shr(160, amount))) if iszero( and( // The arguments of `and` are evaluated from right to left. gt(returndatasize(), 0x5f), // Returns 3 words: `amount`, `expiration`, `nonce`. staticcall(gas(), p, add(m, 0x1c), 0x64, add(m, 0x60), 0x60) ) ) { mstore(0x00, 0x6b836e6b8757f0fd) // `Permit2Failed()` or `Permit2AmountOverflow()`. revert(add(0x18, shl(2, iszero(p))), 0x04) } mstore(m, 0x2b67b570) // `Permit2.permit` (PermitSingle variant). // `owner` is already `add(m, 0x20)`. // `token` is already at `add(m, 0x40)`. mstore(add(m, 0x60), amount) mstore(add(m, 0x80), 0xffffffffffff) // `expiration = type(uint48).max`. // `nonce` is already at `add(m, 0xa0)`. // `spender` is already at `add(m, 0xc0)`. mstore(add(m, 0xe0), deadline) mstore(add(m, 0x100), 0x100) // `signature` offset. mstore(add(m, 0x120), 0x41) // `signature` length. mstore(add(m, 0x140), r) mstore(add(m, 0x160), s) mstore(add(m, 0x180), shl(248, v)) if iszero( // Revert if token does not have code, or if the call fails. mul(extcodesize(token), call(gas(), p, 0, add(m, 0x1c), 0x184, codesize(), 0x00))) { mstore(0x00, 0x6b836e6b) // `Permit2Failed()`. revert(0x1c, 0x04) } } } /// @dev Approves `spender` to spend `amount` of `token` for `address(this)`. function permit2Approve(address token, address spender, uint160 amount, uint48 expiration) internal { /// @solidity memory-safe-assembly assembly { let addressMask := shr(96, not(0)) let m := mload(0x40) mstore(m, 0x87517c45) // `approve(address,address,uint160,uint48)`. mstore(add(m, 0x20), and(addressMask, token)) mstore(add(m, 0x40), and(addressMask, spender)) mstore(add(m, 0x60), and(addressMask, amount)) mstore(add(m, 0x80), and(0xffffffffffff, expiration)) if iszero(call(gas(), PERMIT2, 0, add(m, 0x1c), 0xa0, codesize(), 0x00)) { mstore(0x00, 0x324f14ae) // `Permit2ApproveFailed()`. revert(0x1c, 0x04) } } } /// @dev Revokes an approval for `token` and `spender` for `address(this)`. function permit2Lockdown(address token, address spender) internal { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) mstore(m, 0xcc53287f) // `Permit2.lockdown`. mstore(add(m, 0x20), 0x20) // Offset of the `approvals`. mstore(add(m, 0x40), 1) // `approvals.length`. mstore(add(m, 0x60), shr(96, shl(96, token))) mstore(add(m, 0x80), shr(96, shl(96, spender))) if iszero(call(gas(), PERMIT2, 0, add(m, 0x1c), 0xa0, codesize(), 0x00)) { mstore(0x00, 0x96b3de23) // `Permit2LockdownFailed()`. revert(0x1c, 0x04) } } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol) pragma solidity ^0.8.20; import {IERC20} from "./IERC20.sol"; import {IERC165} from "./IERC165.sol"; /** * @title IERC1363 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363]. * * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction. */ interface IERC1363 is IERC20, IERC165 { /* * Note: the ERC-165 identifier for this interface is 0xb0202a11. * 0xb0202a11 === * bytes4(keccak256('transferAndCall(address,uint256)')) ^ * bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^ * bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^ * bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^ * bytes4(keccak256('approveAndCall(address,uint256)')) ^ * bytes4(keccak256('approveAndCall(address,uint256,bytes)')) */ /** * @dev Moves a `value` amount of tokens from the caller's account to `to` * and then calls {IERC1363Receiver-onTransferReceived} on `to`. * @param to The address which you want to transfer to. * @param value The amount of tokens to be transferred. * @return A boolean value indicating whether the operation succeeded unless throwing. */ function transferAndCall(address to, uint256 value) external returns (bool); /** * @dev Moves a `value` amount of tokens from the caller's account to `to` * and then calls {IERC1363Receiver-onTransferReceived} on `to`. * @param to The address which you want to transfer to. * @param value The amount of tokens to be transferred. * @param data Additional data with no specified format, sent in call to `to`. * @return A boolean value indicating whether the operation succeeded unless throwing. */ function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool); /** * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism * and then calls {IERC1363Receiver-onTransferReceived} on `to`. * @param from The address which you want to send tokens from. * @param to The address which you want to transfer to. * @param value The amount of tokens to be transferred. * @return A boolean value indicating whether the operation succeeded unless throwing. */ function transferFromAndCall(address from, address to, uint256 value) external returns (bool); /** * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism * and then calls {IERC1363Receiver-onTransferReceived} on `to`. * @param from The address which you want to send tokens from. * @param to The address which you want to transfer to. * @param value The amount of tokens to be transferred. * @param data Additional data with no specified format, sent in call to `to`. * @return A boolean value indicating whether the operation succeeded unless throwing. */ function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool); /** * @dev Sets a `value` amount of tokens as the allowance of `spender` over the * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`. * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. * @return A boolean value indicating whether the operation succeeded unless throwing. */ function approveAndCall(address spender, uint256 value) external returns (bool); /** * @dev Sets a `value` amount of tokens as the allowance of `spender` over the * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`. * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. * @param data Additional data with no specified format, sent in call to `spender`. * @return A boolean value indicating whether the operation succeeded unless throwing. */ function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool); }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.26; import { IStakingRewardsErrors } from "../../base/IStakingRewardsErrors.sol"; /// @notice Interface of POL errors interface IPOLErrors is IStakingRewardsErrors { // Signature: 0xf2d81d95 error NotApprovedSender(); // Signature: 0x1db3b859 error NotDelegate(); // Signature: 0x53f0a596 error NotBGT(); // Signature: 0x1b0eb4ec error NotBlockRewardController(); // Signature: 0x385296d5 error NotDistributor(); // Signature: 0x73fcd3fe error NotFeeCollector(); // Signature: 0x36407850 error NotWhitelistedVault(); // Signature:0x7c214f04 error NotOperator(); // Signature: 0xad3a8b9e error NotEnoughBalance(); // Signature: 0xadd377f6 error InvalidActivateBoostDelay(); // Signature: 0x2f14f4f9 error InvalidDropBoostDelay(); // Signature: 0x14969061 error NotEnoughBoostedBalance(); // Signature: 0xe8966d7a error NotEnoughTime(); // Signature: 0xec2caa0d error InvalidStartBlock(); // Signature: 0x3be31f8c error RewardAllocationAlreadyQueued(); // Signature: 0x13134d24 error InvalidRewardAllocationWeights(); // Signature: 0xf6fae721 error TooManyWeights(); // Signature: 0x3e38573f error InvalidateDefaultRewardAllocation(); // Signature: 0xd92e233d error ZeroAddress(); // Signature: 0x462a2bb2 error RewardAllocationBlockDelayTooLarge(); // Signature: 0x08519afa error NotFactoryVault(); // Signature: 0x978dc040 error ZeroPercentageWeight(); /* BLOCK REWARD CONTROLLLER */ // Signature: 0x2e2dab43 error InvalidBaseRate(); // Signature: 0x22be2284 error InvalidRewardRate(); // Signature: 0x15482337 error InvalidMinBoostedRewardRate(); // Signature: 0xb7b2319a error InvalidBoostMultiplier(); // Signature: 0x347f95b2 error InvalidRewardConvexity(); /* STAKING */ // Signature: 0x09ee12d5 error NotAContract(); // Signature: 0xe4ea100b error CannotRecoverRewardToken(); // Signature: 0x1b813803 error CannotRecoverStakingToken(); // Signature: 0x2899103f error CannotRecoverIncentiveToken(); // Signature: 0x38432c89 error IncentiveRateTooHigh(); // Signature: 0x5ee4de0e error NotIncentiveManager(); // Signature: 0xf84835a0 error TokenNotWhitelisted(); // Signature: 0x8d1473a6 error InsufficientDelegateStake(); // Signature: 0x08e88f46 error InsufficientSelfStake(); // Signature: 0xfbf97e07 error TokenAlreadyWhitelistedOrLimitReached(); // Signature: 0xad57d95d error AmountLessThanMinIncentiveRate(); // Signature: 0xfbf1123c error InvalidMaxIncentiveTokensCount(); // Signature: 0x546c7600 error PayoutAmountIsZero(); // Signature: 0x89c622a2 error DonateAmountLessThanPayoutAmount(); // Signature: 0xa4cc22ed error MaxNumWeightsPerRewardAllocationIsZero(); // Signature: 0x0b5c3aff error MinIncentiveRateIsZero(); // Signature: 0x8e7572da error InvariantCheckFailed(); /* BEACON ROOTS */ // Signature: 0x1390f2a1 error IndexOutOfRange(); // Signature: 0x09bde339 error InvalidProof(); // Signature: 0x0a431b2a error TimestampAlreadyProcessed(); /* BEACON DEPOSIT */ /// @dev Error thrown when the deposit amount is too small, to prevent dust deposits. // Signature: 0x0e1eddda error InsufficientDeposit(); /// @dev Error thrown when the deposit amount is not a multiple of Gwei. // Signature: 0x40567b38 error DepositNotMultipleOfGwei(); /// @dev Error thrown when the deposit amount is too high, since it is a uint64. // Signature: 0x2aa66734 error DepositValueTooHigh(); /// @dev Error thrown when the public key length is not 48 bytes. // Signature: 0x9f106472 error InvalidPubKeyLength(); /// @dev Error thrown when the withdrawal credentials length is not 32 bytes. // Signature: 0xb39bca16 error InvalidCredentialsLength(); /// @dev Error thrown when the signature length is not 96 bytes. // Signature: 0x4be6321b error InvalidSignatureLength(); /// @dev Error thrown when the input operator is zero address on the first deposit. // Signature: 0x51969a7a error ZeroOperatorOnFirstDeposit(); /// @dev Error thrown when the operator is already set and caller passed non-zero operator. // Signature: 0xc4142b41 error OperatorAlreadySet(); /// @dev Error thrown when the caller is not the current operator. // Signature: 0x819a0d0b error NotNewOperator(); }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.26; import { IStakingRewardsErrors } from "./IStakingRewardsErrors.sol"; /// @notice Interface of staking rewards interface IStakingRewards is IStakingRewardsErrors { /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* EVENTS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @notice Emitted when a reward has been added to the vault. /// @param reward The amount of reward added, scaled by PRECISION. event RewardAdded(uint256 reward); /// @notice Emitted when the staking balance of an account has increased. /// @param account The account that has staked. /// @param amount The amount of staked tokens. event Staked(address indexed account, uint256 amount); /// @notice Emitted when the staking balance of an account has decreased. /// @param account The account that has withdrawn. /// @param amount The amount of withdrawn tokens. event Withdrawn(address indexed account, uint256 amount); /// @notice Emitted when a reward has been claimed. /// @param account The account whose reward has been claimed. /// @param to The address that the reward was sent to. (user or operator). /// @param reward The amount of reward claimed. event RewardPaid(address indexed account, address to, uint256 reward); /// @notice Emitted when the reward duration has been updated. /// @param newDuration The new duration of the reward. event RewardsDurationUpdated(uint256 newDuration); /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* GETTERS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @notice Get the balance of the staked tokens for an account. /// @param account The account to get the balance for. /// @return The balance of the staked tokens. function balanceOf(address account) external view returns (uint256); /// @notice Get the reward balance for a specific account. /// @param account The account to retrieve the reward balance for. /// @return The current reward balance of the specified account. function rewards(address account) external view returns (uint256); /// @notice Get the user reward per token paid. /// @param account The account to retrieve the reward for. /// @return The current reward balance of the specified account. function userRewardPerTokenPaid(address account) external view returns (uint256); /// @notice Retrieves the amount of reward earned by a specific account. /// @param account The account to calculate the reward for. /// @return The amount of reward earned by the account. function earned(address account) external view returns (uint256); /// @notice Retrieves the total reward vested over the specified duration. /// @return The total reward vested over the duration. function getRewardForDuration() external view returns (uint256); /// @notice Returns the timestamp of the last reward distribution. This is either the current timestamp (if rewards /// are still being actively distributed) or the timestamp when the reward duration ended (if all rewards have /// already been distributed). /// @return The timestamp of the last reward distribution. function lastTimeRewardApplicable() external view returns (uint256); /// @notice Retrieves the current value of the global reward per token accumulator. This value is the sum of the /// last checkpoint value and the accumulated value since the last checkpoint. It should increase monotonically /// over time as more rewards are distributed. /// @return The current value of the global reward per token accumulator scaled by 1e18. function rewardPerToken() external view returns (uint256); /// @notice Get the total supply of the staked tokens in the vault. /// @return The total supply of the staked tokens in the vault. function totalSupply() external view returns (uint256); /// @notice Get the end of the current reward period. /// @return The end of the current reward period. function periodFinish() external view returns (uint256); /// @notice Get the reward rate for the current reward period. /// @return The reward rate. function rewardRate() external view returns (uint256); /// @notice Get the time over which the rewards will be distributed. /// @return The duration of the rewards cycle. function rewardsDuration() external view returns (uint256); /// @notice Get the last time the rewards were updated. /// @return The last time the rewards were updated. function lastUpdateTime() external view returns (uint256); /// @notice Get the amount of undistributed rewards. /// @return The amount of undistributed rewards. function undistributedRewards() external view returns (uint256); /// @notice Get the last updated reward per token scaled. /// @return The last updated reward per token. function rewardPerTokenStored() external view returns (uint256); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (access/IAccessControl.sol) pragma solidity ^0.8.20; /** * @dev External interface of AccessControl declared to support ERC-165 detection. */ interface IAccessControl { /** * @dev The `account` is missing a role. */ error AccessControlUnauthorizedAccount(address account, bytes32 neededRole); /** * @dev The caller of a function is not the expected one. * * NOTE: Don't confuse with {AccessControlUnauthorizedAccount}. */ error AccessControlBadConfirmation(); /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call. This account bears the admin role (for the granted role). * Expected in cases where the role was granted using the internal {AccessControl-_grantRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `callerConfirmation`. */ function renounceRole(bytes32 role, address callerConfirmation) external; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/ERC165.sol) pragma solidity ^0.8.20; import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol"; import {Initializable} from "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` */ abstract contract ERC165Upgradeable is Initializable, IERC165 { function __ERC165_init() internal onlyInitializing { } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) { return interfaceId == type(IERC165).interfaceId; } }
// 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); }
// 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(); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol) pragma solidity ^0.8.20; import {IERC20} from "../token/ERC20/IERC20.sol";
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol) pragma solidity ^0.8.20; import {IERC165} from "../utils/introspection/IERC165.sol";
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.26; /// @notice Interface of staking rewards errors interface IStakingRewardsErrors { // Signature: 0xf4ba521f error InsolventReward(); // Signature: 0xf1bc94d2 error InsufficientStake(); // Signature: 0x49835af0 error RewardCycleNotEnded(); // Signature: 0x5ce91fd0 error StakeAmountIsZero(); // Signature: 0xe5cfe957 error TotalSupplyOverflow(); // Signature: 0xa393d14b error WithdrawAmountIsZero(); // Signature: 0x359f174d error RewardsDurationIsZero(); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol) pragma solidity ^0.8.20; /** * @dev Interface of the ERC-165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[ERC]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
// 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); }
// 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); }
// 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.InsufficientBalance(address(this).balance, value); } (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResultFromTarget(target, success, returndata); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResultFromTarget(target, success, returndata); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResultFromTarget(target, success, returndata); } /** * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target * was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case * of an unsuccessful call. */ function verifyCallResultFromTarget( address target, bool success, bytes memory returndata ) internal view returns (bytes memory) { if (!success) { _revert(returndata); } else { // only check if target is a contract if the call was successful and the return data is empty // otherwise we already know that it was a contract if (returndata.length == 0 && target.code.length == 0) { revert AddressEmptyCode(target); } return returndata; } } /** * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the * revert reason or with a default {Errors.FailedCall} error. */ function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) { if (!success) { _revert(returndata); } else { return returndata; } } /** * @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}. */ function _revert(bytes memory returndata) 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 assembly ("memory-safe") { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert Errors.FailedCall(); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol) // This file was procedurally generated from scripts/generate/templates/StorageSlot.js. pragma solidity ^0.8.20; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC-1967 implementation slot: * ```solidity * contract ERC1967 { * // Define the slot. Alternatively, use the SlotDerivation library to derive the slot. * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(newImplementation.code.length > 0); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * TIP: Consider using this library along with {SlotDerivation}. */ library StorageSlot { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } struct Int256Slot { int256 value; } struct StringSlot { string value; } struct BytesSlot { bytes value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly ("memory-safe") { r.slot := slot } } /** * @dev Returns a `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly ("memory-safe") { r.slot := slot } } /** * @dev Returns a `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly ("memory-safe") { r.slot := slot } } /** * @dev Returns a `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly ("memory-safe") { r.slot := slot } } /** * @dev Returns a `Int256Slot` with member `value` located at `slot`. */ function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) { assembly ("memory-safe") { r.slot := slot } } /** * @dev Returns a `StringSlot` with member `value` located at `slot`. */ function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) { assembly ("memory-safe") { r.slot := slot } } /** * @dev Returns an `StringSlot` representation of the string storage pointer `store`. */ function getStringSlot(string storage store) internal pure returns (StringSlot storage r) { assembly ("memory-safe") { r.slot := store.slot } } /** * @dev Returns a `BytesSlot` with member `value` located at `slot`. */ function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) { assembly ("memory-safe") { r.slot := slot } } /** * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`. */ function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) { assembly ("memory-safe") { r.slot := store.slot } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol) pragma solidity ^0.8.20; /** * @dev Collection of common custom errors used in multiple contracts * * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library. * It is recommended to avoid relying on the error API for critical functionality. * * _Available since v5.1._ */ library Errors { /** * @dev The ETH balance of the account is not enough to perform the operation. */ error InsufficientBalance(uint256 balance, uint256 needed); /** * @dev A call to an address target failed. The target may have reverted. */ error FailedCall(); /** * @dev The deployment failed. */ error FailedDeployment(); /** * @dev A necessary precompile is missing. */ error MissingPrecompile(address); }
{ "remappings": [ "@forge-std/=lib/forge-std/src/", "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/", "@openzeppelin-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/", "@berachain/=lib/contracts/src/", "solady/src/=lib/solady/src/", "@mock/=lib/contracts/test/mock/", "@openzeppelin-gov-ext/=lib/contracts/node_modules/@openzeppelin/contracts-upgradeable/governance/extensions/", "@openzeppelin-gov/=lib/contracts/node_modules/@openzeppelin/contracts-upgradeable/governance/", "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/", "@prb/math/=lib/contracts/node_modules/@prb/math/", "@pythnetwork/=lib/contracts/node_modules/@pythnetwork/pyth-sdk-solidity/", "contracts/=lib/contracts/src/", "ds-test/=lib/contracts/lib/openzeppelin-foundry-upgrades/lib/solidity-stringutils/lib/ds-test/src/", "erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/", "forge-std/=lib/forge-std/src/", "halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/", "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/", "openzeppelin-contracts/=lib/openzeppelin-contracts/", "openzeppelin-foundry-upgrades/=lib/contracts/lib/openzeppelin-foundry-upgrades/src/", "solady/test/=lib/contracts/lib/solady/test/", "solidity-stringutils/=lib/contracts/lib/openzeppelin-foundry-upgrades/lib/solidity-stringutils/", "transient-goodies/=lib/contracts/lib/transient-goodies/src/" ], "optimizer": { "enabled": true, "runs": 200 }, "metadata": { "useLiteralContent": false, "bytecodeHash": "ipfs", "appendCBOR": true }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "evmVersion": "cancun", "viaIR": false, "libraries": {} }
Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
Contract ABI
API[{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"allowance","type":"uint256"},{"internalType":"uint256","name":"needed","type":"uint256"}],"name":"ERC20InsufficientAllowance","type":"error"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"uint256","name":"balance","type":"uint256"},{"internalType":"uint256","name":"needed","type":"uint256"}],"name":"ERC20InsufficientBalance","type":"error"},{"inputs":[{"internalType":"address","name":"approver","type":"address"}],"name":"ERC20InvalidApprover","type":"error"},{"inputs":[{"internalType":"address","name":"receiver","type":"address"}],"name":"ERC20InvalidReceiver","type":"error"},{"inputs":[{"internalType":"address","name":"sender","type":"address"}],"name":"ERC20InvalidSender","type":"error"},{"inputs":[{"internalType":"address","name":"spender","type":"address"}],"name":"ERC20InvalidSpender","type":"error"},{"inputs":[],"name":"EmissionFailed","type":"error"},{"inputs":[],"name":"InvalidInitialization","type":"error"},{"inputs":[],"name":"InvariantCheckFailed","type":"error"},{"inputs":[],"name":"NotInitializing","type":"error"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"OwnableInvalidOwner","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"OwnableUnauthorizedAccount","type":"error"},{"inputs":[],"name":"UnauthorizedTransfer","type":"error"},{"inputs":[],"name":"ZeroAddress","type":"error"},{"inputs":[],"name":"ZeroStake","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint64","name":"version","type":"uint64"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"PointsAssigned","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"PointsRevoked","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"assign","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address","name":"_factory","type":"address"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes[]","name":"data","type":"bytes[]"}],"name":"multicall","outputs":[{"internalType":"bytes[]","name":"","type":"bytes[]"}],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"revoke","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"vault","outputs":[{"internalType":"contract RewardVault","name":"","type":"address"}],"stateMutability":"view","type":"function"}]
Contract Creation Code
6080604052348015600e575f80fd5b506114878061001c5f395ff3fe6080604052600436106100fa575f3560e01c80638da5cb5b11610092578063be76048811610062578063be760488146102c5578063dd62ed3e146102e4578063eac449d914610303578063f2fde38b14610322578063fbfa77cf14610341575f80fd5b80638da5cb5b1461022257806395d89b4114610272578063a9059cbb14610286578063ac9650d8146102a5575f80fd5b8063313ce567116100cd578063313ce567146101b3578063485cc955146101ce57806370a08231146101ef578063715018a61461020e575f80fd5b806306fdde03146100fe578063095ea7b31461012857806318160ddd1461015757806323b872dd14610194575b5f80fd5b348015610109575f80fd5b5061011261035f565b60405161011f91906110e1565b60405180910390f35b348015610133575f80fd5b50610147610142366004611107565b61041f565b604051901515815260200161011f565b348015610162575f80fd5b507f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace02545b60405190815260200161011f565b34801561019f575f80fd5b506101476101ae366004611131565b610438565b3480156101be575f80fd5b506040516012815260200161011f565b3480156101d9575f80fd5b506101ed6101e836600461116f565b610476565b005b3480156101fa575f80fd5b506101866102093660046111a6565b6106a2565b348015610219575f80fd5b506101ed6106c8565b34801561022d575f80fd5b507f9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300546001600160a01b03165b6040516001600160a01b03909116815260200161011f565b34801561027d575f80fd5b506101126106db565b348015610291575f80fd5b506101476102a0366004611107565b610719565b6102b86102b33660046111c1565b610755565b60405161011f9190611232565b3480156102d0575f80fd5b506101ed6102df366004611107565b610773565b3480156102ef575f80fd5b506101866102fe36600461116f565b6108c7565b34801561030e575f80fd5b506101ed61031d366004611107565b610910565b34801561032d575f80fd5b506101ed61033c3660046111a6565b610ab3565b34801561034c575f80fd5b505f5461025a906001600160a01b031681565b7f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace0380546060915f805160206114328339815191529161039d90611295565b80601f01602080910402602001604051908101604052809291908181526020018280546103c990611295565b80156104145780601f106103eb57610100808354040283529160200191610414565b820191905f5260205f20905b8154815290600101906020018083116103f757829003601f168201915b505050505091505090565b5f3361042c818585610af5565b60019150505b92915050565b5f80546001600160a01b03163314610463576040516325cdf54f60e21b815260040160405180910390fd5b61046e848484610b07565b949350505050565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a008054600160401b810460ff16159067ffffffffffffffff165f811580156104bb5750825b90505f8267ffffffffffffffff1660011480156104d75750303b155b9050811580156104e5575080155b156105035760405163f92ee8a960e01b815260040160405180910390fd5b845467ffffffffffffffff19166001178555831561052d57845460ff60401b1916600160401b1785555b6001600160a01b038716158061054a57506001600160a01b038616155b156105685760405163d92e233d60e01b815260040160405180910390fd5b61057187610b2a565b6105c16040518060400160405280601381526020017242657261204261646469657320506f696e747360681b8152506040518060400160405280600381526020016204242560ec1b815250610b3b565b60405163577ee5c760e01b81523060048201526001600160a01b0387169063577ee5c7906024016020604051808303815f875af1158015610604573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061062891906112cd565b5f80546001600160a01b0319166001600160a01b039290921691821790556106539030905f19610af5565b831561069957845460ff60401b19168555604051600181527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b50505050505050565b6001600160a01b03165f9081525f80516020611432833981519152602052604090205490565b6106d0610b51565b6106d95f610bac565b565b7f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace0480546060915f805160206114328339815191529161039d90611295565b5f80546001600160a01b03163314610744576040516325cdf54f60e21b815260040160405180910390fd5b61074e8383610c1c565b9392505050565b60603415610761575f80fd5b61043261076e8484610c29565b610cbb565b61077b610b51565b7f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace02545f546107b1906001600160a01b03166106a2565b146107cf5760405163473ab96d60e11b815260040160405180910390fd5b6001600160a01b0382166107f65760405163d92e233d60e01b815260040160405180910390fd5b805f036108165760405163150a67e960e01b815260040160405180910390fd5b6108203082610ccc565b5f54604051633c323a1b60e01b81526001600160a01b0384811660048301526024820184905290911690633c323a1b906044015f604051808303815f87803b15801561086a575f80fd5b505af115801561087c573d5f803e3d5ffd5b50505050816001600160a01b03167f5305c0bdb5dce4c26736d386b3a0b572ef36cc9042be902beb568ef2bb2b3c78826040516108bb91815260200190565b60405180910390a25050565b6001600160a01b039182165f9081527f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace016020908152604080832093909416825291909152205490565b610918610b51565b7f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace02545f5461094e906001600160a01b03166106a2565b1461096c5760405163473ab96d60e11b815260040160405180910390fd5b6001600160a01b0382166109935760405163d92e233d60e01b815260040160405180910390fd5b805f03610a0e575f546040516323d943e760e21b81526001600160a01b03848116600483015230602483015290911690638f650f9c90604401602060405180830381865afa1580156109e7573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610a0b91906112e8565b90505b5f54604051635281244f60e01b81526001600160a01b0384811660048301526024820184905290911690635281244f906044015f604051808303815f87803b158015610a58575f80fd5b505af1158015610a6a573d5f803e3d5ffd5b50505050610a783082610d00565b816001600160a01b03167f01d259196cb66f61d83b98793cdab9721613fb41683b683afb1bfb04413692ca826040516108bb91815260200190565b610abb610b51565b6001600160a01b038116610ae957604051631e4fbdf760e01b81525f60048201526024015b60405180910390fd5b610af281610bac565b50565b610b028383836001610d34565b505050565b5f33610b14858285610e18565b610b1f858585610e7c565b506001949350505050565b610b32610ed9565b610af281610f22565b610b43610ed9565b610b4d8282610f2a565b5050565b33610b837f9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300546001600160a01b031690565b6001600160a01b0316146106d95760405163118cdaa760e01b8152336004820152602401610ae0565b7f9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c19930080546001600160a01b031981166001600160a01b03848116918217845560405192169182907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0905f90a3505050565b5f3361042c818585610e7c565b5f60405190506020815281816020015280604001808360051b808684378201808515610ca3575b8351870180356020820183375f38823584305af4610c70573d5f873e3d86fd5b5082810384523d815260209384019381013d5f823e5f3d8201523d01601f0167ffffffffffffffe0169050818410610c50575b806040528485820360401b1794505050505092915050565b8060401c8167ffffffffffffffff16f35b6001600160a01b038216610cf55760405163ec442f0560e01b81525f6004820152602401610ae0565b610b4d5f8383610f7a565b6001600160a01b038216610d2957604051634b637e8f60e11b81525f6004820152602401610ae0565b610b4d825f83610f7a565b5f805160206114328339815191526001600160a01b038516610d6b5760405163e602df0560e01b81525f6004820152602401610ae0565b6001600160a01b038416610d9457604051634a1406b160e11b81525f6004820152602401610ae0565b6001600160a01b038086165f90815260018301602090815260408083209388168352929052208390558115610e1157836001600160a01b0316856001600160a01b03167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92585604051610e0891815260200190565b60405180910390a35b5050505050565b5f610e2384846108c7565b90505f19811015610e765781811015610e6857604051637dc7a0d960e11b81526001600160a01b03841660048201526024810182905260448101839052606401610ae0565b610e7684848484035f610d34565b50505050565b6001600160a01b038316610ea557604051634b637e8f60e11b81525f6004820152602401610ae0565b6001600160a01b038216610ece5760405163ec442f0560e01b81525f6004820152602401610ae0565b610b02838383610f7a565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a0054600160401b900460ff166106d957604051631afcd79f60e31b815260040160405180910390fd5b610abb610ed9565b610f32610ed9565b5f805160206114328339815191527f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace03610f6b8482611357565b5060048101610e768382611357565b5f805160206114328339815191526001600160a01b038416610fb45781816002015f828254610fa99190611412565b909155506110249050565b6001600160a01b0384165f90815260208290526040902054828110156110065760405163391434e360e21b81526001600160a01b03861660048201526024810182905260448101849052606401610ae0565b6001600160a01b0385165f9081526020839052604090209083900390555b6001600160a01b038316611042576002810180548390039055611060565b6001600160a01b0383165f9081526020829052604090208054830190555b826001600160a01b0316846001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040516110a591815260200190565b60405180910390a350505050565b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b602081525f61074e60208301846110b3565b6001600160a01b0381168114610af2575f80fd5b5f8060408385031215611118575f80fd5b8235611123816110f3565b946020939093013593505050565b5f805f60608486031215611143575f80fd5b833561114e816110f3565b9250602084013561115e816110f3565b929592945050506040919091013590565b5f8060408385031215611180575f80fd5b823561118b816110f3565b9150602083013561119b816110f3565b809150509250929050565b5f602082840312156111b6575f80fd5b813561074e816110f3565b5f80602083850312156111d2575f80fd5b823567ffffffffffffffff8111156111e8575f80fd5b8301601f810185136111f8575f80fd5b803567ffffffffffffffff81111561120e575f80fd5b8560208260051b8401011115611222575f80fd5b6020919091019590945092505050565b5f602082016020835280845180835260408501915060408160051b8601019250602086015f5b8281101561128957603f198786030184526112748583516110b3565b94506020938401939190910190600101611258565b50929695505050505050565b600181811c908216806112a957607f821691505b6020821081036112c757634e487b7160e01b5f52602260045260245ffd5b50919050565b5f602082840312156112dd575f80fd5b815161074e816110f3565b5f602082840312156112f8575f80fd5b5051919050565b634e487b7160e01b5f52604160045260245ffd5b601f821115610b0257805f5260205f20601f840160051c810160208510156113385750805b601f840160051c820191505b81811015610e11575f8155600101611344565b815167ffffffffffffffff811115611371576113716112ff565b6113858161137f8454611295565b84611313565b6020601f8211600181146113b7575f83156113a05750848201515b5f19600385901b1c1916600184901b178455610e11565b5f84815260208120601f198516915b828110156113e657878501518255602094850194600190920191016113c6565b508482101561140357868401515f19600387901b60f8161c191681555b50505050600190811b01905550565b8082018082111561043257634e487b7160e01b5f52601160045260245ffdfe52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace00a26469706673582212205167d5046f32b720f7b2808e344cc795623b0ec10ea86a083354abe8e480da5664736f6c634300081a0033
Deployed Bytecode
0x6080604052600436106100fa575f3560e01c80638da5cb5b11610092578063be76048811610062578063be760488146102c5578063dd62ed3e146102e4578063eac449d914610303578063f2fde38b14610322578063fbfa77cf14610341575f80fd5b80638da5cb5b1461022257806395d89b4114610272578063a9059cbb14610286578063ac9650d8146102a5575f80fd5b8063313ce567116100cd578063313ce567146101b3578063485cc955146101ce57806370a08231146101ef578063715018a61461020e575f80fd5b806306fdde03146100fe578063095ea7b31461012857806318160ddd1461015757806323b872dd14610194575b5f80fd5b348015610109575f80fd5b5061011261035f565b60405161011f91906110e1565b60405180910390f35b348015610133575f80fd5b50610147610142366004611107565b61041f565b604051901515815260200161011f565b348015610162575f80fd5b507f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace02545b60405190815260200161011f565b34801561019f575f80fd5b506101476101ae366004611131565b610438565b3480156101be575f80fd5b506040516012815260200161011f565b3480156101d9575f80fd5b506101ed6101e836600461116f565b610476565b005b3480156101fa575f80fd5b506101866102093660046111a6565b6106a2565b348015610219575f80fd5b506101ed6106c8565b34801561022d575f80fd5b507f9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300546001600160a01b03165b6040516001600160a01b03909116815260200161011f565b34801561027d575f80fd5b506101126106db565b348015610291575f80fd5b506101476102a0366004611107565b610719565b6102b86102b33660046111c1565b610755565b60405161011f9190611232565b3480156102d0575f80fd5b506101ed6102df366004611107565b610773565b3480156102ef575f80fd5b506101866102fe36600461116f565b6108c7565b34801561030e575f80fd5b506101ed61031d366004611107565b610910565b34801561032d575f80fd5b506101ed61033c3660046111a6565b610ab3565b34801561034c575f80fd5b505f5461025a906001600160a01b031681565b7f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace0380546060915f805160206114328339815191529161039d90611295565b80601f01602080910402602001604051908101604052809291908181526020018280546103c990611295565b80156104145780601f106103eb57610100808354040283529160200191610414565b820191905f5260205f20905b8154815290600101906020018083116103f757829003601f168201915b505050505091505090565b5f3361042c818585610af5565b60019150505b92915050565b5f80546001600160a01b03163314610463576040516325cdf54f60e21b815260040160405180910390fd5b61046e848484610b07565b949350505050565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a008054600160401b810460ff16159067ffffffffffffffff165f811580156104bb5750825b90505f8267ffffffffffffffff1660011480156104d75750303b155b9050811580156104e5575080155b156105035760405163f92ee8a960e01b815260040160405180910390fd5b845467ffffffffffffffff19166001178555831561052d57845460ff60401b1916600160401b1785555b6001600160a01b038716158061054a57506001600160a01b038616155b156105685760405163d92e233d60e01b815260040160405180910390fd5b61057187610b2a565b6105c16040518060400160405280601381526020017242657261204261646469657320506f696e747360681b8152506040518060400160405280600381526020016204242560ec1b815250610b3b565b60405163577ee5c760e01b81523060048201526001600160a01b0387169063577ee5c7906024016020604051808303815f875af1158015610604573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061062891906112cd565b5f80546001600160a01b0319166001600160a01b039290921691821790556106539030905f19610af5565b831561069957845460ff60401b19168555604051600181527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b50505050505050565b6001600160a01b03165f9081525f80516020611432833981519152602052604090205490565b6106d0610b51565b6106d95f610bac565b565b7f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace0480546060915f805160206114328339815191529161039d90611295565b5f80546001600160a01b03163314610744576040516325cdf54f60e21b815260040160405180910390fd5b61074e8383610c1c565b9392505050565b60603415610761575f80fd5b61043261076e8484610c29565b610cbb565b61077b610b51565b7f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace02545f546107b1906001600160a01b03166106a2565b146107cf5760405163473ab96d60e11b815260040160405180910390fd5b6001600160a01b0382166107f65760405163d92e233d60e01b815260040160405180910390fd5b805f036108165760405163150a67e960e01b815260040160405180910390fd5b6108203082610ccc565b5f54604051633c323a1b60e01b81526001600160a01b0384811660048301526024820184905290911690633c323a1b906044015f604051808303815f87803b15801561086a575f80fd5b505af115801561087c573d5f803e3d5ffd5b50505050816001600160a01b03167f5305c0bdb5dce4c26736d386b3a0b572ef36cc9042be902beb568ef2bb2b3c78826040516108bb91815260200190565b60405180910390a25050565b6001600160a01b039182165f9081527f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace016020908152604080832093909416825291909152205490565b610918610b51565b7f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace02545f5461094e906001600160a01b03166106a2565b1461096c5760405163473ab96d60e11b815260040160405180910390fd5b6001600160a01b0382166109935760405163d92e233d60e01b815260040160405180910390fd5b805f03610a0e575f546040516323d943e760e21b81526001600160a01b03848116600483015230602483015290911690638f650f9c90604401602060405180830381865afa1580156109e7573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610a0b91906112e8565b90505b5f54604051635281244f60e01b81526001600160a01b0384811660048301526024820184905290911690635281244f906044015f604051808303815f87803b158015610a58575f80fd5b505af1158015610a6a573d5f803e3d5ffd5b50505050610a783082610d00565b816001600160a01b03167f01d259196cb66f61d83b98793cdab9721613fb41683b683afb1bfb04413692ca826040516108bb91815260200190565b610abb610b51565b6001600160a01b038116610ae957604051631e4fbdf760e01b81525f60048201526024015b60405180910390fd5b610af281610bac565b50565b610b028383836001610d34565b505050565b5f33610b14858285610e18565b610b1f858585610e7c565b506001949350505050565b610b32610ed9565b610af281610f22565b610b43610ed9565b610b4d8282610f2a565b5050565b33610b837f9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300546001600160a01b031690565b6001600160a01b0316146106d95760405163118cdaa760e01b8152336004820152602401610ae0565b7f9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c19930080546001600160a01b031981166001600160a01b03848116918217845560405192169182907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0905f90a3505050565b5f3361042c818585610e7c565b5f60405190506020815281816020015280604001808360051b808684378201808515610ca3575b8351870180356020820183375f38823584305af4610c70573d5f873e3d86fd5b5082810384523d815260209384019381013d5f823e5f3d8201523d01601f0167ffffffffffffffe0169050818410610c50575b806040528485820360401b1794505050505092915050565b8060401c8167ffffffffffffffff16f35b6001600160a01b038216610cf55760405163ec442f0560e01b81525f6004820152602401610ae0565b610b4d5f8383610f7a565b6001600160a01b038216610d2957604051634b637e8f60e11b81525f6004820152602401610ae0565b610b4d825f83610f7a565b5f805160206114328339815191526001600160a01b038516610d6b5760405163e602df0560e01b81525f6004820152602401610ae0565b6001600160a01b038416610d9457604051634a1406b160e11b81525f6004820152602401610ae0565b6001600160a01b038086165f90815260018301602090815260408083209388168352929052208390558115610e1157836001600160a01b0316856001600160a01b03167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92585604051610e0891815260200190565b60405180910390a35b5050505050565b5f610e2384846108c7565b90505f19811015610e765781811015610e6857604051637dc7a0d960e11b81526001600160a01b03841660048201526024810182905260448101839052606401610ae0565b610e7684848484035f610d34565b50505050565b6001600160a01b038316610ea557604051634b637e8f60e11b81525f6004820152602401610ae0565b6001600160a01b038216610ece5760405163ec442f0560e01b81525f6004820152602401610ae0565b610b02838383610f7a565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a0054600160401b900460ff166106d957604051631afcd79f60e31b815260040160405180910390fd5b610abb610ed9565b610f32610ed9565b5f805160206114328339815191527f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace03610f6b8482611357565b5060048101610e768382611357565b5f805160206114328339815191526001600160a01b038416610fb45781816002015f828254610fa99190611412565b909155506110249050565b6001600160a01b0384165f90815260208290526040902054828110156110065760405163391434e360e21b81526001600160a01b03861660048201526024810182905260448101849052606401610ae0565b6001600160a01b0385165f9081526020839052604090209083900390555b6001600160a01b038316611042576002810180548390039055611060565b6001600160a01b0383165f9081526020829052604090208054830190555b826001600160a01b0316846001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040516110a591815260200190565b60405180910390a350505050565b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b602081525f61074e60208301846110b3565b6001600160a01b0381168114610af2575f80fd5b5f8060408385031215611118575f80fd5b8235611123816110f3565b946020939093013593505050565b5f805f60608486031215611143575f80fd5b833561114e816110f3565b9250602084013561115e816110f3565b929592945050506040919091013590565b5f8060408385031215611180575f80fd5b823561118b816110f3565b9150602083013561119b816110f3565b809150509250929050565b5f602082840312156111b6575f80fd5b813561074e816110f3565b5f80602083850312156111d2575f80fd5b823567ffffffffffffffff8111156111e8575f80fd5b8301601f810185136111f8575f80fd5b803567ffffffffffffffff81111561120e575f80fd5b8560208260051b8401011115611222575f80fd5b6020919091019590945092505050565b5f602082016020835280845180835260408501915060408160051b8601019250602086015f5b8281101561128957603f198786030184526112748583516110b3565b94506020938401939190910190600101611258565b50929695505050505050565b600181811c908216806112a957607f821691505b6020821081036112c757634e487b7160e01b5f52602260045260245ffd5b50919050565b5f602082840312156112dd575f80fd5b815161074e816110f3565b5f602082840312156112f8575f80fd5b5051919050565b634e487b7160e01b5f52604160045260245ffd5b601f821115610b0257805f5260205f20601f840160051c810160208510156113385750805b601f840160051c820191505b81811015610e11575f8155600101611344565b815167ffffffffffffffff811115611371576113716112ff565b6113858161137f8454611295565b84611313565b6020601f8211600181146113b7575f83156113a05750848201515b5f19600385901b1c1916600184901b178455610e11565b5f84815260208120601f198516915b828110156113e657878501518255602094850194600190920191016113c6565b508482101561140357868401515f19600387901b60f8161c191681555b50505050600190811b01905550565b8082018082111561043257634e487b7160e01b5f52601160045260245ffdfe52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace00a26469706673582212205167d5046f32b720f7b2808e344cc795623b0ec10ea86a083354abe8e480da5664736f6c634300081a0033
Loading...
Loading
Loading...
Loading
Multichain Portfolio | 34 Chains
Chain | Token | Portfolio % | Price | Amount | Value |
---|
Loading...
Loading
Loading...
Loading
A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.