Overview
ETH Balance
0 ETH
Eth Value
$0.00More Info
Private Name Tags
ContractCreator
Latest 16 from a total of 16 transactions
Transaction Hash |
Method
|
Block
|
From
|
To
|
|||||
---|---|---|---|---|---|---|---|---|---|
Create Fund | 21967598 | 14 hrs ago | IN | 0.45 ETH | 0.00121925 | ||||
Create Fund | 21966250 | 18 hrs ago | IN | 0.21335636 ETH | 0.00072025 | ||||
Create Fund | 21958585 | 44 hrs ago | IN | 0.2247857 ETH | 0.00062865 | ||||
Create Fund | 21954709 | 2 days ago | IN | 0.22804265 ETH | 0.00104549 | ||||
Create Fund | 21953104 | 2 days ago | IN | 0.23257296 ETH | 0.00108752 | ||||
Create Fund | 21950516 | 2 days ago | IN | 0.5 ETH | 0.00066874 | ||||
Set Minimum Firs... | 21947155 | 3 days ago | IN | 0 ETH | 0.00002331 | ||||
Create Fund | 21946472 | 3 days ago | IN | 0.09135457 ETH | 0.00063944 | ||||
Create Fund | 21946371 | 3 days ago | IN | 0.23 ETH | 0.00075283 | ||||
Set Protocol Pro... | 21944555 | 3 days ago | IN | 0 ETH | 0.00002532 | ||||
Create Fund | 21943864 | 3 days ago | IN | 0.09522363 ETH | 0.00120135 | ||||
Create Fund | 21941229 | 4 days ago | IN | 0.08749434 ETH | 0.00076876 | ||||
Create Fund | 21940901 | 4 days ago | IN | 0.08836432 ETH | 0.00056829 | ||||
Set Minimum Firs... | 21940844 | 4 days ago | IN | 0 ETH | 0.00002267 | ||||
Create Fund | 21940765 | 4 days ago | IN | 0.22231005 ETH | 0.00042138 | ||||
Set Minimum Firs... | 21940676 | 4 days ago | IN | 0 ETH | 0.00002276 |
Latest 25 internal transactions (View All)
Advanced mode:
Parent Transaction Hash | Block |
From
|
To
|
|||
---|---|---|---|---|---|---|
21967598 | 14 hrs ago | 0.45 ETH | ||||
21967598 | 14 hrs ago | Contract Creation | 0 ETH | |||
21966250 | 18 hrs ago | 0.21335636 ETH | ||||
21966250 | 18 hrs ago | Contract Creation | 0 ETH | |||
21958585 | 44 hrs ago | 0.2247857 ETH | ||||
21958585 | 44 hrs ago | Contract Creation | 0 ETH | |||
21954709 | 2 days ago | 0.22804265 ETH | ||||
21954709 | 2 days ago | Contract Creation | 0 ETH | |||
21953104 | 2 days ago | 0.23257296 ETH | ||||
21953104 | 2 days ago | Contract Creation | 0 ETH | |||
21950516 | 2 days ago | 0.5 ETH | ||||
21950516 | 2 days ago | Contract Creation | 0 ETH | |||
21946472 | 3 days ago | 0.09135457 ETH | ||||
21946472 | 3 days ago | Contract Creation | 0 ETH | |||
21946371 | 3 days ago | 0.23 ETH | ||||
21946371 | 3 days ago | Contract Creation | 0 ETH | |||
21943864 | 3 days ago | 0.09522363 ETH | ||||
21943864 | 3 days ago | Contract Creation | 0 ETH | |||
21941229 | 4 days ago | 0.08749434 ETH | ||||
21941229 | 4 days ago | Contract Creation | 0 ETH | |||
21940901 | 4 days ago | 0.08836432 ETH | ||||
21940901 | 4 days ago | Contract Creation | 0 ETH | |||
21940765 | 4 days ago | 0.22231005 ETH | ||||
21940765 | 4 days ago | Contract Creation | 0 ETH | |||
21940663 | 4 days ago | Contract Creation | 0 ETH |
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:
FundFactory
Compiler Version
v0.8.27+commit.40a35a09
Optimization Enabled:
Yes with 200 runs
Other Settings:
paris EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: MIT pragma solidity =0.8.27; import { Ownable } from '@openzeppelin/contracts/access/Ownable.sol'; import { Pausable } from '@openzeppelin/contracts/utils/Pausable.sol'; import { ERC20 } from '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import { SafeERC20 } from '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; import { Clones } from '@openzeppelin/contracts/proxy/Clones.sol'; import { GuruFund } from 'contracts/GuruFund.sol'; import { EIP712Helper } from 'contracts/helpers/EIP712Helper.sol'; import { SignedPayload } from 'contracts/structs/SignedPayload.sol'; import { IWETH } from 'contracts/interfaces/IWETH.sol'; import { InitialDeposit } from 'contracts/structs/InitialDeposit.sol'; import { Error } from 'contracts/lib/Error.sol'; contract FundFactory is EIP712Helper, Pausable { // Immutable variables (stored in code, not storage) IWETH public immutable weth; GuruFund public immutable fundImplementation; // Constants (not stored in storage) bytes32 public constant SIGNED_ACTION_TYPEHASH = keccak256( 'SignedAction(uint256 nonce,address account,bytes data,uint256 expiresAt)' ); uint24 public constant FEE_DENOMINATOR = 100_000; uint16 public constant MAX_PROFIT_FEE = 20_000; // 20% uint16 public constant GURU_PROFIT_FEE = 10_000; // 10% uint16 public constant MAX_DEPOSIT_FEE = 1_000; // 1% uint16 public constant MAX_SWAP_FEE = 200; // 0.2% // Storage variables packed into slots address public vault; // slot 0 (20 bytes) uint32 public signatureValidityPeriod = 10; // slot 0 (4 bytes) uint16 public protocolProfitFee = 5_000; // slot 0 (2 bytes) uint16 public protocolDepositFee = 1_000; // slot 0 (2 bytes) uint16 public protocolSwapFee = 200; // slot 0 (2 bytes) address public guruBurner; // slot 1 (20 bytes) uint64 public minimumGuruInitialDepositValue = 1000_000000; // slot 1 (8 bytes) uint64 public protocolFundCreationFeeValue = 100_000000; // slot 1 (8 bytes) address public admin; // slot 2 (20 bytes) // events event VaultUpdated(address newVault); event GuruBurnerUpdated(address newGuruBurner); event AdminUpdated(address newAdmin); event MinimumGuruInitialDepositValueUpdated( uint64 newMinimumInitialDeposit ); event SignatureValidityPeriodUpdated(uint32 newSignatureValidityPeriod); event ProtocolProfitFeeUpdated(uint16 newProtocolProfitFee); event ProtocolFundCreationFeeUpdated(uint64 newProtocolFundCreationFee); event ProtocolDepositFeeUpdated(uint16 newProtocolDepositFee); event ProtocolSwapFeeUpdated(uint16 newProtocolSwapFee); event FundCreated(address indexed fund, address indexed creator); // errors error InsufficientFirstDeposit(uint256 received, uint256 required); error FeesTooHigh(uint256 fee, uint256 max); constructor( address _offchainSigner, address _vault, address _guruBurner, address _admin, IWETH _wethAddress ) Ownable(msg.sender) EIP712Helper('GURU.FUND', 'v0.1.0', _offchainSigner) { vault = _vault; guruBurner = _guruBurner; weth = _wethAddress; admin = _admin; fundImplementation = new GuruFund(); } function getTotalProfitFee() public view returns (uint256) { return GURU_PROFIT_FEE + protocolProfitFee; } // config function setVault(address _newVault) public onlyOwner { vault = _newVault; emit VaultUpdated(_newVault); } function setGuruBurner(address _newGuruBurner) public onlyOwner { guruBurner = _newGuruBurner; emit GuruBurnerUpdated(_newGuruBurner); } function setAdmin(address _newAdmin) public onlyOwner { admin = _newAdmin; emit AdminUpdated(_newAdmin); } function setProtocolFundCreationFee( uint64 _newProtocolFundCreationFee ) public onlyOwner { protocolFundCreationFeeValue = _newProtocolFundCreationFee; emit ProtocolFundCreationFeeUpdated(_newProtocolFundCreationFee); } function setProtocolDepositFee( uint16 _newProtocolDepositFee ) public onlyOwner { require( _newProtocolDepositFee <= MAX_DEPOSIT_FEE, FeesTooHigh(_newProtocolDepositFee, MAX_DEPOSIT_FEE) ); protocolDepositFee = _newProtocolDepositFee; emit ProtocolDepositFeeUpdated(_newProtocolDepositFee); } function setProtocolProfitFee( uint16 _newProtocolFeeOnProfits ) public onlyOwner { require( GURU_PROFIT_FEE + _newProtocolFeeOnProfits <= MAX_PROFIT_FEE, FeesTooHigh( GURU_PROFIT_FEE + _newProtocolFeeOnProfits, MAX_PROFIT_FEE ) ); protocolProfitFee = _newProtocolFeeOnProfits; emit ProtocolProfitFeeUpdated(_newProtocolFeeOnProfits); } function setProtocolSwapFee(uint16 _newProtocolSwapFee) public onlyOwner { require( _newProtocolSwapFee <= MAX_SWAP_FEE, FeesTooHigh(_newProtocolSwapFee, MAX_SWAP_FEE) ); protocolSwapFee = _newProtocolSwapFee; emit ProtocolSwapFeeUpdated(_newProtocolSwapFee); } function setMinimumFirstDepositValue(uint64 _newMinimum) public onlyOwner { minimumGuruInitialDepositValue = _newMinimum; emit MinimumGuruInitialDepositValueUpdated(_newMinimum); } function setSignatureValidityPeriod( uint32 _newSignatureValidityPeriod ) public onlyOwner { signatureValidityPeriod = _newSignatureValidityPeriod; emit SignatureValidityPeriodUpdated(_newSignatureValidityPeriod); } function verifySignature( address account, SignedPayload calldata _signedPayload ) public { _verifyEIP712(SIGNED_ACTION_TYPEHASH, account, _signedPayload); } function pause() public onlyOwner { _pause(); } function unpause() public onlyOwner { _unpause(); } /** * @notice Creates a new fund with a minimum deposit of 1000 USDT worth of WETH * @param _name Name of the fund token * @param _symbol Symbol of the fund token * @param _signedPayload Signed payload containing expiration, signature, and * the encoded price feed with latest WETH/USDT price */ function createFund( string calldata _name, string calldata _symbol, SignedPayload calldata _signedPayload ) public payable whenNotPaused { verifySignature(msg.sender, _signedPayload); InitialDeposit memory initialDeposit = abi.decode( _signedPayload.data, (InitialDeposit) ); // Any check on the deposit min amount is handled offchain: here we // just verify that the amount received is matching the signed payload require( initialDeposit.amountsWei.input + initialDeposit.amountsWei.buybackFee == msg.value, Error.MismatchingDepositAmount(initialDeposit.amountsWei, msg.value) ); address fund = Clones.clone(address(fundImplementation)); GuruFund(payable(fund)).initialize{ value: msg.value }( msg.sender, _name, _symbol, initialDeposit ); emit FundCreated(fund, msg.sender); } }
// 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 // 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.1.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.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) (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 // OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol) pragma solidity ^0.8.20; import {Context} from "../utils/Context.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 Ownable is Context { address private _owner; /** * @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. */ constructor(address initialOwner) { 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) { 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 { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
// 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.1.0) (interfaces/IERC1271.sol) pragma solidity ^0.8.20; /** * @dev Interface of the ERC-1271 standard signature validation method for * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271]. */ interface IERC1271 { /** * @dev Should return whether the signature provided is valid for the provided data * @param hash Hash of the data to be signed * @param signature Signature byte array associated with _data */ function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue); }
// 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: 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: 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/IERC5267.sol) pragma solidity ^0.8.20; interface IERC5267 { /** * @dev MAY be emitted to signal that the domain could have changed. */ event EIP712DomainChanged(); /** * @dev returns the fields and values that describe the domain separator used by this contract for EIP-712 * signature. */ function eip712Domain() external view returns ( bytes1 fields, string memory name, string memory version, uint256 chainId, address verifyingContract, bytes32 salt, uint256[] memory extensions ); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (proxy/Clones.sol) pragma solidity ^0.8.20; import {Errors} from "../utils/Errors.sol"; /** * @dev https://eips.ethereum.org/EIPS/eip-1167[ERC-1167] is a standard for * deploying minimal proxy contracts, also known as "clones". * * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies * > a minimal bytecode implementation that delegates all calls to a known, fixed address. * * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2` * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the * deterministic method. */ library Clones { /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create opcode, which should never revert. */ function clone(address implementation) internal returns (address instance) { return clone(implementation, 0); } /** * @dev Same as {xref-Clones-clone-address-}[clone], but with a `value` parameter to send native currency * to the new contract. * * NOTE: Using a non-zero value at creation will require the contract using this function (e.g. a factory) * to always have enough balance for new deployments. Consider exposing this function under a payable method. */ function clone(address implementation, uint256 value) internal returns (address instance) { if (address(this).balance < value) { revert Errors.InsufficientBalance(address(this).balance, value); } assembly ("memory-safe") { // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes // of the `implementation` address with the bytecode before the address. mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000)) // Packs the remaining 17 bytes of `implementation` with the bytecode after the address. mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3)) instance := create(value, 0x09, 0x37) } if (instance == address(0)) { revert Errors.FailedDeployment(); } } /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create2 opcode and a `salt` to deterministically deploy * the clone. Using the same `implementation` and `salt` multiple time will revert, since * the clones cannot be deployed twice at the same address. */ function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) { return cloneDeterministic(implementation, salt, 0); } /** * @dev Same as {xref-Clones-cloneDeterministic-address-bytes32-}[cloneDeterministic], but with * a `value` parameter to send native currency to the new contract. * * NOTE: Using a non-zero value at creation will require the contract using this function (e.g. a factory) * to always have enough balance for new deployments. Consider exposing this function under a payable method. */ function cloneDeterministic( address implementation, bytes32 salt, uint256 value ) internal returns (address instance) { if (address(this).balance < value) { revert Errors.InsufficientBalance(address(this).balance, value); } assembly ("memory-safe") { // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes // of the `implementation` address with the bytecode before the address. mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000)) // Packs the remaining 17 bytes of `implementation` with the bytecode after the address. mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3)) instance := create2(value, 0x09, 0x37, salt) } if (instance == address(0)) { revert Errors.FailedDeployment(); } } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress( address implementation, bytes32 salt, address deployer ) internal pure returns (address predicted) { assembly ("memory-safe") { let ptr := mload(0x40) mstore(add(ptr, 0x38), deployer) mstore(add(ptr, 0x24), 0x5af43d82803e903d91602b57fd5bf3ff) mstore(add(ptr, 0x14), implementation) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73) mstore(add(ptr, 0x58), salt) mstore(add(ptr, 0x78), keccak256(add(ptr, 0x0c), 0x37)) predicted := and(keccak256(add(ptr, 0x43), 0x55), 0xffffffffffffffffffffffffffffffffffffffff) } } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress( address implementation, bytes32 salt ) internal view returns (address predicted) { return predictDeterministicAddress(implementation, salt, address(this)); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.20; import {IERC20} from "./IERC20.sol"; import {IERC20Metadata} from "./extensions/IERC20Metadata.sol"; import {Context} from "../../utils/Context.sol"; import {IERC20Errors} from "../../interfaces/draft-IERC6093.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 ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors { mapping(address account => uint256) private _balances; mapping(address account => mapping(address spender => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { 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) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual returns (uint256) { 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) { 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 { 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 { 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.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.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/utils/SafeERC20.sol) pragma solidity ^0.8.20; import { IERC20 } from '../IERC20.sol'; import { IERC1363 } from '../../../interfaces/IERC1363.sol'; import { Address } from '../../../utils/Address.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.1.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, ) = recipient.call{value: amount}(""); if (!success) { revert Errors.FailedCall(); } } /** * @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.0.1) (utils/Context.sol) pragma solidity ^0.8.20; /** * @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 Context { 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) (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.20; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS } /** * @dev The signature derives the `address(0)`. */ error ECDSAInvalidSignature(); /** * @dev The signature has an invalid length. */ error ECDSAInvalidSignatureLength(uint256 length); /** * @dev The signature has an S value that is in the upper half order. */ error ECDSAInvalidSignatureS(bytes32 s); /** * @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not * return address(0) without also returning an error description. Errors are documented using an enum (error type) * and a bytes32 providing additional information about the error. * * If no error is returned, then the address can be used for verification purposes. * * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] */ function tryRecover( bytes32 hash, bytes memory signature ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) { if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly ("memory-safe") { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else { return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length)); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature); _throwError(error, errorArg); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[ERC-2098 short signatures] */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) { unchecked { bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); // We do not check for an overflow here since the shift operation results in 0 or 1. uint8 v = uint8((uint256(vs) >> 255) + 27); return tryRecover(hash, v, r, s); } } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. */ function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) { (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs); _throwError(error, errorArg); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS, s); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature, bytes32(0)); } return (signer, RecoverError.NoError, bytes32(0)); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s); _throwError(error, errorArg); return recovered; } /** * @dev Optionally reverts with the corresponding custom error according to the `error` argument provided. */ function _throwError(RecoverError error, bytes32 errorArg) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert ECDSAInvalidSignature(); } else if (error == RecoverError.InvalidSignatureLength) { revert ECDSAInvalidSignatureLength(uint256(errorArg)); } else if (error == RecoverError.InvalidSignatureS) { revert ECDSAInvalidSignatureS(errorArg); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/EIP712.sol) pragma solidity ^0.8.20; import {MessageHashUtils} from "./MessageHashUtils.sol"; import {ShortStrings, ShortString} from "../ShortStrings.sol"; import {IERC5267} from "../../interfaces/IERC5267.sol"; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP-712] is a standard for hashing and signing of typed structured data. * * The encoding scheme specified in the EIP requires a domain separator and a hash of the typed structured data, whose * encoding is very generic and therefore its implementation in Solidity is not feasible, thus this contract * does not implement the encoding itself. Protocols need to implement the type-specific encoding they need in order to * produce the hash of their typed data using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP-712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain * separator of the implementation contract. This will cause the {_domainSeparatorV4} function to always rebuild the * separator from the immutable values, which is cheaper than accessing a cached version in cold storage. * * @custom:oz-upgrades-unsafe-allow state-variable-immutable */ abstract contract EIP712 is IERC5267 { using ShortStrings for *; bytes32 private constant TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to // invalidate the cached domain separator if the chain id changes. bytes32 private immutable _cachedDomainSeparator; uint256 private immutable _cachedChainId; address private immutable _cachedThis; bytes32 private immutable _hashedName; bytes32 private immutable _hashedVersion; ShortString private immutable _name; ShortString private immutable _version; string private _nameFallback; string private _versionFallback; /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP-712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) { _name = name.toShortStringWithFallback(_nameFallback); _version = version.toShortStringWithFallback(_versionFallback); _hashedName = keccak256(bytes(name)); _hashedVersion = keccak256(bytes(version)); _cachedChainId = block.chainid; _cachedDomainSeparator = _buildDomainSeparator(); _cachedThis = address(this); } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { if (address(this) == _cachedThis && block.chainid == _cachedChainId) { return _cachedDomainSeparator; } else { return _buildDomainSeparator(); } } function _buildDomainSeparator() private view returns (bytes32) { return keccak256(abi.encode(TYPE_HASH, _hashedName, _hashedVersion, block.chainid, address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return MessageHashUtils.toTypedDataHash(_domainSeparatorV4(), structHash); } /** * @dev See {IERC-5267}. */ function eip712Domain() public view virtual returns ( bytes1 fields, string memory name, string memory version, uint256 chainId, address verifyingContract, bytes32 salt, uint256[] memory extensions ) { return ( hex"0f", // 01111 _EIP712Name(), _EIP712Version(), block.chainid, address(this), bytes32(0), new uint256[](0) ); } /** * @dev The name parameter for the EIP712 domain. * * NOTE: By default this function reads _name which is an immutable value. * It only reads from storage if necessary (in case the value is too large to fit in a ShortString). */ // solhint-disable-next-line func-name-mixedcase function _EIP712Name() internal view returns (string memory) { return _name.toStringWithFallback(_nameFallback); } /** * @dev The version parameter for the EIP712 domain. * * NOTE: By default this function reads _version which is an immutable value. * It only reads from storage if necessary (in case the value is too large to fit in a ShortString). */ // solhint-disable-next-line func-name-mixedcase function _EIP712Version() internal view returns (string memory) { return _version.toStringWithFallback(_versionFallback); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/MessageHashUtils.sol) pragma solidity ^0.8.20; import {Strings} from "../Strings.sol"; /** * @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing. * * The library provides methods for generating a hash of a message that conforms to the * https://eips.ethereum.org/EIPS/eip-191[ERC-191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712] * specifications. */ library MessageHashUtils { /** * @dev Returns the keccak256 digest of an ERC-191 signed data with version * `0x45` (`personal_sign` messages). * * The digest is calculated by prefixing a bytes32 `messageHash` with * `"\x19Ethereum Signed Message:\n32"` and hashing the result. It corresponds with the * hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method. * * NOTE: The `messageHash` parameter is intended to be the result of hashing a raw message with * keccak256, although any bytes32 value can be safely used because the final digest will * be re-hashed. * * See {ECDSA-recover}. */ function toEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32 digest) { assembly ("memory-safe") { mstore(0x00, "\x19Ethereum Signed Message:\n32") // 32 is the bytes-length of messageHash mstore(0x1c, messageHash) // 0x1c (28) is the length of the prefix digest := keccak256(0x00, 0x3c) // 0x3c is the length of the prefix (0x1c) + messageHash (0x20) } } /** * @dev Returns the keccak256 digest of an ERC-191 signed data with version * `0x45` (`personal_sign` messages). * * The digest is calculated by prefixing an arbitrary `message` with * `"\x19Ethereum Signed Message:\n" + len(message)` and hashing the result. It corresponds with the * hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method. * * See {ECDSA-recover}. */ function toEthSignedMessageHash(bytes memory message) internal pure returns (bytes32) { return keccak256(bytes.concat("\x19Ethereum Signed Message:\n", bytes(Strings.toString(message.length)), message)); } /** * @dev Returns the keccak256 digest of an ERC-191 signed data with version * `0x00` (data with intended validator). * * The digest is calculated by prefixing an arbitrary `data` with `"\x19\x00"` and the intended * `validator` address. Then hashing the result. * * See {ECDSA-recover}. */ function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) { return keccak256(abi.encodePacked(hex"19_00", validator, data)); } /** * @dev Returns the keccak256 digest of an EIP-712 typed data (ERC-191 version `0x01`). * * The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with * `\x19\x01` and hashing the result. It corresponds to the hash signed by the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712. * * See {ECDSA-recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 digest) { assembly ("memory-safe") { let ptr := mload(0x40) mstore(ptr, hex"19_01") mstore(add(ptr, 0x02), domainSeparator) mstore(add(ptr, 0x22), structHash) digest := keccak256(ptr, 0x42) } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/SignatureChecker.sol) pragma solidity ^0.8.20; import {ECDSA} from "./ECDSA.sol"; import {IERC1271} from "../../interfaces/IERC1271.sol"; /** * @dev Signature verification helper that can be used instead of `ECDSA.recover` to seamlessly support both ECDSA * signatures from externally owned accounts (EOAs) as well as ERC-1271 signatures from smart contract wallets like * Argent and Safe Wallet (previously Gnosis Safe). */ library SignatureChecker { /** * @dev Checks if a signature is valid for a given signer and data hash. If the signer is a smart contract, the * signature is validated against that smart contract using ERC-1271, otherwise it's validated using `ECDSA.recover`. * * NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus * change through time. It could return true at block N and false at block N+1 (or the opposite). */ function isValidSignatureNow(address signer, bytes32 hash, bytes memory signature) internal view returns (bool) { if (signer.code.length == 0) { (address recovered, ECDSA.RecoverError err, ) = ECDSA.tryRecover(hash, signature); return err == ECDSA.RecoverError.NoError && recovered == signer; } else { return isValidERC1271SignatureNow(signer, hash, signature); } } /** * @dev Checks if a signature is valid for a given signer and data hash. The signature is validated * against the signer smart contract using ERC-1271. * * NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus * change through time. It could return true at block N and false at block N+1 (or the opposite). */ function isValidERC1271SignatureNow( address signer, bytes32 hash, bytes memory signature ) internal view returns (bool) { (bool success, bytes memory result) = signer.staticcall( abi.encodeCall(IERC1271.isValidSignature, (hash, signature)) ); return (success && result.length >= 32 && abi.decode(result, (bytes32)) == bytes32(IERC1271.isValidSignature.selector)); } }
// 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); }
// 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.1.0) (utils/math/Math.sol) pragma solidity ^0.8.20; import {Panic} from "../Panic.sol"; import {SafeCast} from "./SafeCast.sol"; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { enum Rounding { Floor, // Toward negative infinity Ceil, // Toward positive infinity Trunc, // Toward zero Expand // Away from zero } /** * @dev Returns the addition of two unsigned integers, with an success flag (no overflow). */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the subtraction of two unsigned integers, with an success flag (no overflow). */ function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an success flag (no overflow). */ function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a success flag (no division by zero). */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero). */ function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant. * * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone. * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute * one branch when needed, making this function more expensive. */ function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) { unchecked { // branchless ternary works because: // b ^ (a ^ b) == a // b ^ 0 == b return b ^ ((a ^ b) * SafeCast.toUint(condition)); } } /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return ternary(a > b, a, b); } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return ternary(a < b, a, b); } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds towards infinity instead * of rounding towards zero. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { if (b == 0) { // Guarantee the same behavior as in a regular Solidity division. Panic.panic(Panic.DIVISION_BY_ZERO); } // The following calculation ensures accurate ceiling division without overflow. // Since a is non-zero, (a - 1) / b will not overflow. // The largest possible result occurs when (a - 1) / b is type(uint256).max, // but the largest value we can obtain is type(uint256).max - 1, which happens // when a = type(uint256).max and b = 1. unchecked { return SafeCast.toUint(a > 0) * ((a - 1) / b + 1); } } /** * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or * denominator == 0. * * Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by * Uniswap Labs also under MIT license. */ function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) { unchecked { // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2²⁵⁶ + prod0. uint256 prod0 = x * y; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(x, y, not(0)) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division. if (prod1 == 0) { // Solidity will revert if denominator == 0, unlike the div opcode on its own. // The surrounding unchecked block does not change this fact. // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic. return prod0 / denominator; } // Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0. if (denominator <= prod1) { Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW)); } /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0]. uint256 remainder; assembly { // Compute remainder using mulmod. remainder := mulmod(x, y, denominator) // Subtract 256 bit number from 512 bit number. prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator and compute largest power of two divisor of denominator. // Always >= 1. See https://cs.stackexchange.com/q/138556/92363. uint256 twos = denominator & (0 - denominator); assembly { // Divide denominator by twos. denominator := div(denominator, twos) // Divide [prod1 prod0] by twos. prod0 := div(prod0, twos) // Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one. twos := add(div(sub(0, twos), twos), 1) } // Shift in bits from prod1 into prod0. prod0 |= prod1 * twos; // Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such // that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for // four bits. That is, denominator * inv ≡ 1 mod 2⁴. uint256 inverse = (3 * denominator) ^ 2; // Use the 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. inverse *= 2 - denominator * inverse; // inverse mod 2⁸ inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶ inverse *= 2 - denominator * inverse; // inverse mod 2³² inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴ inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸ inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶ // Because the division is now exact we can divide by multiplying with the modular inverse of denominator. // This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is // less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inverse; return result; } } /** * @dev Calculates x * y / denominator with full precision, following the selected rounding direction. */ function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) { return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0); } /** * @dev Calculate the modular multiplicative inverse of a number in Z/nZ. * * If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0. * If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible. * * If the input value is not inversible, 0 is returned. * * NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the * inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}. */ function invMod(uint256 a, uint256 n) internal pure returns (uint256) { unchecked { if (n == 0) return 0; // The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version) // Used to compute integers x and y such that: ax + ny = gcd(a, n). // When the gcd is 1, then the inverse of a modulo n exists and it's x. // ax + ny = 1 // ax = 1 + (-y)n // ax ≡ 1 (mod n) # x is the inverse of a modulo n // If the remainder is 0 the gcd is n right away. uint256 remainder = a % n; uint256 gcd = n; // Therefore the initial coefficients are: // ax + ny = gcd(a, n) = n // 0a + 1n = n int256 x = 0; int256 y = 1; while (remainder != 0) { uint256 quotient = gcd / remainder; (gcd, remainder) = ( // The old remainder is the next gcd to try. remainder, // Compute the next remainder. // Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd // where gcd is at most n (capped to type(uint256).max) gcd - remainder * quotient ); (x, y) = ( // Increment the coefficient of a. y, // Decrement the coefficient of n. // Can overflow, but the result is casted to uint256 so that the // next value of y is "wrapped around" to a value between 0 and n - 1. x - y * int256(quotient) ); } if (gcd != 1) return 0; // No inverse exists. return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative. } } /** * @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`. * * From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is * prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that * `a**(p-2)` is the modular multiplicative inverse of a in Fp. * * NOTE: this function does NOT check that `p` is a prime greater than `2`. */ function invModPrime(uint256 a, uint256 p) internal view returns (uint256) { unchecked { return Math.modExp(a, p - 2, p); } } /** * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m) * * Requirements: * - modulus can't be zero * - underlying staticcall to precompile must succeed * * IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make * sure the chain you're using it on supports the precompiled contract for modular exponentiation * at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, * the underlying function will succeed given the lack of a revert, but the result may be incorrectly * interpreted as 0. */ function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) { (bool success, uint256 result) = tryModExp(b, e, m); if (!success) { Panic.panic(Panic.DIVISION_BY_ZERO); } return result; } /** * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m). * It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying * to operate modulo 0 or if the underlying precompile reverted. * * IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain * you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in * https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack * of a revert, but the result may be incorrectly interpreted as 0. */ function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) { if (m == 0) return (false, 0); assembly ("memory-safe") { let ptr := mload(0x40) // | Offset | Content | Content (Hex) | // |-----------|------------|--------------------------------------------------------------------| // | 0x00:0x1f | size of b | 0x0000000000000000000000000000000000000000000000000000000000000020 | // | 0x20:0x3f | size of e | 0x0000000000000000000000000000000000000000000000000000000000000020 | // | 0x40:0x5f | size of m | 0x0000000000000000000000000000000000000000000000000000000000000020 | // | 0x60:0x7f | value of b | 0x<.............................................................b> | // | 0x80:0x9f | value of e | 0x<.............................................................e> | // | 0xa0:0xbf | value of m | 0x<.............................................................m> | mstore(ptr, 0x20) mstore(add(ptr, 0x20), 0x20) mstore(add(ptr, 0x40), 0x20) mstore(add(ptr, 0x60), b) mstore(add(ptr, 0x80), e) mstore(add(ptr, 0xa0), m) // Given the result < m, it's guaranteed to fit in 32 bytes, // so we can use the memory scratch space located at offset 0. success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20) result := mload(0x00) } } /** * @dev Variant of {modExp} that supports inputs of arbitrary length. */ function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) { (bool success, bytes memory result) = tryModExp(b, e, m); if (!success) { Panic.panic(Panic.DIVISION_BY_ZERO); } return result; } /** * @dev Variant of {tryModExp} that supports inputs of arbitrary length. */ function tryModExp( bytes memory b, bytes memory e, bytes memory m ) internal view returns (bool success, bytes memory result) { if (_zeroBytes(m)) return (false, new bytes(0)); uint256 mLen = m.length; // Encode call args in result and move the free memory pointer result = abi.encodePacked(b.length, e.length, mLen, b, e, m); assembly ("memory-safe") { let dataPtr := add(result, 0x20) // Write result on top of args to avoid allocating extra memory. success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen) // Overwrite the length. // result.length > returndatasize() is guaranteed because returndatasize() == m.length mstore(result, mLen) // Set the memory pointer after the returned data. mstore(0x40, add(dataPtr, mLen)) } } /** * @dev Returns whether the provided byte array is zero. */ function _zeroBytes(bytes memory byteArray) private pure returns (bool) { for (uint256 i = 0; i < byteArray.length; ++i) { if (byteArray[i] != 0) { return false; } } return true; } /** * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded * towards zero. * * This method is based on Newton's method for computing square roots; the algorithm is restricted to only * using integer operations. */ function sqrt(uint256 a) internal pure returns (uint256) { unchecked { // Take care of easy edge cases when a == 0 or a == 1 if (a <= 1) { return a; } // In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a // sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between // the current value as `ε_n = | x_n - sqrt(a) |`. // // For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root // of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is // bigger than any uint256. // // By noticing that // `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)` // we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar // to the msb function. uint256 aa = a; uint256 xn = 1; if (aa >= (1 << 128)) { aa >>= 128; xn <<= 64; } if (aa >= (1 << 64)) { aa >>= 64; xn <<= 32; } if (aa >= (1 << 32)) { aa >>= 32; xn <<= 16; } if (aa >= (1 << 16)) { aa >>= 16; xn <<= 8; } if (aa >= (1 << 8)) { aa >>= 8; xn <<= 4; } if (aa >= (1 << 4)) { aa >>= 4; xn <<= 2; } if (aa >= (1 << 2)) { xn <<= 1; } // We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1). // // We can refine our estimation by noticing that the middle of that interval minimizes the error. // If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2). // This is going to be our x_0 (and ε_0) xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2) // From here, Newton's method give us: // x_{n+1} = (x_n + a / x_n) / 2 // // One should note that: // x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a // = ((x_n² + a) / (2 * x_n))² - a // = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a // = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²) // = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²) // = (x_n² - a)² / (2 * x_n)² // = ((x_n² - a) / (2 * x_n))² // ≥ 0 // Which proves that for all n ≥ 1, sqrt(a) ≤ x_n // // This gives us the proof of quadratic convergence of the sequence: // ε_{n+1} = | x_{n+1} - sqrt(a) | // = | (x_n + a / x_n) / 2 - sqrt(a) | // = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) | // = | (x_n - sqrt(a))² / (2 * x_n) | // = | ε_n² / (2 * x_n) | // = ε_n² / | (2 * x_n) | // // For the first iteration, we have a special case where x_0 is known: // ε_1 = ε_0² / | (2 * x_0) | // ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2))) // ≤ 2**(2*e-4) / (3 * 2**(e-1)) // ≤ 2**(e-3) / 3 // ≤ 2**(e-3-log2(3)) // ≤ 2**(e-4.5) // // For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n: // ε_{n+1} = ε_n² / | (2 * x_n) | // ≤ (2**(e-k))² / (2 * 2**(e-1)) // ≤ 2**(2*e-2*k) / 2**e // ≤ 2**(e-2*k) xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5) -- special case, see above xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9) -- general case with k = 4.5 xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18) -- general case with k = 9 xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36) -- general case with k = 18 xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72) -- general case with k = 36 xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144) -- general case with k = 72 // Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision // ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either // sqrt(a) or sqrt(a) + 1. return xn - SafeCast.toUint(xn > a / xn); } } /** * @dev Calculates sqrt(a), following the selected rounding direction. */ function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = sqrt(a); return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a); } } /** * @dev Return the log in base 2 of a positive value rounded towards zero. * Returns 0 if given 0. */ function log2(uint256 value) internal pure returns (uint256) { uint256 result = 0; uint256 exp; unchecked { exp = 128 * SafeCast.toUint(value > (1 << 128) - 1); value >>= exp; result += exp; exp = 64 * SafeCast.toUint(value > (1 << 64) - 1); value >>= exp; result += exp; exp = 32 * SafeCast.toUint(value > (1 << 32) - 1); value >>= exp; result += exp; exp = 16 * SafeCast.toUint(value > (1 << 16) - 1); value >>= exp; result += exp; exp = 8 * SafeCast.toUint(value > (1 << 8) - 1); value >>= exp; result += exp; exp = 4 * SafeCast.toUint(value > (1 << 4) - 1); value >>= exp; result += exp; exp = 2 * SafeCast.toUint(value > (1 << 2) - 1); value >>= exp; result += exp; result += SafeCast.toUint(value > 1); } return result; } /** * @dev Return the log in base 2, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log2(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log2(value); return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value); } } /** * @dev Return the log in base 10 of a positive value rounded towards zero. * Returns 0 if given 0. */ function log10(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >= 10 ** 64) { value /= 10 ** 64; result += 64; } if (value >= 10 ** 32) { value /= 10 ** 32; result += 32; } if (value >= 10 ** 16) { value /= 10 ** 16; result += 16; } if (value >= 10 ** 8) { value /= 10 ** 8; result += 8; } if (value >= 10 ** 4) { value /= 10 ** 4; result += 4; } if (value >= 10 ** 2) { value /= 10 ** 2; result += 2; } if (value >= 10 ** 1) { result += 1; } } return result; } /** * @dev Return the log in base 10, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log10(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log10(value); return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value); } } /** * @dev Return the log in base 256 of a positive value rounded towards zero. * Returns 0 if given 0. * * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string. */ function log256(uint256 value) internal pure returns (uint256) { uint256 result = 0; uint256 isGt; unchecked { isGt = SafeCast.toUint(value > (1 << 128) - 1); value >>= isGt * 128; result += isGt * 16; isGt = SafeCast.toUint(value > (1 << 64) - 1); value >>= isGt * 64; result += isGt * 8; isGt = SafeCast.toUint(value > (1 << 32) - 1); value >>= isGt * 32; result += isGt * 4; isGt = SafeCast.toUint(value > (1 << 16) - 1); value >>= isGt * 16; result += isGt * 2; result += SafeCast.toUint(value > (1 << 8) - 1); } return result; } /** * @dev Return the log in base 256, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log256(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log256(value); return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value); } } /** * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers. */ function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) { return uint8(rounding) % 2 == 1; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol) // This file was procedurally generated from scripts/generate/templates/SafeCast.js. pragma solidity ^0.8.20; /** * @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeCast { /** * @dev Value doesn't fit in an uint of `bits` size. */ error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value); /** * @dev An int value doesn't fit in an uint of `bits` size. */ error SafeCastOverflowedIntToUint(int256 value); /** * @dev Value doesn't fit in an int of `bits` size. */ error SafeCastOverflowedIntDowncast(uint8 bits, int256 value); /** * @dev An uint value doesn't fit in an int of `bits` size. */ error SafeCastOverflowedUintToInt(uint256 value); /** * @dev Returns the downcasted uint248 from uint256, reverting on * overflow (when the input is greater than largest uint248). * * Counterpart to Solidity's `uint248` operator. * * Requirements: * * - input must fit into 248 bits */ function toUint248(uint256 value) internal pure returns (uint248) { if (value > type(uint248).max) { revert SafeCastOverflowedUintDowncast(248, value); } return uint248(value); } /** * @dev Returns the downcasted uint240 from uint256, reverting on * overflow (when the input is greater than largest uint240). * * Counterpart to Solidity's `uint240` operator. * * Requirements: * * - input must fit into 240 bits */ function toUint240(uint256 value) internal pure returns (uint240) { if (value > type(uint240).max) { revert SafeCastOverflowedUintDowncast(240, value); } return uint240(value); } /** * @dev Returns the downcasted uint232 from uint256, reverting on * overflow (when the input is greater than largest uint232). * * Counterpart to Solidity's `uint232` operator. * * Requirements: * * - input must fit into 232 bits */ function toUint232(uint256 value) internal pure returns (uint232) { if (value > type(uint232).max) { revert SafeCastOverflowedUintDowncast(232, value); } return uint232(value); } /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { if (value > type(uint224).max) { revert SafeCastOverflowedUintDowncast(224, value); } return uint224(value); } /** * @dev Returns the downcasted uint216 from uint256, reverting on * overflow (when the input is greater than largest uint216). * * Counterpart to Solidity's `uint216` operator. * * Requirements: * * - input must fit into 216 bits */ function toUint216(uint256 value) internal pure returns (uint216) { if (value > type(uint216).max) { revert SafeCastOverflowedUintDowncast(216, value); } return uint216(value); } /** * @dev Returns the downcasted uint208 from uint256, reverting on * overflow (when the input is greater than largest uint208). * * Counterpart to Solidity's `uint208` operator. * * Requirements: * * - input must fit into 208 bits */ function toUint208(uint256 value) internal pure returns (uint208) { if (value > type(uint208).max) { revert SafeCastOverflowedUintDowncast(208, value); } return uint208(value); } /** * @dev Returns the downcasted uint200 from uint256, reverting on * overflow (when the input is greater than largest uint200). * * Counterpart to Solidity's `uint200` operator. * * Requirements: * * - input must fit into 200 bits */ function toUint200(uint256 value) internal pure returns (uint200) { if (value > type(uint200).max) { revert SafeCastOverflowedUintDowncast(200, value); } return uint200(value); } /** * @dev Returns the downcasted uint192 from uint256, reverting on * overflow (when the input is greater than largest uint192). * * Counterpart to Solidity's `uint192` operator. * * Requirements: * * - input must fit into 192 bits */ function toUint192(uint256 value) internal pure returns (uint192) { if (value > type(uint192).max) { revert SafeCastOverflowedUintDowncast(192, value); } return uint192(value); } /** * @dev Returns the downcasted uint184 from uint256, reverting on * overflow (when the input is greater than largest uint184). * * Counterpart to Solidity's `uint184` operator. * * Requirements: * * - input must fit into 184 bits */ function toUint184(uint256 value) internal pure returns (uint184) { if (value > type(uint184).max) { revert SafeCastOverflowedUintDowncast(184, value); } return uint184(value); } /** * @dev Returns the downcasted uint176 from uint256, reverting on * overflow (when the input is greater than largest uint176). * * Counterpart to Solidity's `uint176` operator. * * Requirements: * * - input must fit into 176 bits */ function toUint176(uint256 value) internal pure returns (uint176) { if (value > type(uint176).max) { revert SafeCastOverflowedUintDowncast(176, value); } return uint176(value); } /** * @dev Returns the downcasted uint168 from uint256, reverting on * overflow (when the input is greater than largest uint168). * * Counterpart to Solidity's `uint168` operator. * * Requirements: * * - input must fit into 168 bits */ function toUint168(uint256 value) internal pure returns (uint168) { if (value > type(uint168).max) { revert SafeCastOverflowedUintDowncast(168, value); } return uint168(value); } /** * @dev Returns the downcasted uint160 from uint256, reverting on * overflow (when the input is greater than largest uint160). * * Counterpart to Solidity's `uint160` operator. * * Requirements: * * - input must fit into 160 bits */ function toUint160(uint256 value) internal pure returns (uint160) { if (value > type(uint160).max) { revert SafeCastOverflowedUintDowncast(160, value); } return uint160(value); } /** * @dev Returns the downcasted uint152 from uint256, reverting on * overflow (when the input is greater than largest uint152). * * Counterpart to Solidity's `uint152` operator. * * Requirements: * * - input must fit into 152 bits */ function toUint152(uint256 value) internal pure returns (uint152) { if (value > type(uint152).max) { revert SafeCastOverflowedUintDowncast(152, value); } return uint152(value); } /** * @dev Returns the downcasted uint144 from uint256, reverting on * overflow (when the input is greater than largest uint144). * * Counterpart to Solidity's `uint144` operator. * * Requirements: * * - input must fit into 144 bits */ function toUint144(uint256 value) internal pure returns (uint144) { if (value > type(uint144).max) { revert SafeCastOverflowedUintDowncast(144, value); } return uint144(value); } /** * @dev Returns the downcasted uint136 from uint256, reverting on * overflow (when the input is greater than largest uint136). * * Counterpart to Solidity's `uint136` operator. * * Requirements: * * - input must fit into 136 bits */ function toUint136(uint256 value) internal pure returns (uint136) { if (value > type(uint136).max) { revert SafeCastOverflowedUintDowncast(136, value); } return uint136(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { if (value > type(uint128).max) { revert SafeCastOverflowedUintDowncast(128, value); } return uint128(value); } /** * @dev Returns the downcasted uint120 from uint256, reverting on * overflow (when the input is greater than largest uint120). * * Counterpart to Solidity's `uint120` operator. * * Requirements: * * - input must fit into 120 bits */ function toUint120(uint256 value) internal pure returns (uint120) { if (value > type(uint120).max) { revert SafeCastOverflowedUintDowncast(120, value); } return uint120(value); } /** * @dev Returns the downcasted uint112 from uint256, reverting on * overflow (when the input is greater than largest uint112). * * Counterpart to Solidity's `uint112` operator. * * Requirements: * * - input must fit into 112 bits */ function toUint112(uint256 value) internal pure returns (uint112) { if (value > type(uint112).max) { revert SafeCastOverflowedUintDowncast(112, value); } return uint112(value); } /** * @dev Returns the downcasted uint104 from uint256, reverting on * overflow (when the input is greater than largest uint104). * * Counterpart to Solidity's `uint104` operator. * * Requirements: * * - input must fit into 104 bits */ function toUint104(uint256 value) internal pure returns (uint104) { if (value > type(uint104).max) { revert SafeCastOverflowedUintDowncast(104, value); } return uint104(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits */ function toUint96(uint256 value) internal pure returns (uint96) { if (value > type(uint96).max) { revert SafeCastOverflowedUintDowncast(96, value); } return uint96(value); } /** * @dev Returns the downcasted uint88 from uint256, reverting on * overflow (when the input is greater than largest uint88). * * Counterpart to Solidity's `uint88` operator. * * Requirements: * * - input must fit into 88 bits */ function toUint88(uint256 value) internal pure returns (uint88) { if (value > type(uint88).max) { revert SafeCastOverflowedUintDowncast(88, value); } return uint88(value); } /** * @dev Returns the downcasted uint80 from uint256, reverting on * overflow (when the input is greater than largest uint80). * * Counterpart to Solidity's `uint80` operator. * * Requirements: * * - input must fit into 80 bits */ function toUint80(uint256 value) internal pure returns (uint80) { if (value > type(uint80).max) { revert SafeCastOverflowedUintDowncast(80, value); } return uint80(value); } /** * @dev Returns the downcasted uint72 from uint256, reverting on * overflow (when the input is greater than largest uint72). * * Counterpart to Solidity's `uint72` operator. * * Requirements: * * - input must fit into 72 bits */ function toUint72(uint256 value) internal pure returns (uint72) { if (value > type(uint72).max) { revert SafeCastOverflowedUintDowncast(72, value); } return uint72(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { if (value > type(uint64).max) { revert SafeCastOverflowedUintDowncast(64, value); } return uint64(value); } /** * @dev Returns the downcasted uint56 from uint256, reverting on * overflow (when the input is greater than largest uint56). * * Counterpart to Solidity's `uint56` operator. * * Requirements: * * - input must fit into 56 bits */ function toUint56(uint256 value) internal pure returns (uint56) { if (value > type(uint56).max) { revert SafeCastOverflowedUintDowncast(56, value); } return uint56(value); } /** * @dev Returns the downcasted uint48 from uint256, reverting on * overflow (when the input is greater than largest uint48). * * Counterpart to Solidity's `uint48` operator. * * Requirements: * * - input must fit into 48 bits */ function toUint48(uint256 value) internal pure returns (uint48) { if (value > type(uint48).max) { revert SafeCastOverflowedUintDowncast(48, value); } return uint48(value); } /** * @dev Returns the downcasted uint40 from uint256, reverting on * overflow (when the input is greater than largest uint40). * * Counterpart to Solidity's `uint40` operator. * * Requirements: * * - input must fit into 40 bits */ function toUint40(uint256 value) internal pure returns (uint40) { if (value > type(uint40).max) { revert SafeCastOverflowedUintDowncast(40, value); } return uint40(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { if (value > type(uint32).max) { revert SafeCastOverflowedUintDowncast(32, value); } return uint32(value); } /** * @dev Returns the downcasted uint24 from uint256, reverting on * overflow (when the input is greater than largest uint24). * * Counterpart to Solidity's `uint24` operator. * * Requirements: * * - input must fit into 24 bits */ function toUint24(uint256 value) internal pure returns (uint24) { if (value > type(uint24).max) { revert SafeCastOverflowedUintDowncast(24, value); } return uint24(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { if (value > type(uint16).max) { revert SafeCastOverflowedUintDowncast(16, value); } return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits */ function toUint8(uint256 value) internal pure returns (uint8) { if (value > type(uint8).max) { revert SafeCastOverflowedUintDowncast(8, value); } return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { if (value < 0) { revert SafeCastOverflowedIntToUint(value); } return uint256(value); } /** * @dev Returns the downcasted int248 from int256, reverting on * overflow (when the input is less than smallest int248 or * greater than largest int248). * * Counterpart to Solidity's `int248` operator. * * Requirements: * * - input must fit into 248 bits */ function toInt248(int256 value) internal pure returns (int248 downcasted) { downcasted = int248(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(248, value); } } /** * @dev Returns the downcasted int240 from int256, reverting on * overflow (when the input is less than smallest int240 or * greater than largest int240). * * Counterpart to Solidity's `int240` operator. * * Requirements: * * - input must fit into 240 bits */ function toInt240(int256 value) internal pure returns (int240 downcasted) { downcasted = int240(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(240, value); } } /** * @dev Returns the downcasted int232 from int256, reverting on * overflow (when the input is less than smallest int232 or * greater than largest int232). * * Counterpart to Solidity's `int232` operator. * * Requirements: * * - input must fit into 232 bits */ function toInt232(int256 value) internal pure returns (int232 downcasted) { downcasted = int232(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(232, value); } } /** * @dev Returns the downcasted int224 from int256, reverting on * overflow (when the input is less than smallest int224 or * greater than largest int224). * * Counterpart to Solidity's `int224` operator. * * Requirements: * * - input must fit into 224 bits */ function toInt224(int256 value) internal pure returns (int224 downcasted) { downcasted = int224(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(224, value); } } /** * @dev Returns the downcasted int216 from int256, reverting on * overflow (when the input is less than smallest int216 or * greater than largest int216). * * Counterpart to Solidity's `int216` operator. * * Requirements: * * - input must fit into 216 bits */ function toInt216(int256 value) internal pure returns (int216 downcasted) { downcasted = int216(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(216, value); } } /** * @dev Returns the downcasted int208 from int256, reverting on * overflow (when the input is less than smallest int208 or * greater than largest int208). * * Counterpart to Solidity's `int208` operator. * * Requirements: * * - input must fit into 208 bits */ function toInt208(int256 value) internal pure returns (int208 downcasted) { downcasted = int208(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(208, value); } } /** * @dev Returns the downcasted int200 from int256, reverting on * overflow (when the input is less than smallest int200 or * greater than largest int200). * * Counterpart to Solidity's `int200` operator. * * Requirements: * * - input must fit into 200 bits */ function toInt200(int256 value) internal pure returns (int200 downcasted) { downcasted = int200(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(200, value); } } /** * @dev Returns the downcasted int192 from int256, reverting on * overflow (when the input is less than smallest int192 or * greater than largest int192). * * Counterpart to Solidity's `int192` operator. * * Requirements: * * - input must fit into 192 bits */ function toInt192(int256 value) internal pure returns (int192 downcasted) { downcasted = int192(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(192, value); } } /** * @dev Returns the downcasted int184 from int256, reverting on * overflow (when the input is less than smallest int184 or * greater than largest int184). * * Counterpart to Solidity's `int184` operator. * * Requirements: * * - input must fit into 184 bits */ function toInt184(int256 value) internal pure returns (int184 downcasted) { downcasted = int184(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(184, value); } } /** * @dev Returns the downcasted int176 from int256, reverting on * overflow (when the input is less than smallest int176 or * greater than largest int176). * * Counterpart to Solidity's `int176` operator. * * Requirements: * * - input must fit into 176 bits */ function toInt176(int256 value) internal pure returns (int176 downcasted) { downcasted = int176(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(176, value); } } /** * @dev Returns the downcasted int168 from int256, reverting on * overflow (when the input is less than smallest int168 or * greater than largest int168). * * Counterpart to Solidity's `int168` operator. * * Requirements: * * - input must fit into 168 bits */ function toInt168(int256 value) internal pure returns (int168 downcasted) { downcasted = int168(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(168, value); } } /** * @dev Returns the downcasted int160 from int256, reverting on * overflow (when the input is less than smallest int160 or * greater than largest int160). * * Counterpart to Solidity's `int160` operator. * * Requirements: * * - input must fit into 160 bits */ function toInt160(int256 value) internal pure returns (int160 downcasted) { downcasted = int160(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(160, value); } } /** * @dev Returns the downcasted int152 from int256, reverting on * overflow (when the input is less than smallest int152 or * greater than largest int152). * * Counterpart to Solidity's `int152` operator. * * Requirements: * * - input must fit into 152 bits */ function toInt152(int256 value) internal pure returns (int152 downcasted) { downcasted = int152(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(152, value); } } /** * @dev Returns the downcasted int144 from int256, reverting on * overflow (when the input is less than smallest int144 or * greater than largest int144). * * Counterpart to Solidity's `int144` operator. * * Requirements: * * - input must fit into 144 bits */ function toInt144(int256 value) internal pure returns (int144 downcasted) { downcasted = int144(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(144, value); } } /** * @dev Returns the downcasted int136 from int256, reverting on * overflow (when the input is less than smallest int136 or * greater than largest int136). * * Counterpart to Solidity's `int136` operator. * * Requirements: * * - input must fit into 136 bits */ function toInt136(int256 value) internal pure returns (int136 downcasted) { downcasted = int136(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(136, value); } } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits */ function toInt128(int256 value) internal pure returns (int128 downcasted) { downcasted = int128(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(128, value); } } /** * @dev Returns the downcasted int120 from int256, reverting on * overflow (when the input is less than smallest int120 or * greater than largest int120). * * Counterpart to Solidity's `int120` operator. * * Requirements: * * - input must fit into 120 bits */ function toInt120(int256 value) internal pure returns (int120 downcasted) { downcasted = int120(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(120, value); } } /** * @dev Returns the downcasted int112 from int256, reverting on * overflow (when the input is less than smallest int112 or * greater than largest int112). * * Counterpart to Solidity's `int112` operator. * * Requirements: * * - input must fit into 112 bits */ function toInt112(int256 value) internal pure returns (int112 downcasted) { downcasted = int112(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(112, value); } } /** * @dev Returns the downcasted int104 from int256, reverting on * overflow (when the input is less than smallest int104 or * greater than largest int104). * * Counterpart to Solidity's `int104` operator. * * Requirements: * * - input must fit into 104 bits */ function toInt104(int256 value) internal pure returns (int104 downcasted) { downcasted = int104(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(104, value); } } /** * @dev Returns the downcasted int96 from int256, reverting on * overflow (when the input is less than smallest int96 or * greater than largest int96). * * Counterpart to Solidity's `int96` operator. * * Requirements: * * - input must fit into 96 bits */ function toInt96(int256 value) internal pure returns (int96 downcasted) { downcasted = int96(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(96, value); } } /** * @dev Returns the downcasted int88 from int256, reverting on * overflow (when the input is less than smallest int88 or * greater than largest int88). * * Counterpart to Solidity's `int88` operator. * * Requirements: * * - input must fit into 88 bits */ function toInt88(int256 value) internal pure returns (int88 downcasted) { downcasted = int88(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(88, value); } } /** * @dev Returns the downcasted int80 from int256, reverting on * overflow (when the input is less than smallest int80 or * greater than largest int80). * * Counterpart to Solidity's `int80` operator. * * Requirements: * * - input must fit into 80 bits */ function toInt80(int256 value) internal pure returns (int80 downcasted) { downcasted = int80(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(80, value); } } /** * @dev Returns the downcasted int72 from int256, reverting on * overflow (when the input is less than smallest int72 or * greater than largest int72). * * Counterpart to Solidity's `int72` operator. * * Requirements: * * - input must fit into 72 bits */ function toInt72(int256 value) internal pure returns (int72 downcasted) { downcasted = int72(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(72, value); } } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits */ function toInt64(int256 value) internal pure returns (int64 downcasted) { downcasted = int64(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(64, value); } } /** * @dev Returns the downcasted int56 from int256, reverting on * overflow (when the input is less than smallest int56 or * greater than largest int56). * * Counterpart to Solidity's `int56` operator. * * Requirements: * * - input must fit into 56 bits */ function toInt56(int256 value) internal pure returns (int56 downcasted) { downcasted = int56(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(56, value); } } /** * @dev Returns the downcasted int48 from int256, reverting on * overflow (when the input is less than smallest int48 or * greater than largest int48). * * Counterpart to Solidity's `int48` operator. * * Requirements: * * - input must fit into 48 bits */ function toInt48(int256 value) internal pure returns (int48 downcasted) { downcasted = int48(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(48, value); } } /** * @dev Returns the downcasted int40 from int256, reverting on * overflow (when the input is less than smallest int40 or * greater than largest int40). * * Counterpart to Solidity's `int40` operator. * * Requirements: * * - input must fit into 40 bits */ function toInt40(int256 value) internal pure returns (int40 downcasted) { downcasted = int40(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(40, value); } } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits */ function toInt32(int256 value) internal pure returns (int32 downcasted) { downcasted = int32(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(32, value); } } /** * @dev Returns the downcasted int24 from int256, reverting on * overflow (when the input is less than smallest int24 or * greater than largest int24). * * Counterpart to Solidity's `int24` operator. * * Requirements: * * - input must fit into 24 bits */ function toInt24(int256 value) internal pure returns (int24 downcasted) { downcasted = int24(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(24, value); } } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits */ function toInt16(int256 value) internal pure returns (int16 downcasted) { downcasted = int16(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(16, value); } } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits */ function toInt8(int256 value) internal pure returns (int8 downcasted) { downcasted = int8(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(8, value); } } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive if (value > uint256(type(int256).max)) { revert SafeCastOverflowedUintToInt(value); } return int256(value); } /** * @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump. */ function toUint(bool b) internal pure returns (uint256 u) { assembly ("memory-safe") { u := iszero(iszero(b)) } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SignedMath.sol) pragma solidity ^0.8.20; import {SafeCast} from "./SafeCast.sol"; /** * @dev Standard signed math utilities missing in the Solidity language. */ library SignedMath { /** * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant. * * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone. * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute * one branch when needed, making this function more expensive. */ function ternary(bool condition, int256 a, int256 b) internal pure returns (int256) { unchecked { // branchless ternary works because: // b ^ (a ^ b) == a // b ^ 0 == b return b ^ ((a ^ b) * int256(SafeCast.toUint(condition))); } } /** * @dev Returns the largest of two signed numbers. */ function max(int256 a, int256 b) internal pure returns (int256) { return ternary(a > b, a, b); } /** * @dev Returns the smallest of two signed numbers. */ function min(int256 a, int256 b) internal pure returns (int256) { return ternary(a < b, a, b); } /** * @dev Returns the average of two signed numbers without overflow. * The result is rounded towards zero. */ function average(int256 a, int256 b) internal pure returns (int256) { // Formula from the book "Hacker's Delight" int256 x = (a & b) + ((a ^ b) >> 1); return x + (int256(uint256(x) >> 255) & (a ^ b)); } /** * @dev Returns the absolute unsigned value of a signed value. */ function abs(int256 n) internal pure returns (uint256) { unchecked { // Formula from the "Bit Twiddling Hacks" by Sean Eron Anderson. // Since `n` is a signed integer, the generated bytecode will use the SAR opcode to perform the right shift, // taking advantage of the most significant (or "sign" bit) in two's complement representation. // This opcode adds new most significant bits set to the value of the previous most significant bit. As a result, // the mask will either be `bytes32(0)` (if n is positive) or `~bytes32(0)` (if n is negative). int256 mask = n >> 255; // A `bytes32(0)` mask leaves the input unchanged, while a `~bytes32(0)` mask complements it. return uint256((n + mask) ^ mask); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol) pragma solidity ^0.8.20; /** * @dev Helper library for emitting standardized panic codes. * * ```solidity * contract Example { * using Panic for uint256; * * // Use any of the declared internal constants * function foo() { Panic.GENERIC.panic(); } * * // Alternatively * function foo() { Panic.panic(Panic.GENERIC); } * } * ``` * * Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil]. * * _Available since v5.1._ */ // slither-disable-next-line unused-state library Panic { /// @dev generic / unspecified error uint256 internal constant GENERIC = 0x00; /// @dev used by the assert() builtin uint256 internal constant ASSERT = 0x01; /// @dev arithmetic underflow or overflow uint256 internal constant UNDER_OVERFLOW = 0x11; /// @dev division or modulo by zero uint256 internal constant DIVISION_BY_ZERO = 0x12; /// @dev enum conversion error uint256 internal constant ENUM_CONVERSION_ERROR = 0x21; /// @dev invalid encoding in storage uint256 internal constant STORAGE_ENCODING_ERROR = 0x22; /// @dev empty array pop uint256 internal constant EMPTY_ARRAY_POP = 0x31; /// @dev array out of bounds access uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32; /// @dev resource error (too large allocation or too large array) uint256 internal constant RESOURCE_ERROR = 0x41; /// @dev calling invalid internal function uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51; /// @dev Reverts with a panic code. Recommended to use with /// the internal constants with predefined codes. function panic(uint256 code) internal pure { assembly ("memory-safe") { mstore(0x00, 0x4e487b71) mstore(0x20, code) revert(0x1c, 0x24) } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/Pausable.sol) pragma solidity ^0.8.20; import {Context} from "../utils/Context.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 Pausable is Context { bool private _paused; /** * @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. */ constructor() { _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) { 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 { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (utils/ShortStrings.sol) pragma solidity ^0.8.20; import {StorageSlot} from "./StorageSlot.sol"; // | string | 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA | // | length | 0x BB | type ShortString is bytes32; /** * @dev This library provides functions to convert short memory strings * into a `ShortString` type that can be used as an immutable variable. * * Strings of arbitrary length can be optimized using this library if * they are short enough (up to 31 bytes) by packing them with their * length (1 byte) in a single EVM word (32 bytes). Additionally, a * fallback mechanism can be used for every other case. * * Usage example: * * ```solidity * contract Named { * using ShortStrings for *; * * ShortString private immutable _name; * string private _nameFallback; * * constructor(string memory contractName) { * _name = contractName.toShortStringWithFallback(_nameFallback); * } * * function name() external view returns (string memory) { * return _name.toStringWithFallback(_nameFallback); * } * } * ``` */ library ShortStrings { // Used as an identifier for strings longer than 31 bytes. bytes32 private constant FALLBACK_SENTINEL = 0x00000000000000000000000000000000000000000000000000000000000000FF; error StringTooLong(string str); error InvalidShortString(); /** * @dev Encode a string of at most 31 chars into a `ShortString`. * * This will trigger a `StringTooLong` error is the input string is too long. */ function toShortString(string memory str) internal pure returns (ShortString) { bytes memory bstr = bytes(str); if (bstr.length > 31) { revert StringTooLong(str); } return ShortString.wrap(bytes32(uint256(bytes32(bstr)) | bstr.length)); } /** * @dev Decode a `ShortString` back to a "normal" string. */ function toString(ShortString sstr) internal pure returns (string memory) { uint256 len = byteLength(sstr); // using `new string(len)` would work locally but is not memory safe. string memory str = new string(32); assembly ("memory-safe") { mstore(str, len) mstore(add(str, 0x20), sstr) } return str; } /** * @dev Return the length of a `ShortString`. */ function byteLength(ShortString sstr) internal pure returns (uint256) { uint256 result = uint256(ShortString.unwrap(sstr)) & 0xFF; if (result > 31) { revert InvalidShortString(); } return result; } /** * @dev Encode a string into a `ShortString`, or write it to storage if it is too long. */ function toShortStringWithFallback(string memory value, string storage store) internal returns (ShortString) { if (bytes(value).length < 32) { return toShortString(value); } else { StorageSlot.getStringSlot(store).value = value; return ShortString.wrap(FALLBACK_SENTINEL); } } /** * @dev Decode a string that was encoded to `ShortString` or written to storage using {setWithFallback}. */ function toStringWithFallback(ShortString value, string storage store) internal pure returns (string memory) { if (ShortString.unwrap(value) != FALLBACK_SENTINEL) { return toString(value); } else { return store; } } /** * @dev Return the length of a string that was encoded to `ShortString` or written to storage using * {setWithFallback}. * * WARNING: This will return the "byte length" of the string. This may not reflect the actual length in terms of * actual characters as the UTF-8 encoding of a single character can span over multiple bytes. */ function byteLengthWithFallback(ShortString value, string storage store) internal view returns (uint256) { if (ShortString.unwrap(value) != FALLBACK_SENTINEL) { return byteLength(value); } else { return bytes(store).length; } } }
// 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/Strings.sol) pragma solidity ^0.8.20; import {Math} from "./math/Math.sol"; import {SignedMath} from "./math/SignedMath.sol"; /** * @dev String operations. */ library Strings { bytes16 private constant HEX_DIGITS = "0123456789abcdef"; uint8 private constant ADDRESS_LENGTH = 20; /** * @dev The `value` string doesn't fit in the specified `length`. */ error StringsInsufficientHexLength(uint256 value, uint256 length); /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { unchecked { uint256 length = Math.log10(value) + 1; string memory buffer = new string(length); uint256 ptr; assembly ("memory-safe") { ptr := add(buffer, add(32, length)) } while (true) { ptr--; assembly ("memory-safe") { mstore8(ptr, byte(mod(value, 10), HEX_DIGITS)) } value /= 10; if (value == 0) break; } return buffer; } } /** * @dev Converts a `int256` to its ASCII `string` decimal representation. */ function toStringSigned(int256 value) internal pure returns (string memory) { return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value))); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { unchecked { return toHexString(value, Math.log256(value) + 1); } } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { uint256 localValue = value; bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = HEX_DIGITS[localValue & 0xf]; localValue >>= 4; } if (localValue != 0) { revert StringsInsufficientHexLength(value, length); } return string(buffer); } /** * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal * representation. */ function toHexString(address addr) internal pure returns (string memory) { return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH); } /** * @dev Converts an `address` with fixed length of 20 bytes to its checksummed ASCII `string` hexadecimal * representation, according to EIP-55. */ function toChecksumHexString(address addr) internal pure returns (string memory) { bytes memory buffer = bytes(toHexString(addr)); // hash the hex part of buffer (skip length + 2 bytes, length 40) uint256 hashValue; assembly ("memory-safe") { hashValue := shr(96, keccak256(add(buffer, 0x22), 40)) } for (uint256 i = 41; i > 1; --i) { // possible values for buffer[i] are 48 (0) to 57 (9) and 97 (a) to 102 (f) if (hashValue & 0xf > 7 && uint8(buffer[i]) > 96) { // case shift by xoring with 0x20 buffer[i] ^= 0x20; } hashValue >>= 4; } return string(buffer); } /** * @dev Returns true if the two strings are equal. */ function equal(string memory a, string memory b) internal pure returns (bool) { return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b)); } }
// SPDX-License-Identifier: MIT pragma solidity =0.8.27; import { OwnableUpgradeable } from '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol'; import { ReentrancyGuardUpgradeable } from '@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol'; import { ERC20Upgradeable } from '@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol'; import { SafeERC20 } from '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; import { ERC20 } from '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import { SignedPayload } from 'contracts/helpers/EIP712Helper.sol'; import { SwapHelper } from 'contracts/helpers/SwapHelper.sol'; import { TransferHelper } from 'contracts/helpers/TransferHelper.sol'; import { Error } from 'contracts/lib/Error.sol'; import { FundAction } from 'contracts/lib/FundAction.sol'; import { InitialDeposit } from 'contracts/structs/InitialDeposit.sol'; import { DepositAmounts } from 'contracts/structs/DepositAmounts.sol'; import { WithdrawalAmounts } from 'contracts/structs/WithdrawalAmounts.sol'; import { FundFactory } from 'contracts/FundFactory.sol'; import { AssetIndex } from 'contracts/structs/AssetIndex.sol'; /** * @title GuruFund * @author @numa0x * @notice This is the contract for a GuruFund, which is a fund handled by a manager (Guru) that invests in a set of digital assets. * The fund is represented by a FundToken, which is minted to the Guru when the fund is created as well as to investors when they deposit. * - Implements 6-decimals ERC20 for fund tokens, representing the users' shares of the fund * - Implements cooldowns for ERC20 transfers to have users wait before withdrawing their funds * - Requires signed payloads for every key operations * - Funds support up to 8 ERC20 assets * - Tracks invested capital per user to accurately compute PnL and fees * - Uses nonce system to prevent outdated deposit transactions * - Has protocol-wide pause functionality */ contract GuruFund is ReentrancyGuardUpgradeable, OwnableUpgradeable, SwapHelper, ERC20Upgradeable, TransferHelper { using SafeERC20 for ERC20; /// Constants /// /** * @notice The duration of the grace period after the fund is closed. The protocol will * not allow any withdrawals after this period. */ uint256 public constant GRACE_PERIOD_DURATION = 180 days; uint256 public constant MAX_DEPOSIT_COOLDOWN = 90 days; uint256 public constant MANAGEMENT_FEE_PERIOD = 30 days; /** * @notice The denominator for the management fee mint amount. * Monthly rate denominator: * ------------------------------------------------------------ * Two percent yearly rate: 2/100 * * Pro-rated monthly: 1/12 * = 2/100 * 1/12 = 2/1200 = 1/600 * ------------------------------------------------------------ * So: if the minted amount needs to be 1/600 of the total supply AFTER the mint, * then we need to mint 1/599 of the total supply BEFORE the mint. */ uint256 public constant MANAGEMENT_FEE_DENOMINATOR = 599; /// States /// /** * @notice The factory that created this fund. */ FundFactory public immutable fundFactory; /** * @notice Whether the fund is open for deposits and withdrawals. */ bool public isOpen; /** * @notice The fund's assets */ ERC20[8] public assets; /** * @notice A nonce updated on every rebalance, to prevent users from * submitting deposits with outdated swaps. */ uint256 public nonce; /** * @notice The minimum deposit value for a user to deposit into the fund. */ uint256 public minUserDepositValue; /** * @notice The minimum time for a user to wait before withdrawing their deposit */ uint256 public minUserDepositCooldown; /** * @notice The timestamp of the last management fee mint */ uint256 public latestManagementFeeMint; /** * @notice The end of the grace period after the Guru closed the fund, users can * withdraw their funds up to this timestamp */ uint256 public gracePeriodEnd; /** * @notice The invested capital for each user. * @dev This is the sum of the positive TVL deltas during deposits, subtracted * of all capital removed through withdrawals. */ mapping(address => uint256) public investedCapital; /** * @notice The cooldowns of the users */ mapping(address => CooldownsByUser) private _cooldownsByUser; /** * @notice User deposit cooldown entry * @dev The offset is used to skip the cooldowns that have already been processed */ struct CooldownsByUser { uint256 offset; Cooldown[] cooldowns; } /** * @param timestamp The timestamp of the cooldown end * @param amount The amount of tokens that are still locked */ struct Cooldown { uint256 timestamp; uint256 amount; } /// Events /// /** * @notice Emitted when a deposit is made to the fund from a Disciple. * @param from The address of the Disciple * @param tvlDelta The TVL difference between the initial TVL and the final TVL * @param amountsWei The deposit amounts in wei units * @param amountsValue The deposit amounts in USDT units */ event Deposited( address indexed from, int256 tvlDelta, uint256 fundTokensMinted, DepositAmounts amountsWei, DepositAmounts amountsValue ); /** * @notice Emitted when an ERC20 asset is added into the fund by the Guru. * @param asset The asset deposited * @param amount The amount of the asset deposited * @param tvlDelta The TVL difference between the initial TVL and the final TVL */ event DepositedAsset(ERC20 asset, uint256 amount, int256 tvlDelta); /** * @notice Emitted when the assets of the fund are updated. * @param assets The updated list of assets */ event AssetsUpdated(ERC20[8] assets); /** * @notice Emitted when the fund is rebalanced. */ event Rebalanced(); /** * @notice Emitted when a user withdraws their share of the fund. * This will swap the assets back to ETH and return it to the user. * @param from The address of the user liquidating * @param burnAmount The amount of Fund tokens burned * @param amountsWei The withdrawal amounts in wei units * @param amountsValue The withdrawal amounts in USDT units * @param tvlDelta The TVL difference between the initial TVL and the final TVL */ event Withdrawn( address indexed from, uint256 burnAmount, WithdrawalAmounts amountsWei, WithdrawalAmounts amountsValue, int256 tvlDelta ); /** * @notice Emitted when the fund is closed by the Guru */ event Closed(); /** * @notice Emitted when the minimum deposit value for a user is updated. * @param newMinimum The new minimum deposit value */ event MinUserDepositValueUpdated(uint256 newMinimum); /** * @notice Emitted when the minimum deposit cooldown for a user is updated. * @param newMinimum The new minimum deposit cooldown */ event MinUserDepositCooldownUpdated(uint256 newMinimum); /** * @notice Emitted when the management fee is minted. * @param amount The amount of management fee minted */ event ManagementFeeMinted(uint256 amount); /** * @notice Emitted when the grace period is extended. * @param newGracePeriodEnd The new grace period end */ event GracePeriodExtended(uint256 newGracePeriodEnd); /** * @notice Emitted when the protocol owner claims remaining funds for buyback and burn */ event AbandonedFundsClaimed(); // errors error FundClosed(); error ProtocolHalted(); error UnexpectedFeeData( uint256 fees, uint256 maxExpectedFees, address feeRecipient ); error MaxCooldownExceeded(uint256 cooldown); error DepositMustIncreaseTvl(int256 tvlDelta); error InvalidDepositNonce(uint256 depositNonce, uint256 currentNonce); error InvalidSwapDirection(address tokenFrom, address tokenTo); error AssetIndexAlreadyOccupied(uint8 index, ERC20 assetAtIndex); error CooldownNotExpired(uint256 availableBalance, uint256 transferAmount); error InvalidTransferAmount( uint256 availableBalance, uint256 transferAmount ); error ManagementFeePeriodNotElapsed(); error GracePeriodEnded(); // modifiers modifier onlyOpen() { require(isOpen, FundClosed()); _; } modifier onlyNotPaused() { require(!fundFactory.paused(), ProtocolHalted()); _; } modifier verifyingSignature(SignedPayload calldata _payload) { fundFactory.verifySignature(msg.sender, _payload); _; } /** * @dev This will only be called once when deploying the Fund Factory. * Clones initializers will be called by the FundFactory. */ constructor() { fundFactory = FundFactory(msg.sender); _disableInitializers(); } /// External Functions /// /** * @notice Initializes the fund with a deposit of ETH, which is wrapped. * @dev Only the fund factory can call this function, after verifying the signature of the payload. * @param _guru The address of the Guru (owner) of the fund * @param _initialDeposit The initial deposit of the fund */ function initialize( address _guru, string calldata _name, string calldata _symbol, InitialDeposit calldata _initialDeposit ) external payable initializer { require(msg.sender == address(fundFactory), Error.Unauthorized()); require( _initialDeposit.minUserDepositCooldown <= MAX_DEPOSIT_COOLDOWN, MaxCooldownExceeded(_initialDeposit.minUserDepositCooldown) ); __SwapHelper_init_unchained( address(fundFactory.weth()), address(fundFactory.vault()) ); __Ownable_init_unchained(_guru); __ERC20_init_unchained(_name, _symbol); // Open the fund minUserDepositValue = _initialDeposit.minUserDepositValue; minUserDepositCooldown = _initialDeposit.minUserDepositCooldown; latestManagementFeeMint = block.timestamp; // Allows first mint in the next period isOpen = true; // Wrap the initial deposit net amount _wrapETH(msg.value - _initialDeposit.amountsWei.buybackFee); // Initialize the assets array with WETH assets[0] = ERC20(address(fundFactory.weth())); emit AssetsUpdated(assets); // Mint the fund tokens to the Guru _mint(_guru, _initialDeposit.amountsValue.input); // Update the invested capital investedCapital[_guru] = uint256(_initialDeposit.amountsValue.input); // Handle buyback and burn _safeTransferETH( fundFactory.guruBurner(), _initialDeposit.amountsWei.buybackFee ); emit Deposited( _guru, int256(_initialDeposit.amountsValue.input), // first ∆ TVL is the initial deposit value _initialDeposit.amountsValue.input, // first deposit mint amount matches its USDT value _initialDeposit.amountsWei, _initialDeposit.amountsValue ); } /** * @notice Gurus can call this function to directly deposit an asset into the fund. * @param _signedAssetDeposit The signed payload containing the asset to deposit */ function depositAsset( SignedPayload calldata _signedAssetDeposit ) external nonReentrant onlyOwner verifyingSignature(_signedAssetDeposit) { FundAction.AssetDeposit memory _deposit = abi.decode( _signedAssetDeposit.data, (FundAction.AssetDeposit) ); require( _deposit.tvlDelta >= 0, DepositMustIncreaseTvl(_deposit.tvlDelta) ); /// 1. Update asset index require( assets[_deposit.assetIndex] == ERC20(address(0)) || assets[_deposit.assetIndex] == _deposit.asset, AssetIndexAlreadyOccupied( _deposit.assetIndex, assets[_deposit.assetIndex] ) ); assets[_deposit.assetIndex] = _deposit.asset; /// 2. Transfer deposit in _deposit.asset.safeTransferFrom( msg.sender, address(this), _deposit.amount ); /// 3. Mint fund tokens _mint(msg.sender, _deposit.mintAmount); /// 4. Update invested capital investedCapital[msg.sender] += uint256(_deposit.tvlDelta); emit DepositedAsset(_deposit.asset, _deposit.amount, _deposit.tvlDelta); } /** * @notice Deposits ETH into the fund, which will get swapped and rebalanced * accordingly to the current fund composition. * @param _signedDepositPayload The signed payload containing the deposit data, * including the amount of ETH to deposit and the swaps to execute. */ function deposit( SignedPayload calldata _signedDepositPayload ) external payable nonReentrant onlyOpen onlyNotPaused verifyingSignature(_signedDepositPayload) { // Prevents management from accidentally depositing into any fund require(msg.sender != fundFactory.admin(), Error.Unauthorized()); FundAction.Deposit memory _deposit = abi.decode( _signedDepositPayload.data, (FundAction.Deposit) ); require( _deposit.nonce == nonce, InvalidDepositNonce(_deposit.nonce, nonce) ); require( _deposit.tvlDelta >= 0, DepositMustIncreaseTvl(_deposit.tvlDelta) ); /// 1. Validate fees and deposit amounts uint256 fees = _deposit.amountsWei.fee + _deposit.amountsWei.buybackFee; require( fees <= (msg.value * fundFactory.protocolDepositFee()) / 100_000 && _deposit.feeRecipient != address(0), UnexpectedFeeData( fees, fundFactory.protocolDepositFee(), _deposit.feeRecipient ) ); uint256 netDeposit = msg.value - fees; require( _deposit.amountsWei.input == netDeposit, Error.MismatchingDepositAmount(_deposit.amountsWei, netDeposit) ); /// 2. Wrap ETH _wrapETH(netDeposit); /// 3. Loop and swap _executeSwaps(_deposit.swaps); /// 4. Mint fund tokens _mint(msg.sender, _deposit.mintAmount); /// 5. Update invested capital investedCapital[msg.sender] += uint256(_deposit.tvlDelta); /// 6. Collect fees if (_deposit.amountsWei.fee > 0) { _safeTransferETH(_deposit.feeRecipient, _deposit.amountsWei.fee); } if (_deposit.amountsWei.buybackFee > 0) { _safeTransferETH( fundFactory.guruBurner(), _deposit.amountsWei.buybackFee ); } emit Deposited( msg.sender, _deposit.tvlDelta, _deposit.mintAmount, _deposit.amountsWei, _deposit.amountsValue ); } /** * @notice Swaps tokens for ETH. * @param _signedSwapPayload The signed payload containing the swap data */ function swapTokensForETH( SignedPayload calldata _signedSwapPayload ) external nonReentrant onlyOpen onlyNotPaused onlyOwner verifyingSignature(_signedSwapPayload) { FundAction.SingleSwap memory swapAction = abi.decode( _signedSwapPayload.data, (FundAction.SingleSwap) ); require( address(swapAction.swap.tokenOut) == address(fundFactory.weth()), InvalidSwapDirection( address(swapAction.swap.tokenIn), address(swapAction.swap.tokenOut) ) ); _executeSingleSwap(swapAction.swap); _updateAssets(swapAction.assetIndexes); unchecked { nonce++; } } /** * @notice Swaps ETH for tokens. * @param _signedSwapPayload The signed payload containing the swap data */ function swapETHForTokens( SignedPayload calldata _signedSwapPayload ) external nonReentrant onlyOpen onlyNotPaused onlyOwner verifyingSignature(_signedSwapPayload) { FundAction.SingleSwap memory swapAction = abi.decode( _signedSwapPayload.data, (FundAction.SingleSwap) ); require( address(swapAction.swap.tokenIn) == address(fundFactory.weth()), InvalidSwapDirection( address(swapAction.swap.tokenIn), address(swapAction.swap.tokenOut) ) ); _executeSingleSwap(swapAction.swap); _updateAssets(swapAction.assetIndexes); unchecked { nonce++; } } /** * @notice Rebalances the fund by changing the allocations of the assets. * @param _signedRebalancePayload The signed payload containing the rebalancing data, * including the changes to apply to the asset lists and the swaps to execute. */ function rebalance( SignedPayload calldata _signedRebalancePayload ) external nonReentrant onlyOpen onlyNotPaused onlyOwner verifyingSignature(_signedRebalancePayload) { FundAction.Rebalance memory _rebalance = abi.decode( _signedRebalancePayload.data, (FundAction.Rebalance) ); _updateAssets(_rebalance.assetIndexes); _executeSwaps(_rebalance.swaps); unchecked { nonce++; } emit Rebalanced(); } /** * @notice Withdraws the user's share of the fund, swapping the assets back to ETH. * @param _signedWithdrawPayload The signed payload containing the withdrawal data, */ function withdraw( SignedPayload calldata _signedWithdrawPayload ) external nonReentrant verifyingSignature(_signedWithdrawPayload) { if (!isOpen) { // Investors can withdraw only until the grace period ends require(block.timestamp <= gracePeriodEnd, GracePeriodEnded()); } FundAction.Withdraw memory _userWithdrawal = abi.decode( _signedWithdrawPayload.data, (FundAction.Withdraw) ); // 1. Burn tokens _burn(msg.sender, _userWithdrawal.burnAmount); // 2. Update invested capital unchecked { investedCapital[msg.sender] -= _userWithdrawal .amountsValue .investedCapital; } // 3. Execute swaps _executeSwaps(_userWithdrawal.swaps); // 4. Handle ETH transfers and fees _executeWithdrawalTransfers(_userWithdrawal.amountsWei); emit Withdrawn( msg.sender, _userWithdrawal.burnAmount, _userWithdrawal.amountsWei, _userWithdrawal.amountsValue, _userWithdrawal.tvlDelta ); } /** * @notice Executes the withdrawal transfers, including fees. * @param amountsWei The withdrawal amounts in wei units */ function _executeWithdrawalTransfers( WithdrawalAmounts memory amountsWei ) internal { if (amountsWei.grossPnl <= 0) { _unwrapETH(amountsWei.netOutput); } else { unchecked { _unwrapETH( amountsWei.netOutput + amountsWei.protocolFee + amountsWei.guruFee ); } _safeTransferETH(fundFactory.vault(), amountsWei.protocolFee); _safeTransferETH(owner(), amountsWei.guruFee); } _safeTransferETH(msg.sender, amountsWei.netOutput); } /** * @notice Mints the management fee to the admin. * @dev Only the management admin can call this function. */ function mintManagementFee() external onlyOpen onlyNotPaused { require(msg.sender == fundFactory.admin(), Error.Unauthorized()); require( block.timestamp - latestManagementFeeMint > MANAGEMENT_FEE_PERIOD, ManagementFeePeriodNotElapsed() ); uint256 amount = totalSupply() / MANAGEMENT_FEE_DENOMINATOR; _mint(fundFactory.admin(), amount); latestManagementFeeMint = block.timestamp; emit ManagementFeeMinted(amount); } /** * @notice Closes the fund, liquidating all assets. Users will be able to withdraw their capital. * @param _signedClosePayload The signed payload containing the close data */ function close( SignedPayload calldata _signedClosePayload ) external nonReentrant onlyOpen onlyOwner verifyingSignature(_signedClosePayload) { isOpen = false; gracePeriodEnd = block.timestamp + GRACE_PERIOD_DURATION; // Liquidate all assets FundAction.Close memory _liquidation = abi.decode( _signedClosePayload.data, (FundAction.Close) ); _executeSwaps(_liquidation.swaps); emit Closed(); } /** * @notice Extends the grace period. * @param _newGracePeriodEnd The new grace period end */ function extendGracePeriod(uint256 _newGracePeriodEnd) external { // Only protocol owner can extend the grace period require( msg.sender == fundFactory.owner() && _newGracePeriodEnd > gracePeriodEnd, Error.Unauthorized() ); gracePeriodEnd = _newGracePeriodEnd; emit GracePeriodExtended(_newGracePeriodEnd); } /** * @notice After the grace period ends, the protocol owner can claim any * remaining funds to buyback and burn $GURU. */ function claimAbandonedFundsForBuybackAndBurn() external { require( !isOpen && msg.sender == fundFactory.owner() && block.timestamp > gracePeriodEnd, Error.Unauthorized() ); _unwrapETH(fundFactory.weth().balanceOf(address(this))); _safeTransferETH(fundFactory.guruBurner(), address(this).balance); emit AbandonedFundsClaimed(); } /** * @notice Updates the minimum deposit value for a user. * @param _newMinValue The new minimum deposit value */ function updateMinUserDepositValue( uint256 _newMinValue ) external onlyOpen onlyOwner { minUserDepositValue = _newMinValue; emit MinUserDepositValueUpdated(_newMinValue); } /** * @notice Updates the minimum deposit cooldown for a user. * @param _newMinCooldown The new minimum deposit cooldown */ function updateMinDepositCooldown( uint256 _newMinCooldown ) external onlyOpen onlyOwner { require( _newMinCooldown <= MAX_DEPOSIT_COOLDOWN, MaxCooldownExceeded(_newMinCooldown) ); minUserDepositCooldown = _newMinCooldown; emit MinUserDepositCooldownUpdated(_newMinCooldown); } /** * @notice Returns the available balance for a user, i.e. the balance that is not cooling down. * @param _account The address of the user * @return availableBalance The available balance for the user */ function availableBalanceOf( address _account ) external view returns (uint256 availableBalance) { availableBalance = balanceOf(_account); if (hasCooldown(_account)) { (uint256 lockedBalance, ) = _getCooldownDetails(_account); availableBalance -= lockedBalance; } } /** * @notice Returns the assets of the fund. */ function getAssets() external view returns (ERC20[8] memory) { if (isOpen) { return assets; } else { ERC20[8] memory _assets; _assets[0] = ERC20(address(fundFactory.weth())); return _assets; } } /** * @notice Returns the cooldown details for a user. * @param _account The address of the user * @return cooldownDetails The cooldown details for the user */ function getCooldownByUser( address _account ) public view returns (CooldownsByUser memory) { return _cooldownsByUser[_account]; } /// Public Functions /// /** * @dev [ERC20] Using 6 decimals to match USDT precision */ function decimals() public pure override returns (uint8) { return 6; } /** * @notice Returns whether a user has a cooldown. * @param _account The address of the user * @return Whether the user has a cooldown */ function hasCooldown(address _account) public view returns (bool) { return _cooldownsByUser[_account].cooldowns.length > 0; } /** * @notice Disable direct token transfers */ function transfer(address, uint256) public pure override returns (bool) { revert Error.Unauthorized(); } /** * @notice Disable direct token transfers */ function transferFrom( address, address, uint256 ) public pure override returns (bool) { revert Error.Unauthorized(); } /** * @notice Transfers shares to another account updating the invested capital. * @param to The address of the recipient * @param amount The amount of shares to transfer * @return Whether the transfer was successful */ function transferShares(address to, uint256 amount) public returns (bool) { uint256 senderBalance = balanceOf(msg.sender); // Validate transfer amount require( senderBalance >= amount && amount != 0, InvalidTransferAmount(senderBalance, amount) ); // Update invested capital for both sender and recipient when transferring between accounts unchecked { // Transfer amount validation ensures arithmetic safety: cannot divide by zero uint256 capitalTransferred = (amount * investedCapital[msg.sender]) / senderBalance; // `capitalTransferred` is proportional to `amount`, which is capped to sender balance, // so it cannot exceed sender's invested capital investedCapital[msg.sender] -= capitalTransferred; investedCapital[to] += capitalTransferred; } _transfer(msg.sender, to, amount); return true; } /** * @notice Disable ownership renouncement */ function renounceOwnership() public pure override { revert Error.Unauthorized(); } /** * @notice Transfer ownership to a new address * @param newOwner The address of the new owner */ function transferOwnership(address newOwner) public override onlyOwner { require(newOwner != address(0), Error.Unauthorized()); uint256 ownerBalance = balanceOf(owner()); if (ownerBalance > 0) { transferShares(newOwner, ownerBalance); } _transferOwnership(newOwner); } /// Internal Functions /// /** * @dev Wraps ETH into WETH */ function _wrapETH(uint256 amount) internal { fundFactory.weth().deposit{ value: amount }(); } /** * @dev Unwraps WETH into ETH */ function _unwrapETH(uint256 amount) internal { fundFactory.weth().withdraw(amount); } /** * @dev Updates the fund asset list. * NOTE: Validation of these asset list updates is done off-chain * @param _updates The updates to apply */ function _updateAssets(AssetIndex[] memory _updates) internal { for (uint8 i = 0; i < _updates.length; i++) { assets[_updates[i].index] = _updates[i].asset; } emit AssetsUpdated(assets); } /** * @notice Returns the cooldown details for a user. * NOTE: this assumes that the user does have a cooldown, meaning: * `_cooldownsByUser[_user].cooldowns.length > 0` * @dev The offset represents the index before which all cooldowns have expired. * The loop is checking backwards, from the end of the cooldowns array (most * recent) to the beginning (earliest) and stopping when it finds a cooldown that * has eventually expired. This means that any previous cooldowns are also expired, * and we can update the offset with the current index. * @param account The address of the user * @return coolingDownBalance User balance that is still locked due to cooldown * @return offset The index offset of the cooldowns array, possibly to be updated in * the _cooldownsByUser struct: all cooldowns before this offset are expired. */ function _getCooldownDetails( address account ) internal view returns (uint256 coolingDownBalance, uint256 offset) { uint256 newOffset = _cooldownsByUser[account].cooldowns.length; offset = _cooldownsByUser[account].offset; while (newOffset > offset) { Cooldown memory _cooldown = _cooldownsByUser[account].cooldowns[ newOffset - 1 ]; if (block.timestamp <= _cooldown.timestamp) { unchecked { coolingDownBalance += _cooldown.amount; newOffset--; } } else { offset = newOffset; } } } /** * @dev [ERC20] Overrides the default ERC20 _update function to implement cooldown logic. * @param from The address of the user * @param to The address of the recipient * @param amount The amount of tokens to transfer */ function _update( address from, address to, uint256 amount ) internal override { if (isOpen) { if (from == address(0) && to != fundFactory.admin()) { // When minting tokens (except for management fee), apply cooldown: _cooldownsByUser[to].cooldowns.push( Cooldown({ timestamp: block.timestamp + minUserDepositCooldown, amount: amount }) ); } else if (hasCooldown(from)) { // Otherwise check cooldown for user: (uint256 lockedBalance, uint256 offset) = _getCooldownDetails( from ); // NOTE: lockedBalance is the amount of tokens that are still locked due to cooldown. // Therefore, the available balance for the user is: uint256 availableBalance = balanceOf(from) - lockedBalance; require( availableBalance >= amount, CooldownNotExpired(availableBalance, amount) ); if (offset == _cooldownsByUser[from].cooldowns.length) { delete _cooldownsByUser[from]; } else { _cooldownsByUser[from].offset = offset; } } } super._update(from, to, amount); } /** * @dev Allows contract to unwrap WETH */ receive() external payable {} }
// SPDX-License-Identifier: MIT pragma solidity =0.8.27; import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import '@openzeppelin/contracts/utils/cryptography/EIP712.sol'; import '@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol'; import 'contracts/lib/Error.sol'; import 'contracts/structs/SignedPayload.sol'; /// @title EIP712Helper: Verifies EIP712 signatures abstract contract EIP712Helper is EIP712, Ownable { address private signer; mapping(address => uint256) public noncesByUser; error InvalidSignature(); error ExpiredSignature(); event SignerUpdated(address signer); /** * @param _name Name of the signing domain. * @param _version Version of the signing domain. * @param _signer Signer */ constructor( string memory _name, string memory _version, address _signer ) EIP712(_name, _version) { _setOffchainSigner(_signer); } /** * @notice Get the off-chain signer * @return Signer address */ function getOffchainSigner() external view returns (address) { return signer; } /** * @notice Set the off-chain signer (only Owner) * @param _signer New signer */ function setOffchainSigner(address _signer) external onlyOwner { _setOffchainSigner(_signer); } /// @param _signer Signer function _setOffchainSigner(address _signer) internal { require( _signer != address(0) && signer != _signer, Error.InvalidAddress() ); signer = _signer; emit SignerUpdated(_signer); } /** * @dev Verifies the signature * @param _typeHash Type hash * @param _account Address of the user the signature was signed for * @param _payload Signed payload containing the data, signature and expiration */ function _verifyEIP712( bytes32 _typeHash, address _account, SignedPayload calldata _payload ) internal { require(_payload.expiresAt >= block.number, ExpiredSignature()); unchecked { require( SignatureChecker.isValidSignatureNow( signer, _hashTypedDataV4( keccak256( abi.encode( _typeHash, noncesByUser[_account]++, _account, keccak256(_payload.data), _payload.expiresAt ) ) ), _payload.signature ), InvalidSignature() ); } } }
// SPDX-License-Identifier: MIT pragma solidity =0.8.27; import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; import '@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol'; import 'contracts/structs/Swap.sol'; contract SwapHelper is Initializable { using SafeERC20 for ERC20; address public weth; address public feeCollector; function __SwapHelper_init_unchained( address _weth, address _feeCollector ) internal onlyInitializing { weth = _weth; feeCollector = _feeCollector; } event SwapExecuted( address indexed sender, address indexed tokenIn, address indexed tokenOut, uint256 amountSent, uint256 amountReceived, address router ); /** * @notice Execute the swaps in the provided order, based on the swap type and fee tier * @param _swaps The swaps to execute */ function _executeSwaps(Swap[] memory _swaps) internal { for (uint8 i = 0; i < _swaps.length; i++) { _executeSingleSwap(_swaps[i]); } } /** * @notice Executes a single swap. * @param _swap The swap to execute */ function _executeSingleSwap(Swap memory _swap) internal { uint256 tokenInBalanceBefore = _swap.tokenIn.balanceOf(address(this)); uint256 tokenOutBalanceBefore = _swap.tokenOut.balanceOf(address(this)); // Approve the router to spend the tokenIn _swap.tokenIn.forceApprove(address(_swap.router), _swap.amountToSend); // Forward the call to the router (bool success, bytes memory returnData) = _swap.router.call( _swap.callData ); require(success, string(returnData)); ERC20(weth).safeTransfer(feeCollector, _swap.swapFee); uint256 tokenInBalanceAfter = _swap.tokenIn.balanceOf(address(this)); uint256 tokenOutBalanceAfter = _swap.tokenOut.balanceOf(address(this)); emit SwapExecuted( msg.sender, address(_swap.tokenIn), address(_swap.tokenOut), tokenInBalanceBefore - tokenInBalanceAfter, tokenOutBalanceAfter - tokenOutBalanceBefore, _swap.router ); } }
// SPDX-License-Identifier: MIT pragma solidity =0.8.27; contract TransferHelper { mapping(address => uint256) creditByAddress; event CreditAdded(address indexed creditor, uint256 value); event CreditWithdrawn(address indexed recipient, uint256 value); error NativeTransferFailed(); /** * @notice Safe transfer of ETH to an address. If the transfer fails, the value is added to the credit of the address. * @param recipient The address to transfer ETH to * @param value The amount of ETH to transfer */ function _safeTransferETH(address recipient, uint256 value) internal { (bool success, ) = recipient.call{ value: value }(''); if (!success) { creditByAddress[recipient] += value; emit CreditAdded(recipient, value); } } /** * @notice Withdraws the caller's credit to the specified recipient. This transfer will either succeed or revert. * @param recipient The address to transfer the ETH to */ function withdrawCredit(address recipient) external { uint256 value = creditByAddress[msg.sender]; creditByAddress[msg.sender] = 0; (bool success, ) = recipient.call{ value: value }(''); require(success, NativeTransferFailed()); emit CreditWithdrawn(recipient, value); } }
/// SPDX-License-Identifier: MIT pragma solidity =0.8.27; interface IWETH { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function totalSupply() external view returns (uint); function approve(address spender, uint wad) external returns (bool); function transfer(address to, uint wad) external returns (bool); function transferFrom(address from, address to, uint wad) external returns (bool); function deposit() external payable; function withdraw(uint wad) external; event Approval(address indexed owner, address indexed spender, uint wad); event Transfer(address indexed from, address indexed to, uint wad); event Deposit(address indexed to, uint wad); event Withdrawal(address indexed from, uint wad); }
// SPDX-License-Identifier: MIT pragma solidity =0.8.27; import 'contracts/structs/DepositAmounts.sol'; library Error { error InvalidAddress(); error Unauthorized(); error MismatchingDepositAmount( DepositAmounts depositAmounts, uint256 msgValue ); }
// SPDX-License-Identifier: MIT pragma solidity =0.8.27; import { Swap } from 'contracts/structs/Swap.sol'; import { AssetIndex } from 'contracts/structs/AssetIndex.sol'; import { DepositAmounts } from 'contracts/structs/DepositAmounts.sol'; import { WithdrawalAmounts } from 'contracts/structs/WithdrawalAmounts.sol'; import { ERC20 } from '@openzeppelin/contracts/token/ERC20/ERC20.sol'; library FundAction { struct Deposit { /** * @notice The nonce at the time of the deposit */ uint256 nonce; /** * @notice Deposit amounts in wei units */ DepositAmounts amountsWei; /** * @notice Deposit amounts in USDT units */ DepositAmounts amountsValue; /** * @notice Swaps to be executed to maintain the fund allocations after deposit */ Swap[] swaps; /** * @notice The amount of Fund tokens to mint */ uint256 mintAmount; /** * @notice Either the vault or a referral address */ address feeRecipient; /** * @notice The difference in TVL between the initial TVL and the final TVL */ int256 tvlDelta; } struct AssetDeposit { /** * @notice The index of the asset to deposit */ uint8 assetIndex; /** * @notice The asset to deposit */ ERC20 asset; /** * @notice The amount of asset to deposit */ uint256 amount; /** * @notice The amount of Fund tokens to mint */ uint256 mintAmount; /** * @notice The difference in TVL between the initial TVL and the final TVL */ int256 tvlDelta; } struct Rebalance { /** * @notice Updates to the fund assets */ AssetIndex[] assetIndexes; /** * @notice Swaps to be executed to rebalance the fund allocations */ Swap[] swaps; } struct SingleSwap { /** * @notice The indexes of the assets to swap */ AssetIndex[] assetIndexes; /** * @notice The swap to execute */ Swap swap; } struct Withdraw { /** * @notice The amount of Fund tokens to burn */ uint256 burnAmount; /** * @notice Swaps to be executed to withdraw the position */ Swap[] swaps; /** * @notice The amounts in wei units */ WithdrawalAmounts amountsWei; /** * @notice The amounts in USDT units */ WithdrawalAmounts amountsValue; /** * @notice The difference in TVL between the initial TVL and the final TVL */ int256 tvlDelta; } struct Close { /** * @notice Swaps to be executed to liquidate the fund */ Swap[] swaps; } }
// SPDX-License-Identifier: MIT pragma solidity =0.8.27; import { ERC20 } from '@openzeppelin/contracts/token/ERC20/ERC20.sol'; /** * @notice Data structure including the index of the asset in the asset list and the new asset address */ struct AssetIndex { /** * @notice Index of the asset in the asset list */ uint8 index; /** * @notice Address of the new asset (0x0 to remove the asset at the index) */ ERC20 asset; }
// SPDX-License-Identifier: MIT pragma solidity =0.8.27; struct DepositAmounts { /** * @notice The raw amount input to the contract by the user */ uint256 input; /** * @notice Protocol fees either for project vault or referral */ uint256 fee; /** * @notice Fees to be used for buybacks and burn */ uint256 buybackFee; }
// SPDX-License-Identifier: MIT pragma solidity =0.8.27; import 'contracts/structs/DepositAmounts.sol'; struct InitialDeposit { /** * @notice Wei amounts of the deposit */ DepositAmounts amountsWei; /** * @notice Values in USDT units */ DepositAmounts amountsValue; /** * @notice Value of the min deposit in USDT units by the users */ uint256 minUserDepositValue; /** * @notice Minimum time for a user to wait before withdrawing their deposit */ uint256 minUserDepositCooldown; }
// SPDX-License-Identifier: MIT pragma solidity =0.8.27; struct SignedPayload { /** * @notice Encoded payload */ bytes data; /** * @notice Signature of the payload */ bytes signature; /** * @notice Expiration block number of the payload */ uint256 expiresAt; }
// SPDX-License-Identifier: MIT pragma solidity =0.8.27; import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; struct Swap { /** * @notice The address of the router to use for the swap */ address router; /** * @notice The encoded function call data for the swap */ bytes callData; /** * @notice The token to send */ ERC20 tokenIn; /** * @notice The token to receive */ ERC20 tokenOut; /** * @notice The amount of tokenIn, decoded for token approval */ uint256 amountToSend; /** * @notice The swap fee amount we apply to this swap */ uint256 swapFee; }
// SPDX-License-Identifier: MIT pragma solidity =0.8.27; struct WithdrawalAmounts { /** * @notice The withdrawn portion of the user's capital * that was invested in the fund */ uint256 investedCapital; /** * @notice The gross PNL: positive for profit, negative for loss */ int256 grossPnl; /** * @notice Guru's fee (0 if at loss) */ uint256 guruFee; /** * @notice The protocol fee (0 if at loss) */ uint256 protocolFee; /** * @notice The net amount of ETH received by the user. * In case of a profit: user will receive more than their invested capital, deducted of fee. * In case of a loss: fees will be zero but the user will receive less than their invested capital. * @dev netOutput = investedCapital + grossPnl - guruFee - protocolFee */ uint256 netOutput; }
{ "optimizer": { "enabled": true, "runs": 200 }, "evmVersion": "paris", "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "libraries": {} }
Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
Contract ABI
API[{"inputs":[{"internalType":"address","name":"_offchainSigner","type":"address"},{"internalType":"address","name":"_vault","type":"address"},{"internalType":"address","name":"_guruBurner","type":"address"},{"internalType":"address","name":"_admin","type":"address"},{"internalType":"contract IWETH","name":"_wethAddress","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"EnforcedPause","type":"error"},{"inputs":[],"name":"ExpectedPause","type":"error"},{"inputs":[],"name":"ExpiredSignature","type":"error"},{"inputs":[],"name":"FailedDeployment","type":"error"},{"inputs":[{"internalType":"uint256","name":"fee","type":"uint256"},{"internalType":"uint256","name":"max","type":"uint256"}],"name":"FeesTooHigh","type":"error"},{"inputs":[{"internalType":"uint256","name":"balance","type":"uint256"},{"internalType":"uint256","name":"needed","type":"uint256"}],"name":"InsufficientBalance","type":"error"},{"inputs":[{"internalType":"uint256","name":"received","type":"uint256"},{"internalType":"uint256","name":"required","type":"uint256"}],"name":"InsufficientFirstDeposit","type":"error"},{"inputs":[],"name":"InvalidAddress","type":"error"},{"inputs":[],"name":"InvalidShortString","type":"error"},{"inputs":[],"name":"InvalidSignature","type":"error"},{"inputs":[{"components":[{"internalType":"uint256","name":"input","type":"uint256"},{"internalType":"uint256","name":"fee","type":"uint256"},{"internalType":"uint256","name":"buybackFee","type":"uint256"}],"internalType":"struct DepositAmounts","name":"depositAmounts","type":"tuple"},{"internalType":"uint256","name":"msgValue","type":"uint256"}],"name":"MismatchingDepositAmount","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":[{"internalType":"string","name":"str","type":"string"}],"name":"StringTooLong","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"newAdmin","type":"address"}],"name":"AdminUpdated","type":"event"},{"anonymous":false,"inputs":[],"name":"EIP712DomainChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"fund","type":"address"},{"indexed":true,"internalType":"address","name":"creator","type":"address"}],"name":"FundCreated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"newGuruBurner","type":"address"}],"name":"GuruBurnerUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint64","name":"newMinimumInitialDeposit","type":"uint64"}],"name":"MinimumGuruInitialDepositValueUpdated","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":false,"internalType":"address","name":"account","type":"address"}],"name":"Paused","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint16","name":"newProtocolDepositFee","type":"uint16"}],"name":"ProtocolDepositFeeUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint64","name":"newProtocolFundCreationFee","type":"uint64"}],"name":"ProtocolFundCreationFeeUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint16","name":"newProtocolProfitFee","type":"uint16"}],"name":"ProtocolProfitFeeUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint16","name":"newProtocolSwapFee","type":"uint16"}],"name":"ProtocolSwapFeeUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint32","name":"newSignatureValidityPeriod","type":"uint32"}],"name":"SignatureValidityPeriodUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"signer","type":"address"}],"name":"SignerUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Unpaused","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"newVault","type":"address"}],"name":"VaultUpdated","type":"event"},{"inputs":[],"name":"FEE_DENOMINATOR","outputs":[{"internalType":"uint24","name":"","type":"uint24"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"GURU_PROFIT_FEE","outputs":[{"internalType":"uint16","name":"","type":"uint16"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MAX_DEPOSIT_FEE","outputs":[{"internalType":"uint16","name":"","type":"uint16"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MAX_PROFIT_FEE","outputs":[{"internalType":"uint16","name":"","type":"uint16"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MAX_SWAP_FEE","outputs":[{"internalType":"uint16","name":"","type":"uint16"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"SIGNED_ACTION_TYPEHASH","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"admin","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"_name","type":"string"},{"internalType":"string","name":"_symbol","type":"string"},{"components":[{"internalType":"bytes","name":"data","type":"bytes"},{"internalType":"bytes","name":"signature","type":"bytes"},{"internalType":"uint256","name":"expiresAt","type":"uint256"}],"internalType":"struct SignedPayload","name":"_signedPayload","type":"tuple"}],"name":"createFund","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"eip712Domain","outputs":[{"internalType":"bytes1","name":"fields","type":"bytes1"},{"internalType":"string","name":"name","type":"string"},{"internalType":"string","name":"version","type":"string"},{"internalType":"uint256","name":"chainId","type":"uint256"},{"internalType":"address","name":"verifyingContract","type":"address"},{"internalType":"bytes32","name":"salt","type":"bytes32"},{"internalType":"uint256[]","name":"extensions","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"fundImplementation","outputs":[{"internalType":"contract GuruFund","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getOffchainSigner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getTotalProfitFee","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"guruBurner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"minimumGuruInitialDepositValue","outputs":[{"internalType":"uint64","name":"","type":"uint64"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"noncesByUser","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"paused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"protocolDepositFee","outputs":[{"internalType":"uint16","name":"","type":"uint16"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"protocolFundCreationFeeValue","outputs":[{"internalType":"uint64","name":"","type":"uint64"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"protocolProfitFee","outputs":[{"internalType":"uint16","name":"","type":"uint16"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"protocolSwapFee","outputs":[{"internalType":"uint16","name":"","type":"uint16"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_newAdmin","type":"address"}],"name":"setAdmin","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_newGuruBurner","type":"address"}],"name":"setGuruBurner","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint64","name":"_newMinimum","type":"uint64"}],"name":"setMinimumFirstDepositValue","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_signer","type":"address"}],"name":"setOffchainSigner","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint16","name":"_newProtocolDepositFee","type":"uint16"}],"name":"setProtocolDepositFee","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint64","name":"_newProtocolFundCreationFee","type":"uint64"}],"name":"setProtocolFundCreationFee","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint16","name":"_newProtocolFeeOnProfits","type":"uint16"}],"name":"setProtocolProfitFee","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint16","name":"_newProtocolSwapFee","type":"uint16"}],"name":"setProtocolSwapFee","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint32","name":"_newSignatureValidityPeriod","type":"uint32"}],"name":"setSignatureValidityPeriod","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_newVault","type":"address"}],"name":"setVault","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"signatureValidityPeriod","outputs":[{"internalType":"uint32","name":"","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"unpause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"vault","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"components":[{"internalType":"bytes","name":"data","type":"bytes"},{"internalType":"bytes","name":"signature","type":"bytes"},{"internalType":"uint256","name":"expiresAt","type":"uint256"}],"internalType":"struct SignedPayload","name":"_signedPayload","type":"tuple"}],"name":"verifySignature","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"weth","outputs":[{"internalType":"contract IWETH","name":"","type":"address"}],"stateMutability":"view","type":"function"}]
Contract Creation Code
6101a060405260058054600160a81b600160f81b0319167dc803e813880000000a00000000000000000000000000000000000000000017905560068054600160a01b600160e01b031916621dcd6560a91b179055600780546305f5e1006001600160401b031990911617905534801561007757600080fd5b50604051617321380380617321833981016040819052610096916103f7565b604080518082018252600981526811d554954b9195539160ba1b60208083019190915282518084019093526006835265076302e312e360d41b9083015290863383836100e3826000610278565b610120526100f2816001610278565b61014052815160208084019190912060e052815190820120610100524660a05261017f60e05161010051604080517f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f60208201529081019290925260608201524660808201523060a082015260009060c00160405160208183030381529060405280519060200120905090565b60805250503060c0526001600160a01b0381166101b757604051631e4fbdf760e01b8152600060048201526024015b60405180910390fd5b6101c0816102ab565b506101ca816102fd565b5050600580546001600160a01b03808816610100026001600160a81b031990921691909117909155600680548683166001600160a01b031990911617905582811661016052600780549185166801000000000000000002600160401b600160e01b031990921691909117905550604051610243906103d2565b604051809103906000f08015801561025f573d6000803e3d6000fd5b506001600160a01b0316610180525061063b9350505050565b60006020835110156102945761028d83610394565b90506102a5565b8161029f848261050b565b5060ff90505b92915050565b600280546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b6001600160a01b0381161580159061032357506003546001600160a01b03828116911614155b6103405760405163e6c4247b60e01b815260040160405180910390fd5b600380546001600160a01b0319166001600160a01b0383169081179091556040519081527f5553331329228fbd4123164423717a4a7539f6dfa1c3279a923b98fd681a6c739060200160405180910390a150565b600080829050601f815111156103bf578260405163305a27a960e01b81526004016101ae91906105c9565b80516103ca82610617565b179392505050565b614f62806123bf83390190565b6001600160a01b03811681146103f457600080fd5b50565b600080600080600060a0868803121561040f57600080fd5b855161041a816103df565b602087015190955061042b816103df565b604087015190945061043c816103df565b606087015190935061044d816103df565b608087015190925061045e816103df565b809150509295509295909350565b634e487b7160e01b600052604160045260246000fd5b600181811c9082168061049657607f821691505b6020821081036104b657634e487b7160e01b600052602260045260246000fd5b50919050565b601f82111561050657806000526020600020601f840160051c810160208510156104e35750805b601f840160051c820191505b8181101561050357600081556001016104ef565b50505b505050565b81516001600160401b038111156105245761052461046c565b610538816105328454610482565b846104bc565b6020601f82116001811461056c57600083156105545750848201515b600019600385901b1c1916600184901b178455610503565b600084815260208120601f198516915b8281101561059c578785015182556020948501946001909201910161057c565b50848210156105ba5786840151600019600387901b60f8161c191681555b50505050600190811b01905550565b602081526000825180602084015260005b818110156105f757602081860181015160408684010152016105da565b506000604082850101526040601f19601f83011684010191505092915050565b805160208083015191908110156104b65760001960209190910360031b1b16919050565b60805160a05160c05160e0516101005161012051610140516101605161018051611d0d6106b2600039600081816102690152610c600152600061033101526000611120015260006110ee015260006114600152600061143801526000611393015260006113bd015260006113e70152611d0d6000f3fe6080604052600436106102305760003560e01c806384b0196e1161012e578063c6d87dd5116100ab578063f1b94cc91161006f578063f1b94cc9146106f6578063f2fde38b1461070c578063f851a4401461072c578063fbfa77cf14610753578063ffed81c31461077857600080fd5b8063c6d87dd514610662578063d056812d14610678578063d73792a914610698578063d84a7b4f146106c3578063d895ace2146106d657600080fd5b8063aa358dc1116100f2578063aa358dc1146105c9578063aad1f00a146105de578063ab3d85441461060b578063b06459b514610620578063b9c87e7d1461064257600080fd5b806384b0196e146105235780638d10d29d1461054b5780638da5cb5b1461056d578063987af2b61461058b578063a4af999d146105ab57600080fd5b806366dc898d116101bc578063715018a611610180578063715018a6146104975780637cd3d277146104ac5780637d95173a146104ce5780638456cb59146104ee5780638480ac421461050357600080fd5b806366dc898d146103de578063670fc207146103fe5780636817031b1461041e578063704b6c021461043e578063709563e21461045e57600080fd5b80633f4ba83a116102035780633f4ba83a1461030a5780633fc8cef31461031f57806349de54d3146103535780635c975abb1461039257806362ace683146103b557600080fd5b806304f81b11146102355780630b30767414610257578063139d99a1146102a85780631854dc7a146102c8575b600080fd5b34801561024157600080fd5b5061025561025036600461172c565b610798565b005b34801561026357600080fd5b5061028b7f000000000000000000000000000000000000000000000000000000000000000081565b6040516001600160a01b0390911681526020015b60405180910390f35b3480156102b457600080fd5b506102556102c336600461175f565b6107ac565b3480156102d457600080fd5b506102fc7f7a5e13c00d001fd24f434a2322118b8a340058f1abefa200fe4683e26bf103f081565b60405190815260200161029f565b34801561031657600080fd5b506102556107db565b34801561032b57600080fd5b5061028b7f000000000000000000000000000000000000000000000000000000000000000081565b34801561035f57600080fd5b5060065461037a90600160a01b90046001600160401b031681565b6040516001600160401b03909116815260200161029f565b34801561039e57600080fd5b5060055460ff16604051901515815260200161029f565b3480156103c157600080fd5b506103cb61271081565b60405161ffff909116815260200161029f565b3480156103ea57600080fd5b506102556103f93660046117ac565b6107ed565b34801561040a57600080fd5b506102556104193660046117d5565b610857565b34801561042a57600080fd5b5061025561043936600461172c565b610907565b34801561044a57600080fd5b5061025561045936600461172c565b610965565b34801561046a57600080fd5b5060055461048290600160a81b900463ffffffff1681565b60405163ffffffff909116815260200161029f565b3480156104a357600080fd5b506102556109cc565b3480156104b857600080fd5b506005546103cb90600160d81b900461ffff1681565b3480156104da57600080fd5b506102556104e93660046117d5565b6109de565b3480156104fa57600080fd5b50610255610a6e565b34801561050f57600080fd5b5061025561051e3660046117d5565b610a7e565b34801561052f57600080fd5b50610538610b0f565b60405161029f9796959493929190611849565b34801561055757600080fd5b506005546103cb90600160c81b900461ffff1681565b34801561057957600080fd5b506002546001600160a01b031661028b565b34801561059757600080fd5b5060065461028b906001600160a01b031681565b3480156105b757600080fd5b506003546001600160a01b031661028b565b3480156105d557600080fd5b506102fc610b55565b3480156105ea57600080fd5b506102fc6105f936600461172c565b60046020526000908152604090205481565b34801561061757600080fd5b506103cb60c881565b34801561062c57600080fd5b506005546103cb90600160e81b900461ffff1681565b34801561064e57600080fd5b5060075461037a906001600160401b031681565b34801561066e57600080fd5b506103cb6103e881565b34801561068457600080fd5b506102556106933660046118e1565b610b7b565b3480156106a457600080fd5b506106af620186a081565b60405162ffffff909116815260200161029f565b6102556106d136600461194f565b610bd7565b3480156106e257600080fd5b506102556106f13660046117ac565b610d2e565b34801561070257600080fd5b506103cb614e2081565b34801561071857600080fd5b5061025561072736600461172c565b610d85565b34801561073857600080fd5b5060075461028b90600160401b90046001600160a01b031681565b34801561075f57600080fd5b5060055461028b9061010090046001600160a01b031681565b34801561078457600080fd5b5061025561079336600461172c565b610dc0565b6107a0610e16565b6107a981610e43565b50565b6107d77f7a5e13c00d001fd24f434a2322118b8a340058f1abefa200fe4683e26bf103f08383610ed4565b5050565b6107e3610e16565b6107eb611006565b565b6107f5610e16565b6006805467ffffffffffffffff60a01b1916600160a01b6001600160401b038416908102919091179091556040519081527f488901414bff238cb14e4407dfb9e74841a2344ed3594b172eb1a55042f7e002906020015b60405180910390a150565b61085f610e16565b614e2061086e82612710611a02565b61ffff16111561088082612710611a02565b614e2090916108b557604051637db814ed60e11b815261ffff9283166004820152911660248201526044015b60405180910390fd5b50506005805461ffff60c81b1916600160c81b61ffff8416908102919091179091556040519081527feb2312e4985048cc5255947a02f69e0098b4e661fe3ba17df2982786c934800e9060200161084c565b61090f610e16565b60058054610100600160a81b0319166101006001600160a01b038416908102919091179091556040519081527f161584aed96e7f34998117c9ad67e2d21ff46d2a42775c22b11ed282f3c7b2cd9060200161084c565b61096d610e16565b6007805468010000000000000000600160e01b031916600160401b6001600160a01b038416908102919091179091556040519081527f54e4612788f90384e6843298d7854436f3a585b2c3831ab66abf1de63bfa6c2d9060200161084c565b6109d4610e16565b6107eb6000611058565b6109e6610e16565b8060c861ffff8216811015610a1c57604051637db814ed60e11b815261ffff9283166004820152911660248201526044016108ac565b50506005805461ffff60e81b1916600160e81b61ffff8416908102919091179091556040519081527f1736886ad28d8a9e6db70c1bd1594336b7a3f55e9484e9bbba56234499a5acb09060200161084c565b610a76610e16565b6107eb6110aa565b610a86610e16565b806103e861ffff8216811015610abd57604051637db814ed60e11b815261ffff9283166004820152911660248201526044016108ac565b50506005805461ffff60d81b1916600160d81b61ffff8416908102919091179091556040519081527f905b3cd2efc627e8c9527e9ce3df3010afcbedeaccdc0a645a159dabc844ffa49060200161084c565b600060608060008060006060610b236110e7565b610b2b611119565b60408051600080825260208201909252600f60f81b9b939a50919850469750309650945092509050565b600554600090610b7290600160c81b900461ffff16612710611a02565b61ffff16905090565b610b83610e16565b6005805463ffffffff60a81b1916600160a81b63ffffffff8416908102919091179091556040519081527fb2e40a35d8210676ab1f5c7f65cce5c19920db28fbddb8caf507b6ab9f3fbf0f9060200161084c565b610bdf611146565b610be933826107ac565b6000610bf58280611a1c565b810190610c029190611ac8565b8051604081015190519192503491610c1a9190611b4c565b825191349114610c57576040805162ec5dcb60e81b81528351600482015260208401516024820152920151604483015260648201526084016108ac565b50506000610c847f000000000000000000000000000000000000000000000000000000000000000061116a565b9050806001600160a01b031663906737e734338a8a8a8a896040518863ffffffff1660e01b8152600401610cbd96959493929190611b88565b6000604051808303818588803b158015610cd657600080fd5b505af1158015610cea573d6000803e3d6000fd5b50506040513393506001600160a01b03851692507f9de2be681a220396ec1518a4ecd6c853a760e34fb9174e9213d7aa5a8b12f3799150600090a350505050505050565b610d36610e16565b6007805467ffffffffffffffff19166001600160401b0383169081179091556040519081527f2d711c31560be95e9b50a0c2512e8e4a3b4029e1538745809d042e13f25841ca9060200161084c565b610d8d610e16565b6001600160a01b038116610db757604051631e4fbdf760e01b8152600060048201526024016108ac565b6107a981611058565b610dc8610e16565b600680546001600160a01b0319166001600160a01b0383169081179091556040519081527f0155b0dc5b332e364f3dc39ddc27990be72382e760585da8d99b334e0e3845159060200161084c565b6002546001600160a01b031633146107eb5760405163118cdaa760e01b81523360048201526024016108ac565b6001600160a01b03811615801590610e6957506003546001600160a01b03828116911614155b610e865760405163e6c4247b60e01b815260040160405180910390fd5b600380546001600160a01b0319166001600160a01b0383169081179091556040519081527f5553331329228fbd4123164423717a4a7539f6dfa1c3279a923b98fd681a6c739060200161084c565b4381604001351015610ef95760405163df4cc36d60e01b815260040160405180910390fd5b6003546001600160a01b038381166000908152600460205260409020805460018101909155610fe4929190911690610f9d90869086610f388780611a1c565b604051610f46929190611c27565b604080519182900382206020830195909552818101939093526001600160a01b039091166060820152608081019290925285013560a082015260c0016040516020818303038152906040528051906020012061117d565b610faa6020850185611a1c565b8080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152506111aa92505050565b61100157604051638baa579f60e01b815260040160405180910390fd5b505050565b61100e611221565b6005805460ff191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa335b6040516001600160a01b03909116815260200160405180910390a1565b600280546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b6110b2611146565b6005805460ff191660011790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a25861103b3390565b60606111147f00000000000000000000000000000000000000000000000000000000000000006000611244565b905090565b60606111147f00000000000000000000000000000000000000000000000000000000000000006001611244565b60055460ff16156107eb5760405163d93c066560e01b815260040160405180910390fd5b60006111778260006112f0565b92915050565b600061117761118a611386565b8360405161190160f01b8152600281019290925260228201526042902090565b6000836001600160a01b03163b60000361120c576000806111cb85856114b1565b50909250905060008160038111156111e5576111e5611c37565b1480156112035750856001600160a01b0316826001600160a01b0316145b9250505061121a565b6112178484846114fe565b90505b9392505050565b60055460ff166107eb57604051638dfc202b60e01b815260040160405180910390fd5b606060ff831461125e57611257836115da565b9050611177565b81805461126a90611c4d565b80601f016020809104026020016040519081016040528092919081815260200182805461129690611c4d565b80156112e35780601f106112b8576101008083540402835291602001916112e3565b820191906000526020600020905b8154815290600101906020018083116112c657829003601f168201915b5050505050905092915050565b60008147101561131c5760405163cf47918160e01b8152476004820152602481018390526044016108ac565b763d602d80600a3d3981f3363d3d373d3d3d363d730000008360601b60e81c176000526e5af43d82803e903d91602b57fd5bf38360781b176020526037600983f090506001600160a01b0381166111775760405163b06ebf3d60e01b815260040160405180910390fd5b6000306001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000161480156113df57507f000000000000000000000000000000000000000000000000000000000000000046145b1561140957507f000000000000000000000000000000000000000000000000000000000000000090565b611114604080517f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f60208201527f0000000000000000000000000000000000000000000000000000000000000000918101919091527f000000000000000000000000000000000000000000000000000000000000000060608201524660808201523060a082015260009060c00160405160208183030381529060405280519060200120905090565b600080600083516041036114eb5760208401516040850151606086015160001a6114dd88828585611619565b9550955095505050506114f7565b50508151600091506002905b9250925092565b6000806000856001600160a01b03168585604051602401611520929190611c81565b60408051601f198184030181529181526020820180516001600160e01b0316630b135d3f60e11b179052516115559190611ca2565b600060405180830381855afa9150503d8060008114611590576040519150601f19603f3d011682016040523d82523d6000602084013e611595565b606091505b50915091508180156115a957506020815110155b80156115d057508051630b135d3f60e11b906115ce9083016020908101908401611cbe565b145b9695505050505050565b606060006115e7836116e8565b604080516020808252818301909252919250600091906020820181803683375050509182525060208101929092525090565b600080807f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a084111561165457506000915060039050826116de565b604080516000808252602082018084528a905260ff891692820192909252606081018790526080810186905260019060a0016020604051602081039080840390855afa1580156116a8573d6000803e3d6000fd5b5050604051601f1901519150506001600160a01b0381166116d4575060009250600191508290506116de565b9250600091508190505b9450945094915050565b600060ff8216601f81111561117757604051632cd44ac360e21b815260040160405180910390fd5b80356001600160a01b038116811461172757600080fd5b919050565b60006020828403121561173e57600080fd5b61121a82611710565b60006060828403121561175957600080fd5b50919050565b6000806040838503121561177257600080fd5b61177b83611710565b915060208301356001600160401b0381111561179657600080fd5b6117a285828601611747565b9150509250929050565b6000602082840312156117be57600080fd5b81356001600160401b038116811461121a57600080fd5b6000602082840312156117e757600080fd5b813561ffff8116811461121a57600080fd5b60005b838110156118145781810151838201526020016117fc565b50506000910152565b600081518084526118358160208601602086016117f9565b601f01601f19169290920160200192915050565b60ff60f81b8816815260e06020820152600061186860e083018961181d565b828103604084015261187a818961181d565b606084018890526001600160a01b038716608085015260a0840186905283810360c08501528451808252602080870193509091019060005b818110156118d05783518352602093840193909201916001016118b2565b50909b9a5050505050505050505050565b6000602082840312156118f357600080fd5b813563ffffffff8116811461121a57600080fd5b60008083601f84011261191957600080fd5b5081356001600160401b0381111561193057600080fd5b60208301915083602082850101111561194857600080fd5b9250929050565b60008060008060006060868803121561196757600080fd5b85356001600160401b0381111561197d57600080fd5b61198988828901611907565b90965094505060208601356001600160401b038111156119a857600080fd5b6119b488828901611907565b90945092505060408601356001600160401b038111156119d357600080fd5b6119df88828901611747565b9150509295509295909350565b634e487b7160e01b600052601160045260246000fd5b61ffff8181168382160190811115611177576111776119ec565b6000808335601e19843603018112611a3357600080fd5b8301803591506001600160401b03821115611a4d57600080fd5b60200191503681900382131561194857600080fd5b600060608284031215611a7457600080fd5b604051606081016001600160401b0381118282101715611aa457634e487b7160e01b600052604160045260246000fd5b60409081528335825260208085013590830152928301359281019290925250919050565b6000610100828403128015611adc57600080fd5b50604051600090608081016001600160401b0381118282101715611b0e57634e487b7160e01b83526041600452602483fd5b604052611b1b8585611a62565b8152611b2a8560608601611a62565b602082015260c0840135604082015260e0909301356060840152509092915050565b80820180821115611177576111776119ec565b81835281816020850137506000828201602090810191909152601f909101601f19169091010190565b6001600160a01b038716815261016060208201819052600090611bae9083018789611b5f565b8281036040840152611bc1818688611b5f565b845180516060860152602081015160808601526040015160a08501529150611be69050565b602083810151805160c08501529081015160e08401526040908101516101008401528301516101208301526060909201516101409091015295945050505050565b8183823760009101908152919050565b634e487b7160e01b600052602160045260246000fd5b600181811c90821680611c6157607f821691505b60208210810361175957634e487b7160e01b600052602260045260246000fd5b828152604060208201526000611c9a604083018461181d565b949350505050565b60008251611cb48184602087016117f9565b9190910192915050565b600060208284031215611cd057600080fd5b505191905056fea264697066735822122098eedaba7f8f04cb0b2e00015e50e386d94dd401f7a23ec4ebf0fdd34e35b4b464736f6c634300081b003360a060405234801561001057600080fd5b503360805261001d610022565b6100d4565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00805468010000000000000000900460ff16156100725760405163f92ee8a960e01b815260040160405180910390fd5b80546001600160401b03908116146100d15780546001600160401b0319166001600160401b0390811782556040519081527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b50565b608051614d856101dd600039600081816104b70152818161095801528181610a9801528181610b5701528181610be001528181610e5901528181610ef901528181611017015281816110e1015281816111a401528181611298015281816113a40152818161146101528181611520015281816115a901528181611793015281816118ee015281816119ad01528181611c3401528181611ca301528181611d2501528181611e5f01528181611f7b015281816120f8015281816124610152818161251801528181612583015281816126c3015281816127790152818161291701528181612a380152818161314d015281816134610152818161361001526138f50152614d856000f3fe6080604052600436106102815760003560e01c80636c8cc9d91161014f578063a9059cbb116100c1578063cf35bdd01161007a578063cf35bdd01461078b578063dae2a76c146107ab578063dd62ed3e146107c1578063e6b4d21c14610826578063eb3b7fd814610839578063f2fde38b1461085957600080fd5b8063a9059cbb146106e0578063affed0e0146106fb578063b5adcc5414610711578063bbc18f6f1461073e578063c415b95c14610755578063ce6772351461077557600080fd5b80638da5cb5b116101135780638da5cb5b1461064c5780638fcb4e5b14610661578063906737e71461068157806395d89b411461069457806399e89a3c146106a95780639c8cebf1146106c057600080fd5b80636c8cc9d9146105b7578063700f2c58146105d757806370a08231146105f7578063715018a6146106175780638610d2a41461062c57600080fd5b80632fa45fe8116101f3578063413f6f59116101ac578063413f6f591461051157806347535d7b146105315780635ded93211461054b5780636768dc321461056057806367e4ac2c146105755780636a17b0221461059757600080fd5b80632fa45fe814610446578063313ce5671461045d578063334dcfee146104795780633ad0e5c11461048f5780633dea9e66146104a55780633fc8cef3146104f157600080fd5b806323b872dd1161024557806323b872dd1461037557806325c1a4dd1461039557806325d998bb146103b55780632cd522fc146103d55780632dd19bed146103eb5780632f2060681461040b57600080fd5b806306fdde031461028d578063095ea7b3146102b85780630af3af0a146102e857806318160ddd1461030a5780631efc751b1461034857600080fd5b3661028857005b600080fd5b34801561029957600080fd5b506102a2610879565b6040516102af9190613dbc565b60405180910390f35b3480156102c457600080fd5b506102d86102d3366004613e0f565b61093c565b60405190151581526020016102af565b3480156102f457600080fd5b50610308610303366004613e3b565b610956565b005b34801561031657600080fd5b507f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace02545b6040519081526020016102af565b34801561035457600080fd5b5061033a610363366004613e54565b60116020526000908152604090205481565b34801561038157600080fd5b506102d8610390366004613e78565b610a51565b3480156103a157600080fd5b506103086103b0366004613eb9565b610a6b565b3480156103c157600080fd5b5061033a6103d0366004613e54565b610cf4565b3480156103e157600080fd5b5061033a600f5481565b3480156103f757600080fd5b50610308610406366004613e3b565b610d4b565b34801561041757600080fd5b506102d8610426366004613e54565b6001600160a01b0316600090815260126020526040902060010154151590565b34801561045257600080fd5b5061033a6276a70081565b34801561046957600080fd5b50604051600681526020016102af565b34801561048557600080fd5b5061033a600e5481565b34801561049b57600080fd5b5061033a600d5481565b3480156104b157600080fd5b506104d97f000000000000000000000000000000000000000000000000000000000000000081565b6040516001600160a01b0390911681526020016102af565b3480156104fd57600080fd5b506000546104d9906001600160a01b031681565b34801561051d57600080fd5b5061030861052c366004613e3b565b610dd4565b34801561053d57600080fd5b506003546102d89060ff1681565b34801561055757600080fd5b50610308610e34565b34801561056c57600080fd5b506103086110d1565b34801561058157600080fd5b5061058a611349565b6040516102af9190613ef3565b3480156105a357600080fd5b506103086105b2366004613eb9565b611434565b3480156105c357600080fd5b506103086105d2366004613e54565b611678565b3480156105e357600080fd5b506103086105f2366004613eb9565b611747565b34801561060357600080fd5b5061033a610612366004613e54565b611881565b34801561062357600080fd5b506103086118a9565b34801561063857600080fd5b50610308610647366004613eb9565b6118c1565b34801561065857600080fd5b506104d9611a99565b34801561066d57600080fd5b506102d861067c366004613e0f565b611ac7565b61030861068f366004613f76565b611b72565b3480156106a057600080fd5b506102a2612090565b3480156106b557600080fd5b5061033a62278d0081565b3480156106cc57600080fd5b506103086106db366004613eb9565b6120cf565b3480156106ec57600080fd5b506102d8610390366004613e0f565b34801561070757600080fd5b5061033a600c5481565b34801561071d57600080fd5b5061073161072c366004613e54565b612360565b6040516102af9190614018565b34801561074a57600080fd5b5061033a62ed4e0081565b34801561076157600080fd5b506001546104d9906001600160a01b031681565b34801561078157600080fd5b5061033a61025781565b34801561079757600080fd5b506104d96107a6366004613e3b565b612414565b3480156107b757600080fd5b5061033a60105481565b3480156107cd57600080fd5b5061033a6107dc366004614080565b6001600160a01b0391821660009081527f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace016020908152604080832093909416825291909152205490565b610308610834366004613eb9565b612434565b34801561084557600080fd5b50610308610854366004613eb9565b612a17565b34801561086557600080fd5b50610308610874366004613e54565b612b99565b7f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace038054606091600080516020614d10833981519152916108b8906140b9565b80601f01602080910402602001604051908101604052809291908181526020018280546108e4906140b9565b80156109315780601f1061090657610100808354040283529160200191610931565b820191906000526020600020905b81548152906001019060200180831161091457829003601f168201915b505050505091505090565b60003361094a818585612bf5565b60019150505b92915050565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316638da5cb5b6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156109b4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109d891906140f3565b6001600160a01b0316336001600160a01b03161480156109f9575060105481115b610a15576040516282b42960e81b815260040160405180910390fd5b60108190556040518181527f9811c28c9a13f1919200fd56ce5e849d33a25e9e693b76292ad3df46937c9aed906020015b60405180910390a150565b60006040516282b42960e81b815260040160405180910390fd5b610a73612c07565b60035460ff16610a9657604051630bc4868d60e11b815260040160405180910390fd5b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316635c975abb6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610af4573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b189190614110565b15610b365760405163d69df31760e01b815260040160405180910390fd5b610b3e612c3f565b60405163139d99a160e01b815281906001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063139d99a190610b8e90339085906004016141a0565b600060405180830381600087803b158015610ba857600080fd5b505af1158015610bbc573d6000803e3d6000fd5b5060009250610bcf915084905080614216565b810190610bdc91906144ef565b90507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316633fc8cef36040518163ffffffff1660e01b8152600401602060405180830381865afa158015610c3c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c6091906140f3565b6020820151604081015160609091015190916001600160a01b03838116911614610cb557604051637bed389160e01b81526001600160a01b039283166004820152911660248201526044015b60405180910390fd5b5050610cc48160200151612c73565b8051610ccf90612f8c565b5050600c80546001019055610cf16001600080516020614d3083398151915255565b50565b6000610cff82611881565b9050610d25826001600160a01b0316600090815260126020526040902060010154151590565b15610d46576000610d3583613054565b509050610d42818361459f565b9150505b919050565b60035460ff16610d6e57604051630bc4868d60e11b815260040160405180910390fd5b610d76612c3f565b806276a700811115610d9e576040516372c50e0d60e11b8152600401610cac91815260200190565b50600e8190556040518181527f0b322229f2d3dfa405aa31c93977d24557d0810957ba17ac4ca950b93ba077c690602001610a46565b60035460ff16610df757604051630bc4868d60e11b815260040160405180910390fd5b610dff612c3f565b600d8190556040518181527f08bfea04f54ad359c30eeb68a7490abf15d5cf22d91a1279f3b26768b77717fb90602001610a46565b60035460ff16610e5757604051630bc4868d60e11b815260040160405180910390fd5b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316635c975abb6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610eb5573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ed99190614110565b15610ef75760405163d69df31760e01b815260040160405180910390fd5b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663f851a4406040518163ffffffff1660e01b8152600401602060405180830381865afa158015610f55573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f7991906140f3565b6001600160a01b0316336001600160a01b031614610fa9576040516282b42960e81b815260040160405180910390fd5b62278d00600f5442610fbb919061459f565b11610fd95760405163248fb7ff60e01b815260040160405180910390fd5b60006102576110067f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace025490565b61101091906145c8565b905061109d7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663f851a4406040518163ffffffff1660e01b8152600401602060405180830381865afa158015611073573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061109791906140f3565b82613115565b42600f556040518181527f41c725bc51912ad4b67c601410606bf7ec3aa627cd30eaab4c91c77e576ceb5f90602001610a46565b60035460ff1615801561117657507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316638da5cb5b6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561113d573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061116191906140f3565b6001600160a01b0316336001600160a01b0316145b8015611183575060105442115b61119f576040516282b42960e81b815260040160405180910390fd5b6112937f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316633fc8cef36040518163ffffffff1660e01b8152600401602060405180830381865afa158015611200573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061122491906140f3565b6040516370a0823160e01b81523060048201526001600160a01b0391909116906370a0823190602401602060405180830381865afa15801561126a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061128e91906145ea565b61314b565b61131e7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663987af2b66040518163ffffffff1660e01b8152600401602060405180830381865afa1580156112f4573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061131891906140f3565b4761322f565b6040517fa0b4c7abcd59421dd308af86eb655a256def5dfd3cd36e98c440a826461db6f690600090a1565b611351613d3e565b60035460ff161561139a57604080516101008101918290529060049060089082845b81546001600160a01b03168152600190910190602001808311611373575050505050905090565b6113a2613d3e565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316633fc8cef36040518163ffffffff1660e01b8152600401602060405180830381865afa158015611400573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061142491906140f3565b6001600160a01b03168152919050565b61143c612c07565b60035460ff1661145f57604051630bc4868d60e11b815260040160405180910390fd5b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316635c975abb6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156114bd573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906114e19190614110565b156114ff5760405163d69df31760e01b815260040160405180910390fd5b611507612c3f565b60405163139d99a160e01b815281906001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063139d99a19061155790339085906004016141a0565b600060405180830381600087803b15801561157157600080fd5b505af1158015611585573d6000803e3d6000fd5b5060009250611598915084905080614216565b8101906115a591906144ef565b90507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316633fc8cef36040518163ffffffff1660e01b8152600401602060405180830381865afa158015611605573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061162991906140f3565b60208201516060810151604090910151916001600160a01b03828116911614610cb557604051637bed389160e01b81526001600160a01b03928316600482015291166024820152604401610cac565b3360009081526002602052604080822080549083905590519091906001600160a01b0384169083908381818185875af1925050503d80600081146116d8576040519150601f19603f3d011682016040523d82523d6000602084013e6116dd565b606091505b50509050806116ff57604051633d2cec6f60e21b815260040160405180910390fd5b826001600160a01b03167f6b00960292e7976c9eb5434816470b38a441061eee645921536131ccb937cafe8360405161173a91815260200190565b60405180910390a2505050565b61174f612c07565b60035460ff1661177257604051630bc4868d60e11b815260040160405180910390fd5b61177a612c3f565b60405163139d99a160e01b815281906001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063139d99a1906117ca90339085906004016141a0565b600060405180830381600087803b1580156117e457600080fd5b505af11580156117f8573d6000803e3d6000fd5b50506003805460ff1916905550611814905062ed4e0042614619565b60105560006118238380614216565b81019061183091906146ae565b905061183f81600001516132f2565b6040517f1cdde67b72a90f19919ac732a437ac2f7a10fc128d28c2a6e525d89ce5cd9d3a90600090a15050610cf16001600080516020614d3083398151915255565b6001600160a01b03166000908152600080516020614d10833981519152602052604090205490565b6040516282b42960e81b815260040160405180910390fd5b6118c9612c07565b60035460ff166118ec57604051630bc4868d60e11b815260040160405180910390fd5b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316635c975abb6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561194a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061196e9190614110565b1561198c5760405163d69df31760e01b815260040160405180910390fd5b611994612c3f565b60405163139d99a160e01b815281906001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063139d99a1906119e490339085906004016141a0565b600060405180830381600087803b1580156119fe57600080fd5b505af1158015611a12573d6000803e3d6000fd5b5060009250611a25915084905080614216565b810190611a32919061473a565b9050611a418160000151612f8c565b611a4e81602001516132f2565b600c805460010190556040517fc741dbaad15a4f298fe8d80943fa8e005e7bcb2f5b0a0c8dec1fc35be457f14690600090a15050610cf16001600080516020614d3083398151915255565b7f9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300546001600160a01b031690565b600080611ad333611881565b9050828110158015611ae457508215155b81849091611b0e57604051633a854faf60e21b815260048101929092526024820152604401610cac565b5050336000908152601160205260408120548290850281611b3157611b316145b2565b33600081815260116020526040808220805495909404948590039093556001600160a01b038916815291909120805490920190915561094a91508585613338565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a008054600160401b810460ff1615906001600160401b0316600081158015611bb75750825b90506000826001600160401b03166001148015611bd35750303b155b905081158015611be1575080155b15611bff5760405163f92ee8a960e01b815260040160405180910390fd5b845467ffffffffffffffff191660011785558315611c2957845460ff60401b1916600160401b1785555b336001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001614611c71576040516282b42960e81b815260040160405180910390fd5b60e08601356276a700811115611c9d576040516372c50e0d60e11b8152600401610cac91815260200190565b50611daa7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316633fc8cef36040518163ffffffff1660e01b8152600401602060405180830381865afa158015611cff573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611d2391906140f3565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663fbfa77cf6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611d81573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611da591906140f3565b613397565b611db38b6133cd565b611e268a8a8080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525050604080516020601f8e018190048102820181019092528c815292508c91508b908190840183828082843760009201919091525061340892505050565b60c0860135600d5560e0860135600e5542600f556003805460ff19166001179055611e5d611e5860408801353461459f565b61345f565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316633fc8cef36040518163ffffffff1660e01b8152600401602060405180830381865afa158015611ebb573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611edf91906140f3565b600480546001600160a01b0319166001600160a01b03929092169190911781556040517fc18e7f80e60372d1fd896a89b5550a10b4f712fcc8e4fc3a006f529617f1e73791611f2d916147c6565b60405180910390a1611f438b6060880135613115565b6001600160a01b03808c1660009081526011602090815260409182902060608a013590558151634c3d795b60e11b81529151611ff1937f0000000000000000000000000000000000000000000000000000000000000000169263987af2b69260048083019391928290030181865afa158015611fc3573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611fe791906140f3565b604088013561322f565b6040516001600160a01b038c16907f6f301d931e6dfbda4364250e68b430fb2357688c019bc4bd78f4627f3714c039906120359060608a0180359182918c916147f8565b60405180910390a2831561208357845460ff60401b19168555604051600181527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b5050505050505050505050565b7f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace048054606091600080516020614d10833981519152916108b8906140b9565b6120d7612c07565b6120df612c3f565b60405163139d99a160e01b815281906001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063139d99a19061212f90339085906004016141a0565b600060405180830381600087803b15801561214957600080fd5b505af115801561215d573d6000803e3d6000fd5b5060009250612170915084905080614216565b81019061217d919061484d565b608081015190915060008112156121aa57604051631120b22f60e21b8152600401610cac91815260200190565b50805160009060049060ff16600881106121c6576121c6614603565b01546001600160a01b0316148061220d575080602001516001600160a01b03166004826000015160ff166008811061220057612200614603565b01546001600160a01b0316145b8151600460ff82166008811061222557612225614603565b015490916001600160a01b039091169061226657604051633232f2d560e21b815260ff90921660048301526001600160a01b03166024820152604401610cac565b50506020810151815160049060ff166008811061228557612285614603565b0180546001600160a01b0319166001600160a01b03928316179055604082015160208301516122b992169033903090613537565b6122c7338260600151613115565b608081015133600090815260116020526040812080549091906122eb908490614619565b9091555050602080820151604080840151608085015182516001600160a01b039094168452938301528101919091527f241954c029f95a1524821b3549607058b38dfb162d5cf4381ad9f1ec5866827c9060600160405180910390a15050610cf16001600080516020614d3083398151915255565b6040805180820190915260008152606060208201526001600160a01b038216600090815260126020908152604080832081518083018352815481526001820180548451818702810187019095528085529195929486810194939192919084015b82821015612406578382906000526020600020906002020160405180604001604052908160008201548152602001600182015481525050815260200190600101906123c0565b505050915250909392505050565b6004816008811061242457600080fd5b01546001600160a01b0316905081565b61243c612c07565b60035460ff1661245f57604051630bc4868d60e11b815260040160405180910390fd5b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316635c975abb6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156124bd573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906124e19190614110565b156124ff5760405163d69df31760e01b815260040160405180910390fd5b60405163139d99a160e01b815281906001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063139d99a19061254f90339085906004016141a0565b600060405180830381600087803b15801561256957600080fd5b505af115801561257d573d6000803e3d6000fd5b505050507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663f851a4406040518163ffffffff1660e01b8152600401602060405180830381865afa1580156125df573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061260391906140f3565b6001600160a01b0316330361262a576040516282b42960e81b815260040160405180910390fd5b60006126368380614216565b8101906126439190614906565b600c5481519192508181146126745760405163538d84ef60e11b815260048101929092526024820152604401610cac565b505060c081015160008112156126a057604051631120b22f60e21b8152600401610cac91815260200190565b5060208082015160408101519101516000916126bb91614619565b9050620186a07f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316637cd3d2776040518163ffffffff1660e01b8152600401602060405180830381865afa15801561271f573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061274391906149cd565b6127519061ffff16346149f1565b61275b91906145c8565b8111158015612776575060a08201516001600160a01b031615155b817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316637cd3d2776040518163ffffffff1660e01b8152600401602060405180830381865afa1580156127d5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906127f991906149cd565b8460a0015190919261283b5760405163d956e22b60e01b8152600481019390935261ffff90911660248301526001600160a01b03166044820152606401610cac565b5050506000813461284c919061459f565b602084015180519192509082908114612892576040805162ec5dcb60e81b8152835160048201526020840151602482015292015160448301526064820152608401610cac565b505061289d8161345f565b6128aa83606001516132f2565b6128b8338460800151613115565b60c083015133600090815260116020526040812080549091906128dc908490614619565b9091555050602080840151015115612904576129048360a0015184602001516020015161322f565b602083015160400151156129a5576129a57f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663987af2b66040518163ffffffff1660e01b8152600401602060405180830381865afa158015612973573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061299791906140f3565b84602001516040015161322f565b336001600160a01b03167f6f301d931e6dfbda4364250e68b430fb2357688c019bc4bd78f4627f3714c0398460c001518560800151866020015187604001516040516129f49493929190614a08565b60405180910390a250505050610cf16001600080516020614d3083398151915255565b612a1f612c07565b60405163139d99a160e01b815281906001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063139d99a190612a6f90339085906004016141a0565b600060405180830381600087803b158015612a8957600080fd5b505af1158015612a9d573d6000803e3d6000fd5b505060035460ff169150612ad0905057601054421115612ad057604051637eb24ab960e11b815260040160405180910390fd5b6000612adc8380614216565b810190612ae99190614aa7565b9050612af933826000015161359e565b606081015151336000908152601160209081526040909120805492909203909155810151612b26906132f2565b612b3381604001516135d4565b805160408083015160608401516080850151925133947f019dba413e23d35ab205236bc43f8e4a6ba5e4c4ce92b58ebd456f9524873f3794612b789491939192614b51565b60405180910390a25050610cf16001600080516020614d3083398151915255565b612ba1612c3f565b6001600160a01b038116612bc7576040516282b42960e81b815260040160405180910390fd5b6000612bd4610612611a99565b90508015612be857612be68282611ac7565b505b612bf1826136bd565b5050565b612c02838383600161372e565b505050565b600080516020614d30833981519152805460011901612c3957604051633ee5aeb560e01b815260040160405180910390fd5b60029055565b33612c48611a99565b6001600160a01b031614612c715760405163118cdaa760e01b8152336004820152602401610cac565b565b60408082015190516370a0823160e01b81523060048201526000916001600160a01b0316906370a0823190602401602060405180830381865afa158015612cbe573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612ce291906145ea565b60608301516040516370a0823160e01b81523060048201529192506000916001600160a01b03909116906370a0823190602401602060405180830381865afa158015612d32573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612d5691906145ea565b835160808501516040860151929350612d79926001600160a01b03169190613815565b60008084600001516001600160a01b03168560200151604051612d9c9190614bcf565b6000604051808303816000865af19150503d8060008114612dd9576040519150601f19603f3d011682016040523d82523d6000602084013e612dde565b606091505b5091509150818190612e035760405162461bcd60e51b8152600401610cac9190613dbc565b5060015460a0860151600054612e27926001600160a01b03918216929116906138a5565b60408086015190516370a0823160e01b81523060048201526000916001600160a01b0316906370a0823190602401602060405180830381865afa158015612e72573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612e9691906145ea565b60608701516040516370a0823160e01b81523060048201529192506000916001600160a01b03909116906370a0823190602401602060405180830381865afa158015612ee6573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612f0a91906145ea565b606088015160408901519192506001600160a01b039081169116337f300b4a9ac356114be2eaffe0f530cd615f14560df4b634adc11142d1358e8976612f50868b61459f565b612f5a8a8761459f565b8c516040805193845260208401929092526001600160a01b03169082015260600160405180910390a450505050505050565b60005b81518160ff16101561302357818160ff1681518110612fb057612fb0614603565b6020026020010151602001516004838360ff1681518110612fd357612fd3614603565b60200260200101516000015160ff1660088110612ff257612ff2614603565b0180546001600160a01b0319166001600160a01b03929092169190911790558061301b81614beb565b915050612f8f565b507fc18e7f80e60372d1fd896a89b5550a10b4f712fcc8e4fc3a006f529617f1e7376004604051610a4691906147c6565b6001600160a01b038116600090815260126020526040812060018101549054905b8181111561310f576001600160a01b03841660009081526012602052604081206001908101906130a5908461459f565b815481106130b5576130b5614603565b906000526020600020906002020160405180604001604052908160008201548152602001600182015481525050905080600001514211613105576020810151939093019260001990910190613109565b8192505b50613075565b50915091565b6001600160a01b03821661313f5760405163ec442f0560e01b815260006004820152602401610cac565b612bf1600083836138d6565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316633fc8cef36040518163ffffffff1660e01b8152600401602060405180830381865afa1580156131a9573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906131cd91906140f3565b6001600160a01b0316632e1a7d4d826040518263ffffffff1660e01b81526004016131fa91815260200190565b600060405180830381600087803b15801561321457600080fd5b505af1158015613228573d6000803e3d6000fd5b5050505050565b6000826001600160a01b03168260405160006040518083038185875af1925050503d806000811461327c576040519150601f19603f3d011682016040523d82523d6000602084013e613281565b606091505b5050905080612c02576001600160a01b038316600090815260026020526040812080548492906132b2908490614619565b90915550506040518281526001600160a01b038416907f648ec643b30463f72debf7027a0f9ff84bbdf4dc1a2a7ab973cb77dec53265689060200161173a565b60005b81518160ff161015612bf157613326828260ff168151811061331957613319614603565b6020026020010151612c73565b8061333081614beb565b9150506132f5565b6001600160a01b03831661336257604051634b637e8f60e11b815260006004820152602401610cac565b6001600160a01b03821661338c5760405163ec442f0560e01b815260006004820152602401610cac565b612c028383836138d6565b61339f613af7565b600080546001600160a01b039384166001600160a01b03199182161790915560018054929093169116179055565b6133d5613af7565b6001600160a01b0381166133ff57604051631e4fbdf760e01b815260006004820152602401610cac565b610cf1816136bd565b613410613af7565b600080516020614d108339815191527f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace0361344a8482614c51565b50600481016134598382614c51565b50505050565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316633fc8cef36040518163ffffffff1660e01b8152600401602060405180830381865afa1580156134bd573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906134e191906140f3565b6001600160a01b031663d0e30db0826040518263ffffffff1660e01b81526004016000604051808303818588803b15801561351b57600080fd5b505af115801561352f573d6000803e3d6000fd5b505050505050565b6040516001600160a01b0384811660248301528381166044830152606482018390526134599186918216906323b872dd906084015b604051602081830303815290604052915060e01b6020820180516001600160e01b038381831617835250505050613b40565b6001600160a01b0382166135c857604051634b637e8f60e11b815260006004820152602401610cac565b612bf1826000836138d6565b60008160200151136135f2576135ed816080015161314b565b6136af565b61360b816040015182606001518360800151010161314b565b61369a7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663fbfa77cf6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561366c573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061369091906140f3565b826060015161322f565b6136af6136a5611a99565b826040015161322f565b610cf133826080015161322f565b7f9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c19930080546001600160a01b031981166001600160a01b03848116918217845560405192169182907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a3505050565b600080516020614d108339815191526001600160a01b0385166137675760405163e602df0560e01b815260006004820152602401610cac565b6001600160a01b03841661379157604051634a1406b160e11b815260006004820152602401610cac565b6001600160a01b0380861660009081526001830160209081526040808320938816835292905220839055811561322857836001600160a01b0316856001600160a01b03167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9258560405161380691815260200190565b60405180910390a35050505050565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663095ea7b360e01b1790526138668482613bb1565b613459576040516001600160a01b0384811660248301526000604483015261389b91869182169063095ea7b39060640161356c565b6134598482613b40565b6040516001600160a01b03838116602483015260448201839052612c0291859182169063a9059cbb9060640161356c565b60035460ff1615613aec576001600160a01b03831615801561398b57507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663f851a4406040518163ffffffff1660e01b8152600401602060405180830381865afa158015613951573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061397591906140f3565b6001600160a01b0316826001600160a01b031614155b15613a035760126000836001600160a01b03166001600160a01b031681526020019081526020016000206001016040518060400160405280600e54426139d19190614619565b815260209081018490528254600181810185556000948552938290208351600290920201908155910151910155613aec565b6001600160a01b03831660009081526012602052604090206001015415613aec57600080613a3085613054565b91509150600082613a4087611881565b613a4a919061459f565b9050808480821015613a785760405163b388f18d60e01b815260048101929092526024820152604401610cac565b50506001600160a01b0386166000908152601260205260409020600101548203613acc576001600160a01b038616600090815260126020526040812081815590613ac56001830182613d5d565b5050613ae8565b6001600160a01b03861660009081526012602052604090208290555b5050505b612c02838383613c00565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a0054600160401b900460ff16612c7157604051631afcd79f60e31b815260040160405180910390fd5b600080602060008451602086016000885af180613b63576040513d6000823e3d81fd5b50506000513d91508115613b7b578060011415613b88565b6001600160a01b0384163b155b1561345957604051635274afe760e01b81526001600160a01b0385166004820152602401610cac565b6000806000806020600086516020880160008a5af192503d91506000519050828015613bf657508115613be75780600114613bf6565b6000866001600160a01b03163b115b9695505050505050565b600080516020614d108339815191526001600160a01b038416613c3c5781816002016000828254613c319190614619565b90915550613cae9050565b6001600160a01b03841660009081526020829052604090205482811015613c8f5760405163391434e360e21b81526001600160a01b03861660048201526024810182905260448101849052606401610cac565b6001600160a01b03851660009081526020839052604090209083900390555b6001600160a01b038316613ccc576002810180548390039055613ceb565b6001600160a01b03831660009081526020829052604090208054830190555b826001600160a01b0316846001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef84604051613d3091815260200190565b60405180910390a350505050565b6040518061010001604052806008906020820280368337509192915050565b5080546000825560020290600052602060002090810190610cf191905b80821115613d945760008082556001820155600201613d7a565b5090565b60005b83811015613db3578181015183820152602001613d9b565b50506000910152565b6020815260008251806020840152613ddb816040850160208701613d98565b601f01601f19169190910160400192915050565b6001600160a01b0381168114610cf157600080fd5b8035610d4681613def565b60008060408385031215613e2257600080fd5b8235613e2d81613def565b946020939093013593505050565b600060208284031215613e4d57600080fd5b5035919050565b600060208284031215613e6657600080fd5b8135613e7181613def565b9392505050565b600080600060608486031215613e8d57600080fd5b8335613e9881613def565b92506020840135613ea881613def565b929592945050506040919091013590565b600060208284031215613ecb57600080fd5b81356001600160401b03811115613ee157600080fd5b820160608185031215613e7157600080fd5b6101008101818360005b6008811015613f255781516001600160a01b0316835260209283019290910190600101613efd565b50505092915050565b60008083601f840112613f4057600080fd5b5081356001600160401b03811115613f5757600080fd5b602083019150836020828501011115613f6f57600080fd5b9250929050565b600080600080600080868803610160811215613f9157600080fd5b8735613f9c81613def565b965060208801356001600160401b03811115613fb757600080fd5b613fc38a828b01613f2e565b90975095505060408801356001600160401b03811115613fe257600080fd5b613fee8a828b01613f2e565b909550935050610100605f198201121561400757600080fd5b506060870190509295509295509295565b6020808252825182820152828101516040808401528051606084018190526000929190910190829060808501905b80831015614076578351805183526020810151602084015250604082019150602084019350600183019250614046565b5095945050505050565b6000806040838503121561409357600080fd5b823561409e81613def565b915060208301356140ae81613def565b809150509250929050565b600181811c908216806140cd57607f821691505b6020821081036140ed57634e487b7160e01b600052602260045260246000fd5b50919050565b60006020828403121561410557600080fd5b8151613e7181613def565b60006020828403121561412257600080fd5b81518015158114613e7157600080fd5b6000808335601e1984360301811261414957600080fd5b83016020810192503590506001600160401b0381111561416857600080fd5b803603821315613f6f57600080fd5b81835281816020850137506000828201602090810191909152601f909101601f19169091010190565b6001600160a01b03831681526040602082015260006141bf8380614132565b606060408501526141d460a085018284614177565b9150506141e46020850185614132565b848303603f190160608601526141fb838284614177565b60409690960135608095909501949094525092949350505050565b6000808335601e1984360301811261422d57600080fd5b8301803591506001600160401b0382111561424757600080fd5b602001915036819003821315613f6f57600080fd5b634e487b7160e01b600052604160045260246000fd5b604080519081016001600160401b03811182821017156142945761429461425c565b60405290565b60405160c081016001600160401b03811182821017156142945761429461425c565b60405160a081016001600160401b03811182821017156142945761429461425c565b60405160e081016001600160401b03811182821017156142945761429461425c565b604051601f8201601f191681016001600160401b03811182821017156143285761432861425c565b604052919050565b60006001600160401b038211156143495761434961425c565b5060051b60200190565b803560ff81168114610d4657600080fd5b600082601f83011261437557600080fd5b813561438861438382614330565b614300565b8082825260208201915060208360061b8601019250858311156143aa57600080fd5b602085015b8381101561407657604081880312156143c757600080fd5b6143cf614272565b6143d882614353565b815260208201356143e881613def565b60208281019190915290845292909201916040016143af565b600060c0828403121561441357600080fd5b61441b61429a565b9050813561442881613def565b815260208201356001600160401b0381111561444357600080fd5b8201601f8101841361445457600080fd5b80356001600160401b0381111561446d5761446d61425c565b614480601f8201601f1916602001614300565b81815285602083850101111561449557600080fd5b816020840160208301376000602083830101528060208501525050506144bd60408301613e04565b60408201526144ce60608301613e04565b60608201526080828101359082015260a09182013591810191909152919050565b60006020828403121561450157600080fd5b81356001600160401b0381111561451757600080fd5b82016040818503121561452957600080fd5b614531614272565b81356001600160401b0381111561454757600080fd5b61455386828501614364565b82525060208201356001600160401b0381111561456f57600080fd5b61457b86828501614401565b602083015250949350505050565b634e487b7160e01b600052601160045260246000fd5b8181038181111561095057610950614589565b634e487b7160e01b600052601260045260246000fd5b6000826145e557634e487b7160e01b600052601260045260246000fd5b500490565b6000602082840312156145fc57600080fd5b5051919050565b634e487b7160e01b600052603260045260246000fd5b8082018082111561095057610950614589565b600082601f83011261463d57600080fd5b813561464b61438382614330565b8082825260208201915060208360051b86010192508583111561466d57600080fd5b602085015b838110156140765780356001600160401b0381111561469057600080fd5b61469f886020838a0101614401565b84525060209283019201614672565b6000602082840312156146c057600080fd5b81356001600160401b038111156146d657600080fd5b8201602081850312156146e857600080fd5b604051602081016001600160401b038111828210171561470a5761470a61425c565b60405281356001600160401b0381111561472357600080fd5b61472f8682850161462c565b825250949350505050565b60006020828403121561474c57600080fd5b81356001600160401b0381111561476257600080fd5b82016040818503121561477457600080fd5b61477c614272565b81356001600160401b0381111561479257600080fd5b61479e86828501614364565b82525060208201356001600160401b038111156147ba57600080fd5b61457b8682850161462c565b6101008101818360005b6008811015613f255781546001600160a01b03168352602090920191600191820191016147d0565b84815260208101849052610100810161482860408301858035825260208082013590830152604090810135910152565b823560a0830152602083013560c0830152604083013560e08301525b95945050505050565b600060a082840312801561486057600080fd5b506148696142bc565b61487283614353565b8152602083013561488281613def565b602082015260408381013590820152606080840135908201526080928301359281019290925250919050565b6000606082840312156148c057600080fd5b604051606081016001600160401b03811182821017156148e2576148e261425c565b60409081528335825260208085013590830152928301359281019290925250919050565b60006020828403121561491857600080fd5b81356001600160401b0381111561492e57600080fd5b8201610160818503121561494157600080fd5b6149496142de565b8135815261495a85602084016148ae565b602082015261496c85608084016148ae565b604082015260e08201356001600160401b0381111561498a57600080fd5b6149968682850161462c565b60608301525061010082013560808201526149b46101208301613e04565b60a0820152610140919091013560c08201529392505050565b6000602082840312156149df57600080fd5b815161ffff81168114613e7157600080fd5b808202811582820484141761095057610950614589565b848152602081018490526101008101614a3860408301858051825260208082015190830152604090810151910152565b825160a0830152602083015160c0830152604083015160e0830152614844565b600060a08284031215614a6a57600080fd5b614a726142bc565b823581526020808401359082015260408084013590820152606080840135908201526080928301359281019290925250919050565b600060208284031215614ab957600080fd5b81356001600160401b03811115614acf57600080fd5b82016101a08185031215614ae257600080fd5b614aea6142bc565b8135815260208201356001600160401b03811115614b0757600080fd5b614b138682850161462c565b602083015250614b268560408401614a58565b6040820152614b388560e08401614a58565b6060820152610180919091013560808201529392505050565b8481526101808101614b91602083018680518252602081015160208301526040810151604083015260608101516060830152608081015160808301525050565b835160c0830152602084015160e083015260408401516101008301526060840151610120830152608090930151610140820152610160015292915050565b60008251614be1818460208701613d98565b9190910192915050565b600060ff821660ff8103614c0157614c01614589565b60010192915050565b601f821115612c0257806000526020600020601f840160051c81016020851015614c315750805b601f840160051c820191505b818110156132285760008155600101614c3d565b81516001600160401b03811115614c6a57614c6a61425c565b614c7e81614c7884546140b9565b84614c0a565b6020601f821160018114614cb25760008315614c9a5750848201515b600019600385901b1c1916600184901b178455613228565b600084815260208120601f198516915b82811015614ce25787850151825560209485019460019092019101614cc2565b5084821015614d005786840151600019600387901b60f8161c191681555b50505050600190811b0190555056fe52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace009b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00a2646970667358221220b2dcf96f84f27556268f96c9980cecf5e384ed26c57938cc177dbdcf3d6953c064736f6c634300081b003300000000000000000000000027cc44506ba2b1fb89ad15bd7ae1a197502d68ea00000000000000000000000089bb5313b2c16c0720585081e6913f99e469c5f2000000000000000000000000cf55de5b335caa6cb7e11133963cfb885fa80807000000000000000000000000a0f7af9bc211eeec89f6d7f66fe71aa5ce40c92f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Deployed Bytecode
0x6080604052600436106102305760003560e01c806384b0196e1161012e578063c6d87dd5116100ab578063f1b94cc91161006f578063f1b94cc9146106f6578063f2fde38b1461070c578063f851a4401461072c578063fbfa77cf14610753578063ffed81c31461077857600080fd5b8063c6d87dd514610662578063d056812d14610678578063d73792a914610698578063d84a7b4f146106c3578063d895ace2146106d657600080fd5b8063aa358dc1116100f2578063aa358dc1146105c9578063aad1f00a146105de578063ab3d85441461060b578063b06459b514610620578063b9c87e7d1461064257600080fd5b806384b0196e146105235780638d10d29d1461054b5780638da5cb5b1461056d578063987af2b61461058b578063a4af999d146105ab57600080fd5b806366dc898d116101bc578063715018a611610180578063715018a6146104975780637cd3d277146104ac5780637d95173a146104ce5780638456cb59146104ee5780638480ac421461050357600080fd5b806366dc898d146103de578063670fc207146103fe5780636817031b1461041e578063704b6c021461043e578063709563e21461045e57600080fd5b80633f4ba83a116102035780633f4ba83a1461030a5780633fc8cef31461031f57806349de54d3146103535780635c975abb1461039257806362ace683146103b557600080fd5b806304f81b11146102355780630b30767414610257578063139d99a1146102a85780631854dc7a146102c8575b600080fd5b34801561024157600080fd5b5061025561025036600461172c565b610798565b005b34801561026357600080fd5b5061028b7f000000000000000000000000ec8902afffb06d0b075ea2d6fb3a45ec8598c39b81565b6040516001600160a01b0390911681526020015b60405180910390f35b3480156102b457600080fd5b506102556102c336600461175f565b6107ac565b3480156102d457600080fd5b506102fc7f7a5e13c00d001fd24f434a2322118b8a340058f1abefa200fe4683e26bf103f081565b60405190815260200161029f565b34801561031657600080fd5b506102556107db565b34801561032b57600080fd5b5061028b7f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc281565b34801561035f57600080fd5b5060065461037a90600160a01b90046001600160401b031681565b6040516001600160401b03909116815260200161029f565b34801561039e57600080fd5b5060055460ff16604051901515815260200161029f565b3480156103c157600080fd5b506103cb61271081565b60405161ffff909116815260200161029f565b3480156103ea57600080fd5b506102556103f93660046117ac565b6107ed565b34801561040a57600080fd5b506102556104193660046117d5565b610857565b34801561042a57600080fd5b5061025561043936600461172c565b610907565b34801561044a57600080fd5b5061025561045936600461172c565b610965565b34801561046a57600080fd5b5060055461048290600160a81b900463ffffffff1681565b60405163ffffffff909116815260200161029f565b3480156104a357600080fd5b506102556109cc565b3480156104b857600080fd5b506005546103cb90600160d81b900461ffff1681565b3480156104da57600080fd5b506102556104e93660046117d5565b6109de565b3480156104fa57600080fd5b50610255610a6e565b34801561050f57600080fd5b5061025561051e3660046117d5565b610a7e565b34801561052f57600080fd5b50610538610b0f565b60405161029f9796959493929190611849565b34801561055757600080fd5b506005546103cb90600160c81b900461ffff1681565b34801561057957600080fd5b506002546001600160a01b031661028b565b34801561059757600080fd5b5060065461028b906001600160a01b031681565b3480156105b757600080fd5b506003546001600160a01b031661028b565b3480156105d557600080fd5b506102fc610b55565b3480156105ea57600080fd5b506102fc6105f936600461172c565b60046020526000908152604090205481565b34801561061757600080fd5b506103cb60c881565b34801561062c57600080fd5b506005546103cb90600160e81b900461ffff1681565b34801561064e57600080fd5b5060075461037a906001600160401b031681565b34801561066e57600080fd5b506103cb6103e881565b34801561068457600080fd5b506102556106933660046118e1565b610b7b565b3480156106a457600080fd5b506106af620186a081565b60405162ffffff909116815260200161029f565b6102556106d136600461194f565b610bd7565b3480156106e257600080fd5b506102556106f13660046117ac565b610d2e565b34801561070257600080fd5b506103cb614e2081565b34801561071857600080fd5b5061025561072736600461172c565b610d85565b34801561073857600080fd5b5060075461028b90600160401b90046001600160a01b031681565b34801561075f57600080fd5b5060055461028b9061010090046001600160a01b031681565b34801561078457600080fd5b5061025561079336600461172c565b610dc0565b6107a0610e16565b6107a981610e43565b50565b6107d77f7a5e13c00d001fd24f434a2322118b8a340058f1abefa200fe4683e26bf103f08383610ed4565b5050565b6107e3610e16565b6107eb611006565b565b6107f5610e16565b6006805467ffffffffffffffff60a01b1916600160a01b6001600160401b038416908102919091179091556040519081527f488901414bff238cb14e4407dfb9e74841a2344ed3594b172eb1a55042f7e002906020015b60405180910390a150565b61085f610e16565b614e2061086e82612710611a02565b61ffff16111561088082612710611a02565b614e2090916108b557604051637db814ed60e11b815261ffff9283166004820152911660248201526044015b60405180910390fd5b50506005805461ffff60c81b1916600160c81b61ffff8416908102919091179091556040519081527feb2312e4985048cc5255947a02f69e0098b4e661fe3ba17df2982786c934800e9060200161084c565b61090f610e16565b60058054610100600160a81b0319166101006001600160a01b038416908102919091179091556040519081527f161584aed96e7f34998117c9ad67e2d21ff46d2a42775c22b11ed282f3c7b2cd9060200161084c565b61096d610e16565b6007805468010000000000000000600160e01b031916600160401b6001600160a01b038416908102919091179091556040519081527f54e4612788f90384e6843298d7854436f3a585b2c3831ab66abf1de63bfa6c2d9060200161084c565b6109d4610e16565b6107eb6000611058565b6109e6610e16565b8060c861ffff8216811015610a1c57604051637db814ed60e11b815261ffff9283166004820152911660248201526044016108ac565b50506005805461ffff60e81b1916600160e81b61ffff8416908102919091179091556040519081527f1736886ad28d8a9e6db70c1bd1594336b7a3f55e9484e9bbba56234499a5acb09060200161084c565b610a76610e16565b6107eb6110aa565b610a86610e16565b806103e861ffff8216811015610abd57604051637db814ed60e11b815261ffff9283166004820152911660248201526044016108ac565b50506005805461ffff60d81b1916600160d81b61ffff8416908102919091179091556040519081527f905b3cd2efc627e8c9527e9ce3df3010afcbedeaccdc0a645a159dabc844ffa49060200161084c565b600060608060008060006060610b236110e7565b610b2b611119565b60408051600080825260208201909252600f60f81b9b939a50919850469750309650945092509050565b600554600090610b7290600160c81b900461ffff16612710611a02565b61ffff16905090565b610b83610e16565b6005805463ffffffff60a81b1916600160a81b63ffffffff8416908102919091179091556040519081527fb2e40a35d8210676ab1f5c7f65cce5c19920db28fbddb8caf507b6ab9f3fbf0f9060200161084c565b610bdf611146565b610be933826107ac565b6000610bf58280611a1c565b810190610c029190611ac8565b8051604081015190519192503491610c1a9190611b4c565b825191349114610c57576040805162ec5dcb60e81b81528351600482015260208401516024820152920151604483015260648201526084016108ac565b50506000610c847f000000000000000000000000ec8902afffb06d0b075ea2d6fb3a45ec8598c39b61116a565b9050806001600160a01b031663906737e734338a8a8a8a896040518863ffffffff1660e01b8152600401610cbd96959493929190611b88565b6000604051808303818588803b158015610cd657600080fd5b505af1158015610cea573d6000803e3d6000fd5b50506040513393506001600160a01b03851692507f9de2be681a220396ec1518a4ecd6c853a760e34fb9174e9213d7aa5a8b12f3799150600090a350505050505050565b610d36610e16565b6007805467ffffffffffffffff19166001600160401b0383169081179091556040519081527f2d711c31560be95e9b50a0c2512e8e4a3b4029e1538745809d042e13f25841ca9060200161084c565b610d8d610e16565b6001600160a01b038116610db757604051631e4fbdf760e01b8152600060048201526024016108ac565b6107a981611058565b610dc8610e16565b600680546001600160a01b0319166001600160a01b0383169081179091556040519081527f0155b0dc5b332e364f3dc39ddc27990be72382e760585da8d99b334e0e3845159060200161084c565b6002546001600160a01b031633146107eb5760405163118cdaa760e01b81523360048201526024016108ac565b6001600160a01b03811615801590610e6957506003546001600160a01b03828116911614155b610e865760405163e6c4247b60e01b815260040160405180910390fd5b600380546001600160a01b0319166001600160a01b0383169081179091556040519081527f5553331329228fbd4123164423717a4a7539f6dfa1c3279a923b98fd681a6c739060200161084c565b4381604001351015610ef95760405163df4cc36d60e01b815260040160405180910390fd5b6003546001600160a01b038381166000908152600460205260409020805460018101909155610fe4929190911690610f9d90869086610f388780611a1c565b604051610f46929190611c27565b604080519182900382206020830195909552818101939093526001600160a01b039091166060820152608081019290925285013560a082015260c0016040516020818303038152906040528051906020012061117d565b610faa6020850185611a1c565b8080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152506111aa92505050565b61100157604051638baa579f60e01b815260040160405180910390fd5b505050565b61100e611221565b6005805460ff191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa335b6040516001600160a01b03909116815260200160405180910390a1565b600280546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b6110b2611146565b6005805460ff191660011790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a25861103b3390565b60606111147f475552552e46554e4400000000000000000000000000000000000000000000096000611244565b905090565b60606111147f76302e312e3000000000000000000000000000000000000000000000000000066001611244565b60055460ff16156107eb5760405163d93c066560e01b815260040160405180910390fd5b60006111778260006112f0565b92915050565b600061117761118a611386565b8360405161190160f01b8152600281019290925260228201526042902090565b6000836001600160a01b03163b60000361120c576000806111cb85856114b1565b50909250905060008160038111156111e5576111e5611c37565b1480156112035750856001600160a01b0316826001600160a01b0316145b9250505061121a565b6112178484846114fe565b90505b9392505050565b60055460ff166107eb57604051638dfc202b60e01b815260040160405180910390fd5b606060ff831461125e57611257836115da565b9050611177565b81805461126a90611c4d565b80601f016020809104026020016040519081016040528092919081815260200182805461129690611c4d565b80156112e35780601f106112b8576101008083540402835291602001916112e3565b820191906000526020600020905b8154815290600101906020018083116112c657829003601f168201915b5050505050905092915050565b60008147101561131c5760405163cf47918160e01b8152476004820152602481018390526044016108ac565b763d602d80600a3d3981f3363d3d373d3d3d363d730000008360601b60e81c176000526e5af43d82803e903d91602b57fd5bf38360781b176020526037600983f090506001600160a01b0381166111775760405163b06ebf3d60e01b815260040160405180910390fd5b6000306001600160a01b037f000000000000000000000000d0f4de81e0b6e9d8018f2b8bf7f05da0edbc963f161480156113df57507f000000000000000000000000000000000000000000000000000000000000000146145b1561140957507fe5173c43dd57a6fac5ab7960734599cacb208afe739df346632c24527cd6331a90565b611114604080517f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f60208201527f94a0f5120f156fa910f92e52754b2458bea17ea7bffe034743eeca03a4d0e1d0918101919091527fe32e703a20098305652a91ed3370235a27f244557ddae05f8afc0fc46e3bdc8a60608201524660808201523060a082015260009060c00160405160208183030381529060405280519060200120905090565b600080600083516041036114eb5760208401516040850151606086015160001a6114dd88828585611619565b9550955095505050506114f7565b50508151600091506002905b9250925092565b6000806000856001600160a01b03168585604051602401611520929190611c81565b60408051601f198184030181529181526020820180516001600160e01b0316630b135d3f60e11b179052516115559190611ca2565b600060405180830381855afa9150503d8060008114611590576040519150601f19603f3d011682016040523d82523d6000602084013e611595565b606091505b50915091508180156115a957506020815110155b80156115d057508051630b135d3f60e11b906115ce9083016020908101908401611cbe565b145b9695505050505050565b606060006115e7836116e8565b604080516020808252818301909252919250600091906020820181803683375050509182525060208101929092525090565b600080807f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a084111561165457506000915060039050826116de565b604080516000808252602082018084528a905260ff891692820192909252606081018790526080810186905260019060a0016020604051602081039080840390855afa1580156116a8573d6000803e3d6000fd5b5050604051601f1901519150506001600160a01b0381166116d4575060009250600191508290506116de565b9250600091508190505b9450945094915050565b600060ff8216601f81111561117757604051632cd44ac360e21b815260040160405180910390fd5b80356001600160a01b038116811461172757600080fd5b919050565b60006020828403121561173e57600080fd5b61121a82611710565b60006060828403121561175957600080fd5b50919050565b6000806040838503121561177257600080fd5b61177b83611710565b915060208301356001600160401b0381111561179657600080fd5b6117a285828601611747565b9150509250929050565b6000602082840312156117be57600080fd5b81356001600160401b038116811461121a57600080fd5b6000602082840312156117e757600080fd5b813561ffff8116811461121a57600080fd5b60005b838110156118145781810151838201526020016117fc565b50506000910152565b600081518084526118358160208601602086016117f9565b601f01601f19169290920160200192915050565b60ff60f81b8816815260e06020820152600061186860e083018961181d565b828103604084015261187a818961181d565b606084018890526001600160a01b038716608085015260a0840186905283810360c08501528451808252602080870193509091019060005b818110156118d05783518352602093840193909201916001016118b2565b50909b9a5050505050505050505050565b6000602082840312156118f357600080fd5b813563ffffffff8116811461121a57600080fd5b60008083601f84011261191957600080fd5b5081356001600160401b0381111561193057600080fd5b60208301915083602082850101111561194857600080fd5b9250929050565b60008060008060006060868803121561196757600080fd5b85356001600160401b0381111561197d57600080fd5b61198988828901611907565b90965094505060208601356001600160401b038111156119a857600080fd5b6119b488828901611907565b90945092505060408601356001600160401b038111156119d357600080fd5b6119df88828901611747565b9150509295509295909350565b634e487b7160e01b600052601160045260246000fd5b61ffff8181168382160190811115611177576111776119ec565b6000808335601e19843603018112611a3357600080fd5b8301803591506001600160401b03821115611a4d57600080fd5b60200191503681900382131561194857600080fd5b600060608284031215611a7457600080fd5b604051606081016001600160401b0381118282101715611aa457634e487b7160e01b600052604160045260246000fd5b60409081528335825260208085013590830152928301359281019290925250919050565b6000610100828403128015611adc57600080fd5b50604051600090608081016001600160401b0381118282101715611b0e57634e487b7160e01b83526041600452602483fd5b604052611b1b8585611a62565b8152611b2a8560608601611a62565b602082015260c0840135604082015260e0909301356060840152509092915050565b80820180821115611177576111776119ec565b81835281816020850137506000828201602090810191909152601f909101601f19169091010190565b6001600160a01b038716815261016060208201819052600090611bae9083018789611b5f565b8281036040840152611bc1818688611b5f565b845180516060860152602081015160808601526040015160a08501529150611be69050565b602083810151805160c08501529081015160e08401526040908101516101008401528301516101208301526060909201516101409091015295945050505050565b8183823760009101908152919050565b634e487b7160e01b600052602160045260246000fd5b600181811c90821680611c6157607f821691505b60208210810361175957634e487b7160e01b600052602260045260246000fd5b828152604060208201526000611c9a604083018461181d565b949350505050565b60008251611cb48184602087016117f9565b9190910192915050565b600060208284031215611cd057600080fd5b505191905056fea264697066735822122098eedaba7f8f04cb0b2e00015e50e386d94dd401f7a23ec4ebf0fdd34e35b4b464736f6c634300081b0033
Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)
00000000000000000000000027cc44506ba2b1fb89ad15bd7ae1a197502d68ea00000000000000000000000089bb5313b2c16c0720585081e6913f99e469c5f2000000000000000000000000cf55de5b335caa6cb7e11133963cfb885fa80807000000000000000000000000a0f7af9bc211eeec89f6d7f66fe71aa5ce40c92f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
-----Decoded View---------------
Arg [0] : _offchainSigner (address): 0x27Cc44506Ba2b1fB89AD15Bd7AE1a197502d68ea
Arg [1] : _vault (address): 0x89bb5313b2C16c0720585081e6913F99e469c5F2
Arg [2] : _guruBurner (address): 0xcf55DE5B335CAA6cb7e11133963CFB885fa80807
Arg [3] : _admin (address): 0xa0f7aF9bc211eEeC89f6d7f66FE71aA5ce40C92F
Arg [4] : _wethAddress (address): 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2
-----Encoded View---------------
5 Constructor Arguments found :
Arg [0] : 00000000000000000000000027cc44506ba2b1fb89ad15bd7ae1a197502d68ea
Arg [1] : 00000000000000000000000089bb5313b2c16c0720585081e6913f99e469c5f2
Arg [2] : 000000000000000000000000cf55de5b335caa6cb7e11133963cfb885fa80807
Arg [3] : 000000000000000000000000a0f7af9bc211eeec89f6d7f66fe71aa5ce40c92f
Arg [4] : 000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Loading...
Loading
Loading...
Loading
Multichain Portfolio | 31 Chains
Chain | Token | Portfolio % | Price | Amount | Value |
---|
Loading...
Loading
[ Download: CSV Export ]
[ Download: CSV Export ]
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.