More Info
Private Name Tags
ContractCreator
TokenTracker
Latest 25 from a total of 14,455 transactions
Transaction Hash |
Method
|
Block
|
From
|
To
|
|||||
---|---|---|---|---|---|---|---|---|---|
Withdraw | 18024030 | 6 days ago | IN | 0 ETH | 0.00000135 | ||||
Liquidate | 17676622 | 14 days ago | IN | 0 ETH | 0.00000126 | ||||
Liquidate | 17676616 | 14 days ago | IN | 0 ETH | 0.00000126 | ||||
Liquidate | 17604420 | 15 days ago | IN | 0 ETH | 0.00000106 | ||||
Liquidate | 17586285 | 16 days ago | IN | 0 ETH | 0.00000251 | ||||
Liquidate | 17585960 | 16 days ago | IN | 0 ETH | 0.000003 | ||||
Withdraw | 17569087 | 16 days ago | IN | 0 ETH | 0.00000031 | ||||
Withdraw | 17455816 | 19 days ago | IN | 0 ETH | 0.00000081 | ||||
Withdraw | 17427234 | 20 days ago | IN | 0 ETH | 0.00000091 | ||||
Liquidate | 17411440 | 20 days ago | IN | 0 ETH | 0.00000021 | ||||
Claim Max Gas | 17312483 | 22 days ago | IN | 0 ETH | 0.00000009 | ||||
Liquidate | 17181851 | 25 days ago | IN | 0 ETH | 0.00000065 | ||||
Liquidate | 17181846 | 25 days ago | IN | 0 ETH | 0.00000065 | ||||
Liquidate | 17181844 | 25 days ago | IN | 0 ETH | 0.00000065 | ||||
Withdraw | 17137586 | 26 days ago | IN | 0 ETH | 0.00000084 | ||||
Liquidate | 16932872 | 31 days ago | IN | 0 ETH | 0.00000054 | ||||
Liquidate | 16932792 | 31 days ago | IN | 0 ETH | 0.00000054 | ||||
Liquidate | 16932784 | 31 days ago | IN | 0 ETH | 0.00000054 | ||||
Liquidate | 16932779 | 31 days ago | IN | 0 ETH | 0.00000054 | ||||
Liquidate | 16932775 | 31 days ago | IN | 0 ETH | 0.00000054 | ||||
Liquidate | 16932769 | 31 days ago | IN | 0 ETH | 0.00000054 | ||||
Liquidate | 16932763 | 31 days ago | IN | 0 ETH | 0.00000054 | ||||
Liquidate | 16932755 | 31 days ago | IN | 0 ETH | 0.00000054 | ||||
Liquidate | 16932748 | 31 days ago | IN | 0 ETH | 0.00000054 | ||||
Liquidate | 16932744 | 31 days ago | IN | 0 ETH | 0.00000054 |
Latest 25 internal transactions (View All)
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:
JuiceAccountManager
Compiler Version
v0.8.24+commit.e11b9ed9
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.24; import "../managers/StrategyAccountManager.sol"; import "../interfaces/IJuiceAccountManager.sol"; import "../interfaces/IAssetPriceProvider.sol"; import "../libraries/accounts/AccountLib.sol"; import "../libraries/Errors.sol"; import "./JuiceModule.sol"; import "./JuiceAccount.sol"; import "./ERC20CollateralVault.sol"; import "./periphery/BlastGas.sol"; import "./periphery/BlastPoints.sol"; import "../periphery/PythPusher.sol"; abstract contract JuiceAccountManagerEvents { /// @notice A user has created an account. event AccountCreated(address indexed owner, address account); /// @notice A user has deposited WETH into the contract. event CollateralDeposit(address indexed owner, address account, uint256 amount); /// @notice A user has withdrawn WETH from the contract. event CollateralWithdrawal(address indexed owner, address account, uint256 amount); /// @notice When yield is accrued event YieldAccrued(uint256 amount); /// @notice CollateralLiquidation event CollateralLiquidation( address account, uint256 collateralAmount, uint256 bonusCollateral, uint256 debtAmountNeeded ); } /// @title JuiceAccountManager supports one account implementation /// @notice The AccountManager contract deploys Account contracts. contract JuiceAccountManager is StrategyAccountManager, IJuiceAccountManager, PythPusher, JuiceModule, JuiceAccountManagerEvents, ERC20CollateralVault, BlastGas, BlastPoints { using EnumerableSet for EnumerableSet.AddressSet; using SafeERC20 for IERC20; using Address for address; UD60x18 public constant LIQUIDATION_BONUS = UD60x18.wrap(1.05e18); // 105% or 5% uint256 public MINIMUM_COMPOUND_AMOUNT = 1e6; /// @notice The max loan to value for Accounts /// @dev If 200%, loan can be maximum 200% of their collateral value UD60x18 public maxLtv; /// @notice The liquidation threshold for accounts /// @dev (Investment value + Equity value) / Debt value > liquidationThreshold UD60x18 public liquidationThreshold; /// @notice The implementation address of the Internal/External /// Account contracts to use for cloning address public immutable juiceAccountImplementation; mapping(address => address) private _ownerAccountCache; bool public isAutoCompounding; struct InitParams { address juiceAccount; address blastPointsOperator; bool isAutoCompounding; address liquidationReceiver; address weth; UD60x18 maxLtv; UD60x18 liquidationThreshold; string name; string symbol; uint8 decimals; } /// @notice Constructs the factory /// @param params The parameters for the JuiceAccountManager constructor( address protocolGovernor_, InitParams memory params ) JuiceModule(protocolGovernor_) BlastPoints(protocolGovernor_, params.blastPointsOperator) BlastGas(protocolGovernor_) PythPusher(protocolGovernor_) StrategyAccountManager(protocolGovernor_, params.liquidationReceiver) ERC20CollateralVault(params.weth, params.name, params.symbol, params.decimals) nonZeroAddressAndContract(params.juiceAccount) { juiceAccountImplementation = params.juiceAccount; maxLtv = params.maxLtv; liquidationThreshold = params.liquidationThreshold; IERC20Rebasing(address(params.weth)).configure(YieldMode.CLAIMABLE); isAutoCompounding = params.isAutoCompounding; } function toggleAutoCompounding() public onlyOwner { isAutoCompounding = !isAutoCompounding; } /// @dev Updates maxLtv and liquidationThreshold. /// liquidationThreshold must always be less than maxLtv. function updateLiquidationParameters(UD60x18 maxLtv_, UD60x18 liquidationThreshold_) external onlyOwner { if (liquidationThreshold_ > maxLtv_) { revert Errors.InvalidParams(); } maxLtv = maxLtv_; liquidationThreshold = liquidationThreshold_; } /// @dev This call requires that this contract is the account manager on the lending pool function createAccount() external nonReentrant returns (address payable account) { address owner = msg.sender; if (isCreatedAccount[owner]) { revert Errors.InvalidParams(); } account = payable(Clones.cloneDeterministic(juiceAccountImplementation, _salt(owner))); // Record the account was created isCreatedAccount[account] = true; _ownerAccountCache[owner] = account; _accountOwnerCache[account] = owner; accountCount += 1; emit AccountCreated(owner, account); // Initialize the account JuiceAccount(account).initialize(owner, _getPyth()); } /// @dev Takes assets from `msg.sender`, deposits them into the contract, and mints shares to the receiver. /// The shares are nontransferrable and reside in the receiver's address, but are used to credit the receiver's /// account contract. function deposit( uint256 assets, address receiver ) public override nonReentrant returns (uint256 updatedAssets, uint256 shares) { if (isAutoCompounding) { compound(); } (updatedAssets, shares) = super.deposit(assets, receiver); emit CollateralDeposit(receiver, getAccount(receiver), assets); } /// @dev Burns shares from the account of `msg.sender` and sends them to the receiver. /// `msg.sender` must be owner of account that owns the shares. function withdraw( uint256 shares, address receiver ) public override nonReentrant returns (uint256 updatedAssets, uint256 updatedShares) { (updatedAssets, updatedShares) = _withdraw(msg.sender, receiver, shares, new bytes[](0)); } function _withdraw( address caller, address receiver, uint256 shares, bytes[] memory pythPricesUpdates ) internal returns (uint256 updatedAssets, uint256 updatedShares) { if (isAutoCompounding) { compound(); } (updatedAssets, updatedShares) = super._withdraw(caller, receiver, shares); address account = getAccount(caller); updatePythPriceFeeds(pythPricesUpdates); _requireSolvent(account); emit CollateralWithdrawal(caller, receiver, updatedAssets); } function compound() public returns (uint256 earned) { IERC20Rebasing collateral = IERC20Rebasing(address(_collateral)); earned = collateral.getClaimableAmount(address(this)); // Avoid compounding dust. // We assume the claim just works. if (earned >= MINIMUM_COMPOUND_AMOUNT) { _totalCollateralAssets += earned; earned = IERC20Rebasing(address(_collateral)).claim(address(this), earned); emit YieldAccrued(earned); } } function borrow( uint256 amount, bytes[] memory pythPriceUpdates ) external payable onlyAccount nonReentrant returns (uint256 borrowed) { updatePythPriceFeeds(pythPriceUpdates); borrowed = _borrow(msg.sender, amount); } function withdraw( uint256 shares, address receiver, bytes[] memory pythPriceUpdates ) external payable nonReentrant returns (uint256 updatedAssets, uint256 updatedShares) { (updatedAssets, updatedShares) = _withdraw(msg.sender, receiver, shares, pythPriceUpdates); } function strategyDeposit( address owner, address strategy, uint256 amount, bytes memory data, bytes[] memory pythPriceUpdates ) external payable onlyAccount nonReentrant returns (uint256 shares) { updatePythPriceFeeds(pythPriceUpdates); shares = _strategyDeposit(msg.sender, owner, strategy, amount, data); } function strategyWithdrawal( address owner, address strategy, uint256 assets, bytes[] memory pythPriceUpdates ) external payable onlyAccount nonReentrant { updatePythPriceFeeds(pythPriceUpdates); _strategyWithdrawal(msg.sender, owner, strategy, assets); } /////////////////////////// // COLLATERAL LIQUIDATIONS /////////////////////////// /// @dev This calculation assumes that debt asset and collateral asset have the same decimals and have 18 decimal /// precision. function liquidateCollateral(address account, uint256 debtToCover, address liquidationFeeTo) public { AccountLib.Health memory health = getAccountHealth(account); if (!health.isLiquidatable) revert Errors.AccountHealthy(); // Mark account as liquidatable if it isn't already. if (_accountLiquidationStartTime[account] == 0) { _accountLiquidationStartTime[account] = block.timestamp; emit AccountLiquidationStarted(account); this._afterLiquidationStarted(account); } // The collateral is credited to the owner of the Account, not the Account itself. address accountOwner = _accountOwnerCache[account]; uint256 debtAmount = getDebtAmount(account); AccountLib.CollateralLiquidation memory _result = _simulateCollateralLiquidation(accountOwner, debtAmount, debtToCover); // Transfer collateral to caller and their fee wallet _withdrawAssets(accountOwner, msg.sender, _result.collateralAmount - _result.bonusCollateral); _withdrawAssets(accountOwner, liquidationFeeTo, _result.bonusCollateral); // Transfer debt from sender to account. _lendAsset.safeTransferFrom(msg.sender, account, _result.actualDebtToLiquidate); IAccount(account).repay(_result.actualDebtToLiquidate); emit CollateralLiquidation( account, _result.collateralAmount, _result.bonusCollateral, _result.actualDebtToLiquidate ); } function simulateCollateralLiquidation( address account, uint256 debtToCover ) external view returns (AccountLib.CollateralLiquidation memory) { // The collateral is credited to the owner of the Account, not the Account itself. address accountOwner = _accountOwnerCache[account]; uint256 debtAmount = getDebtAmount(account); return _simulateCollateralLiquidation(accountOwner, debtAmount, debtToCover); } function _simulateCollateralLiquidation( address accountOwner, uint256 debtAmount, uint256 debtToCover ) public view returns (AccountLib.CollateralLiquidation memory) { uint256 actualDebtToLiquidate = debtToCover > debtAmount ? debtAmount : debtToCover; uint256 collateralBalance = balanceOfAssets(accountOwner); (uint256 collateralAmount, uint256 bonusCollateral, uint256 debtAmountNeeded) = _calculateAvailableCollateralToLiquidate(actualDebtToLiquidate, collateralBalance); if (debtAmountNeeded < actualDebtToLiquidate) { actualDebtToLiquidate = debtAmountNeeded; } return AccountLib.CollateralLiquidation({ actualDebtToLiquidate: actualDebtToLiquidate, collateralAmount: collateralAmount, bonusCollateral: bonusCollateral }); } function _calculateAvailableCollateralToLiquidate( uint256 debtToCover, uint256 collateralBalance ) internal view returns (uint256 collateralAmount, uint256 bonusCollateral, uint256 debtAmountNeeded) { UD60x18 collateralPrice = ud(_getPriceProvider().getAssetPrice(address(_collateral))); uint256 maxCollateralAssetsToLiquidate = ud(debtToCover).mul(LIQUIDATION_BONUS).div(collateralPrice).unwrap(); if (maxCollateralAssetsToLiquidate > collateralBalance) { collateralAmount = collateralBalance; debtAmountNeeded = collateralPrice.mul(ud(collateralAmount)).div(LIQUIDATION_BONUS).unwrap(); } else { collateralAmount = maxCollateralAssetsToLiquidate; debtAmountNeeded = debtToCover; } UD60x18 debtAmountInCollateral = ud(debtAmountNeeded).div(collateralPrice); bonusCollateral = ud(collateralAmount).sub(debtAmountInCollateral).unwrap(); } function _getAccountMaxLtv(address) internal view override returns (UD60x18) { return maxLtv; } function totalAssets() public view virtual override returns (uint256) { return _totalCollateralAssets + IERC20Rebasing(address(_collateral)).getClaimableAmount(address(this)); } ///////////////////////// // Account Views ///////////////////////// /// @notice Returns the Account contract address for a given owner, even if it hasn't been created yet. /// Returns address(0) if the account is not valid /// @param owner_ The owner of the Account contract function getAccount(address owner_) public view returns (address account) { account = _ownerAccountCache[owner_]; if (account == address(0)) { account = Clones.predictDeterministicAddress(juiceAccountImplementation, _salt(owner_)); } } function getAccountHealth(address account) public view override returns (AccountLib.Health memory health) { uint256 investmentValue = getTotalAccountValue(account); uint256 collateralValue = getTotalCollateralValue(account); uint256 debtAmount = getDebtAmount(account); uint256 equity = collateralValue + investmentValue; health = AccountLib.Health({ isLiquidatable: false, hasBadDebt: false, debtAmount: debtAmount, collateralValue: collateralValue, investmentValue: investmentValue }); if (debtAmount > 0 && equity > 0) { health.isLiquidatable = equity < (ud(debtAmount).mul(liquidationThreshold)).unwrap(); } else if (debtAmount > 0) { health.hasBadDebt = true; } } /// @dev The nontransferrable collateral vault shares are assigned to the owner of the account so we base /// @dev the value function getTotalCollateralValue(address account) public view override returns (uint256 totalValue) { address owner = _accountOwnerCache[account]; uint256 assets = balanceOfAssets(owner); uint256 price = _getPriceProvider().getAssetPrice(address(_collateral)); totalValue = (assets * price) / (10 ** _collateralAssetDecimals); } }
// 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.0.0) (access/Ownable2Step.sol) pragma solidity ^0.8.20; import {Ownable} from "./Ownable.sol"; /** * @dev Contract module which provides access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * The initial owner is specified at deployment time in the constructor for `Ownable`. This * can later be changed with {transferOwnership} and {acceptOwnership}. * * This module is used through inheritance. It will make available all functions * from parent (Ownable). */ abstract contract Ownable2Step is Ownable { address private _pendingOwner; event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner); /** * @dev Returns the address of the pending owner. */ function pendingOwner() public view virtual returns (address) { return _pendingOwner; } /** * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one. * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual override onlyOwner { _pendingOwner = newOwner; emit OwnershipTransferStarted(owner(), newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner. * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual override { delete _pendingOwner; super._transferOwnership(newOwner); } /** * @dev The new owner accepts the ownership transfer. */ function acceptOwnership() public virtual { address sender = _msgSender(); if (pendingOwner() != sender) { revert OwnableUnauthorizedAccount(sender); } _transferOwnership(sender); } }
// 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.0.1) (metatx/ERC2771Context.sol) pragma solidity ^0.8.20; import {Context} from "../utils/Context.sol"; /** * @dev Context variant with ERC2771 support. * * WARNING: Avoid using this pattern in contracts that rely in a specific calldata length as they'll * be affected by any forwarder whose `msg.data` is suffixed with the `from` address according to the ERC2771 * specification adding the address size in bytes (20) to the calldata size. An example of an unexpected * behavior could be an unintended fallback (or another function) invocation while trying to invoke the `receive` * function only accessible if `msg.data.length == 0`. * * WARNING: The usage of `delegatecall` in this contract is dangerous and may result in context corruption. * Any forwarded request to this contract triggering a `delegatecall` to itself will result in an invalid {_msgSender} * recovery. */ abstract contract ERC2771Context is Context { /// @custom:oz-upgrades-unsafe-allow state-variable-immutable address private immutable _trustedForwarder; /** * @dev Initializes the contract with a trusted forwarder, which will be able to * invoke functions on this contract on behalf of other accounts. * * NOTE: The trusted forwarder can be replaced by overriding {trustedForwarder}. */ /// @custom:oz-upgrades-unsafe-allow constructor constructor(address trustedForwarder_) { _trustedForwarder = trustedForwarder_; } /** * @dev Returns the address of the trusted forwarder. */ function trustedForwarder() public view virtual returns (address) { return _trustedForwarder; } /** * @dev Indicates whether any particular address is the trusted forwarder. */ function isTrustedForwarder(address forwarder) public view virtual returns (bool) { return forwarder == trustedForwarder(); } /** * @dev Override for `msg.sender`. Defaults to the original `msg.sender` whenever * a call is not performed by the trusted forwarder or the calldata length is less than * 20 bytes (an address length). */ function _msgSender() internal view virtual override returns (address) { uint256 calldataLength = msg.data.length; uint256 contextSuffixLength = _contextSuffixLength(); if (isTrustedForwarder(msg.sender) && calldataLength >= contextSuffixLength) { return address(bytes20(msg.data[calldataLength - contextSuffixLength:])); } else { return super._msgSender(); } } /** * @dev Override for `msg.data`. Defaults to the original `msg.data` whenever * a call is not performed by the trusted forwarder or the calldata length is less than * 20 bytes (an address length). */ function _msgData() internal view virtual override returns (bytes calldata) { uint256 calldataLength = msg.data.length; uint256 contextSuffixLength = _contextSuffixLength(); if (isTrustedForwarder(msg.sender) && calldataLength >= contextSuffixLength) { return msg.data[:calldataLength - contextSuffixLength]; } else { return super._msgData(); } } /** * @dev ERC-2771 specifies the context as being a single address (20 bytes). */ function _contextSuffixLength() internal view virtual override returns (uint256) { return 20; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (metatx/ERC2771Forwarder.sol) pragma solidity ^0.8.20; import {ERC2771Context} from "./ERC2771Context.sol"; import {ECDSA} from "../utils/cryptography/ECDSA.sol"; import {EIP712} from "../utils/cryptography/EIP712.sol"; import {Nonces} from "../utils/Nonces.sol"; import {Address} from "../utils/Address.sol"; /** * @dev A forwarder compatible with ERC2771 contracts. See {ERC2771Context}. * * This forwarder operates on forward requests that include: * * * `from`: An address to operate on behalf of. It is required to be equal to the request signer. * * `to`: The address that should be called. * * `value`: The amount of native token to attach with the requested call. * * `gas`: The amount of gas limit that will be forwarded with the requested call. * * `nonce`: A unique transaction ordering identifier to avoid replayability and request invalidation. * * `deadline`: A timestamp after which the request is not executable anymore. * * `data`: Encoded `msg.data` to send with the requested call. * * Relayers are able to submit batches if they are processing a high volume of requests. With high * throughput, relayers may run into limitations of the chain such as limits on the number of * transactions in the mempool. In these cases the recommendation is to distribute the load among * multiple accounts. * * NOTE: Batching requests includes an optional refund for unused `msg.value` that is achieved by * performing a call with empty calldata. While this is within the bounds of ERC-2771 compliance, * if the refund receiver happens to consider the forwarder a trusted forwarder, it MUST properly * handle `msg.data.length == 0`. `ERC2771Context` in OpenZeppelin Contracts versions prior to 4.9.3 * do not handle this properly. * * ==== Security Considerations * * If a relayer submits a forward request, it should be willing to pay up to 100% of the gas amount * specified in the request. This contract does not implement any kind of retribution for this gas, * and it is assumed that there is an out of band incentive for relayers to pay for execution on * behalf of signers. Often, the relayer is operated by a project that will consider it a user * acquisition cost. * * By offering to pay for gas, relayers are at risk of having that gas used by an attacker toward * some other purpose that is not aligned with the expected out of band incentives. If you operate a * relayer, consider whitelisting target contracts and function selectors. When relaying ERC-721 or * ERC-1155 transfers specifically, consider rejecting the use of the `data` field, since it can be * used to execute arbitrary code. */ contract ERC2771Forwarder is EIP712, Nonces { using ECDSA for bytes32; struct ForwardRequestData { address from; address to; uint256 value; uint256 gas; uint48 deadline; bytes data; bytes signature; } bytes32 internal constant _FORWARD_REQUEST_TYPEHASH = keccak256( "ForwardRequest(address from,address to,uint256 value,uint256 gas,uint256 nonce,uint48 deadline,bytes data)" ); /** * @dev Emitted when a `ForwardRequest` is executed. * * NOTE: An unsuccessful forward request could be due to an invalid signature, an expired deadline, * or simply a revert in the requested call. The contract guarantees that the relayer is not able to force * the requested call to run out of gas. */ event ExecutedForwardRequest(address indexed signer, uint256 nonce, bool success); /** * @dev The request `from` doesn't match with the recovered `signer`. */ error ERC2771ForwarderInvalidSigner(address signer, address from); /** * @dev The `requestedValue` doesn't match with the available `msgValue`. */ error ERC2771ForwarderMismatchedValue(uint256 requestedValue, uint256 msgValue); /** * @dev The request `deadline` has expired. */ error ERC2771ForwarderExpiredRequest(uint48 deadline); /** * @dev The request target doesn't trust the `forwarder`. */ error ERC2771UntrustfulTarget(address target, address forwarder); /** * @dev See {EIP712-constructor}. */ constructor(string memory name) EIP712(name, "1") {} /** * @dev Returns `true` if a request is valid for a provided `signature` at the current block timestamp. * * A transaction is considered valid when the target trusts this forwarder, the request hasn't expired * (deadline is not met), and the signer matches the `from` parameter of the signed request. * * NOTE: A request may return false here but it won't cause {executeBatch} to revert if a refund * receiver is provided. */ function verify(ForwardRequestData calldata request) public view virtual returns (bool) { (bool isTrustedForwarder, bool active, bool signerMatch, ) = _validate(request); return isTrustedForwarder && active && signerMatch; } /** * @dev Executes a `request` on behalf of `signature`'s signer using the ERC-2771 protocol. The gas * provided to the requested call may not be exactly the amount requested, but the call will not run * out of gas. Will revert if the request is invalid or the call reverts, in this case the nonce is not consumed. * * Requirements: * * - The request value should be equal to the provided `msg.value`. * - The request should be valid according to {verify}. */ function execute(ForwardRequestData calldata request) public payable virtual { // We make sure that msg.value and request.value match exactly. // If the request is invalid or the call reverts, this whole function // will revert, ensuring value isn't stuck. if (msg.value != request.value) { revert ERC2771ForwarderMismatchedValue(request.value, msg.value); } if (!_execute(request, true)) { revert Address.FailedInnerCall(); } } /** * @dev Batch version of {execute} with optional refunding and atomic execution. * * In case a batch contains at least one invalid request (see {verify}), the * request will be skipped and the `refundReceiver` parameter will receive back the * unused requested value at the end of the execution. This is done to prevent reverting * the entire batch when a request is invalid or has already been submitted. * * If the `refundReceiver` is the `address(0)`, this function will revert when at least * one of the requests was not valid instead of skipping it. This could be useful if * a batch is required to get executed atomically (at least at the top-level). For example, * refunding (and thus atomicity) can be opt-out if the relayer is using a service that avoids * including reverted transactions. * * Requirements: * * - The sum of the requests' values should be equal to the provided `msg.value`. * - All of the requests should be valid (see {verify}) when `refundReceiver` is the zero address. * * NOTE: Setting a zero `refundReceiver` guarantees an all-or-nothing requests execution only for * the first-level forwarded calls. In case a forwarded request calls to a contract with another * subcall, the second-level call may revert without the top-level call reverting. */ function executeBatch( ForwardRequestData[] calldata requests, address payable refundReceiver ) public payable virtual { bool atomic = refundReceiver == address(0); uint256 requestsValue; uint256 refundValue; for (uint256 i; i < requests.length; ++i) { requestsValue += requests[i].value; bool success = _execute(requests[i], atomic); if (!success) { refundValue += requests[i].value; } } // The batch should revert if there's a mismatched msg.value provided // to avoid request value tampering if (requestsValue != msg.value) { revert ERC2771ForwarderMismatchedValue(requestsValue, msg.value); } // Some requests with value were invalid (possibly due to frontrunning). // To avoid leaving ETH in the contract this value is refunded. if (refundValue != 0) { // We know refundReceiver != address(0) && requestsValue == msg.value // meaning we can ensure refundValue is not taken from the original contract's balance // and refundReceiver is a known account. Address.sendValue(refundReceiver, refundValue); } } /** * @dev Validates if the provided request can be executed at current block timestamp with * the given `request.signature` on behalf of `request.signer`. */ function _validate( ForwardRequestData calldata request ) internal view virtual returns (bool isTrustedForwarder, bool active, bool signerMatch, address signer) { (bool isValid, address recovered) = _recoverForwardRequestSigner(request); return ( _isTrustedByTarget(request.to), request.deadline >= block.timestamp, isValid && recovered == request.from, recovered ); } /** * @dev Returns a tuple with the recovered the signer of an EIP712 forward request message hash * and a boolean indicating if the signature is valid. * * NOTE: The signature is considered valid if {ECDSA-tryRecover} indicates no recover error for it. */ function _recoverForwardRequestSigner( ForwardRequestData calldata request ) internal view virtual returns (bool, address) { (address recovered, ECDSA.RecoverError err, ) = _hashTypedDataV4( keccak256( abi.encode( _FORWARD_REQUEST_TYPEHASH, request.from, request.to, request.value, request.gas, nonces(request.from), request.deadline, keccak256(request.data) ) ) ).tryRecover(request.signature); return (err == ECDSA.RecoverError.NoError, recovered); } /** * @dev Validates and executes a signed request returning the request call `success` value. * * Internal function without msg.value validation. * * Requirements: * * - The caller must have provided enough gas to forward with the call. * - The request must be valid (see {verify}) if the `requireValidRequest` is true. * * Emits an {ExecutedForwardRequest} event. * * IMPORTANT: Using this function doesn't check that all the `msg.value` was sent, potentially * leaving value stuck in the contract. */ function _execute( ForwardRequestData calldata request, bool requireValidRequest ) internal virtual returns (bool success) { (bool isTrustedForwarder, bool active, bool signerMatch, address signer) = _validate(request); // Need to explicitly specify if a revert is required since non-reverting is default for // batches and reversion is opt-in since it could be useful in some scenarios if (requireValidRequest) { if (!isTrustedForwarder) { revert ERC2771UntrustfulTarget(request.to, address(this)); } if (!active) { revert ERC2771ForwarderExpiredRequest(request.deadline); } if (!signerMatch) { revert ERC2771ForwarderInvalidSigner(signer, request.from); } } // Ignore an invalid request because requireValidRequest = false if (isTrustedForwarder && signerMatch && active) { // Nonce should be used before the call to prevent reusing by reentrancy uint256 currentNonce = _useNonce(signer); uint256 reqGas = request.gas; address to = request.to; uint256 value = request.value; bytes memory data = abi.encodePacked(request.data, request.from); uint256 gasLeft; assembly { success := call(reqGas, to, value, add(data, 0x20), mload(data), 0, 0) gasLeft := gas() } _checkForwardedGas(gasLeft, request); emit ExecutedForwardRequest(signer, currentNonce, success); } } /** * @dev Returns whether the target trusts this forwarder. * * This function performs a static call to the target contract calling the * {ERC2771Context-isTrustedForwarder} function. */ function _isTrustedByTarget(address target) private view returns (bool) { bytes memory encodedParams = abi.encodeCall(ERC2771Context.isTrustedForwarder, (address(this))); bool success; uint256 returnSize; uint256 returnValue; /// @solidity memory-safe-assembly assembly { // Perform the staticcal and save the result in the scratch space. // | Location | Content | Content (Hex) | // |-----------|----------|--------------------------------------------------------------------| // | | | result ↓ | // | 0x00:0x1F | selector | 0x0000000000000000000000000000000000000000000000000000000000000001 | success := staticcall(gas(), target, add(encodedParams, 0x20), mload(encodedParams), 0, 0x20) returnSize := returndatasize() returnValue := mload(0) } return success && returnSize >= 0x20 && returnValue > 0; } /** * @dev Checks if the requested gas was correctly forwarded to the callee. * * As a consequence of https://eips.ethereum.org/EIPS/eip-150[EIP-150]: * - At most `gasleft() - floor(gasleft() / 64)` is forwarded to the callee. * - At least `floor(gasleft() / 64)` is kept in the caller. * * It reverts consuming all the available gas if the forwarded gas is not the requested gas. * * IMPORTANT: The `gasLeft` parameter should be measured exactly at the end of the forwarded call. * Any gas consumed in between will make room for bypassing this check. */ function _checkForwardedGas(uint256 gasLeft, ForwardRequestData calldata request) private pure { // To avoid insufficient gas griefing attacks, as referenced in https://ronan.eth.limo/blog/ethereum-gas-dangers/ // // A malicious relayer can attempt to shrink the gas forwarded so that the underlying call reverts out-of-gas // but the forwarding itself still succeeds. In order to make sure that the subcall received sufficient gas, // we will inspect gasleft() after the forwarding. // // Let X be the gas available before the subcall, such that the subcall gets at most X * 63 / 64. // We can't know X after CALL dynamic costs, but we want it to be such that X * 63 / 64 >= req.gas. // Let Y be the gas used in the subcall. gasleft() measured immediately after the subcall will be gasleft() = X - Y. // If the subcall ran out of gas, then Y = X * 63 / 64 and gasleft() = X - Y = X / 64. // Under this assumption req.gas / 63 > gasleft() is true is true if and only if // req.gas / 63 > X / 64, or equivalently req.gas > X * 63 / 64. // This means that if the subcall runs out of gas we are able to detect that insufficient gas was passed. // // We will now also see that req.gas / 63 > gasleft() implies that req.gas >= X * 63 / 64. // The contract guarantees Y <= req.gas, thus gasleft() = X - Y >= X - req.gas. // - req.gas / 63 > gasleft() // - req.gas / 63 >= X - req.gas // - req.gas >= X * 63 / 64 // In other words if req.gas < X * 63 / 64 then req.gas / 63 <= gasleft(), thus if the relayer behaves honestly // the forwarding does not revert. if (gasLeft < request.gas / 63) { // We explicitly trigger invalid opcode to consume all gas and bubble-up the effects, since // neither revert or assert consume all gas since Solidity 0.8.20 // https://docs.soliditylang.org/en/v0.8.20/control-structures.html#panic-via-assert-and-error-via-require /// @solidity memory-safe-assembly assembly { invalid() } } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (proxy/Clones.sol) pragma solidity ^0.8.20; /** * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 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 A clone instance deployment failed. */ error ERC1167FailedCreateClone(); /** * @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) { /// @solidity memory-safe-assembly assembly { // 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(0, 0x09, 0x37) } if (instance == address(0)) { revert ERC1167FailedCreateClone(); } } /** * @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) { /// @solidity memory-safe-assembly assembly { // 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(0, 0x09, 0x37, salt) } if (instance == address(0)) { revert ERC1167FailedCreateClone(); } } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress( address implementation, bytes32 salt, address deployer ) internal pure returns (address predicted) { /// @solidity memory-safe-assembly assembly { 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 := keccak256(add(ptr, 0x43), 0x55) } } /** * @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.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.0.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.20; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); /** * @dev Returns the 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.0.0) (token/ERC20/extensions/IERC20Permit.sol) pragma solidity ^0.8.20; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. * * ==== Security Considerations * * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be * considered as an intention to spend the allowance in any specific way. The second is that because permits have * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be * generally recommended is: * * ```solidity * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public { * try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {} * doThing(..., value); * } * * function doThing(..., uint256 value) public { * token.safeTransferFrom(msg.sender, address(this), value); * ... * } * ``` * * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also * {SafeERC20-safeTransferFrom}). * * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so * contracts should have entry points that don't rely on permit. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. * * CAUTION: See Security Considerations above. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.20; import {IERC20} from "../IERC20.sol"; import {IERC20Permit} from "../extensions/IERC20Permit.sol"; import {Address} from "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; /** * @dev An operation with an ERC20 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. */ 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. */ 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. */ 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 Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data); if (returndata.length != 0 && !abi.decode(returndata, (bool))) { 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 silents catches all reverts and returns a bool instead. */ function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false // and not revert is the subcall reverts. (bool success, bytes memory returndata) = address(token).call(data); return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol) pragma solidity ^0.8.20; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev The ETH balance of the account is not enough to perform the operation. */ error AddressInsufficientBalance(address account); /** * @dev There's no code at `target` (it is not a contract). */ error AddressEmptyCode(address target); /** * @dev A call to an address target failed. The target may have reverted. */ error FailedInnerCall(); /** * @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 AddressInsufficientBalance(address(this)); } (bool success, ) = recipient.call{value: amount}(""); if (!success) { revert FailedInnerCall(); } } /** * @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 * {FailedInnerCall} 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 AddressInsufficientBalance(address(this)); } (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 {FailedInnerCall}) 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 {FailedInnerCall} 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 {FailedInnerCall}. */ 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 /// @solidity memory-safe-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert FailedInnerCall(); } } }
// 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.0.1) (utils/Multicall.sol) pragma solidity ^0.8.20; import {Address} from "./Address.sol"; import {Context} from "./Context.sol"; /** * @dev Provides a function to batch together multiple calls in a single external call. * * Consider any assumption about calldata validation performed by the sender may be violated if it's not especially * careful about sending transactions invoking {multicall}. For example, a relay address that filters function * selectors won't filter calls nested within a {multicall} operation. * * NOTE: Since 5.0.1 and 4.9.4, this contract identifies non-canonical contexts (i.e. `msg.sender` is not {_msgSender}). * If a non-canonical context is identified, the following self `delegatecall` appends the last bytes of `msg.data` * to the subcall. This makes it safe to use with {ERC2771Context}. Contexts that don't affect the resolution of * {_msgSender} are not propagated to subcalls. */ abstract contract Multicall is Context { /** * @dev Receives and executes a batch of function calls on this contract. * @custom:oz-upgrades-unsafe-allow-reachable delegatecall */ function multicall(bytes[] calldata data) external virtual returns (bytes[] memory results) { bytes memory context = msg.sender == _msgSender() ? new bytes(0) : msg.data[msg.data.length - _contextSuffixLength():]; results = new bytes[](data.length); for (uint256 i = 0; i < data.length; i++) { results[i] = Address.functionDelegateCall(address(this), bytes.concat(data[i], context)); } return results; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/Nonces.sol) pragma solidity ^0.8.20; /** * @dev Provides tracking nonces for addresses. Nonces will only increment. */ abstract contract Nonces { /** * @dev The nonce used for an `account` is not the expected current nonce. */ error InvalidAccountNonce(address account, uint256 currentNonce); mapping(address account => uint256) private _nonces; /** * @dev Returns the next unused nonce for an address. */ function nonces(address owner) public view virtual returns (uint256) { return _nonces[owner]; } /** * @dev Consumes a nonce. * * Returns the current value and increments nonce. */ function _useNonce(address owner) internal virtual returns (uint256) { // For each account, the nonce has an initial value of 0, can only be incremented by one, and cannot be // decremented or reset. This guarantees that the nonce never overflows. unchecked { // It is important to do x++ and not ++x here. return _nonces[owner]++; } } /** * @dev Same as {_useNonce} but checking that `nonce` is the next valid for `owner`. */ function _useCheckedNonce(address owner, uint256 nonce) internal virtual { uint256 current = _useNonce(owner); if (nonce != current) { revert InvalidAccountNonce(owner, current); } } }
// 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.0.0) (utils/ReentrancyGuard.sol) pragma solidity ^0.8.20; /** * @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 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 ReentrancyGuard { // 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; uint256 private _status; /** * @dev Unauthorized reentrant call. */ error ReentrancyGuardReentrantCall(); constructor() { _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 { // 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 { // 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) { return _status == ENTERED; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.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); /// @solidity memory-safe-assembly assembly { 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.0.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 ERC1967 implementation slot: * ```solidity * contract ERC1967 { * 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; * } * } * ``` */ library StorageSlot { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 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) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `StringSlot` with member `value` located at `slot`. */ function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) { /// @solidity memory-safe-assembly assembly { 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) { /// @solidity memory-safe-assembly assembly { r.slot := store.slot } } /** * @dev Returns an `BytesSlot` with member `value` located at `slot`. */ function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) { /// @solidity memory-safe-assembly assembly { 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) { /// @solidity memory-safe-assembly assembly { r.slot := store.slot } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.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; /// @solidity memory-safe-assembly assembly { ptr := add(buffer, add(32, length)) } while (true) { ptr--; /// @solidity memory-safe-assembly assembly { 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 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 // OpenZeppelin Contracts (last updated v5.0.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, RecoverError, bytes32) { 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. /// @solidity memory-safe-assembly assembly { 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[EIP-2098 short signatures] */ function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError, bytes32) { 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, RecoverError, bytes32) { // 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.0.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.0.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[EIP 191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712] * specifications. */ library MessageHashUtils { /** * @dev Returns the keccak256 digest of an EIP-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) { /// @solidity memory-safe-assembly assembly { 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 EIP-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 EIP-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 (EIP-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) { /// @solidity memory-safe-assembly assembly { 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.0.0) (utils/math/Math.sol) pragma solidity ^0.8.20; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Muldiv operation overflow. */ error MathOverflowedMulDiv(); 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 overflow flag. */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the subtraction of two unsigned integers, with an overflow flag. */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { 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 division by zero flag. */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a > b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return 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. return a / b; } // (a + b - 1) / b can overflow on addition, so we distribute. return a == 0 ? 0 : (a - 1) / b + 1; } /** * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or * denominator == 0. * @dev 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^256 and mod 2^256 - 1, then use // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2^256 + 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^256. Also prevents denominator == 0. if (denominator <= prod1) { revert MathOverflowedMulDiv(); } /////////////////////////////////////////////// // 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^256 / 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^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for // four bits. That is, denominator * inv = 1 mod 2^4. 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^8 inverse *= 2 - denominator * inverse; // inverse mod 2^16 inverse *= 2 - denominator * inverse; // inverse mod 2^32 inverse *= 2 - denominator * inverse; // inverse mod 2^64 inverse *= 2 - denominator * inverse; // inverse mod 2^128 inverse *= 2 - denominator * inverse; // inverse mod 2^256 // 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^256. Since the preconditions guarantee that the outcome is // less than 2^256, 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; } } /** * @notice 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) { uint256 result = mulDiv(x, y, denominator); if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) { result += 1; } return result; } /** * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded * towards zero. * * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11). */ function sqrt(uint256 a) internal pure returns (uint256) { if (a == 0) { return 0; } // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target. // // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`. // // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)` // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))` // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)` // // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit. uint256 result = 1 << (log2(a) >> 1); // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128, // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision // into the expected uint128 result. unchecked { result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; return min(result, a / result); } } /** * @notice 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 + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0); } } /** * @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; unchecked { if (value >> 128 > 0) { value >>= 128; result += 128; } if (value >> 64 > 0) { value >>= 64; result += 64; } if (value >> 32 > 0) { value >>= 32; result += 32; } if (value >> 16 > 0) { value >>= 16; result += 16; } if (value >> 8 > 0) { value >>= 8; result += 8; } if (value >> 4 > 0) { value >>= 4; result += 4; } if (value >> 2 > 0) { value >>= 2; result += 2; } if (value >> 1 > 0) { result += 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 + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0); } } /** * @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 + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0); } } /** * @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; unchecked { if (value >> 128 > 0) { value >>= 128; result += 16; } if (value >> 64 > 0) { value >>= 64; result += 8; } if (value >> 32 > 0) { value >>= 32; result += 4; } if (value >> 16 > 0) { value >>= 16; result += 2; } if (value >> 8 > 0) { result += 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 + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0); } } /** * @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.0.0) (utils/math/SignedMath.sol) pragma solidity ^0.8.20; /** * @dev Standard signed math utilities missing in the Solidity language. */ library SignedMath { /** * @dev Returns the largest of two signed numbers. */ function max(int256 a, int256 b) internal pure returns (int256) { return a > b ? a : b; } /** * @dev Returns the smallest of two signed numbers. */ function min(int256 a, int256 b) internal pure returns (int256) { return 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 { // must be unchecked in order to support `n = type(int256).min` return uint256(n >= 0 ? n : -n); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/structs/EnumerableSet.sol) // This file was procedurally generated from scripts/generate/templates/EnumerableSet.js. pragma solidity ^0.8.20; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ```solidity * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. * * [WARNING] * ==== * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure * unusable. * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info. * * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an * array of EnumerableSet. * ==== */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position is the index of the value in the `values` array plus 1. // Position 0 is used to mean a value is not in the set. mapping(bytes32 value => uint256) _positions; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._positions[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We cache the value's position to prevent multiple reads from the same storage slot uint256 position = set._positions[value]; if (position != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 valueIndex = position - 1; uint256 lastIndex = set._values.length - 1; if (valueIndex != lastIndex) { bytes32 lastValue = set._values[lastIndex]; // Move the lastValue to the index where the value to delete is set._values[valueIndex] = lastValue; // Update the tracked position of the lastValue (that was just moved) set._positions[lastValue] = position; } // Delete the slot where the moved value was stored set._values.pop(); // Delete the tracked position for the deleted slot delete set._positions[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._positions[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { bytes32[] memory store = _values(set._inner); bytes32[] memory result; /// @solidity memory-safe-assembly assembly { result := store } return result; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; /// @solidity memory-safe-assembly assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values in the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; /// @solidity memory-safe-assembly assembly { result := store } return result; } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; // Common.sol // // Common mathematical functions used in both SD59x18 and UD60x18. Note that these global functions do not // always operate with SD59x18 and UD60x18 numbers. /*////////////////////////////////////////////////////////////////////////// CUSTOM ERRORS //////////////////////////////////////////////////////////////////////////*/ /// @notice Thrown when the resultant value in {mulDiv} overflows uint256. error PRBMath_MulDiv_Overflow(uint256 x, uint256 y, uint256 denominator); /// @notice Thrown when the resultant value in {mulDiv18} overflows uint256. error PRBMath_MulDiv18_Overflow(uint256 x, uint256 y); /// @notice Thrown when one of the inputs passed to {mulDivSigned} is `type(int256).min`. error PRBMath_MulDivSigned_InputTooSmall(); /// @notice Thrown when the resultant value in {mulDivSigned} overflows int256. error PRBMath_MulDivSigned_Overflow(int256 x, int256 y); /*////////////////////////////////////////////////////////////////////////// CONSTANTS //////////////////////////////////////////////////////////////////////////*/ /// @dev The maximum value a uint128 number can have. uint128 constant MAX_UINT128 = type(uint128).max; /// @dev The maximum value a uint40 number can have. uint40 constant MAX_UINT40 = type(uint40).max; /// @dev The unit number, which the decimal precision of the fixed-point types. uint256 constant UNIT = 1e18; /// @dev The unit number inverted mod 2^256. uint256 constant UNIT_INVERSE = 78156646155174841979727994598816262306175212592076161876661_508869554232690281; /// @dev The the largest power of two that divides the decimal value of `UNIT`. The logarithm of this value is the least significant /// bit in the binary representation of `UNIT`. uint256 constant UNIT_LPOTD = 262144; /*////////////////////////////////////////////////////////////////////////// FUNCTIONS //////////////////////////////////////////////////////////////////////////*/ /// @notice Calculates the binary exponent of x using the binary fraction method. /// @dev Has to use 192.64-bit fixed-point numbers. See https://ethereum.stackexchange.com/a/96594/24693. /// @param x The exponent as an unsigned 192.64-bit fixed-point number. /// @return result The result as an unsigned 60.18-decimal fixed-point number. /// @custom:smtchecker abstract-function-nondet function exp2(uint256 x) pure returns (uint256 result) { unchecked { // Start from 0.5 in the 192.64-bit fixed-point format. result = 0x800000000000000000000000000000000000000000000000; // The following logic multiplies the result by $\sqrt{2^{-i}}$ when the bit at position i is 1. Key points: // // 1. Intermediate results will not overflow, as the starting point is 2^191 and all magic factors are under 2^65. // 2. The rationale for organizing the if statements into groups of 8 is gas savings. If the result of performing // a bitwise AND operation between x and any value in the array [0x80; 0x40; 0x20; 0x10; 0x08; 0x04; 0x02; 0x01] is 1, // we know that `x & 0xFF` is also 1. if (x & 0xFF00000000000000 > 0) { if (x & 0x8000000000000000 > 0) { result = (result * 0x16A09E667F3BCC909) >> 64; } if (x & 0x4000000000000000 > 0) { result = (result * 0x1306FE0A31B7152DF) >> 64; } if (x & 0x2000000000000000 > 0) { result = (result * 0x1172B83C7D517ADCE) >> 64; } if (x & 0x1000000000000000 > 0) { result = (result * 0x10B5586CF9890F62A) >> 64; } if (x & 0x800000000000000 > 0) { result = (result * 0x1059B0D31585743AE) >> 64; } if (x & 0x400000000000000 > 0) { result = (result * 0x102C9A3E778060EE7) >> 64; } if (x & 0x200000000000000 > 0) { result = (result * 0x10163DA9FB33356D8) >> 64; } if (x & 0x100000000000000 > 0) { result = (result * 0x100B1AFA5ABCBED61) >> 64; } } if (x & 0xFF000000000000 > 0) { if (x & 0x80000000000000 > 0) { result = (result * 0x10058C86DA1C09EA2) >> 64; } if (x & 0x40000000000000 > 0) { result = (result * 0x1002C605E2E8CEC50) >> 64; } if (x & 0x20000000000000 > 0) { result = (result * 0x100162F3904051FA1) >> 64; } if (x & 0x10000000000000 > 0) { result = (result * 0x1000B175EFFDC76BA) >> 64; } if (x & 0x8000000000000 > 0) { result = (result * 0x100058BA01FB9F96D) >> 64; } if (x & 0x4000000000000 > 0) { result = (result * 0x10002C5CC37DA9492) >> 64; } if (x & 0x2000000000000 > 0) { result = (result * 0x1000162E525EE0547) >> 64; } if (x & 0x1000000000000 > 0) { result = (result * 0x10000B17255775C04) >> 64; } } if (x & 0xFF0000000000 > 0) { if (x & 0x800000000000 > 0) { result = (result * 0x1000058B91B5BC9AE) >> 64; } if (x & 0x400000000000 > 0) { result = (result * 0x100002C5C89D5EC6D) >> 64; } if (x & 0x200000000000 > 0) { result = (result * 0x10000162E43F4F831) >> 64; } if (x & 0x100000000000 > 0) { result = (result * 0x100000B1721BCFC9A) >> 64; } if (x & 0x80000000000 > 0) { result = (result * 0x10000058B90CF1E6E) >> 64; } if (x & 0x40000000000 > 0) { result = (result * 0x1000002C5C863B73F) >> 64; } if (x & 0x20000000000 > 0) { result = (result * 0x100000162E430E5A2) >> 64; } if (x & 0x10000000000 > 0) { result = (result * 0x1000000B172183551) >> 64; } } if (x & 0xFF00000000 > 0) { if (x & 0x8000000000 > 0) { result = (result * 0x100000058B90C0B49) >> 64; } if (x & 0x4000000000 > 0) { result = (result * 0x10000002C5C8601CC) >> 64; } if (x & 0x2000000000 > 0) { result = (result * 0x1000000162E42FFF0) >> 64; } if (x & 0x1000000000 > 0) { result = (result * 0x10000000B17217FBB) >> 64; } if (x & 0x800000000 > 0) { result = (result * 0x1000000058B90BFCE) >> 64; } if (x & 0x400000000 > 0) { result = (result * 0x100000002C5C85FE3) >> 64; } if (x & 0x200000000 > 0) { result = (result * 0x10000000162E42FF1) >> 64; } if (x & 0x100000000 > 0) { result = (result * 0x100000000B17217F8) >> 64; } } if (x & 0xFF000000 > 0) { if (x & 0x80000000 > 0) { result = (result * 0x10000000058B90BFC) >> 64; } if (x & 0x40000000 > 0) { result = (result * 0x1000000002C5C85FE) >> 64; } if (x & 0x20000000 > 0) { result = (result * 0x100000000162E42FF) >> 64; } if (x & 0x10000000 > 0) { result = (result * 0x1000000000B17217F) >> 64; } if (x & 0x8000000 > 0) { result = (result * 0x100000000058B90C0) >> 64; } if (x & 0x4000000 > 0) { result = (result * 0x10000000002C5C860) >> 64; } if (x & 0x2000000 > 0) { result = (result * 0x1000000000162E430) >> 64; } if (x & 0x1000000 > 0) { result = (result * 0x10000000000B17218) >> 64; } } if (x & 0xFF0000 > 0) { if (x & 0x800000 > 0) { result = (result * 0x1000000000058B90C) >> 64; } if (x & 0x400000 > 0) { result = (result * 0x100000000002C5C86) >> 64; } if (x & 0x200000 > 0) { result = (result * 0x10000000000162E43) >> 64; } if (x & 0x100000 > 0) { result = (result * 0x100000000000B1721) >> 64; } if (x & 0x80000 > 0) { result = (result * 0x10000000000058B91) >> 64; } if (x & 0x40000 > 0) { result = (result * 0x1000000000002C5C8) >> 64; } if (x & 0x20000 > 0) { result = (result * 0x100000000000162E4) >> 64; } if (x & 0x10000 > 0) { result = (result * 0x1000000000000B172) >> 64; } } if (x & 0xFF00 > 0) { if (x & 0x8000 > 0) { result = (result * 0x100000000000058B9) >> 64; } if (x & 0x4000 > 0) { result = (result * 0x10000000000002C5D) >> 64; } if (x & 0x2000 > 0) { result = (result * 0x1000000000000162E) >> 64; } if (x & 0x1000 > 0) { result = (result * 0x10000000000000B17) >> 64; } if (x & 0x800 > 0) { result = (result * 0x1000000000000058C) >> 64; } if (x & 0x400 > 0) { result = (result * 0x100000000000002C6) >> 64; } if (x & 0x200 > 0) { result = (result * 0x10000000000000163) >> 64; } if (x & 0x100 > 0) { result = (result * 0x100000000000000B1) >> 64; } } if (x & 0xFF > 0) { if (x & 0x80 > 0) { result = (result * 0x10000000000000059) >> 64; } if (x & 0x40 > 0) { result = (result * 0x1000000000000002C) >> 64; } if (x & 0x20 > 0) { result = (result * 0x10000000000000016) >> 64; } if (x & 0x10 > 0) { result = (result * 0x1000000000000000B) >> 64; } if (x & 0x8 > 0) { result = (result * 0x10000000000000006) >> 64; } if (x & 0x4 > 0) { result = (result * 0x10000000000000003) >> 64; } if (x & 0x2 > 0) { result = (result * 0x10000000000000001) >> 64; } if (x & 0x1 > 0) { result = (result * 0x10000000000000001) >> 64; } } // In the code snippet below, two operations are executed simultaneously: // // 1. The result is multiplied by $(2^n + 1)$, where $2^n$ represents the integer part, and the additional 1 // accounts for the initial guess of 0.5. This is achieved by subtracting from 191 instead of 192. // 2. The result is then converted to an unsigned 60.18-decimal fixed-point format. // // The underlying logic is based on the relationship $2^{191-ip} = 2^{ip} / 2^{191}$, where $ip$ denotes the, // integer part, $2^n$. result *= UNIT; result >>= (191 - (x >> 64)); } } /// @notice Finds the zero-based index of the first 1 in the binary representation of x. /// /// @dev See the note on "msb" in this Wikipedia article: https://en.wikipedia.org/wiki/Find_first_set /// /// Each step in this implementation is equivalent to this high-level code: /// /// ```solidity /// if (x >= 2 ** 128) { /// x >>= 128; /// result += 128; /// } /// ``` /// /// Where 128 is replaced with each respective power of two factor. See the full high-level implementation here: /// https://gist.github.com/PaulRBerg/f932f8693f2733e30c4d479e8e980948 /// /// The Yul instructions used below are: /// /// - "gt" is "greater than" /// - "or" is the OR bitwise operator /// - "shl" is "shift left" /// - "shr" is "shift right" /// /// @param x The uint256 number for which to find the index of the most significant bit. /// @return result The index of the most significant bit as a uint256. /// @custom:smtchecker abstract-function-nondet function msb(uint256 x) pure returns (uint256 result) { // 2^128 assembly ("memory-safe") { let factor := shl(7, gt(x, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) x := shr(factor, x) result := or(result, factor) } // 2^64 assembly ("memory-safe") { let factor := shl(6, gt(x, 0xFFFFFFFFFFFFFFFF)) x := shr(factor, x) result := or(result, factor) } // 2^32 assembly ("memory-safe") { let factor := shl(5, gt(x, 0xFFFFFFFF)) x := shr(factor, x) result := or(result, factor) } // 2^16 assembly ("memory-safe") { let factor := shl(4, gt(x, 0xFFFF)) x := shr(factor, x) result := or(result, factor) } // 2^8 assembly ("memory-safe") { let factor := shl(3, gt(x, 0xFF)) x := shr(factor, x) result := or(result, factor) } // 2^4 assembly ("memory-safe") { let factor := shl(2, gt(x, 0xF)) x := shr(factor, x) result := or(result, factor) } // 2^2 assembly ("memory-safe") { let factor := shl(1, gt(x, 0x3)) x := shr(factor, x) result := or(result, factor) } // 2^1 // No need to shift x any more. assembly ("memory-safe") { let factor := gt(x, 0x1) result := or(result, factor) } } /// @notice Calculates x*y÷denominator with 512-bit precision. /// /// @dev Credits to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv. /// /// Notes: /// - The result is rounded toward zero. /// /// Requirements: /// - The denominator must not be zero. /// - The result must fit in uint256. /// /// @param x The multiplicand as a uint256. /// @param y The multiplier as a uint256. /// @param denominator The divisor as a uint256. /// @return result The result as a uint256. /// @custom:smtchecker abstract-function-nondet function mulDiv(uint256 x, uint256 y, uint256 denominator) pure returns (uint256 result) { // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use // use the Chinese Remainder Theorem to reconstruct the 512-bit result. The result is stored in two 256 // variables such that product = prod1 * 2^256 + prod0. uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly ("memory-safe") { let mm := mulmod(x, y, not(0)) prod0 := mul(x, y) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division. if (prod1 == 0) { unchecked { return prod0 / denominator; } } // Make sure the result is less than 2^256. Also prevents denominator == 0. if (prod1 >= denominator) { revert PRBMath_MulDiv_Overflow(x, y, denominator); } //////////////////////////////////////////////////////////////////////////// // 512 by 256 division //////////////////////////////////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0]. uint256 remainder; assembly ("memory-safe") { // Compute remainder using the mulmod Yul instruction. remainder := mulmod(x, y, denominator) // Subtract 256 bit number from 512-bit number. prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } unchecked { // Calculate the largest power of two divisor of the denominator using the unary operator ~. This operation cannot overflow // because the denominator cannot be zero at this point in the function execution. The result is always >= 1. // For more detail, see https://cs.stackexchange.com/q/138556/92363. uint256 lpotdod = denominator & (~denominator + 1); uint256 flippedLpotdod; assembly ("memory-safe") { // Factor powers of two out of denominator. denominator := div(denominator, lpotdod) // Divide [prod1 prod0] by lpotdod. prod0 := div(prod0, lpotdod) // Get the flipped value `2^256 / lpotdod`. If the `lpotdod` is zero, the flipped value is one. // `sub(0, lpotdod)` produces the two's complement version of `lpotdod`, which is equivalent to flipping all the bits. // However, `div` interprets this value as an unsigned value: https://ethereum.stackexchange.com/q/147168/24693 flippedLpotdod := add(div(sub(0, lpotdod), lpotdod), 1) } // Shift in bits from prod1 into prod0. prod0 |= prod1 * flippedLpotdod; // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for // four bits. That is, denominator * inv = 1 mod 2^4. 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^8 inverse *= 2 - denominator * inverse; // inverse mod 2^16 inverse *= 2 - denominator * inverse; // inverse mod 2^32 inverse *= 2 - denominator * inverse; // inverse mod 2^64 inverse *= 2 - denominator * inverse; // inverse mod 2^128 inverse *= 2 - denominator * inverse; // inverse mod 2^256 // 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^256. Since the preconditions guarantee that the outcome is // less than 2^256, 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; } } /// @notice Calculates x*y÷1e18 with 512-bit precision. /// /// @dev A variant of {mulDiv} with constant folding, i.e. in which the denominator is hard coded to 1e18. /// /// Notes: /// - The body is purposely left uncommented; to understand how this works, see the documentation in {mulDiv}. /// - The result is rounded toward zero. /// - We take as an axiom that the result cannot be `MAX_UINT256` when x and y solve the following system of equations: /// /// $$ /// \begin{cases} /// x * y = MAX\_UINT256 * UNIT \\ /// (x * y) \% UNIT \geq \frac{UNIT}{2} /// \end{cases} /// $$ /// /// Requirements: /// - Refer to the requirements in {mulDiv}. /// - The result must fit in uint256. /// /// @param x The multiplicand as an unsigned 60.18-decimal fixed-point number. /// @param y The multiplier as an unsigned 60.18-decimal fixed-point number. /// @return result The result as an unsigned 60.18-decimal fixed-point number. /// @custom:smtchecker abstract-function-nondet function mulDiv18(uint256 x, uint256 y) pure returns (uint256 result) { uint256 prod0; uint256 prod1; assembly ("memory-safe") { let mm := mulmod(x, y, not(0)) prod0 := mul(x, y) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } if (prod1 == 0) { unchecked { return prod0 / UNIT; } } if (prod1 >= UNIT) { revert PRBMath_MulDiv18_Overflow(x, y); } uint256 remainder; assembly ("memory-safe") { remainder := mulmod(x, y, UNIT) result := mul( or( div(sub(prod0, remainder), UNIT_LPOTD), mul(sub(prod1, gt(remainder, prod0)), add(div(sub(0, UNIT_LPOTD), UNIT_LPOTD), 1)) ), UNIT_INVERSE ) } } /// @notice Calculates x*y÷denominator with 512-bit precision. /// /// @dev This is an extension of {mulDiv} for signed numbers, which works by computing the signs and the absolute values separately. /// /// Notes: /// - The result is rounded toward zero. /// /// Requirements: /// - Refer to the requirements in {mulDiv}. /// - None of the inputs can be `type(int256).min`. /// - The result must fit in int256. /// /// @param x The multiplicand as an int256. /// @param y The multiplier as an int256. /// @param denominator The divisor as an int256. /// @return result The result as an int256. /// @custom:smtchecker abstract-function-nondet function mulDivSigned(int256 x, int256 y, int256 denominator) pure returns (int256 result) { if (x == type(int256).min || y == type(int256).min || denominator == type(int256).min) { revert PRBMath_MulDivSigned_InputTooSmall(); } // Get hold of the absolute values of x, y and the denominator. uint256 xAbs; uint256 yAbs; uint256 dAbs; unchecked { xAbs = x < 0 ? uint256(-x) : uint256(x); yAbs = y < 0 ? uint256(-y) : uint256(y); dAbs = denominator < 0 ? uint256(-denominator) : uint256(denominator); } // Compute the absolute value of x*y÷denominator. The result must fit in int256. uint256 resultAbs = mulDiv(xAbs, yAbs, dAbs); if (resultAbs > uint256(type(int256).max)) { revert PRBMath_MulDivSigned_Overflow(x, y); } // Get the signs of x, y and the denominator. uint256 sx; uint256 sy; uint256 sd; assembly ("memory-safe") { // "sgt" is the "signed greater than" assembly instruction and "sub(0,1)" is -1 in two's complement. sx := sgt(x, sub(0, 1)) sy := sgt(y, sub(0, 1)) sd := sgt(denominator, sub(0, 1)) } // XOR over sx, sy and sd. What this does is to check whether there are 1 or 3 negative signs in the inputs. // If there are, the result should be negative. Otherwise, it should be positive. unchecked { result = sx ^ sy ^ sd == 0 ? -int256(resultAbs) : int256(resultAbs); } } /// @notice Calculates the square root of x using the Babylonian method. /// /// @dev See https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method. /// /// Notes: /// - If x is not a perfect square, the result is rounded down. /// - Credits to OpenZeppelin for the explanations in comments below. /// /// @param x The uint256 number for which to calculate the square root. /// @return result The result as a uint256. /// @custom:smtchecker abstract-function-nondet function sqrt(uint256 x) pure returns (uint256 result) { if (x == 0) { return 0; } // For our first guess, we calculate the biggest power of 2 which is smaller than the square root of x. // // We know that the "msb" (most significant bit) of x is a power of 2 such that we have: // // $$ // msb(x) <= x <= 2*msb(x)$ // $$ // // We write $msb(x)$ as $2^k$, and we get: // // $$ // k = log_2(x) // $$ // // Thus, we can write the initial inequality as: // // $$ // 2^{log_2(x)} <= x <= 2*2^{log_2(x)+1} \\ // sqrt(2^k) <= sqrt(x) < sqrt(2^{k+1}) \\ // 2^{k/2} <= sqrt(x) < 2^{(k+1)/2} <= 2^{(k/2)+1} // $$ // // Consequently, $2^{log_2(x) /2} is a good first approximation of sqrt(x) with at least one correct bit. uint256 xAux = uint256(x); result = 1; if (xAux >= 2 ** 128) { xAux >>= 128; result <<= 64; } if (xAux >= 2 ** 64) { xAux >>= 64; result <<= 32; } if (xAux >= 2 ** 32) { xAux >>= 32; result <<= 16; } if (xAux >= 2 ** 16) { xAux >>= 16; result <<= 8; } if (xAux >= 2 ** 8) { xAux >>= 8; result <<= 4; } if (xAux >= 2 ** 4) { xAux >>= 4; result <<= 2; } if (xAux >= 2 ** 2) { result <<= 1; } // At this point, `result` is an estimation with at least one bit of precision. We know the true value has at // most 128 bits, since it is the square root of a uint256. Newton's method converges quadratically (precision // doubles at every iteration). We thus need at most 7 iteration to turn our partial result with one bit of // precision into the expected uint128 result. unchecked { result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; // If x is not a perfect square, round the result toward zero. uint256 roundedResult = x / result; if (result >= roundedResult) { result = roundedResult; } } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; /* ██████╗ ██████╗ ██████╗ ███╗ ███╗ █████╗ ████████╗██╗ ██╗ ██╔══██╗██╔══██╗██╔══██╗████╗ ████║██╔══██╗╚══██╔══╝██║ ██║ ██████╔╝██████╔╝██████╔╝██╔████╔██║███████║ ██║ ███████║ ██╔═══╝ ██╔══██╗██╔══██╗██║╚██╔╝██║██╔══██║ ██║ ██╔══██║ ██║ ██║ ██║██████╔╝██║ ╚═╝ ██║██║ ██║ ██║ ██║ ██║ ╚═╝ ╚═╝ ╚═╝╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ██╗ ██╗██████╗ ██████╗ ██████╗ ██╗ ██╗ ██╗ █████╗ ██║ ██║██╔══██╗██╔════╝ ██╔═████╗╚██╗██╔╝███║██╔══██╗ ██║ ██║██║ ██║███████╗ ██║██╔██║ ╚███╔╝ ╚██║╚█████╔╝ ██║ ██║██║ ██║██╔═══██╗████╔╝██║ ██╔██╗ ██║██╔══██╗ ╚██████╔╝██████╔╝╚██████╔╝╚██████╔╝██╔╝ ██╗ ██║╚█████╔╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚════╝ */ import "./ud60x18/Casting.sol"; import "./ud60x18/Constants.sol"; import "./ud60x18/Conversions.sol"; import "./ud60x18/Errors.sol"; import "./ud60x18/Helpers.sol"; import "./ud60x18/Math.sol"; import "./ud60x18/ValueType.sol";
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; import "../Common.sol" as Common; import "./Errors.sol" as CastingErrors; import { SD59x18 } from "../sd59x18/ValueType.sol"; import { UD2x18 } from "../ud2x18/ValueType.sol"; import { UD60x18 } from "../ud60x18/ValueType.sol"; import { SD1x18 } from "./ValueType.sol"; /// @notice Casts an SD1x18 number into SD59x18. /// @dev There is no overflow check because the domain of SD1x18 is a subset of SD59x18. function intoSD59x18(SD1x18 x) pure returns (SD59x18 result) { result = SD59x18.wrap(int256(SD1x18.unwrap(x))); } /// @notice Casts an SD1x18 number into UD2x18. /// - x must be positive. function intoUD2x18(SD1x18 x) pure returns (UD2x18 result) { int64 xInt = SD1x18.unwrap(x); if (xInt < 0) { revert CastingErrors.PRBMath_SD1x18_ToUD2x18_Underflow(x); } result = UD2x18.wrap(uint64(xInt)); } /// @notice Casts an SD1x18 number into UD60x18. /// @dev Requirements: /// - x must be positive. function intoUD60x18(SD1x18 x) pure returns (UD60x18 result) { int64 xInt = SD1x18.unwrap(x); if (xInt < 0) { revert CastingErrors.PRBMath_SD1x18_ToUD60x18_Underflow(x); } result = UD60x18.wrap(uint64(xInt)); } /// @notice Casts an SD1x18 number into uint256. /// @dev Requirements: /// - x must be positive. function intoUint256(SD1x18 x) pure returns (uint256 result) { int64 xInt = SD1x18.unwrap(x); if (xInt < 0) { revert CastingErrors.PRBMath_SD1x18_ToUint256_Underflow(x); } result = uint256(uint64(xInt)); } /// @notice Casts an SD1x18 number into uint128. /// @dev Requirements: /// - x must be positive. function intoUint128(SD1x18 x) pure returns (uint128 result) { int64 xInt = SD1x18.unwrap(x); if (xInt < 0) { revert CastingErrors.PRBMath_SD1x18_ToUint128_Underflow(x); } result = uint128(uint64(xInt)); } /// @notice Casts an SD1x18 number into uint40. /// @dev Requirements: /// - x must be positive. /// - x must be less than or equal to `MAX_UINT40`. function intoUint40(SD1x18 x) pure returns (uint40 result) { int64 xInt = SD1x18.unwrap(x); if (xInt < 0) { revert CastingErrors.PRBMath_SD1x18_ToUint40_Underflow(x); } if (xInt > int64(uint64(Common.MAX_UINT40))) { revert CastingErrors.PRBMath_SD1x18_ToUint40_Overflow(x); } result = uint40(uint64(xInt)); } /// @notice Alias for {wrap}. function sd1x18(int64 x) pure returns (SD1x18 result) { result = SD1x18.wrap(x); } /// @notice Unwraps an SD1x18 number into int64. function unwrap(SD1x18 x) pure returns (int64 result) { result = SD1x18.unwrap(x); } /// @notice Wraps an int64 number into SD1x18. function wrap(int64 x) pure returns (SD1x18 result) { result = SD1x18.wrap(x); }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; import { SD1x18 } from "./ValueType.sol"; /// @dev Euler's number as an SD1x18 number. SD1x18 constant E = SD1x18.wrap(2_718281828459045235); /// @dev The maximum value an SD1x18 number can have. int64 constant uMAX_SD1x18 = 9_223372036854775807; SD1x18 constant MAX_SD1x18 = SD1x18.wrap(uMAX_SD1x18); /// @dev The maximum value an SD1x18 number can have. int64 constant uMIN_SD1x18 = -9_223372036854775808; SD1x18 constant MIN_SD1x18 = SD1x18.wrap(uMIN_SD1x18); /// @dev PI as an SD1x18 number. SD1x18 constant PI = SD1x18.wrap(3_141592653589793238); /// @dev The unit number, which gives the decimal precision of SD1x18. SD1x18 constant UNIT = SD1x18.wrap(1e18); int256 constant uUNIT = 1e18;
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; import { SD1x18 } from "./ValueType.sol"; /// @notice Thrown when trying to cast a SD1x18 number that doesn't fit in UD2x18. error PRBMath_SD1x18_ToUD2x18_Underflow(SD1x18 x); /// @notice Thrown when trying to cast a SD1x18 number that doesn't fit in UD60x18. error PRBMath_SD1x18_ToUD60x18_Underflow(SD1x18 x); /// @notice Thrown when trying to cast a SD1x18 number that doesn't fit in uint128. error PRBMath_SD1x18_ToUint128_Underflow(SD1x18 x); /// @notice Thrown when trying to cast a SD1x18 number that doesn't fit in uint256. error PRBMath_SD1x18_ToUint256_Underflow(SD1x18 x); /// @notice Thrown when trying to cast a SD1x18 number that doesn't fit in uint40. error PRBMath_SD1x18_ToUint40_Overflow(SD1x18 x); /// @notice Thrown when trying to cast a SD1x18 number that doesn't fit in uint40. error PRBMath_SD1x18_ToUint40_Underflow(SD1x18 x);
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; import "./Casting.sol" as Casting; /// @notice The signed 1.18-decimal fixed-point number representation, which can have up to 1 digit and up to 18 /// decimals. The values of this are bound by the minimum and the maximum values permitted by the underlying Solidity /// type int64. This is useful when end users want to use int64 to save gas, e.g. with tight variable packing in contract /// storage. type SD1x18 is int64; /*////////////////////////////////////////////////////////////////////////// CASTING //////////////////////////////////////////////////////////////////////////*/ using { Casting.intoSD59x18, Casting.intoUD2x18, Casting.intoUD60x18, Casting.intoUint256, Casting.intoUint128, Casting.intoUint40, Casting.unwrap } for SD1x18 global;
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; import "./Errors.sol" as CastingErrors; import { MAX_UINT128, MAX_UINT40 } from "../Common.sol"; import { uMAX_SD1x18, uMIN_SD1x18 } from "../sd1x18/Constants.sol"; import { SD1x18 } from "../sd1x18/ValueType.sol"; import { uMAX_UD2x18 } from "../ud2x18/Constants.sol"; import { UD2x18 } from "../ud2x18/ValueType.sol"; import { UD60x18 } from "../ud60x18/ValueType.sol"; import { SD59x18 } from "./ValueType.sol"; /// @notice Casts an SD59x18 number into int256. /// @dev This is basically a functional alias for {unwrap}. function intoInt256(SD59x18 x) pure returns (int256 result) { result = SD59x18.unwrap(x); } /// @notice Casts an SD59x18 number into SD1x18. /// @dev Requirements: /// - x must be greater than or equal to `uMIN_SD1x18`. /// - x must be less than or equal to `uMAX_SD1x18`. function intoSD1x18(SD59x18 x) pure returns (SD1x18 result) { int256 xInt = SD59x18.unwrap(x); if (xInt < uMIN_SD1x18) { revert CastingErrors.PRBMath_SD59x18_IntoSD1x18_Underflow(x); } if (xInt > uMAX_SD1x18) { revert CastingErrors.PRBMath_SD59x18_IntoSD1x18_Overflow(x); } result = SD1x18.wrap(int64(xInt)); } /// @notice Casts an SD59x18 number into UD2x18. /// @dev Requirements: /// - x must be positive. /// - x must be less than or equal to `uMAX_UD2x18`. function intoUD2x18(SD59x18 x) pure returns (UD2x18 result) { int256 xInt = SD59x18.unwrap(x); if (xInt < 0) { revert CastingErrors.PRBMath_SD59x18_IntoUD2x18_Underflow(x); } if (xInt > int256(uint256(uMAX_UD2x18))) { revert CastingErrors.PRBMath_SD59x18_IntoUD2x18_Overflow(x); } result = UD2x18.wrap(uint64(uint256(xInt))); } /// @notice Casts an SD59x18 number into UD60x18. /// @dev Requirements: /// - x must be positive. function intoUD60x18(SD59x18 x) pure returns (UD60x18 result) { int256 xInt = SD59x18.unwrap(x); if (xInt < 0) { revert CastingErrors.PRBMath_SD59x18_IntoUD60x18_Underflow(x); } result = UD60x18.wrap(uint256(xInt)); } /// @notice Casts an SD59x18 number into uint256. /// @dev Requirements: /// - x must be positive. function intoUint256(SD59x18 x) pure returns (uint256 result) { int256 xInt = SD59x18.unwrap(x); if (xInt < 0) { revert CastingErrors.PRBMath_SD59x18_IntoUint256_Underflow(x); } result = uint256(xInt); } /// @notice Casts an SD59x18 number into uint128. /// @dev Requirements: /// - x must be positive. /// - x must be less than or equal to `uMAX_UINT128`. function intoUint128(SD59x18 x) pure returns (uint128 result) { int256 xInt = SD59x18.unwrap(x); if (xInt < 0) { revert CastingErrors.PRBMath_SD59x18_IntoUint128_Underflow(x); } if (xInt > int256(uint256(MAX_UINT128))) { revert CastingErrors.PRBMath_SD59x18_IntoUint128_Overflow(x); } result = uint128(uint256(xInt)); } /// @notice Casts an SD59x18 number into uint40. /// @dev Requirements: /// - x must be positive. /// - x must be less than or equal to `MAX_UINT40`. function intoUint40(SD59x18 x) pure returns (uint40 result) { int256 xInt = SD59x18.unwrap(x); if (xInt < 0) { revert CastingErrors.PRBMath_SD59x18_IntoUint40_Underflow(x); } if (xInt > int256(uint256(MAX_UINT40))) { revert CastingErrors.PRBMath_SD59x18_IntoUint40_Overflow(x); } result = uint40(uint256(xInt)); } /// @notice Alias for {wrap}. function sd(int256 x) pure returns (SD59x18 result) { result = SD59x18.wrap(x); } /// @notice Alias for {wrap}. function sd59x18(int256 x) pure returns (SD59x18 result) { result = SD59x18.wrap(x); } /// @notice Unwraps an SD59x18 number into int256. function unwrap(SD59x18 x) pure returns (int256 result) { result = SD59x18.unwrap(x); } /// @notice Wraps an int256 number into SD59x18. function wrap(int256 x) pure returns (SD59x18 result) { result = SD59x18.wrap(x); }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; import { SD59x18 } from "./ValueType.sol"; // NOTICE: the "u" prefix stands for "unwrapped". /// @dev Euler's number as an SD59x18 number. SD59x18 constant E = SD59x18.wrap(2_718281828459045235); /// @dev The maximum input permitted in {exp}. int256 constant uEXP_MAX_INPUT = 133_084258667509499440; SD59x18 constant EXP_MAX_INPUT = SD59x18.wrap(uEXP_MAX_INPUT); /// @dev The maximum input permitted in {exp2}. int256 constant uEXP2_MAX_INPUT = 192e18 - 1; SD59x18 constant EXP2_MAX_INPUT = SD59x18.wrap(uEXP2_MAX_INPUT); /// @dev Half the UNIT number. int256 constant uHALF_UNIT = 0.5e18; SD59x18 constant HALF_UNIT = SD59x18.wrap(uHALF_UNIT); /// @dev $log_2(10)$ as an SD59x18 number. int256 constant uLOG2_10 = 3_321928094887362347; SD59x18 constant LOG2_10 = SD59x18.wrap(uLOG2_10); /// @dev $log_2(e)$ as an SD59x18 number. int256 constant uLOG2_E = 1_442695040888963407; SD59x18 constant LOG2_E = SD59x18.wrap(uLOG2_E); /// @dev The maximum value an SD59x18 number can have. int256 constant uMAX_SD59x18 = 57896044618658097711785492504343953926634992332820282019728_792003956564819967; SD59x18 constant MAX_SD59x18 = SD59x18.wrap(uMAX_SD59x18); /// @dev The maximum whole value an SD59x18 number can have. int256 constant uMAX_WHOLE_SD59x18 = 57896044618658097711785492504343953926634992332820282019728_000000000000000000; SD59x18 constant MAX_WHOLE_SD59x18 = SD59x18.wrap(uMAX_WHOLE_SD59x18); /// @dev The minimum value an SD59x18 number can have. int256 constant uMIN_SD59x18 = -57896044618658097711785492504343953926634992332820282019728_792003956564819968; SD59x18 constant MIN_SD59x18 = SD59x18.wrap(uMIN_SD59x18); /// @dev The minimum whole value an SD59x18 number can have. int256 constant uMIN_WHOLE_SD59x18 = -57896044618658097711785492504343953926634992332820282019728_000000000000000000; SD59x18 constant MIN_WHOLE_SD59x18 = SD59x18.wrap(uMIN_WHOLE_SD59x18); /// @dev PI as an SD59x18 number. SD59x18 constant PI = SD59x18.wrap(3_141592653589793238); /// @dev The unit number, which gives the decimal precision of SD59x18. int256 constant uUNIT = 1e18; SD59x18 constant UNIT = SD59x18.wrap(1e18); /// @dev The unit number squared. int256 constant uUNIT_SQUARED = 1e36; SD59x18 constant UNIT_SQUARED = SD59x18.wrap(uUNIT_SQUARED); /// @dev Zero as an SD59x18 number. SD59x18 constant ZERO = SD59x18.wrap(0);
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; import { SD59x18 } from "./ValueType.sol"; /// @notice Thrown when taking the absolute value of `MIN_SD59x18`. error PRBMath_SD59x18_Abs_MinSD59x18(); /// @notice Thrown when ceiling a number overflows SD59x18. error PRBMath_SD59x18_Ceil_Overflow(SD59x18 x); /// @notice Thrown when converting a basic integer to the fixed-point format overflows SD59x18. error PRBMath_SD59x18_Convert_Overflow(int256 x); /// @notice Thrown when converting a basic integer to the fixed-point format underflows SD59x18. error PRBMath_SD59x18_Convert_Underflow(int256 x); /// @notice Thrown when dividing two numbers and one of them is `MIN_SD59x18`. error PRBMath_SD59x18_Div_InputTooSmall(); /// @notice Thrown when dividing two numbers and one of the intermediary unsigned results overflows SD59x18. error PRBMath_SD59x18_Div_Overflow(SD59x18 x, SD59x18 y); /// @notice Thrown when taking the natural exponent of a base greater than 133_084258667509499441. error PRBMath_SD59x18_Exp_InputTooBig(SD59x18 x); /// @notice Thrown when taking the binary exponent of a base greater than 192e18. error PRBMath_SD59x18_Exp2_InputTooBig(SD59x18 x); /// @notice Thrown when flooring a number underflows SD59x18. error PRBMath_SD59x18_Floor_Underflow(SD59x18 x); /// @notice Thrown when taking the geometric mean of two numbers and their product is negative. error PRBMath_SD59x18_Gm_NegativeProduct(SD59x18 x, SD59x18 y); /// @notice Thrown when taking the geometric mean of two numbers and multiplying them overflows SD59x18. error PRBMath_SD59x18_Gm_Overflow(SD59x18 x, SD59x18 y); /// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in SD1x18. error PRBMath_SD59x18_IntoSD1x18_Overflow(SD59x18 x); /// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in SD1x18. error PRBMath_SD59x18_IntoSD1x18_Underflow(SD59x18 x); /// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in UD2x18. error PRBMath_SD59x18_IntoUD2x18_Overflow(SD59x18 x); /// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in UD2x18. error PRBMath_SD59x18_IntoUD2x18_Underflow(SD59x18 x); /// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in UD60x18. error PRBMath_SD59x18_IntoUD60x18_Underflow(SD59x18 x); /// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in uint128. error PRBMath_SD59x18_IntoUint128_Overflow(SD59x18 x); /// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in uint128. error PRBMath_SD59x18_IntoUint128_Underflow(SD59x18 x); /// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in uint256. error PRBMath_SD59x18_IntoUint256_Underflow(SD59x18 x); /// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in uint40. error PRBMath_SD59x18_IntoUint40_Overflow(SD59x18 x); /// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in uint40. error PRBMath_SD59x18_IntoUint40_Underflow(SD59x18 x); /// @notice Thrown when taking the logarithm of a number less than or equal to zero. error PRBMath_SD59x18_Log_InputTooSmall(SD59x18 x); /// @notice Thrown when multiplying two numbers and one of the inputs is `MIN_SD59x18`. error PRBMath_SD59x18_Mul_InputTooSmall(); /// @notice Thrown when multiplying two numbers and the intermediary absolute result overflows SD59x18. error PRBMath_SD59x18_Mul_Overflow(SD59x18 x, SD59x18 y); /// @notice Thrown when raising a number to a power and the intermediary absolute result overflows SD59x18. error PRBMath_SD59x18_Powu_Overflow(SD59x18 x, uint256 y); /// @notice Thrown when taking the square root of a negative number. error PRBMath_SD59x18_Sqrt_NegativeInput(SD59x18 x); /// @notice Thrown when the calculating the square root overflows SD59x18. error PRBMath_SD59x18_Sqrt_Overflow(SD59x18 x);
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; import { wrap } from "./Casting.sol"; import { SD59x18 } from "./ValueType.sol"; /// @notice Implements the checked addition operation (+) in the SD59x18 type. function add(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) { return wrap(x.unwrap() + y.unwrap()); } /// @notice Implements the AND (&) bitwise operation in the SD59x18 type. function and(SD59x18 x, int256 bits) pure returns (SD59x18 result) { return wrap(x.unwrap() & bits); } /// @notice Implements the AND (&) bitwise operation in the SD59x18 type. function and2(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) { return wrap(x.unwrap() & y.unwrap()); } /// @notice Implements the equal (=) operation in the SD59x18 type. function eq(SD59x18 x, SD59x18 y) pure returns (bool result) { result = x.unwrap() == y.unwrap(); } /// @notice Implements the greater than operation (>) in the SD59x18 type. function gt(SD59x18 x, SD59x18 y) pure returns (bool result) { result = x.unwrap() > y.unwrap(); } /// @notice Implements the greater than or equal to operation (>=) in the SD59x18 type. function gte(SD59x18 x, SD59x18 y) pure returns (bool result) { result = x.unwrap() >= y.unwrap(); } /// @notice Implements a zero comparison check function in the SD59x18 type. function isZero(SD59x18 x) pure returns (bool result) { result = x.unwrap() == 0; } /// @notice Implements the left shift operation (<<) in the SD59x18 type. function lshift(SD59x18 x, uint256 bits) pure returns (SD59x18 result) { result = wrap(x.unwrap() << bits); } /// @notice Implements the lower than operation (<) in the SD59x18 type. function lt(SD59x18 x, SD59x18 y) pure returns (bool result) { result = x.unwrap() < y.unwrap(); } /// @notice Implements the lower than or equal to operation (<=) in the SD59x18 type. function lte(SD59x18 x, SD59x18 y) pure returns (bool result) { result = x.unwrap() <= y.unwrap(); } /// @notice Implements the unchecked modulo operation (%) in the SD59x18 type. function mod(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) { result = wrap(x.unwrap() % y.unwrap()); } /// @notice Implements the not equal operation (!=) in the SD59x18 type. function neq(SD59x18 x, SD59x18 y) pure returns (bool result) { result = x.unwrap() != y.unwrap(); } /// @notice Implements the NOT (~) bitwise operation in the SD59x18 type. function not(SD59x18 x) pure returns (SD59x18 result) { result = wrap(~x.unwrap()); } /// @notice Implements the OR (|) bitwise operation in the SD59x18 type. function or(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) { result = wrap(x.unwrap() | y.unwrap()); } /// @notice Implements the right shift operation (>>) in the SD59x18 type. function rshift(SD59x18 x, uint256 bits) pure returns (SD59x18 result) { result = wrap(x.unwrap() >> bits); } /// @notice Implements the checked subtraction operation (-) in the SD59x18 type. function sub(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) { result = wrap(x.unwrap() - y.unwrap()); } /// @notice Implements the checked unary minus operation (-) in the SD59x18 type. function unary(SD59x18 x) pure returns (SD59x18 result) { result = wrap(-x.unwrap()); } /// @notice Implements the unchecked addition operation (+) in the SD59x18 type. function uncheckedAdd(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) { unchecked { result = wrap(x.unwrap() + y.unwrap()); } } /// @notice Implements the unchecked subtraction operation (-) in the SD59x18 type. function uncheckedSub(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) { unchecked { result = wrap(x.unwrap() - y.unwrap()); } } /// @notice Implements the unchecked unary minus operation (-) in the SD59x18 type. function uncheckedUnary(SD59x18 x) pure returns (SD59x18 result) { unchecked { result = wrap(-x.unwrap()); } } /// @notice Implements the XOR (^) bitwise operation in the SD59x18 type. function xor(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) { result = wrap(x.unwrap() ^ y.unwrap()); }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; import "../Common.sol" as Common; import "./Errors.sol" as Errors; import { uEXP_MAX_INPUT, uEXP2_MAX_INPUT, uHALF_UNIT, uLOG2_10, uLOG2_E, uMAX_SD59x18, uMAX_WHOLE_SD59x18, uMIN_SD59x18, uMIN_WHOLE_SD59x18, UNIT, uUNIT, uUNIT_SQUARED, ZERO } from "./Constants.sol"; import { wrap } from "./Helpers.sol"; import { SD59x18 } from "./ValueType.sol"; /// @notice Calculates the absolute value of x. /// /// @dev Requirements: /// - x must be greater than `MIN_SD59x18`. /// /// @param x The SD59x18 number for which to calculate the absolute value. /// @param result The absolute value of x as an SD59x18 number. /// @custom:smtchecker abstract-function-nondet function abs(SD59x18 x) pure returns (SD59x18 result) { int256 xInt = x.unwrap(); if (xInt == uMIN_SD59x18) { revert Errors.PRBMath_SD59x18_Abs_MinSD59x18(); } result = xInt < 0 ? wrap(-xInt) : x; } /// @notice Calculates the arithmetic average of x and y. /// /// @dev Notes: /// - The result is rounded toward zero. /// /// @param x The first operand as an SD59x18 number. /// @param y The second operand as an SD59x18 number. /// @return result The arithmetic average as an SD59x18 number. /// @custom:smtchecker abstract-function-nondet function avg(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) { int256 xInt = x.unwrap(); int256 yInt = y.unwrap(); unchecked { // This operation is equivalent to `x / 2 + y / 2`, and it can never overflow. int256 sum = (xInt >> 1) + (yInt >> 1); if (sum < 0) { // If at least one of x and y is odd, add 1 to the result, because shifting negative numbers to the right // rounds toward negative infinity. The right part is equivalent to `sum + (x % 2 == 1 || y % 2 == 1)`. assembly ("memory-safe") { result := add(sum, and(or(xInt, yInt), 1)) } } else { // Add 1 if both x and y are odd to account for the double 0.5 remainder truncated after shifting. result = wrap(sum + (xInt & yInt & 1)); } } } /// @notice Yields the smallest whole number greater than or equal to x. /// /// @dev Optimized for fractional value inputs, because every whole value has (1e18 - 1) fractional counterparts. /// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions. /// /// Requirements: /// - x must be less than or equal to `MAX_WHOLE_SD59x18`. /// /// @param x The SD59x18 number to ceil. /// @param result The smallest whole number greater than or equal to x, as an SD59x18 number. /// @custom:smtchecker abstract-function-nondet function ceil(SD59x18 x) pure returns (SD59x18 result) { int256 xInt = x.unwrap(); if (xInt > uMAX_WHOLE_SD59x18) { revert Errors.PRBMath_SD59x18_Ceil_Overflow(x); } int256 remainder = xInt % uUNIT; if (remainder == 0) { result = x; } else { unchecked { // Solidity uses C fmod style, which returns a modulus with the same sign as x. int256 resultInt = xInt - remainder; if (xInt > 0) { resultInt += uUNIT; } result = wrap(resultInt); } } } /// @notice Divides two SD59x18 numbers, returning a new SD59x18 number. /// /// @dev This is an extension of {Common.mulDiv} for signed numbers, which works by computing the signs and the absolute /// values separately. /// /// Notes: /// - Refer to the notes in {Common.mulDiv}. /// - The result is rounded toward zero. /// /// Requirements: /// - Refer to the requirements in {Common.mulDiv}. /// - None of the inputs can be `MIN_SD59x18`. /// - The denominator must not be zero. /// - The result must fit in SD59x18. /// /// @param x The numerator as an SD59x18 number. /// @param y The denominator as an SD59x18 number. /// @param result The quotient as an SD59x18 number. /// @custom:smtchecker abstract-function-nondet function div(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) { int256 xInt = x.unwrap(); int256 yInt = y.unwrap(); if (xInt == uMIN_SD59x18 || yInt == uMIN_SD59x18) { revert Errors.PRBMath_SD59x18_Div_InputTooSmall(); } // Get hold of the absolute values of x and y. uint256 xAbs; uint256 yAbs; unchecked { xAbs = xInt < 0 ? uint256(-xInt) : uint256(xInt); yAbs = yInt < 0 ? uint256(-yInt) : uint256(yInt); } // Compute the absolute value (x*UNIT÷y). The resulting value must fit in SD59x18. uint256 resultAbs = Common.mulDiv(xAbs, uint256(uUNIT), yAbs); if (resultAbs > uint256(uMAX_SD59x18)) { revert Errors.PRBMath_SD59x18_Div_Overflow(x, y); } // Check if x and y have the same sign using two's complement representation. The left-most bit represents the sign (1 for // negative, 0 for positive or zero). bool sameSign = (xInt ^ yInt) > -1; // If the inputs have the same sign, the result should be positive. Otherwise, it should be negative. unchecked { result = wrap(sameSign ? int256(resultAbs) : -int256(resultAbs)); } } /// @notice Calculates the natural exponent of x using the following formula: /// /// $$ /// e^x = 2^{x * log_2{e}} /// $$ /// /// @dev Notes: /// - Refer to the notes in {exp2}. /// /// Requirements: /// - Refer to the requirements in {exp2}. /// - x must be less than 133_084258667509499441. /// /// @param x The exponent as an SD59x18 number. /// @return result The result as an SD59x18 number. /// @custom:smtchecker abstract-function-nondet function exp(SD59x18 x) pure returns (SD59x18 result) { int256 xInt = x.unwrap(); // This check prevents values greater than 192e18 from being passed to {exp2}. if (xInt > uEXP_MAX_INPUT) { revert Errors.PRBMath_SD59x18_Exp_InputTooBig(x); } unchecked { // Inline the fixed-point multiplication to save gas. int256 doubleUnitProduct = xInt * uLOG2_E; result = exp2(wrap(doubleUnitProduct / uUNIT)); } } /// @notice Calculates the binary exponent of x using the binary fraction method using the following formula: /// /// $$ /// 2^{-x} = \frac{1}{2^x} /// $$ /// /// @dev See https://ethereum.stackexchange.com/q/79903/24693. /// /// Notes: /// - If x is less than -59_794705707972522261, the result is zero. /// /// Requirements: /// - x must be less than 192e18. /// - The result must fit in SD59x18. /// /// @param x The exponent as an SD59x18 number. /// @return result The result as an SD59x18 number. /// @custom:smtchecker abstract-function-nondet function exp2(SD59x18 x) pure returns (SD59x18 result) { int256 xInt = x.unwrap(); if (xInt < 0) { // The inverse of any number less than this is truncated to zero. if (xInt < -59_794705707972522261) { return ZERO; } unchecked { // Inline the fixed-point inversion to save gas. result = wrap(uUNIT_SQUARED / exp2(wrap(-xInt)).unwrap()); } } else { // Numbers greater than or equal to 192e18 don't fit in the 192.64-bit format. if (xInt > uEXP2_MAX_INPUT) { revert Errors.PRBMath_SD59x18_Exp2_InputTooBig(x); } unchecked { // Convert x to the 192.64-bit fixed-point format. uint256 x_192x64 = uint256((xInt << 64) / uUNIT); // It is safe to cast the result to int256 due to the checks above. result = wrap(int256(Common.exp2(x_192x64))); } } } /// @notice Yields the greatest whole number less than or equal to x. /// /// @dev Optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional /// counterparts. See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions. /// /// Requirements: /// - x must be greater than or equal to `MIN_WHOLE_SD59x18`. /// /// @param x The SD59x18 number to floor. /// @param result The greatest whole number less than or equal to x, as an SD59x18 number. /// @custom:smtchecker abstract-function-nondet function floor(SD59x18 x) pure returns (SD59x18 result) { int256 xInt = x.unwrap(); if (xInt < uMIN_WHOLE_SD59x18) { revert Errors.PRBMath_SD59x18_Floor_Underflow(x); } int256 remainder = xInt % uUNIT; if (remainder == 0) { result = x; } else { unchecked { // Solidity uses C fmod style, which returns a modulus with the same sign as x. int256 resultInt = xInt - remainder; if (xInt < 0) { resultInt -= uUNIT; } result = wrap(resultInt); } } } /// @notice Yields the excess beyond the floor of x for positive numbers and the part of the number to the right. /// of the radix point for negative numbers. /// @dev Based on the odd function definition. https://en.wikipedia.org/wiki/Fractional_part /// @param x The SD59x18 number to get the fractional part of. /// @param result The fractional part of x as an SD59x18 number. function frac(SD59x18 x) pure returns (SD59x18 result) { result = wrap(x.unwrap() % uUNIT); } /// @notice Calculates the geometric mean of x and y, i.e. $\sqrt{x * y}$. /// /// @dev Notes: /// - The result is rounded toward zero. /// /// Requirements: /// - x * y must fit in SD59x18. /// - x * y must not be negative, since complex numbers are not supported. /// /// @param x The first operand as an SD59x18 number. /// @param y The second operand as an SD59x18 number. /// @return result The result as an SD59x18 number. /// @custom:smtchecker abstract-function-nondet function gm(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) { int256 xInt = x.unwrap(); int256 yInt = y.unwrap(); if (xInt == 0 || yInt == 0) { return ZERO; } unchecked { // Equivalent to `xy / x != y`. Checking for overflow this way is faster than letting Solidity do it. int256 xyInt = xInt * yInt; if (xyInt / xInt != yInt) { revert Errors.PRBMath_SD59x18_Gm_Overflow(x, y); } // The product must not be negative, since complex numbers are not supported. if (xyInt < 0) { revert Errors.PRBMath_SD59x18_Gm_NegativeProduct(x, y); } // We don't need to multiply the result by `UNIT` here because the x*y product picked up a factor of `UNIT` // during multiplication. See the comments in {Common.sqrt}. uint256 resultUint = Common.sqrt(uint256(xyInt)); result = wrap(int256(resultUint)); } } /// @notice Calculates the inverse of x. /// /// @dev Notes: /// - The result is rounded toward zero. /// /// Requirements: /// - x must not be zero. /// /// @param x The SD59x18 number for which to calculate the inverse. /// @return result The inverse as an SD59x18 number. /// @custom:smtchecker abstract-function-nondet function inv(SD59x18 x) pure returns (SD59x18 result) { result = wrap(uUNIT_SQUARED / x.unwrap()); } /// @notice Calculates the natural logarithm of x using the following formula: /// /// $$ /// ln{x} = log_2{x} / log_2{e} /// $$ /// /// @dev Notes: /// - Refer to the notes in {log2}. /// - The precision isn't sufficiently fine-grained to return exactly `UNIT` when the input is `E`. /// /// Requirements: /// - Refer to the requirements in {log2}. /// /// @param x The SD59x18 number for which to calculate the natural logarithm. /// @return result The natural logarithm as an SD59x18 number. /// @custom:smtchecker abstract-function-nondet function ln(SD59x18 x) pure returns (SD59x18 result) { // Inline the fixed-point multiplication to save gas. This is overflow-safe because the maximum value that // {log2} can return is ~195_205294292027477728. result = wrap(log2(x).unwrap() * uUNIT / uLOG2_E); } /// @notice Calculates the common logarithm of x using the following formula: /// /// $$ /// log_{10}{x} = log_2{x} / log_2{10} /// $$ /// /// However, if x is an exact power of ten, a hard coded value is returned. /// /// @dev Notes: /// - Refer to the notes in {log2}. /// /// Requirements: /// - Refer to the requirements in {log2}. /// /// @param x The SD59x18 number for which to calculate the common logarithm. /// @return result The common logarithm as an SD59x18 number. /// @custom:smtchecker abstract-function-nondet function log10(SD59x18 x) pure returns (SD59x18 result) { int256 xInt = x.unwrap(); if (xInt < 0) { revert Errors.PRBMath_SD59x18_Log_InputTooSmall(x); } // Note that the `mul` in this block is the standard multiplication operation, not {SD59x18.mul}. // prettier-ignore assembly ("memory-safe") { switch x case 1 { result := mul(uUNIT, sub(0, 18)) } case 10 { result := mul(uUNIT, sub(1, 18)) } case 100 { result := mul(uUNIT, sub(2, 18)) } case 1000 { result := mul(uUNIT, sub(3, 18)) } case 10000 { result := mul(uUNIT, sub(4, 18)) } case 100000 { result := mul(uUNIT, sub(5, 18)) } case 1000000 { result := mul(uUNIT, sub(6, 18)) } case 10000000 { result := mul(uUNIT, sub(7, 18)) } case 100000000 { result := mul(uUNIT, sub(8, 18)) } case 1000000000 { result := mul(uUNIT, sub(9, 18)) } case 10000000000 { result := mul(uUNIT, sub(10, 18)) } case 100000000000 { result := mul(uUNIT, sub(11, 18)) } case 1000000000000 { result := mul(uUNIT, sub(12, 18)) } case 10000000000000 { result := mul(uUNIT, sub(13, 18)) } case 100000000000000 { result := mul(uUNIT, sub(14, 18)) } case 1000000000000000 { result := mul(uUNIT, sub(15, 18)) } case 10000000000000000 { result := mul(uUNIT, sub(16, 18)) } case 100000000000000000 { result := mul(uUNIT, sub(17, 18)) } case 1000000000000000000 { result := 0 } case 10000000000000000000 { result := uUNIT } case 100000000000000000000 { result := mul(uUNIT, 2) } case 1000000000000000000000 { result := mul(uUNIT, 3) } case 10000000000000000000000 { result := mul(uUNIT, 4) } case 100000000000000000000000 { result := mul(uUNIT, 5) } case 1000000000000000000000000 { result := mul(uUNIT, 6) } case 10000000000000000000000000 { result := mul(uUNIT, 7) } case 100000000000000000000000000 { result := mul(uUNIT, 8) } case 1000000000000000000000000000 { result := mul(uUNIT, 9) } case 10000000000000000000000000000 { result := mul(uUNIT, 10) } case 100000000000000000000000000000 { result := mul(uUNIT, 11) } case 1000000000000000000000000000000 { result := mul(uUNIT, 12) } case 10000000000000000000000000000000 { result := mul(uUNIT, 13) } case 100000000000000000000000000000000 { result := mul(uUNIT, 14) } case 1000000000000000000000000000000000 { result := mul(uUNIT, 15) } case 10000000000000000000000000000000000 { result := mul(uUNIT, 16) } case 100000000000000000000000000000000000 { result := mul(uUNIT, 17) } case 1000000000000000000000000000000000000 { result := mul(uUNIT, 18) } case 10000000000000000000000000000000000000 { result := mul(uUNIT, 19) } case 100000000000000000000000000000000000000 { result := mul(uUNIT, 20) } case 1000000000000000000000000000000000000000 { result := mul(uUNIT, 21) } case 10000000000000000000000000000000000000000 { result := mul(uUNIT, 22) } case 100000000000000000000000000000000000000000 { result := mul(uUNIT, 23) } case 1000000000000000000000000000000000000000000 { result := mul(uUNIT, 24) } case 10000000000000000000000000000000000000000000 { result := mul(uUNIT, 25) } case 100000000000000000000000000000000000000000000 { result := mul(uUNIT, 26) } case 1000000000000000000000000000000000000000000000 { result := mul(uUNIT, 27) } case 10000000000000000000000000000000000000000000000 { result := mul(uUNIT, 28) } case 100000000000000000000000000000000000000000000000 { result := mul(uUNIT, 29) } case 1000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 30) } case 10000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 31) } case 100000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 32) } case 1000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 33) } case 10000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 34) } case 100000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 35) } case 1000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 36) } case 10000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 37) } case 100000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 38) } case 1000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 39) } case 10000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 40) } case 100000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 41) } case 1000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 42) } case 10000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 43) } case 100000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 44) } case 1000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 45) } case 10000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 46) } case 100000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 47) } case 1000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 48) } case 10000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 49) } case 100000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 50) } case 1000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 51) } case 10000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 52) } case 100000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 53) } case 1000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 54) } case 10000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 55) } case 100000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 56) } case 1000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 57) } case 10000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 58) } default { result := uMAX_SD59x18 } } if (result.unwrap() == uMAX_SD59x18) { unchecked { // Inline the fixed-point division to save gas. result = wrap(log2(x).unwrap() * uUNIT / uLOG2_10); } } } /// @notice Calculates the binary logarithm of x using the iterative approximation algorithm: /// /// $$ /// log_2{x} = n + log_2{y}, \text{ where } y = x*2^{-n}, \ y \in [1, 2) /// $$ /// /// For $0 \leq x \lt 1$, the input is inverted: /// /// $$ /// log_2{x} = -log_2{\frac{1}{x}} /// $$ /// /// @dev See https://en.wikipedia.org/wiki/Binary_logarithm#Iterative_approximation. /// /// Notes: /// - Due to the lossy precision of the iterative approximation, the results are not perfectly accurate to the last decimal. /// /// Requirements: /// - x must be greater than zero. /// /// @param x The SD59x18 number for which to calculate the binary logarithm. /// @return result The binary logarithm as an SD59x18 number. /// @custom:smtchecker abstract-function-nondet function log2(SD59x18 x) pure returns (SD59x18 result) { int256 xInt = x.unwrap(); if (xInt <= 0) { revert Errors.PRBMath_SD59x18_Log_InputTooSmall(x); } unchecked { int256 sign; if (xInt >= uUNIT) { sign = 1; } else { sign = -1; // Inline the fixed-point inversion to save gas. xInt = uUNIT_SQUARED / xInt; } // Calculate the integer part of the logarithm. uint256 n = Common.msb(uint256(xInt / uUNIT)); // This is the integer part of the logarithm as an SD59x18 number. The operation can't overflow // because n is at most 255, `UNIT` is 1e18, and the sign is either 1 or -1. int256 resultInt = int256(n) * uUNIT; // Calculate $y = x * 2^{-n}$. int256 y = xInt >> n; // If y is the unit number, the fractional part is zero. if (y == uUNIT) { return wrap(resultInt * sign); } // Calculate the fractional part via the iterative approximation. // The `delta >>= 1` part is equivalent to `delta /= 2`, but shifting bits is more gas efficient. int256 DOUBLE_UNIT = 2e18; for (int256 delta = uHALF_UNIT; delta > 0; delta >>= 1) { y = (y * y) / uUNIT; // Is y^2 >= 2e18 and so in the range [2e18, 4e18)? if (y >= DOUBLE_UNIT) { // Add the 2^{-m} factor to the logarithm. resultInt = resultInt + delta; // Halve y, which corresponds to z/2 in the Wikipedia article. y >>= 1; } } resultInt *= sign; result = wrap(resultInt); } } /// @notice Multiplies two SD59x18 numbers together, returning a new SD59x18 number. /// /// @dev Notes: /// - Refer to the notes in {Common.mulDiv18}. /// /// Requirements: /// - Refer to the requirements in {Common.mulDiv18}. /// - None of the inputs can be `MIN_SD59x18`. /// - The result must fit in SD59x18. /// /// @param x The multiplicand as an SD59x18 number. /// @param y The multiplier as an SD59x18 number. /// @return result The product as an SD59x18 number. /// @custom:smtchecker abstract-function-nondet function mul(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) { int256 xInt = x.unwrap(); int256 yInt = y.unwrap(); if (xInt == uMIN_SD59x18 || yInt == uMIN_SD59x18) { revert Errors.PRBMath_SD59x18_Mul_InputTooSmall(); } // Get hold of the absolute values of x and y. uint256 xAbs; uint256 yAbs; unchecked { xAbs = xInt < 0 ? uint256(-xInt) : uint256(xInt); yAbs = yInt < 0 ? uint256(-yInt) : uint256(yInt); } // Compute the absolute value (x*y÷UNIT). The resulting value must fit in SD59x18. uint256 resultAbs = Common.mulDiv18(xAbs, yAbs); if (resultAbs > uint256(uMAX_SD59x18)) { revert Errors.PRBMath_SD59x18_Mul_Overflow(x, y); } // Check if x and y have the same sign using two's complement representation. The left-most bit represents the sign (1 for // negative, 0 for positive or zero). bool sameSign = (xInt ^ yInt) > -1; // If the inputs have the same sign, the result should be positive. Otherwise, it should be negative. unchecked { result = wrap(sameSign ? int256(resultAbs) : -int256(resultAbs)); } } /// @notice Raises x to the power of y using the following formula: /// /// $$ /// x^y = 2^{log_2{x} * y} /// $$ /// /// @dev Notes: /// - Refer to the notes in {exp2}, {log2}, and {mul}. /// - Returns `UNIT` for 0^0. /// /// Requirements: /// - Refer to the requirements in {exp2}, {log2}, and {mul}. /// /// @param x The base as an SD59x18 number. /// @param y Exponent to raise x to, as an SD59x18 number /// @return result x raised to power y, as an SD59x18 number. /// @custom:smtchecker abstract-function-nondet function pow(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) { int256 xInt = x.unwrap(); int256 yInt = y.unwrap(); // If both x and y are zero, the result is `UNIT`. If just x is zero, the result is always zero. if (xInt == 0) { return yInt == 0 ? UNIT : ZERO; } // If x is `UNIT`, the result is always `UNIT`. else if (xInt == uUNIT) { return UNIT; } // If y is zero, the result is always `UNIT`. if (yInt == 0) { return UNIT; } // If y is `UNIT`, the result is always x. else if (yInt == uUNIT) { return x; } // Calculate the result using the formula. result = exp2(mul(log2(x), y)); } /// @notice Raises x (an SD59x18 number) to the power y (an unsigned basic integer) using the well-known /// algorithm "exponentiation by squaring". /// /// @dev See https://en.wikipedia.org/wiki/Exponentiation_by_squaring. /// /// Notes: /// - Refer to the notes in {Common.mulDiv18}. /// - Returns `UNIT` for 0^0. /// /// Requirements: /// - Refer to the requirements in {abs} and {Common.mulDiv18}. /// - The result must fit in SD59x18. /// /// @param x The base as an SD59x18 number. /// @param y The exponent as a uint256. /// @return result The result as an SD59x18 number. /// @custom:smtchecker abstract-function-nondet function powu(SD59x18 x, uint256 y) pure returns (SD59x18 result) { uint256 xAbs = uint256(abs(x).unwrap()); // Calculate the first iteration of the loop in advance. uint256 resultAbs = y & 1 > 0 ? xAbs : uint256(uUNIT); // Equivalent to `for(y /= 2; y > 0; y /= 2)`. uint256 yAux = y; for (yAux >>= 1; yAux > 0; yAux >>= 1) { xAbs = Common.mulDiv18(xAbs, xAbs); // Equivalent to `y % 2 == 1`. if (yAux & 1 > 0) { resultAbs = Common.mulDiv18(resultAbs, xAbs); } } // The result must fit in SD59x18. if (resultAbs > uint256(uMAX_SD59x18)) { revert Errors.PRBMath_SD59x18_Powu_Overflow(x, y); } unchecked { // Is the base negative and the exponent odd? If yes, the result should be negative. int256 resultInt = int256(resultAbs); bool isNegative = x.unwrap() < 0 && y & 1 == 1; if (isNegative) { resultInt = -resultInt; } result = wrap(resultInt); } } /// @notice Calculates the square root of x using the Babylonian method. /// /// @dev See https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method. /// /// Notes: /// - Only the positive root is returned. /// - The result is rounded toward zero. /// /// Requirements: /// - x cannot be negative, since complex numbers are not supported. /// - x must be less than `MAX_SD59x18 / UNIT`. /// /// @param x The SD59x18 number for which to calculate the square root. /// @return result The result as an SD59x18 number. /// @custom:smtchecker abstract-function-nondet function sqrt(SD59x18 x) pure returns (SD59x18 result) { int256 xInt = x.unwrap(); if (xInt < 0) { revert Errors.PRBMath_SD59x18_Sqrt_NegativeInput(x); } if (xInt > uMAX_SD59x18 / uUNIT) { revert Errors.PRBMath_SD59x18_Sqrt_Overflow(x); } unchecked { // Multiply x by `UNIT` to account for the factor of `UNIT` picked up when multiplying two SD59x18 numbers. // In this case, the two numbers are both the square root. uint256 resultUint = Common.sqrt(uint256(xInt * uUNIT)); result = wrap(int256(resultUint)); } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; import "./Casting.sol" as Casting; import "./Helpers.sol" as Helpers; import "./Math.sol" as Math; /// @notice The signed 59.18-decimal fixed-point number representation, which can have up to 59 digits and up to 18 /// decimals. The values of this are bound by the minimum and the maximum values permitted by the underlying Solidity /// type int256. type SD59x18 is int256; /*////////////////////////////////////////////////////////////////////////// CASTING //////////////////////////////////////////////////////////////////////////*/ using { Casting.intoInt256, Casting.intoSD1x18, Casting.intoUD2x18, Casting.intoUD60x18, Casting.intoUint256, Casting.intoUint128, Casting.intoUint40, Casting.unwrap } for SD59x18 global; /*////////////////////////////////////////////////////////////////////////// MATHEMATICAL FUNCTIONS //////////////////////////////////////////////////////////////////////////*/ using { Math.abs, Math.avg, Math.ceil, Math.div, Math.exp, Math.exp2, Math.floor, Math.frac, Math.gm, Math.inv, Math.log10, Math.log2, Math.ln, Math.mul, Math.pow, Math.powu, Math.sqrt } for SD59x18 global; /*////////////////////////////////////////////////////////////////////////// HELPER FUNCTIONS //////////////////////////////////////////////////////////////////////////*/ using { Helpers.add, Helpers.and, Helpers.eq, Helpers.gt, Helpers.gte, Helpers.isZero, Helpers.lshift, Helpers.lt, Helpers.lte, Helpers.mod, Helpers.neq, Helpers.not, Helpers.or, Helpers.rshift, Helpers.sub, Helpers.uncheckedAdd, Helpers.uncheckedSub, Helpers.uncheckedUnary, Helpers.xor } for SD59x18 global; /*////////////////////////////////////////////////////////////////////////// OPERATORS //////////////////////////////////////////////////////////////////////////*/ // The global "using for" directive makes it possible to use these operators on the SD59x18 type. using { Helpers.add as +, Helpers.and2 as &, Math.div as /, Helpers.eq as ==, Helpers.gt as >, Helpers.gte as >=, Helpers.lt as <, Helpers.lte as <=, Helpers.mod as %, Math.mul as *, Helpers.neq as !=, Helpers.not as ~, Helpers.or as |, Helpers.sub as -, Helpers.unary as -, Helpers.xor as ^ } for SD59x18 global;
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; import "../Common.sol" as Common; import "./Errors.sol" as Errors; import { uMAX_SD1x18 } from "../sd1x18/Constants.sol"; import { SD1x18 } from "../sd1x18/ValueType.sol"; import { SD59x18 } from "../sd59x18/ValueType.sol"; import { UD60x18 } from "../ud60x18/ValueType.sol"; import { UD2x18 } from "./ValueType.sol"; /// @notice Casts a UD2x18 number into SD1x18. /// - x must be less than or equal to `uMAX_SD1x18`. function intoSD1x18(UD2x18 x) pure returns (SD1x18 result) { uint64 xUint = UD2x18.unwrap(x); if (xUint > uint64(uMAX_SD1x18)) { revert Errors.PRBMath_UD2x18_IntoSD1x18_Overflow(x); } result = SD1x18.wrap(int64(xUint)); } /// @notice Casts a UD2x18 number into SD59x18. /// @dev There is no overflow check because the domain of UD2x18 is a subset of SD59x18. function intoSD59x18(UD2x18 x) pure returns (SD59x18 result) { result = SD59x18.wrap(int256(uint256(UD2x18.unwrap(x)))); } /// @notice Casts a UD2x18 number into UD60x18. /// @dev There is no overflow check because the domain of UD2x18 is a subset of UD60x18. function intoUD60x18(UD2x18 x) pure returns (UD60x18 result) { result = UD60x18.wrap(UD2x18.unwrap(x)); } /// @notice Casts a UD2x18 number into uint128. /// @dev There is no overflow check because the domain of UD2x18 is a subset of uint128. function intoUint128(UD2x18 x) pure returns (uint128 result) { result = uint128(UD2x18.unwrap(x)); } /// @notice Casts a UD2x18 number into uint256. /// @dev There is no overflow check because the domain of UD2x18 is a subset of uint256. function intoUint256(UD2x18 x) pure returns (uint256 result) { result = uint256(UD2x18.unwrap(x)); } /// @notice Casts a UD2x18 number into uint40. /// @dev Requirements: /// - x must be less than or equal to `MAX_UINT40`. function intoUint40(UD2x18 x) pure returns (uint40 result) { uint64 xUint = UD2x18.unwrap(x); if (xUint > uint64(Common.MAX_UINT40)) { revert Errors.PRBMath_UD2x18_IntoUint40_Overflow(x); } result = uint40(xUint); } /// @notice Alias for {wrap}. function ud2x18(uint64 x) pure returns (UD2x18 result) { result = UD2x18.wrap(x); } /// @notice Unwrap a UD2x18 number into uint64. function unwrap(UD2x18 x) pure returns (uint64 result) { result = UD2x18.unwrap(x); } /// @notice Wraps a uint64 number into UD2x18. function wrap(uint64 x) pure returns (UD2x18 result) { result = UD2x18.wrap(x); }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; import { UD2x18 } from "./ValueType.sol"; /// @dev Euler's number as a UD2x18 number. UD2x18 constant E = UD2x18.wrap(2_718281828459045235); /// @dev The maximum value a UD2x18 number can have. uint64 constant uMAX_UD2x18 = 18_446744073709551615; UD2x18 constant MAX_UD2x18 = UD2x18.wrap(uMAX_UD2x18); /// @dev PI as a UD2x18 number. UD2x18 constant PI = UD2x18.wrap(3_141592653589793238); /// @dev The unit number, which gives the decimal precision of UD2x18. uint256 constant uUNIT = 1e18; UD2x18 constant UNIT = UD2x18.wrap(1e18);
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; import { UD2x18 } from "./ValueType.sol"; /// @notice Thrown when trying to cast a UD2x18 number that doesn't fit in SD1x18. error PRBMath_UD2x18_IntoSD1x18_Overflow(UD2x18 x); /// @notice Thrown when trying to cast a UD2x18 number that doesn't fit in uint40. error PRBMath_UD2x18_IntoUint40_Overflow(UD2x18 x);
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; import "./Casting.sol" as Casting; /// @notice The unsigned 2.18-decimal fixed-point number representation, which can have up to 2 digits and up to 18 /// decimals. The values of this are bound by the minimum and the maximum values permitted by the underlying Solidity /// type uint64. This is useful when end users want to use uint64 to save gas, e.g. with tight variable packing in contract /// storage. type UD2x18 is uint64; /*////////////////////////////////////////////////////////////////////////// CASTING //////////////////////////////////////////////////////////////////////////*/ using { Casting.intoSD1x18, Casting.intoSD59x18, Casting.intoUD60x18, Casting.intoUint256, Casting.intoUint128, Casting.intoUint40, Casting.unwrap } for UD2x18 global;
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; import "./Errors.sol" as CastingErrors; import { MAX_UINT128, MAX_UINT40 } from "../Common.sol"; import { uMAX_SD1x18 } from "../sd1x18/Constants.sol"; import { SD1x18 } from "../sd1x18/ValueType.sol"; import { uMAX_SD59x18 } from "../sd59x18/Constants.sol"; import { SD59x18 } from "../sd59x18/ValueType.sol"; import { uMAX_UD2x18 } from "../ud2x18/Constants.sol"; import { UD2x18 } from "../ud2x18/ValueType.sol"; import { UD60x18 } from "./ValueType.sol"; /// @notice Casts a UD60x18 number into SD1x18. /// @dev Requirements: /// - x must be less than or equal to `uMAX_SD1x18`. function intoSD1x18(UD60x18 x) pure returns (SD1x18 result) { uint256 xUint = UD60x18.unwrap(x); if (xUint > uint256(int256(uMAX_SD1x18))) { revert CastingErrors.PRBMath_UD60x18_IntoSD1x18_Overflow(x); } result = SD1x18.wrap(int64(uint64(xUint))); } /// @notice Casts a UD60x18 number into UD2x18. /// @dev Requirements: /// - x must be less than or equal to `uMAX_UD2x18`. function intoUD2x18(UD60x18 x) pure returns (UD2x18 result) { uint256 xUint = UD60x18.unwrap(x); if (xUint > uMAX_UD2x18) { revert CastingErrors.PRBMath_UD60x18_IntoUD2x18_Overflow(x); } result = UD2x18.wrap(uint64(xUint)); } /// @notice Casts a UD60x18 number into SD59x18. /// @dev Requirements: /// - x must be less than or equal to `uMAX_SD59x18`. function intoSD59x18(UD60x18 x) pure returns (SD59x18 result) { uint256 xUint = UD60x18.unwrap(x); if (xUint > uint256(uMAX_SD59x18)) { revert CastingErrors.PRBMath_UD60x18_IntoSD59x18_Overflow(x); } result = SD59x18.wrap(int256(xUint)); } /// @notice Casts a UD60x18 number into uint128. /// @dev This is basically an alias for {unwrap}. function intoUint256(UD60x18 x) pure returns (uint256 result) { result = UD60x18.unwrap(x); } /// @notice Casts a UD60x18 number into uint128. /// @dev Requirements: /// - x must be less than or equal to `MAX_UINT128`. function intoUint128(UD60x18 x) pure returns (uint128 result) { uint256 xUint = UD60x18.unwrap(x); if (xUint > MAX_UINT128) { revert CastingErrors.PRBMath_UD60x18_IntoUint128_Overflow(x); } result = uint128(xUint); } /// @notice Casts a UD60x18 number into uint40. /// @dev Requirements: /// - x must be less than or equal to `MAX_UINT40`. function intoUint40(UD60x18 x) pure returns (uint40 result) { uint256 xUint = UD60x18.unwrap(x); if (xUint > MAX_UINT40) { revert CastingErrors.PRBMath_UD60x18_IntoUint40_Overflow(x); } result = uint40(xUint); } /// @notice Alias for {wrap}. function ud(uint256 x) pure returns (UD60x18 result) { result = UD60x18.wrap(x); } /// @notice Alias for {wrap}. function ud60x18(uint256 x) pure returns (UD60x18 result) { result = UD60x18.wrap(x); } /// @notice Unwraps a UD60x18 number into uint256. function unwrap(UD60x18 x) pure returns (uint256 result) { result = UD60x18.unwrap(x); } /// @notice Wraps a uint256 number into the UD60x18 value type. function wrap(uint256 x) pure returns (UD60x18 result) { result = UD60x18.wrap(x); }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; import { UD60x18 } from "./ValueType.sol"; // NOTICE: the "u" prefix stands for "unwrapped". /// @dev Euler's number as a UD60x18 number. UD60x18 constant E = UD60x18.wrap(2_718281828459045235); /// @dev The maximum input permitted in {exp}. uint256 constant uEXP_MAX_INPUT = 133_084258667509499440; UD60x18 constant EXP_MAX_INPUT = UD60x18.wrap(uEXP_MAX_INPUT); /// @dev The maximum input permitted in {exp2}. uint256 constant uEXP2_MAX_INPUT = 192e18 - 1; UD60x18 constant EXP2_MAX_INPUT = UD60x18.wrap(uEXP2_MAX_INPUT); /// @dev Half the UNIT number. uint256 constant uHALF_UNIT = 0.5e18; UD60x18 constant HALF_UNIT = UD60x18.wrap(uHALF_UNIT); /// @dev $log_2(10)$ as a UD60x18 number. uint256 constant uLOG2_10 = 3_321928094887362347; UD60x18 constant LOG2_10 = UD60x18.wrap(uLOG2_10); /// @dev $log_2(e)$ as a UD60x18 number. uint256 constant uLOG2_E = 1_442695040888963407; UD60x18 constant LOG2_E = UD60x18.wrap(uLOG2_E); /// @dev The maximum value a UD60x18 number can have. uint256 constant uMAX_UD60x18 = 115792089237316195423570985008687907853269984665640564039457_584007913129639935; UD60x18 constant MAX_UD60x18 = UD60x18.wrap(uMAX_UD60x18); /// @dev The maximum whole value a UD60x18 number can have. uint256 constant uMAX_WHOLE_UD60x18 = 115792089237316195423570985008687907853269984665640564039457_000000000000000000; UD60x18 constant MAX_WHOLE_UD60x18 = UD60x18.wrap(uMAX_WHOLE_UD60x18); /// @dev PI as a UD60x18 number. UD60x18 constant PI = UD60x18.wrap(3_141592653589793238); /// @dev The unit number, which gives the decimal precision of UD60x18. uint256 constant uUNIT = 1e18; UD60x18 constant UNIT = UD60x18.wrap(uUNIT); /// @dev The unit number squared. uint256 constant uUNIT_SQUARED = 1e36; UD60x18 constant UNIT_SQUARED = UD60x18.wrap(uUNIT_SQUARED); /// @dev Zero as a UD60x18 number. UD60x18 constant ZERO = UD60x18.wrap(0);
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; import { uMAX_UD60x18, uUNIT } from "./Constants.sol"; import { PRBMath_UD60x18_Convert_Overflow } from "./Errors.sol"; import { UD60x18 } from "./ValueType.sol"; /// @notice Converts a UD60x18 number to a simple integer by dividing it by `UNIT`. /// @dev The result is rounded toward zero. /// @param x The UD60x18 number to convert. /// @return result The same number in basic integer form. function convert(UD60x18 x) pure returns (uint256 result) { result = UD60x18.unwrap(x) / uUNIT; } /// @notice Converts a simple integer to UD60x18 by multiplying it by `UNIT`. /// /// @dev Requirements: /// - x must be less than or equal to `MAX_UD60x18 / UNIT`. /// /// @param x The basic integer to convert. /// @param result The same number converted to UD60x18. function convert(uint256 x) pure returns (UD60x18 result) { if (x > uMAX_UD60x18 / uUNIT) { revert PRBMath_UD60x18_Convert_Overflow(x); } unchecked { result = UD60x18.wrap(x * uUNIT); } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; import { UD60x18 } from "./ValueType.sol"; /// @notice Thrown when ceiling a number overflows UD60x18. error PRBMath_UD60x18_Ceil_Overflow(UD60x18 x); /// @notice Thrown when converting a basic integer to the fixed-point format overflows UD60x18. error PRBMath_UD60x18_Convert_Overflow(uint256 x); /// @notice Thrown when taking the natural exponent of a base greater than 133_084258667509499441. error PRBMath_UD60x18_Exp_InputTooBig(UD60x18 x); /// @notice Thrown when taking the binary exponent of a base greater than 192e18. error PRBMath_UD60x18_Exp2_InputTooBig(UD60x18 x); /// @notice Thrown when taking the geometric mean of two numbers and multiplying them overflows UD60x18. error PRBMath_UD60x18_Gm_Overflow(UD60x18 x, UD60x18 y); /// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in SD1x18. error PRBMath_UD60x18_IntoSD1x18_Overflow(UD60x18 x); /// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in SD59x18. error PRBMath_UD60x18_IntoSD59x18_Overflow(UD60x18 x); /// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in UD2x18. error PRBMath_UD60x18_IntoUD2x18_Overflow(UD60x18 x); /// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in uint128. error PRBMath_UD60x18_IntoUint128_Overflow(UD60x18 x); /// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in uint40. error PRBMath_UD60x18_IntoUint40_Overflow(UD60x18 x); /// @notice Thrown when taking the logarithm of a number less than 1. error PRBMath_UD60x18_Log_InputTooSmall(UD60x18 x); /// @notice Thrown when calculating the square root overflows UD60x18. error PRBMath_UD60x18_Sqrt_Overflow(UD60x18 x);
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; import { wrap } from "./Casting.sol"; import { UD60x18 } from "./ValueType.sol"; /// @notice Implements the checked addition operation (+) in the UD60x18 type. function add(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) { result = wrap(x.unwrap() + y.unwrap()); } /// @notice Implements the AND (&) bitwise operation in the UD60x18 type. function and(UD60x18 x, uint256 bits) pure returns (UD60x18 result) { result = wrap(x.unwrap() & bits); } /// @notice Implements the AND (&) bitwise operation in the UD60x18 type. function and2(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) { result = wrap(x.unwrap() & y.unwrap()); } /// @notice Implements the equal operation (==) in the UD60x18 type. function eq(UD60x18 x, UD60x18 y) pure returns (bool result) { result = x.unwrap() == y.unwrap(); } /// @notice Implements the greater than operation (>) in the UD60x18 type. function gt(UD60x18 x, UD60x18 y) pure returns (bool result) { result = x.unwrap() > y.unwrap(); } /// @notice Implements the greater than or equal to operation (>=) in the UD60x18 type. function gte(UD60x18 x, UD60x18 y) pure returns (bool result) { result = x.unwrap() >= y.unwrap(); } /// @notice Implements a zero comparison check function in the UD60x18 type. function isZero(UD60x18 x) pure returns (bool result) { // This wouldn't work if x could be negative. result = x.unwrap() == 0; } /// @notice Implements the left shift operation (<<) in the UD60x18 type. function lshift(UD60x18 x, uint256 bits) pure returns (UD60x18 result) { result = wrap(x.unwrap() << bits); } /// @notice Implements the lower than operation (<) in the UD60x18 type. function lt(UD60x18 x, UD60x18 y) pure returns (bool result) { result = x.unwrap() < y.unwrap(); } /// @notice Implements the lower than or equal to operation (<=) in the UD60x18 type. function lte(UD60x18 x, UD60x18 y) pure returns (bool result) { result = x.unwrap() <= y.unwrap(); } /// @notice Implements the checked modulo operation (%) in the UD60x18 type. function mod(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) { result = wrap(x.unwrap() % y.unwrap()); } /// @notice Implements the not equal operation (!=) in the UD60x18 type. function neq(UD60x18 x, UD60x18 y) pure returns (bool result) { result = x.unwrap() != y.unwrap(); } /// @notice Implements the NOT (~) bitwise operation in the UD60x18 type. function not(UD60x18 x) pure returns (UD60x18 result) { result = wrap(~x.unwrap()); } /// @notice Implements the OR (|) bitwise operation in the UD60x18 type. function or(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) { result = wrap(x.unwrap() | y.unwrap()); } /// @notice Implements the right shift operation (>>) in the UD60x18 type. function rshift(UD60x18 x, uint256 bits) pure returns (UD60x18 result) { result = wrap(x.unwrap() >> bits); } /// @notice Implements the checked subtraction operation (-) in the UD60x18 type. function sub(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) { result = wrap(x.unwrap() - y.unwrap()); } /// @notice Implements the unchecked addition operation (+) in the UD60x18 type. function uncheckedAdd(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) { unchecked { result = wrap(x.unwrap() + y.unwrap()); } } /// @notice Implements the unchecked subtraction operation (-) in the UD60x18 type. function uncheckedSub(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) { unchecked { result = wrap(x.unwrap() - y.unwrap()); } } /// @notice Implements the XOR (^) bitwise operation in the UD60x18 type. function xor(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) { result = wrap(x.unwrap() ^ y.unwrap()); }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; import "../Common.sol" as Common; import "./Errors.sol" as Errors; import { wrap } from "./Casting.sol"; import { uEXP_MAX_INPUT, uEXP2_MAX_INPUT, uHALF_UNIT, uLOG2_10, uLOG2_E, uMAX_UD60x18, uMAX_WHOLE_UD60x18, UNIT, uUNIT, uUNIT_SQUARED, ZERO } from "./Constants.sol"; import { UD60x18 } from "./ValueType.sol"; /*////////////////////////////////////////////////////////////////////////// MATHEMATICAL FUNCTIONS //////////////////////////////////////////////////////////////////////////*/ /// @notice Calculates the arithmetic average of x and y using the following formula: /// /// $$ /// avg(x, y) = (x & y) + ((xUint ^ yUint) / 2) /// $$ /// /// In English, this is what this formula does: /// /// 1. AND x and y. /// 2. Calculate half of XOR x and y. /// 3. Add the two results together. /// /// This technique is known as SWAR, which stands for "SIMD within a register". You can read more about it here: /// https://devblogs.microsoft.com/oldnewthing/20220207-00/?p=106223 /// /// @dev Notes: /// - The result is rounded toward zero. /// /// @param x The first operand as a UD60x18 number. /// @param y The second operand as a UD60x18 number. /// @return result The arithmetic average as a UD60x18 number. /// @custom:smtchecker abstract-function-nondet function avg(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) { uint256 xUint = x.unwrap(); uint256 yUint = y.unwrap(); unchecked { result = wrap((xUint & yUint) + ((xUint ^ yUint) >> 1)); } } /// @notice Yields the smallest whole number greater than or equal to x. /// /// @dev This is optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional /// counterparts. See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions. /// /// Requirements: /// - x must be less than or equal to `MAX_WHOLE_UD60x18`. /// /// @param x The UD60x18 number to ceil. /// @param result The smallest whole number greater than or equal to x, as a UD60x18 number. /// @custom:smtchecker abstract-function-nondet function ceil(UD60x18 x) pure returns (UD60x18 result) { uint256 xUint = x.unwrap(); if (xUint > uMAX_WHOLE_UD60x18) { revert Errors.PRBMath_UD60x18_Ceil_Overflow(x); } assembly ("memory-safe") { // Equivalent to `x % UNIT`. let remainder := mod(x, uUNIT) // Equivalent to `UNIT - remainder`. let delta := sub(uUNIT, remainder) // Equivalent to `x + remainder > 0 ? delta : 0`. result := add(x, mul(delta, gt(remainder, 0))) } } /// @notice Divides two UD60x18 numbers, returning a new UD60x18 number. /// /// @dev Uses {Common.mulDiv} to enable overflow-safe multiplication and division. /// /// Notes: /// - Refer to the notes in {Common.mulDiv}. /// /// Requirements: /// - Refer to the requirements in {Common.mulDiv}. /// /// @param x The numerator as a UD60x18 number. /// @param y The denominator as a UD60x18 number. /// @param result The quotient as a UD60x18 number. /// @custom:smtchecker abstract-function-nondet function div(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) { result = wrap(Common.mulDiv(x.unwrap(), uUNIT, y.unwrap())); } /// @notice Calculates the natural exponent of x using the following formula: /// /// $$ /// e^x = 2^{x * log_2{e}} /// $$ /// /// @dev Requirements: /// - x must be less than 133_084258667509499441. /// /// @param x The exponent as a UD60x18 number. /// @return result The result as a UD60x18 number. /// @custom:smtchecker abstract-function-nondet function exp(UD60x18 x) pure returns (UD60x18 result) { uint256 xUint = x.unwrap(); // This check prevents values greater than 192e18 from being passed to {exp2}. if (xUint > uEXP_MAX_INPUT) { revert Errors.PRBMath_UD60x18_Exp_InputTooBig(x); } unchecked { // Inline the fixed-point multiplication to save gas. uint256 doubleUnitProduct = xUint * uLOG2_E; result = exp2(wrap(doubleUnitProduct / uUNIT)); } } /// @notice Calculates the binary exponent of x using the binary fraction method. /// /// @dev See https://ethereum.stackexchange.com/q/79903/24693 /// /// Requirements: /// - x must be less than 192e18. /// - The result must fit in UD60x18. /// /// @param x The exponent as a UD60x18 number. /// @return result The result as a UD60x18 number. /// @custom:smtchecker abstract-function-nondet function exp2(UD60x18 x) pure returns (UD60x18 result) { uint256 xUint = x.unwrap(); // Numbers greater than or equal to 192e18 don't fit in the 192.64-bit format. if (xUint > uEXP2_MAX_INPUT) { revert Errors.PRBMath_UD60x18_Exp2_InputTooBig(x); } // Convert x to the 192.64-bit fixed-point format. uint256 x_192x64 = (xUint << 64) / uUNIT; // Pass x to the {Common.exp2} function, which uses the 192.64-bit fixed-point number representation. result = wrap(Common.exp2(x_192x64)); } /// @notice Yields the greatest whole number less than or equal to x. /// @dev Optimized for fractional value inputs, because every whole value has (1e18 - 1) fractional counterparts. /// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions. /// @param x The UD60x18 number to floor. /// @param result The greatest whole number less than or equal to x, as a UD60x18 number. /// @custom:smtchecker abstract-function-nondet function floor(UD60x18 x) pure returns (UD60x18 result) { assembly ("memory-safe") { // Equivalent to `x % UNIT`. let remainder := mod(x, uUNIT) // Equivalent to `x - remainder > 0 ? remainder : 0)`. result := sub(x, mul(remainder, gt(remainder, 0))) } } /// @notice Yields the excess beyond the floor of x using the odd function definition. /// @dev See https://en.wikipedia.org/wiki/Fractional_part. /// @param x The UD60x18 number to get the fractional part of. /// @param result The fractional part of x as a UD60x18 number. /// @custom:smtchecker abstract-function-nondet function frac(UD60x18 x) pure returns (UD60x18 result) { assembly ("memory-safe") { result := mod(x, uUNIT) } } /// @notice Calculates the geometric mean of x and y, i.e. $\sqrt{x * y}$, rounding down. /// /// @dev Requirements: /// - x * y must fit in UD60x18. /// /// @param x The first operand as a UD60x18 number. /// @param y The second operand as a UD60x18 number. /// @return result The result as a UD60x18 number. /// @custom:smtchecker abstract-function-nondet function gm(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) { uint256 xUint = x.unwrap(); uint256 yUint = y.unwrap(); if (xUint == 0 || yUint == 0) { return ZERO; } unchecked { // Checking for overflow this way is faster than letting Solidity do it. uint256 xyUint = xUint * yUint; if (xyUint / xUint != yUint) { revert Errors.PRBMath_UD60x18_Gm_Overflow(x, y); } // We don't need to multiply the result by `UNIT` here because the x*y product picked up a factor of `UNIT` // during multiplication. See the comments in {Common.sqrt}. result = wrap(Common.sqrt(xyUint)); } } /// @notice Calculates the inverse of x. /// /// @dev Notes: /// - The result is rounded toward zero. /// /// Requirements: /// - x must not be zero. /// /// @param x The UD60x18 number for which to calculate the inverse. /// @return result The inverse as a UD60x18 number. /// @custom:smtchecker abstract-function-nondet function inv(UD60x18 x) pure returns (UD60x18 result) { unchecked { result = wrap(uUNIT_SQUARED / x.unwrap()); } } /// @notice Calculates the natural logarithm of x using the following formula: /// /// $$ /// ln{x} = log_2{x} / log_2{e} /// $$ /// /// @dev Notes: /// - Refer to the notes in {log2}. /// - The precision isn't sufficiently fine-grained to return exactly `UNIT` when the input is `E`. /// /// Requirements: /// - Refer to the requirements in {log2}. /// /// @param x The UD60x18 number for which to calculate the natural logarithm. /// @return result The natural logarithm as a UD60x18 number. /// @custom:smtchecker abstract-function-nondet function ln(UD60x18 x) pure returns (UD60x18 result) { unchecked { // Inline the fixed-point multiplication to save gas. This is overflow-safe because the maximum value that // {log2} can return is ~196_205294292027477728. result = wrap(log2(x).unwrap() * uUNIT / uLOG2_E); } } /// @notice Calculates the common logarithm of x using the following formula: /// /// $$ /// log_{10}{x} = log_2{x} / log_2{10} /// $$ /// /// However, if x is an exact power of ten, a hard coded value is returned. /// /// @dev Notes: /// - Refer to the notes in {log2}. /// /// Requirements: /// - Refer to the requirements in {log2}. /// /// @param x The UD60x18 number for which to calculate the common logarithm. /// @return result The common logarithm as a UD60x18 number. /// @custom:smtchecker abstract-function-nondet function log10(UD60x18 x) pure returns (UD60x18 result) { uint256 xUint = x.unwrap(); if (xUint < uUNIT) { revert Errors.PRBMath_UD60x18_Log_InputTooSmall(x); } // Note that the `mul` in this assembly block is the standard multiplication operation, not {UD60x18.mul}. // prettier-ignore assembly ("memory-safe") { switch x case 1 { result := mul(uUNIT, sub(0, 18)) } case 10 { result := mul(uUNIT, sub(1, 18)) } case 100 { result := mul(uUNIT, sub(2, 18)) } case 1000 { result := mul(uUNIT, sub(3, 18)) } case 10000 { result := mul(uUNIT, sub(4, 18)) } case 100000 { result := mul(uUNIT, sub(5, 18)) } case 1000000 { result := mul(uUNIT, sub(6, 18)) } case 10000000 { result := mul(uUNIT, sub(7, 18)) } case 100000000 { result := mul(uUNIT, sub(8, 18)) } case 1000000000 { result := mul(uUNIT, sub(9, 18)) } case 10000000000 { result := mul(uUNIT, sub(10, 18)) } case 100000000000 { result := mul(uUNIT, sub(11, 18)) } case 1000000000000 { result := mul(uUNIT, sub(12, 18)) } case 10000000000000 { result := mul(uUNIT, sub(13, 18)) } case 100000000000000 { result := mul(uUNIT, sub(14, 18)) } case 1000000000000000 { result := mul(uUNIT, sub(15, 18)) } case 10000000000000000 { result := mul(uUNIT, sub(16, 18)) } case 100000000000000000 { result := mul(uUNIT, sub(17, 18)) } case 1000000000000000000 { result := 0 } case 10000000000000000000 { result := uUNIT } case 100000000000000000000 { result := mul(uUNIT, 2) } case 1000000000000000000000 { result := mul(uUNIT, 3) } case 10000000000000000000000 { result := mul(uUNIT, 4) } case 100000000000000000000000 { result := mul(uUNIT, 5) } case 1000000000000000000000000 { result := mul(uUNIT, 6) } case 10000000000000000000000000 { result := mul(uUNIT, 7) } case 100000000000000000000000000 { result := mul(uUNIT, 8) } case 1000000000000000000000000000 { result := mul(uUNIT, 9) } case 10000000000000000000000000000 { result := mul(uUNIT, 10) } case 100000000000000000000000000000 { result := mul(uUNIT, 11) } case 1000000000000000000000000000000 { result := mul(uUNIT, 12) } case 10000000000000000000000000000000 { result := mul(uUNIT, 13) } case 100000000000000000000000000000000 { result := mul(uUNIT, 14) } case 1000000000000000000000000000000000 { result := mul(uUNIT, 15) } case 10000000000000000000000000000000000 { result := mul(uUNIT, 16) } case 100000000000000000000000000000000000 { result := mul(uUNIT, 17) } case 1000000000000000000000000000000000000 { result := mul(uUNIT, 18) } case 10000000000000000000000000000000000000 { result := mul(uUNIT, 19) } case 100000000000000000000000000000000000000 { result := mul(uUNIT, 20) } case 1000000000000000000000000000000000000000 { result := mul(uUNIT, 21) } case 10000000000000000000000000000000000000000 { result := mul(uUNIT, 22) } case 100000000000000000000000000000000000000000 { result := mul(uUNIT, 23) } case 1000000000000000000000000000000000000000000 { result := mul(uUNIT, 24) } case 10000000000000000000000000000000000000000000 { result := mul(uUNIT, 25) } case 100000000000000000000000000000000000000000000 { result := mul(uUNIT, 26) } case 1000000000000000000000000000000000000000000000 { result := mul(uUNIT, 27) } case 10000000000000000000000000000000000000000000000 { result := mul(uUNIT, 28) } case 100000000000000000000000000000000000000000000000 { result := mul(uUNIT, 29) } case 1000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 30) } case 10000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 31) } case 100000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 32) } case 1000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 33) } case 10000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 34) } case 100000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 35) } case 1000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 36) } case 10000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 37) } case 100000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 38) } case 1000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 39) } case 10000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 40) } case 100000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 41) } case 1000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 42) } case 10000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 43) } case 100000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 44) } case 1000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 45) } case 10000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 46) } case 100000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 47) } case 1000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 48) } case 10000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 49) } case 100000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 50) } case 1000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 51) } case 10000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 52) } case 100000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 53) } case 1000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 54) } case 10000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 55) } case 100000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 56) } case 1000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 57) } case 10000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 58) } case 100000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 59) } default { result := uMAX_UD60x18 } } if (result.unwrap() == uMAX_UD60x18) { unchecked { // Inline the fixed-point division to save gas. result = wrap(log2(x).unwrap() * uUNIT / uLOG2_10); } } } /// @notice Calculates the binary logarithm of x using the iterative approximation algorithm: /// /// $$ /// log_2{x} = n + log_2{y}, \text{ where } y = x*2^{-n}, \ y \in [1, 2) /// $$ /// /// For $0 \leq x \lt 1$, the input is inverted: /// /// $$ /// log_2{x} = -log_2{\frac{1}{x}} /// $$ /// /// @dev See https://en.wikipedia.org/wiki/Binary_logarithm#Iterative_approximation /// /// Notes: /// - Due to the lossy precision of the iterative approximation, the results are not perfectly accurate to the last decimal. /// /// Requirements: /// - x must be greater than zero. /// /// @param x The UD60x18 number for which to calculate the binary logarithm. /// @return result The binary logarithm as a UD60x18 number. /// @custom:smtchecker abstract-function-nondet function log2(UD60x18 x) pure returns (UD60x18 result) { uint256 xUint = x.unwrap(); if (xUint < uUNIT) { revert Errors.PRBMath_UD60x18_Log_InputTooSmall(x); } unchecked { // Calculate the integer part of the logarithm. uint256 n = Common.msb(xUint / uUNIT); // This is the integer part of the logarithm as a UD60x18 number. The operation can't overflow because n // n is at most 255 and UNIT is 1e18. uint256 resultUint = n * uUNIT; // Calculate $y = x * 2^{-n}$. uint256 y = xUint >> n; // If y is the unit number, the fractional part is zero. if (y == uUNIT) { return wrap(resultUint); } // Calculate the fractional part via the iterative approximation. // The `delta >>= 1` part is equivalent to `delta /= 2`, but shifting bits is more gas efficient. uint256 DOUBLE_UNIT = 2e18; for (uint256 delta = uHALF_UNIT; delta > 0; delta >>= 1) { y = (y * y) / uUNIT; // Is y^2 >= 2e18 and so in the range [2e18, 4e18)? if (y >= DOUBLE_UNIT) { // Add the 2^{-m} factor to the logarithm. resultUint += delta; // Halve y, which corresponds to z/2 in the Wikipedia article. y >>= 1; } } result = wrap(resultUint); } } /// @notice Multiplies two UD60x18 numbers together, returning a new UD60x18 number. /// /// @dev Uses {Common.mulDiv} to enable overflow-safe multiplication and division. /// /// Notes: /// - Refer to the notes in {Common.mulDiv}. /// /// Requirements: /// - Refer to the requirements in {Common.mulDiv}. /// /// @dev See the documentation in {Common.mulDiv18}. /// @param x The multiplicand as a UD60x18 number. /// @param y The multiplier as a UD60x18 number. /// @return result The product as a UD60x18 number. /// @custom:smtchecker abstract-function-nondet function mul(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) { result = wrap(Common.mulDiv18(x.unwrap(), y.unwrap())); } /// @notice Raises x to the power of y. /// /// For $1 \leq x \leq \infty$, the following standard formula is used: /// /// $$ /// x^y = 2^{log_2{x} * y} /// $$ /// /// For $0 \leq x \lt 1$, since the unsigned {log2} is undefined, an equivalent formula is used: /// /// $$ /// i = \frac{1}{x} /// w = 2^{log_2{i} * y} /// x^y = \frac{1}{w} /// $$ /// /// @dev Notes: /// - Refer to the notes in {log2} and {mul}. /// - Returns `UNIT` for 0^0. /// - It may not perform well with very small values of x. Consider using SD59x18 as an alternative. /// /// Requirements: /// - Refer to the requirements in {exp2}, {log2}, and {mul}. /// /// @param x The base as a UD60x18 number. /// @param y The exponent as a UD60x18 number. /// @return result The result as a UD60x18 number. /// @custom:smtchecker abstract-function-nondet function pow(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) { uint256 xUint = x.unwrap(); uint256 yUint = y.unwrap(); // If both x and y are zero, the result is `UNIT`. If just x is zero, the result is always zero. if (xUint == 0) { return yUint == 0 ? UNIT : ZERO; } // If x is `UNIT`, the result is always `UNIT`. else if (xUint == uUNIT) { return UNIT; } // If y is zero, the result is always `UNIT`. if (yUint == 0) { return UNIT; } // If y is `UNIT`, the result is always x. else if (yUint == uUNIT) { return x; } // If x is greater than `UNIT`, use the standard formula. if (xUint > uUNIT) { result = exp2(mul(log2(x), y)); } // Conversely, if x is less than `UNIT`, use the equivalent formula. else { UD60x18 i = wrap(uUNIT_SQUARED / xUint); UD60x18 w = exp2(mul(log2(i), y)); result = wrap(uUNIT_SQUARED / w.unwrap()); } } /// @notice Raises x (a UD60x18 number) to the power y (an unsigned basic integer) using the well-known /// algorithm "exponentiation by squaring". /// /// @dev See https://en.wikipedia.org/wiki/Exponentiation_by_squaring. /// /// Notes: /// - Refer to the notes in {Common.mulDiv18}. /// - Returns `UNIT` for 0^0. /// /// Requirements: /// - The result must fit in UD60x18. /// /// @param x The base as a UD60x18 number. /// @param y The exponent as a uint256. /// @return result The result as a UD60x18 number. /// @custom:smtchecker abstract-function-nondet function powu(UD60x18 x, uint256 y) pure returns (UD60x18 result) { // Calculate the first iteration of the loop in advance. uint256 xUint = x.unwrap(); uint256 resultUint = y & 1 > 0 ? xUint : uUNIT; // Equivalent to `for(y /= 2; y > 0; y /= 2)`. for (y >>= 1; y > 0; y >>= 1) { xUint = Common.mulDiv18(xUint, xUint); // Equivalent to `y % 2 == 1`. if (y & 1 > 0) { resultUint = Common.mulDiv18(resultUint, xUint); } } result = wrap(resultUint); } /// @notice Calculates the square root of x using the Babylonian method. /// /// @dev See https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method. /// /// Notes: /// - The result is rounded toward zero. /// /// Requirements: /// - x must be less than `MAX_UD60x18 / UNIT`. /// /// @param x The UD60x18 number for which to calculate the square root. /// @return result The result as a UD60x18 number. /// @custom:smtchecker abstract-function-nondet function sqrt(UD60x18 x) pure returns (UD60x18 result) { uint256 xUint = x.unwrap(); unchecked { if (xUint > uMAX_UD60x18 / uUNIT) { revert Errors.PRBMath_UD60x18_Sqrt_Overflow(x); } // Multiply x by `UNIT` to account for the factor of `UNIT` picked up when multiplying two UD60x18 numbers. // In this case, the two numbers are both the square root. result = wrap(Common.sqrt(xUint * uUNIT)); } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; import "./Casting.sol" as Casting; import "./Helpers.sol" as Helpers; import "./Math.sol" as Math; /// @notice The unsigned 60.18-decimal fixed-point number representation, which can have up to 60 digits and up to 18 /// decimals. The values of this are bound by the minimum and the maximum values permitted by the Solidity type uint256. /// @dev The value type is defined here so it can be imported in all other files. type UD60x18 is uint256; /*////////////////////////////////////////////////////////////////////////// CASTING //////////////////////////////////////////////////////////////////////////*/ using { Casting.intoSD1x18, Casting.intoUD2x18, Casting.intoSD59x18, Casting.intoUint128, Casting.intoUint256, Casting.intoUint40, Casting.unwrap } for UD60x18 global; /*////////////////////////////////////////////////////////////////////////// MATHEMATICAL FUNCTIONS //////////////////////////////////////////////////////////////////////////*/ // The global "using for" directive makes the functions in this library callable on the UD60x18 type. using { Math.avg, Math.ceil, Math.div, Math.exp, Math.exp2, Math.floor, Math.frac, Math.gm, Math.inv, Math.ln, Math.log10, Math.log2, Math.mul, Math.pow, Math.powu, Math.sqrt } for UD60x18 global; /*////////////////////////////////////////////////////////////////////////// HELPER FUNCTIONS //////////////////////////////////////////////////////////////////////////*/ // The global "using for" directive makes the functions in this library callable on the UD60x18 type. using { Helpers.add, Helpers.and, Helpers.eq, Helpers.gt, Helpers.gte, Helpers.isZero, Helpers.lshift, Helpers.lt, Helpers.lte, Helpers.mod, Helpers.neq, Helpers.not, Helpers.or, Helpers.rshift, Helpers.sub, Helpers.uncheckedAdd, Helpers.uncheckedSub, Helpers.xor } for UD60x18 global; /*////////////////////////////////////////////////////////////////////////// OPERATORS //////////////////////////////////////////////////////////////////////////*/ // The global "using for" directive makes it possible to use these operators on the UD60x18 type. using { Helpers.add as +, Helpers.and2 as &, Math.div as /, Helpers.eq as ==, Helpers.gt as >, Helpers.gte as >=, Helpers.lt as <, Helpers.lte as <=, Helpers.or as |, Helpers.mod as %, Math.mul as *, Helpers.neq as !=, Helpers.not as ~, Helpers.sub as -, Helpers.xor as ^ } for UD60x18 global;
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import "./PythStructs.sol"; import "./IPythEvents.sol"; /// @title Consume prices from the Pyth Network (https://pyth.network/). /// @dev Please refer to the guidance at https://docs.pyth.network/documentation/pythnet-price-feeds/best-practices for how to consume prices safely. /// @author Pyth Data Association interface IPyth is IPythEvents { /// @notice Returns the period (in seconds) that a price feed is considered valid since its publish time function getValidTimePeriod() external view returns (uint validTimePeriod); /// @notice Returns the price and confidence interval. /// @dev Reverts if the price has not been updated within the last `getValidTimePeriod()` seconds. /// @param id The Pyth Price Feed ID of which to fetch the price and confidence interval. /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely. function getPrice( bytes32 id ) external view returns (PythStructs.Price memory price); /// @notice Returns the exponentially-weighted moving average price and confidence interval. /// @dev Reverts if the EMA price is not available. /// @param id The Pyth Price Feed ID of which to fetch the EMA price and confidence interval. /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely. function getEmaPrice( bytes32 id ) external view returns (PythStructs.Price memory price); /// @notice Returns the price of a price feed without any sanity checks. /// @dev This function returns the most recent price update in this contract without any recency checks. /// This function is unsafe as the returned price update may be arbitrarily far in the past. /// /// Users of this function should check the `publishTime` in the price to ensure that the returned price is /// sufficiently recent for their application. If you are considering using this function, it may be /// safer / easier to use either `getPrice` or `getPriceNoOlderThan`. /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely. function getPriceUnsafe( bytes32 id ) external view returns (PythStructs.Price memory price); /// @notice Returns the price that is no older than `age` seconds of the current time. /// @dev This function is a sanity-checked version of `getPriceUnsafe` which is useful in /// applications that require a sufficiently-recent price. Reverts if the price wasn't updated sufficiently /// recently. /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely. function getPriceNoOlderThan( bytes32 id, uint age ) external view returns (PythStructs.Price memory price); /// @notice Returns the exponentially-weighted moving average price of a price feed without any sanity checks. /// @dev This function returns the same price as `getEmaPrice` in the case where the price is available. /// However, if the price is not recent this function returns the latest available price. /// /// The returned price can be from arbitrarily far in the past; this function makes no guarantees that /// the returned price is recent or useful for any particular application. /// /// Users of this function should check the `publishTime` in the price to ensure that the returned price is /// sufficiently recent for their application. If you are considering using this function, it may be /// safer / easier to use either `getEmaPrice` or `getEmaPriceNoOlderThan`. /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely. function getEmaPriceUnsafe( bytes32 id ) external view returns (PythStructs.Price memory price); /// @notice Returns the exponentially-weighted moving average price that is no older than `age` seconds /// of the current time. /// @dev This function is a sanity-checked version of `getEmaPriceUnsafe` which is useful in /// applications that require a sufficiently-recent price. Reverts if the price wasn't updated sufficiently /// recently. /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely. function getEmaPriceNoOlderThan( bytes32 id, uint age ) external view returns (PythStructs.Price memory price); /// @notice Update price feeds with given update messages. /// This method requires the caller to pay a fee in wei; the required fee can be computed by calling /// `getUpdateFee` with the length of the `updateData` array. /// Prices will be updated if they are more recent than the current stored prices. /// The call will succeed even if the update is not the most recent. /// @dev Reverts if the transferred fee is not sufficient or the updateData is invalid. /// @param updateData Array of price update data. function updatePriceFeeds(bytes[] calldata updateData) external payable; /// @notice Wrapper around updatePriceFeeds that rejects fast if a price update is not necessary. A price update is /// necessary if the current on-chain publishTime is older than the given publishTime. It relies solely on the /// given `publishTimes` for the price feeds and does not read the actual price update publish time within `updateData`. /// /// This method requires the caller to pay a fee in wei; the required fee can be computed by calling /// `getUpdateFee` with the length of the `updateData` array. /// /// `priceIds` and `publishTimes` are two arrays with the same size that correspond to senders known publishTime /// of each priceId when calling this method. If all of price feeds within `priceIds` have updated and have /// a newer or equal publish time than the given publish time, it will reject the transaction to save gas. /// Otherwise, it calls updatePriceFeeds method to update the prices. /// /// @dev Reverts if update is not needed or the transferred fee is not sufficient or the updateData is invalid. /// @param updateData Array of price update data. /// @param priceIds Array of price ids. /// @param publishTimes Array of publishTimes. `publishTimes[i]` corresponds to known `publishTime` of `priceIds[i]` function updatePriceFeedsIfNecessary( bytes[] calldata updateData, bytes32[] calldata priceIds, uint64[] calldata publishTimes ) external payable; /// @notice Returns the required fee to update an array of price updates. /// @param updateData Array of price update data. /// @return feeAmount The required fee in Wei. function getUpdateFee( bytes[] calldata updateData ) external view returns (uint feeAmount); /// @notice Parse `updateData` and return price feeds of the given `priceIds` if they are all published /// within `minPublishTime` and `maxPublishTime`. /// /// You can use this method if you want to use a Pyth price at a fixed time and not the most recent price; /// otherwise, please consider using `updatePriceFeeds`. This method may store the price updates on-chain, if they /// are more recent than the current stored prices. /// /// This method requires the caller to pay a fee in wei; the required fee can be computed by calling /// `getUpdateFee` with the length of the `updateData` array. /// /// /// @dev Reverts if the transferred fee is not sufficient or the updateData is invalid or there is /// no update for any of the given `priceIds` within the given time range. /// @param updateData Array of price update data. /// @param priceIds Array of price ids. /// @param minPublishTime minimum acceptable publishTime for the given `priceIds`. /// @param maxPublishTime maximum acceptable publishTime for the given `priceIds`. /// @return priceFeeds Array of the price feeds corresponding to the given `priceIds` (with the same order). function parsePriceFeedUpdates( bytes[] calldata updateData, bytes32[] calldata priceIds, uint64 minPublishTime, uint64 maxPublishTime ) external payable returns (PythStructs.PriceFeed[] memory priceFeeds); /// @notice Similar to `parsePriceFeedUpdates` but ensures the updates returned are /// the first updates published in minPublishTime. That is, if there are multiple updates for a given timestamp, /// this method will return the first update. This method may store the price updates on-chain, if they /// are more recent than the current stored prices. /// /// /// @dev Reverts if the transferred fee is not sufficient or the updateData is invalid or there is /// no update for any of the given `priceIds` within the given time range and uniqueness condition. /// @param updateData Array of price update data. /// @param priceIds Array of price ids. /// @param minPublishTime minimum acceptable publishTime for the given `priceIds`. /// @param maxPublishTime maximum acceptable publishTime for the given `priceIds`. /// @return priceFeeds Array of the price feeds corresponding to the given `priceIds` (with the same order). function parsePriceFeedUpdatesUnique( bytes[] calldata updateData, bytes32[] calldata priceIds, uint64 minPublishTime, uint64 maxPublishTime ) external payable returns (PythStructs.PriceFeed[] memory priceFeeds); }
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; /// @title IPythEvents contains the events that Pyth contract emits. /// @dev This interface can be used for listening to the updates for off-chain and testing purposes. interface IPythEvents { /// @dev Emitted when the price feed with `id` has received a fresh update. /// @param id The Pyth Price Feed ID. /// @param publishTime Publish time of the given price update. /// @param price Price of the given price update. /// @param conf Confidence interval of the given price update. event PriceFeedUpdate( bytes32 indexed id, uint64 publishTime, int64 price, uint64 conf ); /// @dev Emitted when a batch price update is processed successfully. /// @param chainId ID of the source chain that the batch price update comes from. /// @param sequenceNumber Sequence number of the batch price update. event BatchPriceFeedUpdate(uint16 chainId, uint64 sequenceNumber); }
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; contract PythStructs { // A price with a degree of uncertainty, represented as a price +- a confidence interval. // // The confidence interval roughly corresponds to the standard error of a normal distribution. // Both the price and confidence are stored in a fixed-point numeric representation, // `x * (10^expo)`, where `expo` is the exponent. // // Please refer to the documentation at https://docs.pyth.network/documentation/pythnet-price-feeds/best-practices for how // to how this price safely. struct Price { // Price int64 price; // Confidence interval around the price uint64 conf; // Price exponent int32 expo; // Unix timestamp describing when the price was published uint publishTime; } // PriceFeed represents a current aggregate price from pyth publisher feeds. struct PriceFeed { // The price ID. bytes32 id; // Latest available price Price price; // Latest available exponentially-weighted moving average price Price emaPrice; } }
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.24; import { Multicall } from "@openzeppelin/contracts/utils/Multicall.sol"; import { Pausable } from "@openzeppelin/contracts/utils/Pausable.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import { ERC2771Context } from "@openzeppelin/contracts/metatx/ERC2771Context.sol"; import { SafeERC20, IERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import { Initializable } from "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import { EnumerableSet } from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import { IAccount } from "../interfaces/IAccount.sol"; import { IAccountManager } from "../interfaces/IAccountManager.sol"; import { UD60x18, ud, UNIT, ZERO } from "@prb/math/src/UD60x18.sol"; import { AccountLib } from "../libraries/accounts/AccountLib.sol"; import "../libraries/traits/AddressCheckerTrait.sol"; import "../interfaces/ILendingPool.sol"; import "../libraries/Errors.sol"; abstract contract BaseAccountEvents { ///////////////////////////// // Events ///////////////////////////// /// @notice Event emitted when an `amount` is claimed from the account event Claim(uint256 amount); /// @notice Event emitted when the liquidation fee is taken, records the fee `amount` taken and the `recipient` event LiquidationFeeTaken(address recipient, uint256 amount); } /// @title Base Account /// @notice The Base Account contract is the parent contract for all investment accounts /// @dev ERC2771Context is initialized with a null address because we override the isTrustedForwarder method to use the /// Account Manager as the trustedForwarder. abstract contract BaseAccount is BaseAccountEvents, IAccount, AddressCheckerTrait, Initializable, Pausable, ERC2771Context(address(0)) { using SafeERC20 for IERC20; ///////////////////////////// // Omega Protocol Contracts ///////////////////////////// /// @dev Accounts use the other contracts in the protocol for various functions /// /// AccountManager - Referrences this contract for access control purposes /// LendingPool - Accesses this contract to borrow and repay as well as to /// Read the debt and collateral amounts. /// offchain liquidations. /// @notice The Investment Account Manager IAccountManager internal _manager; /// @notice The asset used by this investment account IERC20 public asset; ///////////////////////////// // State Variables ///////////////////////////// /// @notice The owner of this account address public owner; /** * @dev Only allows the contract's own address to call the function. */ modifier onlySelf() { if (msg.sender != address(this)) { revert Errors.UnauthorizedRole(msg.sender, "SELF"); } _; } /// @notice Empty constructor because this contract is deployed as a clone in the manager constructor() { } /// @notice Initialize this investment account /// @param owner_ The borrower that owns this account function initialize(address owner_) external virtual initializer { _initialize(owner_); } /// @notice Initialize this investment account /// @param owner_ The borrower that owns this account function _initialize(address owner_) internal { _manager = IAccountManager(msg.sender); asset = _manager.getLendAsset(); owner = owner_; // Approve repayments to the lending pool asset.safeIncreaseAllowance(_manager.lendingPool(), type(uint256).max); // Approve manager to transfer assets asset.safeIncreaseAllowance(address(_manager), type(uint256).max); } //////////////////////////// // Access Control Modifiers //////////////////////////// /// @notice Restricts access to the `manager` of the account modifier onlyAccountManager() { if (msg.sender != address(_manager)) revert Errors.Unauthorized(); _; } /// @notice Restricts access to the `owner` of the account /// @dev We use _msgSender() to allow for meta transactions modifier onlyOwner() { if (_msgSender() != owner) revert Errors.Unauthorized(); _; } modifier onlyRepayer() { if (!(_msgSender() == owner || _manager.isLiquidationReceiver(msg.sender) || msg.sender == address(_manager))) { revert Errors.Unauthorized(); } _; } /////////////////////// // ERC2771 Context Methods /////////////////////// function isTrustedForwarder(address forwarder) public view virtual override(ERC2771Context) returns (bool) { return forwarder == address(_manager); } function _msgSender() internal view virtual override(Context, ERC2771Context) returns (address sender) { return ERC2771Context._msgSender(); } // slither-disable-next-line dead-code function _msgData() internal view virtual override(Context, ERC2771Context) returns (bytes calldata) { // slither-disable-next-line dead-code return ERC2771Context._msgData(); } function _contextSuffixLength() internal view virtual override(Context, ERC2771Context) returns (uint256) { return ERC2771Context._contextSuffixLength(); } /////////////////////// // Admin Methods /////////////////////// /// @notice The owner of the accountManager is allowed to: /// - Pause/unpause the contract /// @notice Lets the admin pause the account function pause() external onlyAccountManager { _pause(); } /// @notice Lets the admin unpause the account function unpause() external onlyAccountManager { _unpause(); } ////////////////////////// // Lending Pool Methods ////////////////////////// /// @notice Interactions to borrow and repay from the `lendingPool` /// @notice Borrow from the lending pool /// @dev Manager is in charge of making sure this account is still solvent after borrowing. /// @dev Loans are assessed by looking at the account's debt and collateral. /// @param amount The amount to borrow function borrow(uint256 amount) external virtual onlyOwner whenNotPaused { // Borrow funds uint256 amountBorrowed = _manager.borrow(amount); emit Borrow(amountBorrowed); } /// @notice Repay the lending pool /// @param amount The amount to repay function repay(uint256 amount) external virtual onlyRepayer { uint256 amountRepaid = _manager.repay(address(this), amount); emit Repay(amountRepaid); } //////////////////// // Views //////////////////// /// @notice Returns the AccountManager that created this Account. function getManager() external view returns (IAccountManager) { return _manager; } function claim(uint256 amount) external onlyOwner whenNotPaused { _manager.claim(amount, msg.sender); emit Claim(amount); } function claim(uint256 amount, address recipient) external onlyOwner whenNotPaused { _manager.claim(amount, recipient); emit Claim(amount); } }
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.24; import { EnumerableSet } from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "./BaseAccount.sol"; import { UD60x18, ud } from "@prb/math/src/UD60x18.sol"; import "../libraries/Errors.sol"; /// @title External Account /// @notice This account type supports borrowing from the lending pool /// directly to the owners wallet. LTVs on this account type will be /// less than 100%. This account type relies on off-chain liquidations. contract ExternalAccount is BaseAccount { using SafeERC20 for IERC20; using EnumerableSet for EnumerableSet.AddressSet; /// @notice Initialize this permissionless account /// @param owner_ The borrower that owns this account function initialize(address owner_) public override initializer { _initialize(owner_); } ////////////////////////// // Lending Pool Methods ////////////////////////// /// @notice Borrow from the lending pool /// @param amount The amount to borrow function borrow(uint256 amount) external override onlyOwner whenNotPaused { uint256 amountBorrowed = _manager.borrow(amount); asset.safeTransfer(msg.sender, amountBorrowed); emit Borrow(amountBorrowed); } /// @notice Repay the lending pool /// @param amount The amount to repay function repay(uint256 amount) external override whenNotPaused { uint256 amountRepaid = _manager.repay(address(this), amount); emit Repay(amountRepaid); } function getKind() external pure returns (bytes32) { return keccak256(abi.encode("OMEGA_EXTERNAL_ACCOUNT")); } }
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.24; import { EnumerableSet } from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import { IStrategyVault } from "../interfaces/IStrategyVault.sol"; import { UD60x18, ud } from "@prb/math/src/UD60x18.sol"; import "./BaseAccount.sol"; import "../libraries/Errors.sol"; abstract contract InternalAccountEvents { /// @notice The owner made a deposit of `amount` into `strategy` event StrategyDeposit(address strategy, uint256 amount); /// @notice The owner withdrew `amount` from `strategy` event StrategyWithdraw(address strategy, uint256 amount); /// @notice The deposits into `strategy` have been forcibly withdrawn and `receveredAmount` was returned /// @dev When strategy == address(0) it indicates a liquidation of the balance in the account event StrategyLiquidated(address indexed strategy, uint256 recoveredAmount); } /// @title Internal Account /// @notice This account type is used to manage investments into approved strategies. /// The account owner can deposit and withdraw from approved strategies to earn profits. contract InternalAccount is BaseAccount, InternalAccountEvents { using SafeERC20 for IERC20; /// @notice Empty constructor because this contract is deployed as a clone in the manager constructor() { } /// @notice Initialize this permissioned account /// @param owner_ The borrower that owns this account function initialize(address owner_) public virtual override initializer { _initialize(owner_); } ////////////////////////// // Investment Methods ////////////////////////// /// @notice These methods are used to manage permissioned investment into approved investment strategies /// @notice Deposit into a Omega Strategy Vault /// @dev The `minShares` can be calculated using the `previewDeposit` method on the vault /// @param strategy The address of the strategy to deposit into /// @param amount The amount to deposit in USDC /// @param data encode data for the strategy to process the deposit function strategyDeposit( address strategy, uint256 amount, bytes memory data ) external payable virtual onlyOwner whenNotPaused returns (uint256 receivedShares) { asset.safeIncreaseAllowance(strategy, amount); receivedShares = _manager.strategyDeposit{ value: msg.value }(owner, strategy, amount, data); emit StrategyDeposit(strategy, amount); } /// @notice Withdraw from a Omega Strategy Vault /// @dev The `minUsdc` can be calculated using the `previewWithdraw` method on the vault /// @param strategy The address of the strategy to withdraw from /// @param shares The amount to withdraw in vault shares /// @param data encoded data for the strategy to process the withdrawal function strategyWithdraw( address strategy, uint256 shares, bytes memory data ) external payable onlyOwner whenNotPaused returns (uint256 receivedAssets) { receivedAssets = IStrategyVault(strategy).withdraw{ value: msg.value }(shares, data); _manager.strategyWithdrawal(owner, strategy, receivedAssets); emit StrategyWithdraw(strategy, shares); } ////////////////////////// // View Methods ////////////////////////// /// @notice These methods are used to view information about this account function getKind() external pure virtual returns (bytes32) { return keccak256(abi.encode("OMEGA_INTERNAL_ACCOUNT")); } ////////////////////////// // Liquidator Methods ////////////////////////// function _preStrategyLiquidation(address recipient) internal view returns (uint256 amountBefore) { // Track the amount liquidate by checking the asset balance of the liquidator before and after amountBefore = asset.balanceOf(recipient); } function _postStrategyLiquidation( address strategy, address recipient, uint256 expectedReceived, uint256 amountBefore ) internal { if (asset.balanceOf(address(recipient)) < (expectedReceived + amountBefore)) { revert Errors.WithdrawnAssetsNotReceived(); } // When strategy == address(0) it indicates a liquidation of the balance in the account emit StrategyLiquidated(strategy, expectedReceived); } function liquidateStrategy( address strategy, address recipient, uint256 minAmount, bytes memory data ) external payable onlyAccountManager { uint256 amountBefore = _preStrategyLiquidation(recipient); uint256 receivedAssets = 0; if (strategy != address(0)) { receivedAssets = IStrategyVault(strategy).liquidate{ value: msg.value }(recipient, minAmount, data); _postStrategyLiquidation(strategy, recipient, receivedAssets, amountBefore); } } receive() external payable { } }
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.24; enum YieldMode { AUTOMATIC, VOID, CLAIMABLE } enum GasMode { VOID, CLAIMABLE } interface IBlastPoints { function configurePointsOperator(address operator) external; } interface IBlast { // configure function configureContract(address contractAddress, YieldMode _yield, GasMode gasMode, address governor) external; function configure(YieldMode _yield, GasMode gasMode, address governor) external; // base configuration options function configureClaimableYield() external; function configureClaimableYieldOnBehalf(address contractAddress) external; function configureAutomaticYield() external; function configureAutomaticYieldOnBehalf(address contractAddress) external; function configureVoidYield() external; function configureVoidYieldOnBehalf(address contractAddress) external; function configureClaimableGas() external; function configureClaimableGasOnBehalf(address contractAddress) external; function configureVoidGas() external; function configureVoidGasOnBehalf(address contractAddress) external; function configureGovernor(address _governor) external; function configureGovernorOnBehalf(address _newGovernor, address contractAddress) external; // claim yield function claimYield(address contractAddress, address recipientOfYield, uint256 amount) external returns (uint256); function claimAllYield(address contractAddress, address recipientOfYield) external returns (uint256); // claim gas function claimAllGas(address contractAddress, address recipientOfGas) external returns (uint256); function claimGasAtMinClaimRate( address contractAddress, address recipientOfGas, uint256 minClaimRateBips ) external returns (uint256); function claimMaxGas(address contractAddress, address recipientOfGas) external returns (uint256); function claimGas( address contractAddress, address recipientOfGas, uint256 gasToClaim, uint256 gasSecondsToConsume ) external returns (uint256); // read functions function readClaimableYield(address contractAddress) external view returns (uint256); function readYieldConfiguration(address contractAddress) external view returns (uint8); function readGasParams(address contractAddress) external view returns (uint256 etherSeconds, uint256 etherBalance, uint256 lastUpdated, GasMode); }
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.24; import "./IBlast.sol"; interface IERC20Rebasing { // changes the yield mode of the caller and update the balance // to reflect the configuration function configure(YieldMode) external returns (uint256); // "claimable" yield mode accounts can call this this claim their yield // to another address function claim(address recipient, uint256 amount) external returns (uint256); // read the claimable amount for an account function getClaimableAmount(address account) external view returns (uint256); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function transfer(address recipient, uint256 amount) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); }
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.24; import "solady/src/tokens/ERC20.sol"; import "../libraries/accounts/AccountLib.sol"; import "../interfaces/IAccountManager.sol"; interface IAccount { /// @notice How much was borrowed from the lending pool event Borrow(uint256 amount); /// @notice How much debt was paid back to the lending pool event Repay(uint256 amount); function asset() external view returns (IERC20); function owner() external view returns (address); /// @dev Returns a unique identifier distinguishing this type of account function getKind() external view returns (bytes32); function getManager() external view returns (IAccountManager); function initialize(address owner_) external; function pause() external; function unpause() external; /// Owner interactions function borrow(uint256 amount) external; function repay(uint256 amount) external; function claim(uint256 amount) external; function claim(uint256 amount, address recipient) external; }
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.24; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import { UD60x18, ud } from "@prb/math/src/UD60x18.sol"; import "../libraries/accounts/AccountLib.sol"; import "./ILiquidationReceiver.sol"; interface IAccountManager { function lendingPool() external view returns (address); function isCreatedAccount(address) external view returns (bool); function accountCount() external view returns (uint256); function isApprovedStrategy(address strategy) external view returns (bool); function isLiquidationReceiver(address receiver) external view returns (bool); function pauseAccount(address account) external; function unpauseAccount(address account) external; function getFeeCollector() external view returns (address); function getLiquidationReceiver( address account, address liquidationFeeTo ) external view returns (ILiquidationReceiver); function getLiquidationFee() external returns (AccountLib.LiquidationFee memory); // Following three functions are only callable by the target Account itself. function borrow(uint256 amount) external returns (uint256 borrowedAmount); function repay(address account, uint256 amount) external returns (uint256 repaidAmount); function claim(uint256 amount, address recipient) external; function liquidate(address account, address liquidationFeeTo) external returns (ILiquidationReceiver); /// @notice Deposits assets into a strategy on behalf of msg.sender, which must be an Account. function strategyDeposit( address owner, address strategy, uint256 assets, bytes memory data ) external payable returns (uint256 shares); function strategyWithdrawal(address owner, address strategy, uint256 assets) external; /// @dev Some strategies have an execution fee that needs to be paid for withdrawal so that must be sent to this /// function. function liquidateStrategy( address account, address liquidationFeeTo, address strategy, bytes memory data ) external payable returns (ILiquidationReceiver); function emitLiquidationFeeEvent( address feeCollector, address liquidationFeeTo, uint256 protocolShare, uint256 liquidatorShare ) external; function getLendAsset() external view returns (IERC20); function getDebtAmount(address account) external view returns (uint256); function getTotalCollateralValue(address account) external view returns (uint256 totalValue); function getAccountLoan(address account) external view returns (AccountLib.Loan memory loan); function getAccountHealth(address account) external view returns (AccountLib.Health memory health); /// @notice Returns whether or not an account is liquidatable. If true, return the timestamp its liquidation started /// at. function getAccountLiquidationStatus(address account) external view returns (AccountLib.LiquidationStatus memory); function getAccountLiquidationSlippageTolerance(address account) external view returns (UD60x18); }
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.24; /// @notice Interface for a price oracle preconfigured to return the price of an asset. /// @dev Price can be in any denomination, depending on the preconfiguration. interface IAssetPriceOracle { function getPrice() external view returns (uint256 price); }
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.24; import { IAssetPriceOracle } from "./IAssetPriceOracle.sol"; /** * @title IAssetPriceProvider interface * @notice Interface for the collateral price provider. * */ interface IAssetPriceProvider { /** * @dev returns the asset price in debt token * @param asset the address of the asset * @return the debt token price of the asset * */ function getAssetPrice(address asset) external view returns (uint256); /** * @dev returns the asset oracle address * @param asset the address of the asset * @return the address of the asset oracle */ function getAssetOracle(address asset) external view returns (IAssetPriceOracle); }
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.24; interface IGasTank { function allowList(address user) external returns (bool allowed); function accessControllers(address controller) external returns (bool allowed); function deposit() external payable; function withdraw(uint256 amount) external; function allowListUpdate(address contractAddress, bool allowed) external; function accessControllerUpdate(address accessController, bool allowed) external; function reimburseGas(address receiver, uint256 amount) external; }
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.24; import "solady/src/tokens/ERC20.sol"; import "./IAccount.sol"; interface IInternalAccount is IAccount { function strategyDeposit(address strategy, uint256 amount) external; function strategyWithdraw(address strategy, uint256 amount) external; function liquidateStrategy( address strategy, address recipient, uint256 minAmount, bytes memory data ) external payable; }
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.24; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import { UD60x18, ud } from "@prb/math/src/UD60x18.sol"; import "../libraries/accounts/AccountLib.sol"; import "./ILiquidationReceiver.sol"; interface IJuiceAccountManager { function borrow( uint256 amount, bytes[] memory pythPriceUpdates ) external payable returns (uint256 borrowedAmount); /// @notice Deposits assets into a strategy on behalf of msg.sender, which must be an Account. function strategyDeposit( address owner, address strategy, uint256 assets, bytes memory data, bytes[] memory pythPriceUpdates ) external payable returns (uint256 shares); function strategyWithdrawal( address owner, address strategy, uint256 assets, bytes[] memory pythPriceUpdates ) external payable; }
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.24; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import { UD60x18, ud } from "@prb/math/src/UD60x18.sol"; interface ILendingPool { function allowedLenders(address lender) external view returns (bool); function deposit(uint256 amount) external returns (uint256); function withdraw(uint256 amount) external returns (uint256); function getMinimumOpenBorrow() external view returns (uint256); function setMinimumOpenBorrow(uint256 amount) external; function getDebtAmount(address borrower) external view returns (uint256); function getDepositAmount(address lender) external view returns (uint256); function getTotalSupply() external view returns (uint256); function getTotalBorrow() external view returns (uint256); function getAsset() external view returns (IERC20); function getNormalizedIncome() external view returns (UD60x18); function getNormalizedDebt() external view returns (UD60x18); function accrueInterest() external; // PermissionedLendingPool Only function updateLenderStatus(address lender, bool status) external; // AccountManager function borrow(uint256 amount, address onBehalfOf) external returns (uint256); ///@dev Repays loan of `onBehalfOf`, transferring funds from `onBehalfOf` function repay(uint256 amount, address onBehalfOf) external returns (uint256); ///@dev Repays loan of `onBehalfOf`, transferring funds from `from` function repay(uint256 amount, address onBehalfOf, address from) external returns (uint256); }
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.24; import { SafeERC20, IERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import { IAccount } from "./IAccount.sol"; import { IAccountManager } from "./IAccountManager.sol"; interface ILiquidationReceiver { struct Props { IERC20 asset; IAccountManager manager; IAccount account; address liquidationFeeTo; } function initialize(Props memory props_) external; function repay() external; }
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.24; import { UD60x18 } from "@prb/math/src/UD60x18.sol"; interface IProtocolGovernor { function getOwner() external view returns (address); function getAddress(bytes32 id) external view returns (address); function getImmutableAddress(bytes32 id) external view returns (address); function getFee(bytes32 id) external view returns (UD60x18); function isProtocolDeprecated() external view returns (bool); // Accounts Managers can open loans on behalf of Accounts they create. function updateAccountManagerStatus(address manager, bool active) external; function isAccountManager(address manager) external view returns (bool); // RBAC function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function hasRole(bytes32 role, address account) external view returns (bool); }
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.24; import { UD60x18 } from "@prb/math/src/UD60x18.sol"; // TODO: in the future, we will adjust this based off how long the account has been in liquidation // Note: This slippage tolerance might be better to increase as a function of elapse // time. That is, the slippage is higher the longer the account is in liquidation. // A static slippage like this means we'd need to manually increase the value if the // position can't be liquidate with the set slippage tolerance. /// @notice This contract returns the slippageTolerance for a strategy liquidation as a function of how long that /// strategy has been in /// liquidation mode. interface IStrategySlippageModel { function calculateSlippage(uint256 timeSinceLiquidationStarted) external view returns (UD60x18 slippageTolerance); }
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.24; /// @title Omega Strategy Vault Interface /// /// @notice These vaults accept USDC and invest them into a strategy. /// The deposit is done in USDC but the shares are in the underlying asset. /// The underlying asset is referred to as `asset` in the contract. /// These vaults implement _some_ ERC4626 methods. /// There is one significant change for these vaults: the deposit is /// done using USDC instead of the `asset` (i.e. the underlying asset). /// /// @dev Shares are priced in units of the `asset` NOT in USDC /// interface IStrategyVault { /// @notice Estimate the ETH execution fee needed for this withdrawal function estimateExecuteWithdrawalGasLimit() external view returns (uint256); /// @notice Deposits USDC into the vault /// @param assets The amount of USDC to deposit /// @param data encoded data for the strategy to process the deposit /// @param recipient The address to send the share tokens to function deposit( uint256 assets, bytes memory data, address recipient ) external payable returns (uint256 receivedShares); /// @notice Withdraws `msg.sender` shares from the vault and sends baseAsset to self. /// @param shares The amount of vault shares to withdraw /// @param data encoded data for the strategy to process the withdrawal function withdraw(uint256 shares, bytes memory data) external payable returns (uint256 receivedAmount); /// @notice Performs a complete withdrawal for `msg.sender` and sends funds to receiver. function liquidate(address receiver, uint256 minAmount, bytes memory data) external payable returns (uint256); /// @notice This function allows users to simulate the effects of their withdrawal at the current block. /// @dev Use this to calculate the minAmount of lend token to withdraw during withdrawal /// @param shareAmount The amount of shares to redeem /// @return The amount of lend token that would be redeemed for the amount of shares provided function previewWithdraw(uint256 shareAmount) external view returns (uint256); /// @notice This function allows users to simulate the effects of their deposit at the current block. /// @dev Use this to calculate the minAmount of shares to mint during deposit /// @param assetAmount The amount of assets to deposit /// @return The amount of shares that would be minted for the amount of asset provided function previewDeposit(uint256 assetAmount) external view returns (uint256); /// @notice Returns value of the position of the account denominated in lending token. function getPositionValue(address account) external view returns (uint256); }
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.24; import "../libraries/Errors.sol"; import "../libraries/traits/AddressCheckerTrait.sol"; import { SafeERC20, IERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "solady/src/tokens/ERC20.sol"; import "solady/src/utils/FixedPointMathLib.sol"; /// @notice A vault that holds a single asset as collateral. /// @dev It discards stealth donations and tracks its underlying collateral balance manually. /// It is non-transferrable because of how it is used to track the collateral backing loans taken by user owned smart /// contract accounts. abstract contract ERC20CollateralVault is ERC20, AddressCheckerTrait { using SafeERC20 for IERC20; using FixedPointMathLib for uint256; IERC20 internal immutable _collateral; uint256 internal _totalCollateralAssets; uint8 internal immutable _collateralAssetDecimals; string private _name; string private _symbol; constructor( address collateral_, string memory name_, string memory symbol_, uint8 decimals_ ) nonZeroAddressAndContract(collateral_) { _collateral = IERC20(collateral_); _collateralAssetDecimals = decimals_; _name = name_; _symbol = symbol_; } function name() public view override returns (string memory) { return _name; } function symbol() public view override returns (string memory) { return _symbol; } function decimals() public view override returns (uint8) { return _collateralAssetDecimals; } function deposit(uint256 assets, address receiver) public virtual returns (uint256 updatedAssets, uint256 shares) { (updatedAssets, shares) = _deposit(msg.sender, receiver, assets); } function withdraw( uint256 shares, address receiver ) public virtual returns (uint256 updatedAssets, uint256 updatedShares) { (updatedAssets, updatedShares) = _withdraw(msg.sender, receiver, shares); } function previewDeposit(uint256 assets) public view virtual returns (uint256 updatedAssets, uint256 shares) { shares = _convertToShares(assets); updatedAssets = _convertToAssets(shares); } function previewWithdraw(uint256 shares) public view virtual returns (uint256 assets, uint256 updatedShares) { assets = _convertToAssets(shares); updatedShares = shares; } function _deposit( address caller, address receiver, uint256 assets ) internal virtual returns (uint256 updatedAssets, uint256 shares) { (updatedAssets, shares) = previewDeposit(assets); _totalCollateralAssets += updatedAssets; _collateral.safeTransferFrom(caller, address(this), updatedAssets); _mint(receiver, shares); } function _withdraw( address caller, address receiver, uint256 shares ) internal virtual returns (uint256 updatedAssets, uint256 updatedShares) { (updatedAssets, updatedShares) = previewWithdraw(shares); _totalCollateralAssets -= updatedAssets; _burn(caller, updatedShares); _collateral.safeTransfer(receiver, updatedAssets); } function _withdrawAssets(address caller, address receiver, uint256 assets) internal virtual { // Round up the amount of shares to burn given some assets. uint256 shares = assets.mulDivUp(totalSupply(), totalAssets()); _totalCollateralAssets -= assets; _burn(caller, shares); _collateral.safeTransfer(receiver, assets); } /// @dev Returns the shares minted for given assets, rounding down. function _convertToShares(uint256 assets) internal view returns (uint256) { return totalSupply() == 0 ? assets : assets * totalSupply() / totalAssets(); } /// @dev Returns the assets transferred for given shares, rounding down. function _convertToAssets(uint256 shares) internal view returns (uint256) { return totalSupply() == 0 ? shares : shares * totalAssets() / totalSupply(); } function balanceOfAssets(address account) public view returns (uint256 assets) { return _convertToAssets(balanceOf(account)); } function totalAssets() public view virtual returns (uint256) { return _totalCollateralAssets; } /// @notice Disables transfers other than mint and burn /// @dev Done explicitly because solady transfers do not prevent transferring to zero address. function transfer(address, uint256) public pure override returns (bool) { revert Errors.TransferDisabled(); } function transferFrom(address, address, uint256) public pure override returns (bool) { revert Errors.TransferDisabled(); } }
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.24; import { EnumerableSet } from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import { IStrategyVault } from "../interfaces/IStrategyVault.sol"; import { UD60x18, ud } from "@prb/math/src/UD60x18.sol"; import "../external/blast/IERC20Rebasing.sol"; import "../interfaces/IJuiceAccountManager.sol"; import "../accounts/InternalAccount.sol"; import "./JuiceModule.sol"; import "../libraries/Errors.sol"; /// @title Juice Account /// @notice This account type is used to manage investments into approved strategies. /// The account owner can deposit and withdraw from approved strategies to earn profits. contract JuiceAccount is InternalAccount { using SafeERC20 for IERC20; using EnumerableSet for EnumerableSet.AddressSet; /// @notice Pyth oracle contract IPyth public pyth; /// @notice Active strategies for this account EnumerableSet.AddressSet private activeStrategies; /// @notice Empty constructor because this contract is deployed as a clone in the manager constructor() { } /// @notice Initialize this permissioned account /// @param owner_ The borrower that owns this account function initialize(address owner_, IPyth pyth_) public virtual initializer { _initialize(owner_); pyth = pyth_; IERC20Rebasing(address(asset)).configure(YieldMode.VOID); } function getKind() external pure override returns (bytes32) { return keccak256(abi.encode("JUICE_INVESTMENT_ACCOUNT")); } function borrow( uint256 amount, bytes[] memory pythPriceUpdates ) external payable returns (uint256 borrowedAmount) { borrowedAmount = IJuiceAccountManager(address(_manager)).borrow{ value: msg.value }(amount, pythPriceUpdates); } function strategyDeposit( address strategy, uint256 amount, bytes memory data, bytes[] memory pythPriceUpdates ) external payable onlyOwner whenNotPaused returns (uint256 receivedShares) { asset.safeIncreaseAllowance(strategy, amount); receivedShares = IJuiceAccountManager(address(_manager)).strategyDeposit{ value: msg.value }( owner, strategy, amount, data, pythPriceUpdates ); emit StrategyDeposit(strategy, amount); } function strategyWithdraw( address strategy, uint256 shares, bytes memory data, bytes[] memory pythPriceUpdates ) external payable onlyOwner whenNotPaused returns (uint256 receivedAssets) { receivedAssets = IStrategyVault(strategy).withdraw{ value: msg.value }(shares, data); IJuiceAccountManager(address(_manager)).strategyWithdrawal(owner, strategy, receivedAssets, pythPriceUpdates); emit StrategyWithdraw(strategy, shares); } }
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.24; import "../system/ProtocolGovernor.sol"; import "../external/blast/IBlast.sol"; /** * @title JuiceGovernor * @dev Allows for storing and management of protocol data related to our Blast deployment. */ contract JuiceGovernor is ProtocolGovernor { constructor( InitParams memory params, address blast, address blastPoints ) ProtocolGovernor(params) nonZeroAddressAndContract(blast) nonZeroAddressAndContract(blastPoints) { _setImmutableAddress(GovernorLib.BLAST, blast); _setImmutableAddress(GovernorLib.BLAST_POINTS, blastPoints); } }
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.24; import "./JuiceGovernor.sol"; import "../system/ProtocolModule.sol"; import "../libraries/Roles.sol"; /** * @title JuiceModule */ abstract contract JuiceModule is AddressCheckerTrait { using Roles for IProtocolGovernor; IProtocolGovernor private _protocolGovernor; /** * @dev Constructor that initializes the Juice Governor for this contract. * * @param juiceGovernor_ The contract instance to use as the Juice Governor. */ constructor(address juiceGovernor_) nonZeroAddressAndContract(juiceGovernor_) { _protocolGovernor = IProtocolGovernor(juiceGovernor_); } modifier onlyLendYieldSender() { _protocolGovernor._validateRole(msg.sender, Roles.LEND_YIELD_SENDER, "LEND_YIELD_SENDER"); _; } function _getBlast() internal view returns (IBlast) { return IBlast(_protocolGovernor.getImmutableAddress(GovernorLib.BLAST)); } function _getBlastPoints() internal view returns (IBlastPoints) { return IBlastPoints(_protocolGovernor.getImmutableAddress(GovernorLib.BLAST_POINTS)); } }
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.24; import "../JuiceModule.sol"; /// @title BlastGas /// @notice Exposes a method to claim gas refunds from the contract and send them to the protocol. contract BlastGas { IProtocolGovernor private _protocolGovernor; event GasRefundClaimed(address indexed recipient, uint256 gasClaimed); constructor(address protocolGovernor_) { _protocolGovernor = IProtocolGovernor(protocolGovernor_); IBlast blast = IBlast(_protocolGovernor.getImmutableAddress(GovernorLib.BLAST)); blast.configureClaimableGas(); } /// @notice Claims the maximum possible gas from the contract with some recipient. /// @dev This is permissionless because funds will go to the protocol gasFeeWallet and the maximum possible gas will /// be claimed each time. /// @dev IBlast.claimMaxGas guarnatees a 100% claim rate, but not all pending gas fees will be claimed. /// @dev To check the current gas fee information of a contract, call IBlast.readGasParams(contractAddress). function claimMaxGas() external returns (uint256 gasClaimed) { IBlast blast = IBlast(_protocolGovernor.getImmutableAddress(GovernorLib.BLAST)); address _feeCollector = _protocolGovernor.getAddress(GovernorLib.FEE_COLLECTOR); gasClaimed = blast.claimMaxGas(address(this), _feeCollector); emit GasRefundClaimed(_feeCollector, gasClaimed); } }
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.24; import "../JuiceModule.sol"; /// @title BlastPoints /// @notice Configures a hot wallet that operates the points API for this contract. contract BlastPoints { IProtocolGovernor private _protocolGovernor; event PointsOperatorConfigured(address indexed operator); constructor(address protocolGovernor_, address pointsOperator_) { _protocolGovernor = IProtocolGovernor(protocolGovernor_); IBlastPoints blast = IBlastPoints(_protocolGovernor.getImmutableAddress(GovernorLib.BLAST_POINTS)); blast.configurePointsOperator(pointsOperator_); } }
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.24; import "forge-std/src/console2.sol"; // @notice Collections of protocol error messages. library Errors { // GENERAL /// @notice Unauthorized access error Unauthorized(); /// @notice Disabled functionality error FunctionalityDisabled(); /// @notice Functionality not supported error FunctionalityNotSupported(); /// @notice Invalid parameters passed to function error InvalidParams(); /// @notice ZeroAddress error ZeroAddress(); /// @notice Contract does not exist error ContractDoesNotExist(); /// @notice Invalid amount requested by caller error InvalidAmount(); /// @notice when parameter cannot be equal to zero error ParamCannotBeZero(); /// @notice ERC20 is not transferrable error TransferDisabled(); /// @notice Address doesn't have role error UnauthorizedRole(address account, string role); /// @notice Action disabled because contract is deprecated error Deprecated(); // ACCESS // NOTE: maybe this should be refactored into a generic Errors /// @notice Only the lending pool can call this function error OnlyLendingPool(); // COLLATERAL /// @notice Invalid collateral monitor update error InvalidCollateralMonitorUpdate(); error NoTellorValueRetrieved(uint256 timestamp); error StaleTellorValue(uint256 value, uint256 timestamp); error StaleTellorEVMCallTimestamp(uint256 callTimestamp); error CannotGoBackInTime(); error InvalidYieldClaimed(uint256 expectedYield, uint256 actualYield); // LENDING /// @notice Insufficient liquidity to fulfill action error InsufficientLiquidity(); /// @notice User doesn't have enough collateral backing their position error InsufficientCollateral(); /// @notice Requested borrow is not greater than minimum open borrow amount error InvalidMinimumOpenBorrow(); /// @notice Deposit cap exceeded error DepositCapExceeded(); /// @notice Max deposit per account exceeded error MaxDepositPerAccountExceeded(); // FLASH LOANS /// @notice Invalid flash loan balance error InvalidFlashLoanBalance(); /// @notice Invalid flash loan asset error InvalidFlashLoanAsset(); /// @notice Flash loan unpaid error InvalidPostFlashLoanBalance(); /// @notice Invalid flash loan fee error InsufficientFlashLoanFeeAmount(); /// @notice Flash loan recipient doesn't return success error InvalidFlashLoanRecipientReturn(); // ACCOUNTS /// @notice Account failed solvency check after some action. /// @dev The account's debt isn't sufficiently collateralized and/or the account is liquidatable. error AccountInsolvent(); /// @dev Account cannot be liquidated error AccountHealthy(); /// @notice Account is being liquidated error AccountBeingLiquidated(); /// @notice Account is not being liquidated error AccountNotBeingLiquidated(); /// @notice Account hasn't been created yet error AccountNotCreated(); // INVESTMENT /// @notice Account is not liquidatable error NotLiquidatable(); /// @notice Account is not repayable error NotRepayable(); /// @notice Account type invalid error InvalidAccountType(); /// @notice Interaction with a strategy that is not approved error StrategyNotApproved(); /// @notice Liquidator has no funds to repay error NoLiquidatorFunds(); /// @notice Requested profit is not claimable from account (if account has debt or not enough profit to fill request /// amount) error NotClaimableProfit(); /// @notice Used when Gelato automation task was already started error AlreadyStartedTask(); /// @notice Assets not received error WithdrawnAssetsNotReceived(); /////////////////////////// // Multi-step Strategies /////////////////////////// /// @notice Account is attempting to withdraw more strategy shares than their unlocked share balance. /// @dev An account's balanceOf(strategyShareToken) is their totalShareBalance. /// Since some strategies are multi-step, when a account withdraws, those shares are added to a separate variable /// known /// as their lockedShareBalance. /// A account's unlocked share balance when it comes to withdrawals is their totalShareBalance - lockedShareBalance. error PendingStrategyWithdrawal(address account); /// @notice Account cannot deposit into the same multi-step strategy until their previous deposit has cleared. error PendingStrategyDeposit(address account); ////////////////////////// /// OmegaGMXStrategyVault ////////////////////////// /// @notice When already exist a depositKey in the vault error MustNotHavePendingValue(); /// @notice When not sending eth to pay for the fee in a deposit or withdrawal error MustSendETHForExecutionFee(); /// Pyth error PythPriceFeedNotFound(address asset); error PythInvalidNonPositivePrice(address asset); } library BlastErrors { /// @dev For contracts that need to compound claimable yield onto themselves, they cannot claim with themselves as /// the recipient. /// To get around this, they claim to another contract that reflects the yield back to them. error InvalidReflection(uint256 expected, uint256 actual); }
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.24; /// @notice Store keys used by stores in a Governor contract (ProtocolGovernor, etc). library GovernorLib { /////////////// // COMMON /////////////// /// @notice Returns price of an asset given some address. Prices are denominated in the lending pool loan asset. bytes32 public constant PRICE_PROVIDER = keccak256(abi.encode("PRICE_PROVIDER")); /// @notice Address that receives fee generated by lending, accounts, and strategies bytes32 public constant FEE_COLLECTOR = keccak256(abi.encode("FEE_COLLECTOR")); bytes32 public constant STRATEGY_SLIPPAGE_MODEL = keccak256(abi.encode("STRATEGY_SLIPPAGE_MODEL")); /// @notice Address that is responsible for issuing gas reimbursements to protocol contracts bytes32 public constant GAS_TANK = keccak256(abi.encode("GAS_TANK")); /// @notice Lending Pool bytes32 public constant LENDING_POOL = keccak256(abi.encode("LENDING_POOL")); /// @notice Gelato Automate bytes32 public constant GELATO_AUTOMATE = keccak256(abi.encode("GELATO_AUTOMATE")); /// @notice Pyth Stable bytes32 public constant PYTH = keccak256(abi.encode("PYTH")); /// @notice Asset used to facilitate lending and borrowing. bytes32 public constant LEND_ASSET = keccak256(abi.encode("LEND_ASSET")); /// @notice Blast native contract implementing IBlast interface for configuring gas refunds and native ETH rebasing. bytes32 public constant BLAST = keccak256(abi.encode("BLAST")); /// @notice Blast native contract used on contract initialization to assign an operator that configures points /// received by that smart contract. bytes32 public constant BLAST_POINTS = keccak256(abi.encode("BLAST_POINTS")); /////////////// // FEES /////////////// bytes32 public constant LENDING_FEE = keccak256(abi.encode("LENDING_FEE")); bytes32 public constant FLASH_LOAN_FEE = keccak256(abi.encode("FLASH_LOAN_FEE")); /// @notice % taken from any funds used to repay debt during liquidating state. /* If an Account with 100 USDB Strategy position gets liquidated with protocolShare of 4%, liquidatorShare of 1%. If no slippage, 100 USDB is received by Repayment contract. Repayment contract is executed with: - 4 USDB going to protocol - 1 USDB going to liquidator - 95 USDB going to repay Account debt */ bytes32 public constant PROTOCOL_LIQUIDATION_SHARE = keccak256(abi.encode("PROTOCOL_LIQUIDATION_SHARE")); bytes32 public constant LIQUIDATOR_SHARE = keccak256(abi.encode("LIQUIDATOR_SHARE")); }
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.24; import "./Errors.sol"; import "../interfaces/IProtocolGovernor.sol"; /// @notice List of permissions that can be granted to addresses. library Roles { /// @notice Can call the `sendYield` function on the JuiceLendingPool to redirect yield back to senders. bytes32 public constant LEND_YIELD_SENDER = keccak256(abi.encode("LEND_YIELD_SENDER")); /// @notice Gas tank depositor bytes32 public constant GAS_TANK_DEPOSITOR = keccak256(abi.encode("GAS_TANK_DEPOSITOR")); function _validateRole( IProtocolGovernor governor, address account, bytes32 role, string memory roleName ) internal view { if (!governor.hasRole(role, account)) { revert Errors.UnauthorizedRole(account, roleName); } } }
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.24; import { UD60x18, ud } from "@prb/math/src/UD60x18.sol"; library AccountLib { /// @notice The type of account that can be created enum Type { EXTERNAL, // Accounts that allow taking funds out of the protocol INTERNAL // Accounts that require funds remain in the protocol } /// @notice The health of the account /// The collateral and equity values are all denominated in the debt amount. struct Health { uint256 debtAmount; uint256 collateralValue; uint256 investmentValue; bool isLiquidatable; bool hasBadDebt; } /// @notice Expected values resulting from a collateral liquidation. /// @param actualDebtToLiquidate the amount of debt to cover for the account /// @param collateralAmount the amount of collateral to receive /// @param bonusCollateral the amount of bonus collateral included in the collateralAmount struct CollateralLiquidation { uint256 actualDebtToLiquidate; uint256 collateralAmount; uint256 bonusCollateral; } /// @notice The state of an account's lending pool loan struct Loan { /// @notice The amount of debt the borrower has uint256 debtAmount; /// @notice The value of the borrowers collateral in debt token uint256 collateralValue; /// @notice The current loan to value ratio of the borrower UD60x18 ltv; /// @notice Borrower cannot perform a borrow if it puts their ltv over this amount UD60x18 maxLtv; } struct LiquidationStatus { bool isLiquidating; uint256 liquidationStartTime; } /* @notice Liquidator fee. @dev protocolShare + liquidatorShare = liquidationFee. liquidationFee is % deducted from liquidated funds before they are used towards repayment. */ struct LiquidationFee { UD60x18 protocolShare; UD60x18 liquidatorShare; } /// @notice struct CreateAccountProps { address owner; AccountLib.Type accountType; } /// @notice Custom meta txn for creating an account struct CreateAccountData { address owner; uint256 accountType; bytes signature; } /// @notice Data to sign when creating an account gaslessly struct CreateAccount { address owner; uint256 accountType; } }
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.24; import "../Errors.sol"; /// @title Address checker trait /// @notice Introduces methods and modifiers for checking addresses abstract contract AddressCheckerTrait { /// @dev Prevents a contract using an address if it is a zero address modifier nonZeroAddress(address _address) { if (_address == address(0)) { revert Errors.ZeroAddress(); } _; } /// @dev Prevents a contract using an address if it is either a zero address or is not an existing contract modifier nonZeroAddressAndContract(address _address) { if (_address == address(0)) { revert Errors.ZeroAddress(); } if (!_contractExists(_address)) { revert Errors.ContractDoesNotExist(); } _; } /// @notice Returns true if addr is a contract address /// @param addr The address to check function _contractExists(address addr) internal view returns (bool) { return addr.code.length > 0; } }
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.24; import { Address } from "@openzeppelin/contracts/utils/Address.sol"; import { Clones } from "@openzeppelin/contracts/proxy/Clones.sol"; import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import { ProtocolModule, ProtocolGovernor } from "../system/ProtocolModule.sol"; import { EnumerableSet } from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import { ERC2771Forwarder } from "@openzeppelin/contracts/metatx/ERC2771Forwarder.sol"; import { ILendingPool } from "../interfaces/ILendingPool.sol"; import { SafeERC20, IERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import { UD60x18, ud, UNIT, ZERO } from "@prb/math/src/UD60x18.sol"; import { BaseAccount } from "../accounts/BaseAccount.sol"; import { IAccount } from "../interfaces/IAccount.sol"; import { IAssetPriceOracle } from "../interfaces/IAssetPriceOracle.sol"; import { InternalAccount } from "../accounts/InternalAccount.sol"; import { ExternalAccount } from "../accounts/ExternalAccount.sol"; import "../interfaces/IStrategyVault.sol"; import "../interfaces/IAccountManager.sol"; import "../interfaces/IInternalAccount.sol"; import "../interfaces/IAssetPriceProvider.sol"; import "../interfaces/ILiquidationReceiver.sol"; import "../libraries/accounts/AccountLib.sol"; import "../libraries/Errors.sol"; /// @title Account Factory Events /// @dev Place all events used by the AccountManager contract here abstract contract AccountManagerEvents { /// @notice Additional fees charged to an account (in addition to their lending pool debt). event FeesCharged(address indexed account, uint256 amount); /// @notice Account liquidation started event AccountLiquidationStarted(address indexed account); /// @notice Account liquidation completed event AccountLiquidationCompleted(address indexed account); /// @notice A user has borrowed. event AccountBorrowed(address indexed owner, address indexed account, uint256 amount); /// @notice A user has repaid. event AccountRepaid(address indexed owner, address indexed account, uint256 amount); event LiquidationFeesTaken( address indexed feeCollector, address indexed liquidator, uint256 protocolShare, uint256 liquidatorShare ); /// @dev LiquidationReceiver is created per (account, liquidationFeeTo). event LiquidationReceiverCreated( address indexed account, address indexed liquidationFeeTo, address liquidationReceiver ); /// @notice User claimed assets from their account. event AccountClaimed(address indexed owner, address indexed account, uint256 amount); } /// @title AccountManager /// @notice The AccountManager contract deploys Account contracts. /// Investment Accounts are only createable by the owner of this contract or /// accounts approved by the admin (known as account creators). abstract contract AccountManager is IAccountManager, AccountManagerEvents, ProtocolModule, ReentrancyGuard { using EnumerableSet for EnumerableSet.AddressSet; using SafeERC20 for IERC20; using Address for address; /// @notice The LendingPool contract address for Investment Accounts to use ILendingPool internal immutable _lendingPool; IERC20 internal immutable _lendAsset; /// @notice An mapping of all Account contracts that have been created mapping(address => bool) public isCreatedAccount; /// @notice Account to their owner. mapping(address => address) internal _accountOwnerCache; mapping(address => uint256) internal _accountLiquidationStartTime; mapping(address => mapping(address => ILiquidationReceiver)) public liquidationReceiver; mapping(address => bool) internal _isLiquidationReceiver; /// @notice Counter to keep track of the number of Account contracts that have been created uint256 public accountCount; // Account configurations /////////////////////////// address immutable liquidationReceiverImpl; modifier onlyAccount() { if (!isCreatedAccount[msg.sender]) { revert Errors.Unauthorized(); } _; } modifier onlyAccountOwner(address account) { if (!isCreatedAccount[account]) { revert Errors.AccountNotCreated(); } if (msg.sender != _accountOwnerCache[account]) { revert Errors.Unauthorized(); } _; } /// @notice Constructs the factory constructor( address protocolGovernor_, address liquidationReceiverImpl_ ) ProtocolModule(protocolGovernor_) nonZeroAddressAndContract(address(_getPriceProvider())) nonZeroAddressAndContract(_getLendingPool()) { liquidationReceiverImpl = liquidationReceiverImpl_; _lendingPool = ILendingPool(_getLendingPool()); _lendAsset = IERC20(_getLendAsset()); } ////////////////////////// // Account Administration ////////////////////////// function isLiquidationReceiver(address receiver) external view returns (bool) { return _isLiquidationReceiver[receiver]; } /// @notice Lets the admin pause the account /// @dev We cannot pause an account that isn't solvent because a pause will disable it from being liquidated. function pauseAccount(address account) external onlyOwner { _requireSolvent(account); IAccount(account).pause(); } /// @notice Lets the admin unpause the account function unpauseAccount(address account) external onlyOwner { IAccount(account).unpause(); } ///////////////////////////// // Account Functionality ///////////////////////////// function borrow(uint256 amount) external virtual onlyAccount nonReentrant returns (uint256 borrowed) { borrowed = _borrow(msg.sender, amount); } function _borrow(address caller, uint256 amount) internal returns (uint256 borrowed) { borrowed = _lendingPool.borrow(amount, caller); _requireSolvent(caller); emit AccountBorrowed(_accountOwnerCache[caller], caller, borrowed); this._afterBorrow(caller, borrowed); } function repay(address account, uint256 amount) external virtual nonReentrant returns (uint256 repaid) { // Debt repaid is onBehalfOf, funds are transferred from `from`. repaid = _lendingPool.repay(amount, account, msg.sender); emit AccountRepaid(_accountOwnerCache[account], account, repaid); this._afterRepay(account, repaid); } /// @notice Called by Account when its Owner wants to withdraw excess funds. /// @param amount The amount to withdraw /// @param recipient The address to send the assets to function claim(uint256 amount, address recipient) external nonZeroAddress(recipient) onlyAccount nonReentrant { if (_accountLiquidationStartTime[msg.sender] > 0) { revert Errors.AccountBeingLiquidated(); } if (getDebtAmount(address(msg.sender)) != 0 || _lendAsset.balanceOf(address(msg.sender)) < amount) { revert Errors.NotClaimableProfit(); } _lendAsset.safeTransferFrom(msg.sender, recipient, amount); emit AccountClaimed(_accountOwnerCache[msg.sender], msg.sender, amount); } /// @notice Mark an account as liquidatable. function liquidate( address account, address liquidationFeeTo ) external returns (ILiquidationReceiver liquidationReceiver_) { return _startLiquidation(account, liquidationFeeTo); } function emitLiquidationFeeEvent( address feeCollector_, address liquidationFeeTo, uint256 protocolShare, uint256 liquidatorShare ) external { if (!_isLiquidationReceiver[msg.sender]) revert Errors.Unauthorized(); emit LiquidationFeesTaken(feeCollector_, liquidationFeeTo, protocolShare, liquidatorShare); } /// @dev Starts the liquidation process on an Account if it is liquidatable. function _startLiquidation( address account, address liquidationFeeTo ) internal returns (ILiquidationReceiver liquidationReceiver_) { AccountLib.Health memory health = getAccountHealth(account); if (!health.isLiquidatable) revert Errors.AccountHealthy(); liquidationReceiver_ = liquidationReceiver[account][liquidationFeeTo]; // Create the liquidator receiver. if (address(liquidationReceiver_) == address(0)) { liquidationReceiver_ = ILiquidationReceiver( Clones.cloneDeterministic(liquidationReceiverImpl, keccak256(abi.encode(account, liquidationFeeTo))) ); liquidationReceiver_.initialize( ILiquidationReceiver.Props({ account: IAccount(account), manager: IAccountManager(address(this)), liquidationFeeTo: liquidationFeeTo, asset: _lendAsset }) ); liquidationReceiver[account][liquidationFeeTo] = liquidationReceiver_; _isLiquidationReceiver[address(liquidationReceiver_)] = true; emit LiquidationReceiverCreated(account, liquidationFeeTo, address(liquidationReceiver_)); } // Account has idle borrowed funds, transfer them to the liquidator receiver. if (_lendAsset.balanceOf(address(account)) > 0) { _lendAsset.safeTransferFrom( address(account), address(liquidationReceiver_), _lendAsset.balanceOf(address(account)) ); } // Mark account as liquidatable if it isn't already. if (_accountLiquidationStartTime[account] == 0) { _accountLiquidationStartTime[account] = block.timestamp; emit AccountLiquidationStarted(account); this._afterLiquidationStarted(account); } } function _completeLiquidation(address account) external onlySelf { delete _accountLiquidationStartTime[account]; emit AccountLiquidationCompleted(account); this._afterLiquidationCompleted(account); } ///////////////////////// // Account Views ///////////////////////// function lendingPool() external view returns (address) { return address(_lendingPool); } function getLiquidationReceiver( address account, address liquidationFeeTo ) external view returns (ILiquidationReceiver) { return ILiquidationReceiver( Clones.predictDeterministicAddress( liquidationReceiverImpl, keccak256(abi.encode(account, liquidationFeeTo)) ) ); } function getFeeCollector() external view returns (address) { return _getFeeCollector(); } function getLendAsset() external view returns (IERC20) { return _lendingPool.getAsset(); } function getAccountLiquidationStatus(address account) external view returns (AccountLib.LiquidationStatus memory) { return AccountLib.LiquidationStatus({ isLiquidating: _accountLiquidationStartTime[account] > 0, liquidationStartTime: _accountLiquidationStartTime[account] }); } function getLiquidationFee() external view returns (AccountLib.LiquidationFee memory fee) { fee.protocolShare = _protocolLiquidationShare(); fee.liquidatorShare = _liquidatorShare(); } function getDebtAmount(address account) public view virtual returns (uint256) { return _lendingPool.getDebtAmount(account); } function getAccountLoan(address account) public view returns (AccountLib.Loan memory) { uint256 collateralValue = getTotalCollateralValue(account); uint256 debt = getDebtAmount(account); UD60x18 ltv = ZERO; if (collateralValue > 0) { ltv = ud(debt).div(ud(collateralValue)); } return AccountLib.Loan({ debtAmount: debt, collateralValue: collateralValue, ltv: ltv, maxLtv: _getAccountMaxLtv(account) }); } function getAccountHealth(address) public view virtual returns (AccountLib.Health memory health); /// @dev Total value of investments sitting in the Account. function getTotalAccountValue(address account) public view virtual returns (uint256 totalValue); /// @dev Total value of collateral attributed to the Account. function getTotalCollateralValue(address account) public view virtual returns (uint256 totalValue) { } /// @notice Used to ensure the account has performed an operation that doesn't put their loan into an insolvent /// state. function _requireSolvent(address account) internal view { // Actions depending on solvency cannot be performed during liquidation state. if (_accountLiquidationStartTime[account] > 0) { revert Errors.AccountBeingLiquidated(); } AccountLib.Health memory health = getAccountHealth(account); uint256 borrowLimit = ud(health.collateralValue).mul(_getAccountMaxLtv(account)).unwrap(); // Check if borrowed debt is fully collateralized based off max ltv. if (health.debtAmount > borrowLimit) { revert Errors.AccountInsolvent(); } // If debt is considered fully collateralized, check if the account can be liquidatable. if (health.isLiquidatable) { revert Errors.AccountInsolvent(); } } /////////////////// // HOOKS /////////////////// function _afterRepay(address account, uint256) external virtual onlySelf { AccountLib.Health memory health = getAccountHealth(account); if (_accountLiquidationStartTime[account] > 0 && !health.isLiquidatable) { this._completeLiquidation(account); } } function _afterBorrow(address account, uint256 borrowed) external virtual onlySelf { } function _afterLiquidationStarted(address account) external virtual onlySelf { } function _afterLiquidationCompleted(address account) external virtual onlySelf { } ////////////////// // INTERNAL ////////////////// function _getAccountMaxLtv(address account) internal view virtual returns (UD60x18); /// @notice Hashes an address with this contract's address /// @param addr The address to convert function _salt(address addr) internal view virtual returns (bytes32) { return keccak256(abi.encodePacked(addr, address(this))); } }
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.24; import "./AccountManager.sol"; import "solady/src/utils/FixedPointMathLib.sol"; /// @title Account Factory Events /// @dev Place all events used by the AccountManager contract here abstract contract StrategyAccountManagerEvents { /// @notice The owner has made their first deposit into `strategy` event StrategyActivated(address indexed owner, address indexed account, address indexed strategy); /// @notice The owner has withdrawn their last deposit from `strategy` event StrategyDeactivated(address indexed owner, address indexed account, address indexed strategy); /// @notice The admin has approved the account to use `strategy` event StrategyUpdated(address strategy, bool approval); /// @notice A user has deployed funds into a strategy. event StrategyDeposit(address indexed owner, address indexed strategy, address indexed account, uint256 amount); /// @notice A user has withdrawn funds from a strategy. event StrategyWithdrawal(address indexed owner, address indexed strategy, address indexed account, uint256 amount); /// @notice The slippage tolerated for withdraws from strategies has been updated to `tolerance` event MaximumSlippageToleranceUpdated(UD60x18 tolerance); } /// @title AccountManager /// @notice The AccountManager contract deploys Account contracts. /// Investment Accounts are only createable by the owner of this contract or /// accounts approved by the admin (known as account creators). abstract contract StrategyAccountManager is AccountManager, StrategyAccountManagerEvents { using EnumerableSet for EnumerableSet.AddressSet; using SafeERC20 for IERC20; using Address for address; /// @notice The strategies that are approved to use for permissioned accounts mapping(address => bool) public approvedStrategies; /// @notice Map of accounts to their active strategies mapping(address => EnumerableSet.AddressSet) internal _activeStrategies; /// @notice Constructs the factory constructor( address protocolGovernor_, address liquidationReceiverImpl_ ) AccountManager(protocolGovernor_, liquidationReceiverImpl_) { require(address(_getSlippageModel()) != address(0), "StrategyAccountManager: slippage model is zero address"); } /// @notice Get an active strategy's address by index /// @param index The index of the active strategy function getActiveStrategy(address account, uint256 index) external view returns (address) { return _activeStrategies[account].at(index); } /// @notice Get the number of active strategies function getActiveStrategyCount(address account) external view returns (uint256) { return _activeStrategies[account].length(); } /// @dev This is called by the Account to check if the strategy is approved. /// @dev Mainly to consolidate events into the Manager though. function strategyDeposit( address owner, address strategy, uint256 amount, bytes memory data ) external payable virtual onlyAccount nonReentrant returns (uint256 shares) { shares = _strategyDeposit(msg.sender, owner, strategy, amount, data); } function _strategyDeposit( address caller, address owner, address strategy, uint256 amount, bytes memory data ) internal returns (uint256 shares) { if (!approvedStrategies[strategy]) { revert Errors.StrategyNotApproved(); } if (_activeStrategies[caller].add(strategy)) { emit StrategyActivated(owner, caller, strategy); } shares = IStrategyVault(strategy).deposit{ value: msg.value }(amount, data, caller); emit StrategyDeposit(owner, strategy, caller, amount); _requireSolvent(caller); } function strategyWithdrawal( address owner, address strategy, uint256 assets ) external virtual onlyAccount nonReentrant { _strategyWithdrawal(msg.sender, owner, strategy, assets); } function _strategyWithdrawal(address caller, address owner, address strategy, uint256 assets) internal { emit StrategyWithdrawal(owner, strategy, caller, assets); // Deactivate the strategy if it has no more funds // Strategy balanceOf will not return less than 0 // slither-disable-next-line incorrect-equality if (strategy != address(0) && IStrategyVault(strategy).getPositionValue(caller) == 0) { // slither-disable-next-line unused-return _activeStrategies[caller].remove(strategy); emit StrategyDeactivated(owner, caller, strategy); } _requireSolvent(caller); } /// @dev LiquidationReceiver is the recipient of the liquidated funds. /// In case of multi transaction withdrawal strategies, liquidator must wait for liquidationReceiver to receive /// funds before /// calling liquidationReceiver.repay(). function liquidateStrategy( address account, address liquidationFeeTo, address strategy, bytes memory data ) external payable virtual returns (ILiquidationReceiver liquidationReceiver_) { liquidationReceiver_ = _startLiquidation(account, liquidationFeeTo); // Prepare arguments. // Manager calculates minimumAmount based off how long account has been in liquidation. // Some strategies might disregard this value. uint256 minAmountAfterSlippage = 0; if (strategy != address(0)) { uint256 minAmount = IStrategyVault(strategy).previewWithdraw(IERC20(strategy).balanceOf(address(account))); minAmountAfterSlippage = minAmount - ((ud(minAmount) * getAccountLiquidationSlippageTolerance(account)).unwrap()); } IInternalAccount(account).liquidateStrategy{ value: msg.value }( strategy, address(liquidationReceiver_), minAmountAfterSlippage, data ); // Deactivate the strategy if it has no more funds // Strategy balanceOf will not return less than 0 // slither-disable-next-line incorrect-equality if (strategy != address(0) && IStrategyVault(strategy).getPositionValue(account) == 0) { // slither-disable-next-line unused-return _activeStrategies[account].remove(strategy); emit StrategyDeactivated(_accountOwnerCache[account], account, strategy); } } /// @notice Get the value of all strategies investments /// @return totalValue The value of all strategy investments in lendAsset function getTotalAccountValue(address account) public view override returns (uint256 totalValue) { totalValue = _lendAsset.balanceOf(address(account)); // Sum the value of all active strategy vaults // Note: This needs attention as getPositionValue may revert, it contains external calls // slither-disable-next-line calls-loop for (uint256 i = 0; i < _activeStrategies[account].length(); i++) { // Note: This needs attention as getPositionValue may revert, it contains external calls // slither-disable-next-line calls-loop totalValue += IStrategyVault(_activeStrategies[account].at(i)).getPositionValue(account); } } function getAccountLiquidationSlippageTolerance(address account) public view returns (UD60x18) { uint256 timeSinceLiquidationStarted = FixedPointMathLib.zeroFloorSub(block.timestamp, _accountLiquidationStartTime[account]); return _getSlippageModel().calculateSlippage(timeSinceLiquidationStarted); } function updateStrategyApproval(address strategy, bool approval) external onlyOwner { approvedStrategies[strategy] = approval; emit StrategyUpdated(strategy, approval); } function isApprovedStrategy(address strategy) external view returns (bool) { return approvedStrategies[strategy]; } }
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.24; import "@pythnetwork/pyth-sdk-solidity/IPyth.sol"; import "../interfaces/IProtocolGovernor.sol"; import "../libraries/GovernorLib.sol"; import "../libraries/Errors.sol"; /// @title Pyth /// @dev Adds a method to the contract that allows bundling of Pyth price updates. contract PythPusher { IPyth immutable pyth; constructor(address protocolGovernor_) { pyth = IPyth(IProtocolGovernor(protocolGovernor_).getImmutableAddress(GovernorLib.PYTH)); } function updatePythPriceFeeds(bytes[] memory updateData) public payable { if (updateData.length > 0) { uint256 fee = pyth.getUpdateFee(updateData); pyth.updatePriceFeeds{ value: fee }(updateData); } } }
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.24; import { UD60x18, ud, UNIT, ZERO } from "@prb/math/src/UD60x18.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts/access/Ownable2Step.sol"; import "../libraries/Errors.sol"; import "../libraries/traits/AddressCheckerTrait.sol"; import "../libraries/GovernorLib.sol"; import "../interfaces/IProtocolGovernor.sol"; import "../libraries/Roles.sol"; abstract contract ProtocolGovernorEvents { event FeeUpdated(bytes32 indexed id, UD60x18 newLiquidationFee); event AddressSet(bytes32 indexed id, address newAddress); event ImmutableAddressSet(bytes32 indexed id, address newAddress); event ManagerStatusUpdated(address indexed manager, bool status); event InvestmentAccountRegistered(address indexed account); event InvestmentAccountCreditIncreased(address indexed account, uint256 amount); event InvestmentAccountCreditDecreased(address indexed account, uint256 amount); event RoleSet(bytes32 indexed role, address indexed account, bool status); } /** * @title ProtocolGovernor * @dev Allows for storing and management of common protocol data (roles, addresses, configuration). */ contract ProtocolGovernor is Ownable2Step, AddressCheckerTrait, ProtocolGovernorEvents, IProtocolGovernor { /// @notice Map of contract names to their contract addresses. mapping(bytes32 => address) internal _addresses; /// @notice Immutable map of contract names to their contract addresses. mapping(bytes32 => address) internal _immutableAddresses; /// @notice Map of fee IDs to their fees. /// @dev Fees cannot be greater than or equal to 100%. mapping(bytes32 => UD60x18) internal _fees; /// @notice Managers that can register accounts. mapping(address => bool) internal _managers; /// @notice Tracking roles granted to addresses. mapping(address => mapping(bytes32 => bool)) internal _roles; /// @notice If true, the protocol is deprecated and no longer accepting inflows (lending pool deposit, borrow, /// strategy deposit should be disabled). bool private _isProtocolDeprecated; /// @dev Parameters for initializing the Protocol Governor struct InitParams { address lendAsset; // Address of the asset address feeCollector; address pyth; } constructor(InitParams memory params) Ownable(msg.sender) nonZeroAddress(params.feeCollector) nonZeroAddressAndContract(params.lendAsset) nonZeroAddressAndContract(params.pyth) { _setImmutableAddress(GovernorLib.LEND_ASSET, params.lendAsset); _setImmutableAddress(GovernorLib.PYTH, params.pyth); _setAddress(GovernorLib.FEE_COLLECTOR, params.feeCollector); _fees[GovernorLib.LENDING_FEE] = ud(0.1e18); _fees[GovernorLib.PROTOCOL_LIQUIDATION_SHARE] = ud(0.05e18); _fees[GovernorLib.LIQUIDATOR_SHARE] = ZERO; _fees[GovernorLib.FLASH_LOAN_FEE] = ud(0); } /** * @dev Only allows addresses that are the protocol admin to call the function. */ modifier onlyProtocolOwner() { if (owner() != _msgSender()) { revert Errors.UnauthorizedRole(_msgSender(), "PROTOCOL_ADMIN"); } _; } modifier onlyManager() { if (!_managers[_msgSender()]) { revert Errors.UnauthorizedRole(_msgSender(), "ACCOUNT_MANAGER"); } _; } function getOwner() external view returns (address) { return Ownable.owner(); } function setProtocolDeprecatedStatus(bool status) external onlyProtocolOwner { _isProtocolDeprecated = status; } function isProtocolDeprecated() external view returns (bool) { return _isProtocolDeprecated; } //////////////////// // ADDRESS PROVIDER ////////////////////// /// @dev Sets an address by id function setAddress(bytes32 id, address addr) public onlyProtocolOwner { _setAddress(id, addr); } function _setAddress(bytes32 id, address addr) internal nonZeroAddress(addr) { _addresses[id] = addr; emit AddressSet(id, addr); } // @dev Initialize an address by id, this cannot be changed after being set. function setImmutableAddress(bytes32 id, address addr) public onlyProtocolOwner { _setImmutableAddress(id, addr); } function _setImmutableAddress(bytes32 id, address addr) internal nonZeroAddress(addr) { if (_immutableAddresses[id] != address(0)) { revert Errors.InvalidParams(); } _immutableAddresses[id] = addr; emit ImmutableAddressSet(id, addr); } /// @dev Returns an address by id function getAddress(bytes32 id) external view returns (address) { return _addresses[id]; } /// @dev Returns an immutable address by id function getImmutableAddress(bytes32 id) external view returns (address) { return _immutableAddresses[id]; } /////////////////////// // FEE CONFIGURATION /////////////////////// /// @notice newFee cannot be 100% (it must be < 1e18) function setFee(bytes32 id, UD60x18 newFee) external onlyProtocolOwner { if (newFee >= UNIT) { revert Errors.InvalidParams(); } _fees[id] = newFee; emit FeeUpdated(id, newFee); } function getFee(bytes32 id) external view returns (UD60x18) { return _fees[id]; } ///////////////////// // Protocol wide ACL ///////////////////// function grantRole(bytes32 role, address account) external onlyProtocolOwner { _roles[account][role] = true; emit RoleSet(role, account, true); } function revokeRole(bytes32 role, address account) external onlyProtocolOwner { _roles[account][role] = false; emit RoleSet(role, account, false); } function hasRole(bytes32 role, address account) external view returns (bool) { return _roles[account][role]; } function updateAccountManagerStatus(address manager, bool status) external onlyProtocolOwner { _managers[manager] = status; emit ManagerStatusUpdated(manager, status); } function isAccountManager(address manager) external view returns (bool) { return _managers[manager]; } }
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.24; import "./ProtocolGovernor.sol"; import { Context } from "@openzeppelin/contracts/utils/Context.sol"; import "@pythnetwork/pyth-sdk-solidity/IPyth.sol"; import { Errors } from "../libraries/Errors.sol"; import "../libraries/traits/AddressCheckerTrait.sol"; import { UD60x18, ud } from "@prb/math/src/UD60x18.sol"; import "../interfaces/IGasTank.sol"; import "../interfaces/IAssetPriceProvider.sol"; import "../interfaces/IProtocolGovernor.sol"; import "../interfaces/IStrategySlippageModel.sol"; import "../libraries/GovernorLib.sol"; import "../libraries/Roles.sol"; /** * @title ProtocolModule * @dev Contract for shared protocol functionality */ abstract contract ProtocolModule is Context, AddressCheckerTrait { using Roles for IProtocolGovernor; IProtocolGovernor internal immutable _protocolGovernor; /** * @dev Constructor that initializes the role store for this contract. * @param protocolGovernor_ The contract instance to use as the role store. */ constructor(address protocolGovernor_) { _protocolGovernor = IProtocolGovernor(protocolGovernor_); } ///////////////// /// PERMISSIONS ///////////////// modifier whenProtocolNotDeprecated() { require(!_protocolGovernor.isProtocolDeprecated(), "PROTOCOL_DEPRECATED"); _; } /** * @dev Only allows the contract's own address to call the function. */ modifier onlySelf() { if (msg.sender != address(this)) { revert Errors.UnauthorizedRole(msg.sender, "SELF"); } _; } modifier onlyAccountManager() { if (!_protocolGovernor.isAccountManager(_msgSender())) { revert Errors.UnauthorizedRole(_msgSender(), "ACCOUNT_MANAGER"); } _; } modifier onlyGasTankDepositor() { _protocolGovernor._validateRole(msg.sender, Roles.GAS_TANK_DEPOSITOR, "GAS_TANK_DEPOSITOR"); _; } /** * @dev Only allows addresses that are the protocol admin to call the function. */ modifier onlyOwner() { if (!_isOwner(_msgSender())) { revert Errors.UnauthorizedRole(_msgSender(), "PROTOCOL_ADMIN"); } _; } function _isOwner(address account) internal view returns (bool) { if (_protocolGovernor.getOwner() != account) { return false; } return true; } ///////////////////// // ADDRESS PROVIDER ///////////////////// function getProtocolGovernor() external view virtual returns (address) { return address(_protocolGovernor); } /// @notice Returns fee collector function _getFeeCollector() internal view returns (address) { return _protocolGovernor.getAddress(GovernorLib.FEE_COLLECTOR); } /// @notice Returns asset price provider address. /// @dev This price provider MUST return the asset prices denominated in lend asset. /// @dev If lend asset is USDC, asset prices must be in USDC. function _getPriceProvider() internal view returns (IAssetPriceProvider) { return IAssetPriceProvider(_protocolGovernor.getAddress(GovernorLib.PRICE_PROVIDER)); } /// @notice Gas Tank function _getGasTank() internal view returns (IGasTank) { return IGasTank(_protocolGovernor.getAddress(GovernorLib.GAS_TANK)); } function _getPyth() internal view returns (IPyth) { return IPyth(_protocolGovernor.getImmutableAddress(GovernorLib.PYTH)); } function _getLendAsset() internal view returns (address) { return _protocolGovernor.getImmutableAddress(GovernorLib.LEND_ASSET); } function _getLendingPool() internal view returns (address) { return _protocolGovernor.getImmutableAddress(GovernorLib.LENDING_POOL); } function _getSlippageModel() internal view returns (IStrategySlippageModel) { return IStrategySlippageModel(_protocolGovernor.getAddress(GovernorLib.STRATEGY_SLIPPAGE_MODEL)); } // FEE CONFIGURATION ////////////////////// function _lendingFee() internal view returns (UD60x18) { return _protocolGovernor.getFee(GovernorLib.LENDING_FEE); } function _flashLoanFee() internal view returns (UD60x18) { return _protocolGovernor.getFee(GovernorLib.FLASH_LOAN_FEE); } function _protocolLiquidationShare() internal view returns (UD60x18) { return _protocolGovernor.getFee(GovernorLib.PROTOCOL_LIQUIDATION_SHARE); } function _liquidatorShare() internal view returns (UD60x18) { return _protocolGovernor.getFee(GovernorLib.LIQUIDATOR_SHARE); } }
// SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.9.0; /// @dev The original console.sol uses `int` and `uint` for computing function selectors, but it should /// use `int256` and `uint256`. This modified version fixes that. This version is recommended /// over `console.sol` if you don't need compatibility with Hardhat as the logs will show up in /// forge stack traces. If you do need compatibility with Hardhat, you must use `console.sol`. /// Reference: https://github.com/NomicFoundation/hardhat/issues/2178 library console2 { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _castLogPayloadViewToPure( function(bytes memory) internal view fnIn ) internal pure returns (function(bytes memory) internal pure fnOut) { assembly { fnOut := fnIn } } function _sendLogPayload(bytes memory payload) internal pure { _castLogPayloadViewToPure(_sendLogPayloadView)(payload); } function _sendLogPayloadView(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; /// @solidity memory-safe-assembly assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal pure { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int256 p0) internal pure { _sendLogPayload(abi.encodeWithSignature("log(int256)", p0)); } function logUint(uint256 p0) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256)", p0)); } function logString(string memory p0) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint256 p0) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256)", p0)); } function log(int256 p0) internal pure { _sendLogPayload(abi.encodeWithSignature("log(int256)", p0)); } function log(string memory p0) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint256 p0, uint256 p1) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256)", p0, p1)); } function log(uint256 p0, string memory p1) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,string)", p0, p1)); } function log(uint256 p0, bool p1) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,bool)", p0, p1)); } function log(uint256 p0, address p1) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,address)", p0, p1)); } function log(string memory p0, uint256 p1) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,uint256)", p0, p1)); } function log(string memory p0, int256 p1) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,int256)", p0, p1)); } function log(string memory p0, string memory p1) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint256 p1) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,uint256)", p0, p1)); } function log(bool p0, string memory p1) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint256 p1) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,uint256)", p0, p1)); } function log(address p0, string memory p1) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint256 p0, uint256 p1, uint256 p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,uint256)", p0, p1, p2)); } function log(uint256 p0, uint256 p1, string memory p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,string)", p0, p1, p2)); } function log(uint256 p0, uint256 p1, bool p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,bool)", p0, p1, p2)); } function log(uint256 p0, uint256 p1, address p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,address)", p0, p1, p2)); } function log(uint256 p0, string memory p1, uint256 p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,string,uint256)", p0, p1, p2)); } function log(uint256 p0, string memory p1, string memory p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,string,string)", p0, p1, p2)); } function log(uint256 p0, string memory p1, bool p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,string,bool)", p0, p1, p2)); } function log(uint256 p0, string memory p1, address p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,string,address)", p0, p1, p2)); } function log(uint256 p0, bool p1, uint256 p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,uint256)", p0, p1, p2)); } function log(uint256 p0, bool p1, string memory p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,string)", p0, p1, p2)); } function log(uint256 p0, bool p1, bool p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,bool)", p0, p1, p2)); } function log(uint256 p0, bool p1, address p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,address)", p0, p1, p2)); } function log(uint256 p0, address p1, uint256 p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,address,uint256)", p0, p1, p2)); } function log(uint256 p0, address p1, string memory p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,address,string)", p0, p1, p2)); } function log(uint256 p0, address p1, bool p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,address,bool)", p0, p1, p2)); } function log(uint256 p0, address p1, address p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,address,address)", p0, p1, p2)); } function log(string memory p0, uint256 p1, uint256 p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,uint256,uint256)", p0, p1, p2)); } function log(string memory p0, uint256 p1, string memory p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,uint256,string)", p0, p1, p2)); } function log(string memory p0, uint256 p1, bool p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,uint256,bool)", p0, p1, p2)); } function log(string memory p0, uint256 p1, address p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,uint256,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint256 p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint256)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint256 p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint256)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint256 p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint256)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint256 p1, uint256 p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,uint256)", p0, p1, p2)); } function log(bool p0, uint256 p1, string memory p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,string)", p0, p1, p2)); } function log(bool p0, uint256 p1, bool p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,bool)", p0, p1, p2)); } function log(bool p0, uint256 p1, address p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint256 p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint256)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint256 p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint256)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint256 p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint256)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint256 p1, uint256 p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,uint256,uint256)", p0, p1, p2)); } function log(address p0, uint256 p1, string memory p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,uint256,string)", p0, p1, p2)); } function log(address p0, uint256 p1, bool p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,uint256,bool)", p0, p1, p2)); } function log(address p0, uint256 p1, address p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,uint256,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint256 p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint256)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint256 p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint256)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint256 p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint256)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint256 p0, uint256 p1, uint256 p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,uint256,uint256)", p0, p1, p2, p3)); } function log(uint256 p0, uint256 p1, uint256 p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,uint256,string)", p0, p1, p2, p3)); } function log(uint256 p0, uint256 p1, uint256 p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,uint256,bool)", p0, p1, p2, p3)); } function log(uint256 p0, uint256 p1, uint256 p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,uint256,address)", p0, p1, p2, p3)); } function log(uint256 p0, uint256 p1, string memory p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,string,uint256)", p0, p1, p2, p3)); } function log(uint256 p0, uint256 p1, string memory p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,string,string)", p0, p1, p2, p3)); } function log(uint256 p0, uint256 p1, string memory p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,string,bool)", p0, p1, p2, p3)); } function log(uint256 p0, uint256 p1, string memory p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,string,address)", p0, p1, p2, p3)); } function log(uint256 p0, uint256 p1, bool p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,bool,uint256)", p0, p1, p2, p3)); } function log(uint256 p0, uint256 p1, bool p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,bool,string)", p0, p1, p2, p3)); } function log(uint256 p0, uint256 p1, bool p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,bool,bool)", p0, p1, p2, p3)); } function log(uint256 p0, uint256 p1, bool p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,bool,address)", p0, p1, p2, p3)); } function log(uint256 p0, uint256 p1, address p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,address,uint256)", p0, p1, p2, p3)); } function log(uint256 p0, uint256 p1, address p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,address,string)", p0, p1, p2, p3)); } function log(uint256 p0, uint256 p1, address p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,address,bool)", p0, p1, p2, p3)); } function log(uint256 p0, uint256 p1, address p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,address,address)", p0, p1, p2, p3)); } function log(uint256 p0, string memory p1, uint256 p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,string,uint256,uint256)", p0, p1, p2, p3)); } function log(uint256 p0, string memory p1, uint256 p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,string,uint256,string)", p0, p1, p2, p3)); } function log(uint256 p0, string memory p1, uint256 p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,string,uint256,bool)", p0, p1, p2, p3)); } function log(uint256 p0, string memory p1, uint256 p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,string,uint256,address)", p0, p1, p2, p3)); } function log(uint256 p0, string memory p1, string memory p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,string,string,uint256)", p0, p1, p2, p3)); } function log(uint256 p0, string memory p1, string memory p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,string,string,string)", p0, p1, p2, p3)); } function log(uint256 p0, string memory p1, string memory p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,string,string,bool)", p0, p1, p2, p3)); } function log(uint256 p0, string memory p1, string memory p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,string,string,address)", p0, p1, p2, p3)); } function log(uint256 p0, string memory p1, bool p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,string,bool,uint256)", p0, p1, p2, p3)); } function log(uint256 p0, string memory p1, bool p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,string,bool,string)", p0, p1, p2, p3)); } function log(uint256 p0, string memory p1, bool p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,string,bool,bool)", p0, p1, p2, p3)); } function log(uint256 p0, string memory p1, bool p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,string,bool,address)", p0, p1, p2, p3)); } function log(uint256 p0, string memory p1, address p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,string,address,uint256)", p0, p1, p2, p3)); } function log(uint256 p0, string memory p1, address p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,string,address,string)", p0, p1, p2, p3)); } function log(uint256 p0, string memory p1, address p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,string,address,bool)", p0, p1, p2, p3)); } function log(uint256 p0, string memory p1, address p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,string,address,address)", p0, p1, p2, p3)); } function log(uint256 p0, bool p1, uint256 p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,uint256,uint256)", p0, p1, p2, p3)); } function log(uint256 p0, bool p1, uint256 p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,uint256,string)", p0, p1, p2, p3)); } function log(uint256 p0, bool p1, uint256 p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,uint256,bool)", p0, p1, p2, p3)); } function log(uint256 p0, bool p1, uint256 p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,uint256,address)", p0, p1, p2, p3)); } function log(uint256 p0, bool p1, string memory p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,string,uint256)", p0, p1, p2, p3)); } function log(uint256 p0, bool p1, string memory p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,string,string)", p0, p1, p2, p3)); } function log(uint256 p0, bool p1, string memory p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,string,bool)", p0, p1, p2, p3)); } function log(uint256 p0, bool p1, string memory p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,string,address)", p0, p1, p2, p3)); } function log(uint256 p0, bool p1, bool p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,bool,uint256)", p0, p1, p2, p3)); } function log(uint256 p0, bool p1, bool p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,bool,string)", p0, p1, p2, p3)); } function log(uint256 p0, bool p1, bool p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint256 p0, bool p1, bool p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,bool,address)", p0, p1, p2, p3)); } function log(uint256 p0, bool p1, address p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,address,uint256)", p0, p1, p2, p3)); } function log(uint256 p0, bool p1, address p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,address,string)", p0, p1, p2, p3)); } function log(uint256 p0, bool p1, address p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,address,bool)", p0, p1, p2, p3)); } function log(uint256 p0, bool p1, address p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,address,address)", p0, p1, p2, p3)); } function log(uint256 p0, address p1, uint256 p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,address,uint256,uint256)", p0, p1, p2, p3)); } function log(uint256 p0, address p1, uint256 p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,address,uint256,string)", p0, p1, p2, p3)); } function log(uint256 p0, address p1, uint256 p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,address,uint256,bool)", p0, p1, p2, p3)); } function log(uint256 p0, address p1, uint256 p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,address,uint256,address)", p0, p1, p2, p3)); } function log(uint256 p0, address p1, string memory p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,address,string,uint256)", p0, p1, p2, p3)); } function log(uint256 p0, address p1, string memory p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,address,string,string)", p0, p1, p2, p3)); } function log(uint256 p0, address p1, string memory p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,address,string,bool)", p0, p1, p2, p3)); } function log(uint256 p0, address p1, string memory p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,address,string,address)", p0, p1, p2, p3)); } function log(uint256 p0, address p1, bool p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,address,bool,uint256)", p0, p1, p2, p3)); } function log(uint256 p0, address p1, bool p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,address,bool,string)", p0, p1, p2, p3)); } function log(uint256 p0, address p1, bool p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,address,bool,bool)", p0, p1, p2, p3)); } function log(uint256 p0, address p1, bool p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,address,bool,address)", p0, p1, p2, p3)); } function log(uint256 p0, address p1, address p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,address,address,uint256)", p0, p1, p2, p3)); } function log(uint256 p0, address p1, address p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,address,address,string)", p0, p1, p2, p3)); } function log(uint256 p0, address p1, address p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,address,address,bool)", p0, p1, p2, p3)); } function log(uint256 p0, address p1, address p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(uint256,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint256 p1, uint256 p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,uint256,uint256,uint256)", p0, p1, p2, p3)); } function log(string memory p0, uint256 p1, uint256 p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,uint256,uint256,string)", p0, p1, p2, p3)); } function log(string memory p0, uint256 p1, uint256 p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,uint256,uint256,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint256 p1, uint256 p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,uint256,uint256,address)", p0, p1, p2, p3)); } function log(string memory p0, uint256 p1, string memory p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,uint256,string,uint256)", p0, p1, p2, p3)); } function log(string memory p0, uint256 p1, string memory p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,uint256,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint256 p1, string memory p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,uint256,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint256 p1, string memory p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,uint256,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint256 p1, bool p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,uint256,bool,uint256)", p0, p1, p2, p3)); } function log(string memory p0, uint256 p1, bool p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,uint256,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint256 p1, bool p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,uint256,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint256 p1, bool p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,uint256,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint256 p1, address p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,uint256,address,uint256)", p0, p1, p2, p3)); } function log(string memory p0, uint256 p1, address p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,uint256,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint256 p1, address p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,uint256,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint256 p1, address p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,uint256,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint256 p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint256,uint256)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint256 p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint256,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint256 p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint256,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint256 p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint256,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint256)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint256)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint256)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint256 p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint256,uint256)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint256 p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint256,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint256 p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint256,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint256 p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint256,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint256)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint256)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint256)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint256 p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint256,uint256)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint256 p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint256,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint256 p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint256,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint256 p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint256,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint256)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint256)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint256)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint256 p1, uint256 p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,uint256,uint256)", p0, p1, p2, p3)); } function log(bool p0, uint256 p1, uint256 p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,uint256,string)", p0, p1, p2, p3)); } function log(bool p0, uint256 p1, uint256 p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,uint256,bool)", p0, p1, p2, p3)); } function log(bool p0, uint256 p1, uint256 p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,uint256,address)", p0, p1, p2, p3)); } function log(bool p0, uint256 p1, string memory p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,string,uint256)", p0, p1, p2, p3)); } function log(bool p0, uint256 p1, string memory p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint256 p1, string memory p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint256 p1, string memory p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint256 p1, bool p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,bool,uint256)", p0, p1, p2, p3)); } function log(bool p0, uint256 p1, bool p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint256 p1, bool p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint256 p1, bool p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint256 p1, address p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,address,uint256)", p0, p1, p2, p3)); } function log(bool p0, uint256 p1, address p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint256 p1, address p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint256 p1, address p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint256 p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint256,uint256)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint256 p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint256,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint256 p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint256,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint256 p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint256,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint256)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint256)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint256)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint256 p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint256,uint256)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint256 p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint256,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint256 p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint256,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint256 p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint256,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint256)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint256)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint256)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint256 p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint256,uint256)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint256 p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint256,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint256 p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint256,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint256 p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint256,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint256)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint256)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint256)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint256 p1, uint256 p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,uint256,uint256,uint256)", p0, p1, p2, p3)); } function log(address p0, uint256 p1, uint256 p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,uint256,uint256,string)", p0, p1, p2, p3)); } function log(address p0, uint256 p1, uint256 p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,uint256,uint256,bool)", p0, p1, p2, p3)); } function log(address p0, uint256 p1, uint256 p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,uint256,uint256,address)", p0, p1, p2, p3)); } function log(address p0, uint256 p1, string memory p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,uint256,string,uint256)", p0, p1, p2, p3)); } function log(address p0, uint256 p1, string memory p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,uint256,string,string)", p0, p1, p2, p3)); } function log(address p0, uint256 p1, string memory p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,uint256,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint256 p1, string memory p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,uint256,string,address)", p0, p1, p2, p3)); } function log(address p0, uint256 p1, bool p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,uint256,bool,uint256)", p0, p1, p2, p3)); } function log(address p0, uint256 p1, bool p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,uint256,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint256 p1, bool p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,uint256,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint256 p1, bool p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,uint256,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint256 p1, address p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,uint256,address,uint256)", p0, p1, p2, p3)); } function log(address p0, uint256 p1, address p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,uint256,address,string)", p0, p1, p2, p3)); } function log(address p0, uint256 p1, address p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,uint256,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint256 p1, address p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,uint256,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint256 p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint256,uint256)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint256 p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint256,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint256 p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint256,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint256 p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint256,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint256)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint256)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint256)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint256 p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint256,uint256)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint256 p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint256,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint256 p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint256,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint256 p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint256,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint256)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint256)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint256)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint256 p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint256,uint256)", p0, p1, p2, p3)); } function log(address p0, address p1, uint256 p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint256,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint256 p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint256,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint256 p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint256,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint256)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint256)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint256 p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint256)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal pure { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /// @notice Simple ERC20 + EIP-2612 implementation. /// @author Solady (https://github.com/vectorized/solady/blob/main/src/tokens/ERC20.sol) /// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol) /// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol) /// /// @dev Note: /// - The ERC20 standard allows minting and transferring to and from the zero address, /// minting and transferring zero tokens, as well as self-approvals. /// For performance, this implementation WILL NOT revert for such actions. /// Please add any checks with overrides if desired. /// - The `permit` function uses the ecrecover precompile (0x1). /// /// If you are overriding: /// - NEVER violate the ERC20 invariant: /// the total sum of all balances must be equal to `totalSupply()`. /// - Check that the overridden function is actually used in the function you want to /// change the behavior of. Much of the code has been manually inlined for performance. abstract contract ERC20 { /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* CUSTOM ERRORS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev The total supply has overflowed. error TotalSupplyOverflow(); /// @dev The allowance has overflowed. error AllowanceOverflow(); /// @dev The allowance has underflowed. error AllowanceUnderflow(); /// @dev Insufficient balance. error InsufficientBalance(); /// @dev Insufficient allowance. error InsufficientAllowance(); /// @dev The permit is invalid. error InvalidPermit(); /// @dev The permit has expired. error PermitExpired(); /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* EVENTS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Emitted when `amount` tokens is transferred from `from` to `to`. event Transfer(address indexed from, address indexed to, uint256 amount); /// @dev Emitted when `amount` tokens is approved by `owner` to be used by `spender`. event Approval(address indexed owner, address indexed spender, uint256 amount); /// @dev `keccak256(bytes("Transfer(address,address,uint256)"))`. uint256 private constant _TRANSFER_EVENT_SIGNATURE = 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef; /// @dev `keccak256(bytes("Approval(address,address,uint256)"))`. uint256 private constant _APPROVAL_EVENT_SIGNATURE = 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925; /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* STORAGE */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev The storage slot for the total supply. uint256 private constant _TOTAL_SUPPLY_SLOT = 0x05345cdf77eb68f44c; /// @dev The balance slot of `owner` is given by: /// ``` /// mstore(0x0c, _BALANCE_SLOT_SEED) /// mstore(0x00, owner) /// let balanceSlot := keccak256(0x0c, 0x20) /// ``` uint256 private constant _BALANCE_SLOT_SEED = 0x87a211a2; /// @dev The allowance slot of (`owner`, `spender`) is given by: /// ``` /// mstore(0x20, spender) /// mstore(0x0c, _ALLOWANCE_SLOT_SEED) /// mstore(0x00, owner) /// let allowanceSlot := keccak256(0x0c, 0x34) /// ``` uint256 private constant _ALLOWANCE_SLOT_SEED = 0x7f5e9f20; /// @dev The nonce slot of `owner` is given by: /// ``` /// mstore(0x0c, _NONCES_SLOT_SEED) /// mstore(0x00, owner) /// let nonceSlot := keccak256(0x0c, 0x20) /// ``` uint256 private constant _NONCES_SLOT_SEED = 0x38377508; /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* CONSTANTS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev `(_NONCES_SLOT_SEED << 16) | 0x1901`. uint256 private constant _NONCES_SLOT_SEED_WITH_SIGNATURE_PREFIX = 0x383775081901; /// @dev `keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)")`. bytes32 private constant _DOMAIN_TYPEHASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f; /// @dev `keccak256("1")`. bytes32 private constant _VERSION_HASH = 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6; /// @dev `keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)")`. bytes32 private constant _PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* ERC20 METADATA */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Returns the name of the token. function name() public view virtual returns (string memory); /// @dev Returns the symbol of the token. function symbol() public view virtual returns (string memory); /// @dev Returns the decimals places of the token. function decimals() public view virtual returns (uint8) { return 18; } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* ERC20 */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Returns the amount of tokens in existence. function totalSupply() public view virtual returns (uint256 result) { /// @solidity memory-safe-assembly assembly { result := sload(_TOTAL_SUPPLY_SLOT) } } /// @dev Returns the amount of tokens owned by `owner`. function balanceOf(address owner) public view virtual returns (uint256 result) { /// @solidity memory-safe-assembly assembly { mstore(0x0c, _BALANCE_SLOT_SEED) mstore(0x00, owner) result := sload(keccak256(0x0c, 0x20)) } } /// @dev Returns the amount of tokens that `spender` can spend on behalf of `owner`. function allowance(address owner, address spender) public view virtual returns (uint256 result) { /// @solidity memory-safe-assembly assembly { mstore(0x20, spender) mstore(0x0c, _ALLOWANCE_SLOT_SEED) mstore(0x00, owner) result := sload(keccak256(0x0c, 0x34)) } } /// @dev Sets `amount` as the allowance of `spender` over the caller's tokens. /// /// Emits a {Approval} event. function approve(address spender, uint256 amount) public virtual returns (bool) { /// @solidity memory-safe-assembly assembly { // Compute the allowance slot and store the amount. mstore(0x20, spender) mstore(0x0c, _ALLOWANCE_SLOT_SEED) mstore(0x00, caller()) sstore(keccak256(0x0c, 0x34), amount) // Emit the {Approval} event. mstore(0x00, amount) log3(0x00, 0x20, _APPROVAL_EVENT_SIGNATURE, caller(), shr(96, mload(0x2c))) } return true; } /// @dev Transfer `amount` tokens from the caller to `to`. /// /// Requirements: /// - `from` must at least have `amount`. /// /// Emits a {Transfer} event. function transfer(address to, uint256 amount) public virtual returns (bool) { _beforeTokenTransfer(msg.sender, to, amount); /// @solidity memory-safe-assembly assembly { // Compute the balance slot and load its value. mstore(0x0c, _BALANCE_SLOT_SEED) mstore(0x00, caller()) let fromBalanceSlot := keccak256(0x0c, 0x20) let fromBalance := sload(fromBalanceSlot) // Revert if insufficient balance. if gt(amount, fromBalance) { mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`. revert(0x1c, 0x04) } // Subtract and store the updated balance. sstore(fromBalanceSlot, sub(fromBalance, amount)) // Compute the balance slot of `to`. mstore(0x00, to) let toBalanceSlot := keccak256(0x0c, 0x20) // Add and store the updated balance of `to`. // Will not overflow because the sum of all user balances // cannot exceed the maximum uint256 value. sstore(toBalanceSlot, add(sload(toBalanceSlot), amount)) // Emit the {Transfer} event. mstore(0x20, amount) log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, caller(), shr(96, mload(0x0c))) } _afterTokenTransfer(msg.sender, to, amount); return true; } /// @dev Transfers `amount` tokens from `from` to `to`. /// /// Note: Does not update the allowance if it is the maximum uint256 value. /// /// Requirements: /// - `from` must at least have `amount`. /// - The caller must have at least `amount` of allowance to transfer the tokens of `from`. /// /// Emits a {Transfer} event. function transferFrom(address from, address to, uint256 amount) public virtual returns (bool) { _beforeTokenTransfer(from, to, amount); /// @solidity memory-safe-assembly assembly { let from_ := shl(96, from) // Compute the allowance slot and load its value. mstore(0x20, caller()) mstore(0x0c, or(from_, _ALLOWANCE_SLOT_SEED)) let allowanceSlot := keccak256(0x0c, 0x34) let allowance_ := sload(allowanceSlot) // If the allowance is not the maximum uint256 value. if add(allowance_, 1) { // Revert if the amount to be transferred exceeds the allowance. if gt(amount, allowance_) { mstore(0x00, 0x13be252b) // `InsufficientAllowance()`. revert(0x1c, 0x04) } // Subtract and store the updated allowance. sstore(allowanceSlot, sub(allowance_, amount)) } // Compute the balance slot and load its value. mstore(0x0c, or(from_, _BALANCE_SLOT_SEED)) let fromBalanceSlot := keccak256(0x0c, 0x20) let fromBalance := sload(fromBalanceSlot) // Revert if insufficient balance. if gt(amount, fromBalance) { mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`. revert(0x1c, 0x04) } // Subtract and store the updated balance. sstore(fromBalanceSlot, sub(fromBalance, amount)) // Compute the balance slot of `to`. mstore(0x00, to) let toBalanceSlot := keccak256(0x0c, 0x20) // Add and store the updated balance of `to`. // Will not overflow because the sum of all user balances // cannot exceed the maximum uint256 value. sstore(toBalanceSlot, add(sload(toBalanceSlot), amount)) // Emit the {Transfer} event. mstore(0x20, amount) log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, from_), shr(96, mload(0x0c))) } _afterTokenTransfer(from, to, amount); return true; } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* EIP-2612 */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev For more performance, override to return the constant value /// of `keccak256(bytes(name()))` if `name()` will never change. function _constantNameHash() internal view virtual returns (bytes32 result) {} /// @dev Returns the current nonce for `owner`. /// This value is used to compute the signature for EIP-2612 permit. function nonces(address owner) public view virtual returns (uint256 result) { /// @solidity memory-safe-assembly assembly { // Compute the nonce slot and load its value. mstore(0x0c, _NONCES_SLOT_SEED) mstore(0x00, owner) result := sload(keccak256(0x0c, 0x20)) } } /// @dev Sets `value` as the allowance of `spender` over the tokens of `owner`, /// authorized by a signed approval by `owner`. /// /// Emits a {Approval} event. function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual { bytes32 nameHash = _constantNameHash(); // We simply calculate it on-the-fly to allow for cases where the `name` may change. if (nameHash == bytes32(0)) nameHash = keccak256(bytes(name())); /// @solidity memory-safe-assembly assembly { // Revert if the block timestamp is greater than `deadline`. if gt(timestamp(), deadline) { mstore(0x00, 0x1a15a3cc) // `PermitExpired()`. revert(0x1c, 0x04) } let m := mload(0x40) // Grab the free memory pointer. // Clean the upper 96 bits. owner := shr(96, shl(96, owner)) spender := shr(96, shl(96, spender)) // Compute the nonce slot and load its value. mstore(0x0e, _NONCES_SLOT_SEED_WITH_SIGNATURE_PREFIX) mstore(0x00, owner) let nonceSlot := keccak256(0x0c, 0x20) let nonceValue := sload(nonceSlot) // Prepare the domain separator. mstore(m, _DOMAIN_TYPEHASH) mstore(add(m, 0x20), nameHash) mstore(add(m, 0x40), _VERSION_HASH) mstore(add(m, 0x60), chainid()) mstore(add(m, 0x80), address()) mstore(0x2e, keccak256(m, 0xa0)) // Prepare the struct hash. mstore(m, _PERMIT_TYPEHASH) mstore(add(m, 0x20), owner) mstore(add(m, 0x40), spender) mstore(add(m, 0x60), value) mstore(add(m, 0x80), nonceValue) mstore(add(m, 0xa0), deadline) mstore(0x4e, keccak256(m, 0xc0)) // Prepare the ecrecover calldata. mstore(0x00, keccak256(0x2c, 0x42)) mstore(0x20, and(0xff, v)) mstore(0x40, r) mstore(0x60, s) let t := staticcall(gas(), 1, 0, 0x80, 0x20, 0x20) // If the ecrecover fails, the returndatasize will be 0x00, // `owner` will be checked if it equals the hash at 0x00, // which evaluates to false (i.e. 0), and we will revert. // If the ecrecover succeeds, the returndatasize will be 0x20, // `owner` will be compared against the returned address at 0x20. if iszero(eq(mload(returndatasize()), owner)) { mstore(0x00, 0xddafbaef) // `InvalidPermit()`. revert(0x1c, 0x04) } // Increment and store the updated nonce. sstore(nonceSlot, add(nonceValue, t)) // `t` is 1 if ecrecover succeeds. // Compute the allowance slot and store the value. // The `owner` is already at slot 0x20. mstore(0x40, or(shl(160, _ALLOWANCE_SLOT_SEED), spender)) sstore(keccak256(0x2c, 0x34), value) // Emit the {Approval} event. log3(add(m, 0x60), 0x20, _APPROVAL_EVENT_SIGNATURE, owner, spender) mstore(0x40, m) // Restore the free memory pointer. mstore(0x60, 0) // Restore the zero pointer. } } /// @dev Returns the EIP-712 domain separator for the EIP-2612 permit. function DOMAIN_SEPARATOR() public view virtual returns (bytes32 result) { bytes32 nameHash = _constantNameHash(); // We simply calculate it on-the-fly to allow for cases where the `name` may change. if (nameHash == bytes32(0)) nameHash = keccak256(bytes(name())); /// @solidity memory-safe-assembly assembly { let m := mload(0x40) // Grab the free memory pointer. mstore(m, _DOMAIN_TYPEHASH) mstore(add(m, 0x20), nameHash) mstore(add(m, 0x40), _VERSION_HASH) mstore(add(m, 0x60), chainid()) mstore(add(m, 0x80), address()) result := keccak256(m, 0xa0) } } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* INTERNAL MINT FUNCTIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Mints `amount` tokens to `to`, increasing the total supply. /// /// Emits a {Transfer} event. function _mint(address to, uint256 amount) internal virtual { _beforeTokenTransfer(address(0), to, amount); /// @solidity memory-safe-assembly assembly { let totalSupplyBefore := sload(_TOTAL_SUPPLY_SLOT) let totalSupplyAfter := add(totalSupplyBefore, amount) // Revert if the total supply overflows. if lt(totalSupplyAfter, totalSupplyBefore) { mstore(0x00, 0xe5cfe957) // `TotalSupplyOverflow()`. revert(0x1c, 0x04) } // Store the updated total supply. sstore(_TOTAL_SUPPLY_SLOT, totalSupplyAfter) // Compute the balance slot and load its value. mstore(0x0c, _BALANCE_SLOT_SEED) mstore(0x00, to) let toBalanceSlot := keccak256(0x0c, 0x20) // Add and store the updated balance. sstore(toBalanceSlot, add(sload(toBalanceSlot), amount)) // Emit the {Transfer} event. mstore(0x20, amount) log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, 0, shr(96, mload(0x0c))) } _afterTokenTransfer(address(0), to, amount); } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* INTERNAL BURN FUNCTIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Burns `amount` tokens from `from`, reducing the total supply. /// /// Emits a {Transfer} event. function _burn(address from, uint256 amount) internal virtual { _beforeTokenTransfer(from, address(0), amount); /// @solidity memory-safe-assembly assembly { // Compute the balance slot and load its value. mstore(0x0c, _BALANCE_SLOT_SEED) mstore(0x00, from) let fromBalanceSlot := keccak256(0x0c, 0x20) let fromBalance := sload(fromBalanceSlot) // Revert if insufficient balance. if gt(amount, fromBalance) { mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`. revert(0x1c, 0x04) } // Subtract and store the updated balance. sstore(fromBalanceSlot, sub(fromBalance, amount)) // Subtract and store the updated total supply. sstore(_TOTAL_SUPPLY_SLOT, sub(sload(_TOTAL_SUPPLY_SLOT), amount)) // Emit the {Transfer} event. mstore(0x00, amount) log3(0x00, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, shl(96, from)), 0) } _afterTokenTransfer(from, address(0), amount); } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* INTERNAL TRANSFER FUNCTIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Moves `amount` of tokens from `from` to `to`. function _transfer(address from, address to, uint256 amount) internal virtual { _beforeTokenTransfer(from, to, amount); /// @solidity memory-safe-assembly assembly { let from_ := shl(96, from) // Compute the balance slot and load its value. mstore(0x0c, or(from_, _BALANCE_SLOT_SEED)) let fromBalanceSlot := keccak256(0x0c, 0x20) let fromBalance := sload(fromBalanceSlot) // Revert if insufficient balance. if gt(amount, fromBalance) { mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`. revert(0x1c, 0x04) } // Subtract and store the updated balance. sstore(fromBalanceSlot, sub(fromBalance, amount)) // Compute the balance slot of `to`. mstore(0x00, to) let toBalanceSlot := keccak256(0x0c, 0x20) // Add and store the updated balance of `to`. // Will not overflow because the sum of all user balances // cannot exceed the maximum uint256 value. sstore(toBalanceSlot, add(sload(toBalanceSlot), amount)) // Emit the {Transfer} event. mstore(0x20, amount) log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, from_), shr(96, mload(0x0c))) } _afterTokenTransfer(from, to, amount); } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* INTERNAL ALLOWANCE FUNCTIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Updates the allowance of `owner` for `spender` based on spent `amount`. function _spendAllowance(address owner, address spender, uint256 amount) internal virtual { /// @solidity memory-safe-assembly assembly { // Compute the allowance slot and load its value. mstore(0x20, spender) mstore(0x0c, _ALLOWANCE_SLOT_SEED) mstore(0x00, owner) let allowanceSlot := keccak256(0x0c, 0x34) let allowance_ := sload(allowanceSlot) // If the allowance is not the maximum uint256 value. if add(allowance_, 1) { // Revert if the amount to be transferred exceeds the allowance. if gt(amount, allowance_) { mstore(0x00, 0x13be252b) // `InsufficientAllowance()`. revert(0x1c, 0x04) } // Subtract and store the updated allowance. sstore(allowanceSlot, sub(allowance_, amount)) } } } /// @dev Sets `amount` as the allowance of `spender` over the tokens of `owner`. /// /// Emits a {Approval} event. function _approve(address owner, address spender, uint256 amount) internal virtual { /// @solidity memory-safe-assembly assembly { let owner_ := shl(96, owner) // Compute the allowance slot and store the amount. mstore(0x20, spender) mstore(0x0c, or(owner_, _ALLOWANCE_SLOT_SEED)) sstore(keccak256(0x0c, 0x34), amount) // Emit the {Approval} event. mstore(0x00, amount) log3(0x00, 0x20, _APPROVAL_EVENT_SIGNATURE, shr(96, owner_), shr(96, mload(0x2c))) } } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* HOOKS TO OVERRIDE */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Hook that is called before any transfer of tokens. /// This includes minting and burning. function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {} /// @dev Hook that is called after any transfer of tokens. /// This includes minting and burning. function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {} }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /// @notice Arithmetic library with operations for fixed-point numbers. /// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/FixedPointMathLib.sol) /// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol) library FixedPointMathLib { /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* CUSTOM ERRORS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev The operation failed, as the output exceeds the maximum value of uint256. error ExpOverflow(); /// @dev The operation failed, as the output exceeds the maximum value of uint256. error FactorialOverflow(); /// @dev The operation failed, due to an overflow. error RPowOverflow(); /// @dev The mantissa is too big to fit. error MantissaOverflow(); /// @dev The operation failed, due to an multiplication overflow. error MulWadFailed(); /// @dev The operation failed, due to an multiplication overflow. error SMulWadFailed(); /// @dev The operation failed, either due to a multiplication overflow, or a division by a zero. error DivWadFailed(); /// @dev The operation failed, either due to a multiplication overflow, or a division by a zero. error SDivWadFailed(); /// @dev The operation failed, either due to a multiplication overflow, or a division by a zero. error MulDivFailed(); /// @dev The division failed, as the denominator is zero. error DivFailed(); /// @dev The full precision multiply-divide operation failed, either due /// to the result being larger than 256 bits, or a division by a zero. error FullMulDivFailed(); /// @dev The output is undefined, as the input is less-than-or-equal to zero. error LnWadUndefined(); /// @dev The input outside the acceptable domain. error OutOfDomain(); /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* CONSTANTS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev The scalar of ETH and most ERC20s. uint256 internal constant WAD = 1e18; /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* SIMPLIFIED FIXED POINT OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Equivalent to `(x * y) / WAD` rounded down. function mulWad(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { // Equivalent to `require(y == 0 || x <= type(uint256).max / y)`. if mul(y, gt(x, div(not(0), y))) { mstore(0x00, 0xbac65e5b) // `MulWadFailed()`. revert(0x1c, 0x04) } z := div(mul(x, y), WAD) } } /// @dev Equivalent to `(x * y) / WAD` rounded down. function sMulWad(int256 x, int256 y) internal pure returns (int256 z) { /// @solidity memory-safe-assembly assembly { z := mul(x, y) // Equivalent to `require((x == 0 || z / x == y) && !(x == -1 && y == type(int256).min))`. if iszero(gt(or(iszero(x), eq(sdiv(z, x), y)), lt(not(x), eq(y, shl(255, 1))))) { mstore(0x00, 0xedcd4dd4) // `SMulWadFailed()`. revert(0x1c, 0x04) } z := sdiv(z, WAD) } } /// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks. function rawMulWad(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := div(mul(x, y), WAD) } } /// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks. function rawSMulWad(int256 x, int256 y) internal pure returns (int256 z) { /// @solidity memory-safe-assembly assembly { z := sdiv(mul(x, y), WAD) } } /// @dev Equivalent to `(x * y) / WAD` rounded up. function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { // Equivalent to `require(y == 0 || x <= type(uint256).max / y)`. if mul(y, gt(x, div(not(0), y))) { mstore(0x00, 0xbac65e5b) // `MulWadFailed()`. revert(0x1c, 0x04) } z := add(iszero(iszero(mod(mul(x, y), WAD))), div(mul(x, y), WAD)) } } /// @dev Equivalent to `(x * y) / WAD` rounded up, but without overflow checks. function rawMulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := add(iszero(iszero(mod(mul(x, y), WAD))), div(mul(x, y), WAD)) } } /// @dev Equivalent to `(x * WAD) / y` rounded down. function divWad(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { // Equivalent to `require(y != 0 && (WAD == 0 || x <= type(uint256).max / WAD))`. if iszero(mul(y, iszero(mul(WAD, gt(x, div(not(0), WAD)))))) { mstore(0x00, 0x7c5f487d) // `DivWadFailed()`. revert(0x1c, 0x04) } z := div(mul(x, WAD), y) } } /// @dev Equivalent to `(x * WAD) / y` rounded down. function sDivWad(int256 x, int256 y) internal pure returns (int256 z) { /// @solidity memory-safe-assembly assembly { z := mul(x, WAD) // Equivalent to `require(y != 0 && ((x * WAD) / WAD == x))`. if iszero(and(iszero(iszero(y)), eq(sdiv(z, WAD), x))) { mstore(0x00, 0x5c43740d) // `SDivWadFailed()`. revert(0x1c, 0x04) } z := sdiv(mul(x, WAD), y) } } /// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks. function rawDivWad(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := div(mul(x, WAD), y) } } /// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks. function rawSDivWad(int256 x, int256 y) internal pure returns (int256 z) { /// @solidity memory-safe-assembly assembly { z := sdiv(mul(x, WAD), y) } } /// @dev Equivalent to `(x * WAD) / y` rounded up. function divWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { // Equivalent to `require(y != 0 && (WAD == 0 || x <= type(uint256).max / WAD))`. if iszero(mul(y, iszero(mul(WAD, gt(x, div(not(0), WAD)))))) { mstore(0x00, 0x7c5f487d) // `DivWadFailed()`. revert(0x1c, 0x04) } z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y)) } } /// @dev Equivalent to `(x * WAD) / y` rounded up, but without overflow and divide by zero checks. function rawDivWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y)) } } /// @dev Equivalent to `x` to the power of `y`. /// because `x ** y = (e ** ln(x)) ** y = e ** (ln(x) * y)`. function powWad(int256 x, int256 y) internal pure returns (int256) { // Using `ln(x)` means `x` must be greater than 0. return expWad((lnWad(x) * y) / int256(WAD)); } /// @dev Returns `exp(x)`, denominated in `WAD`. /// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln function expWad(int256 x) internal pure returns (int256 r) { unchecked { // When the result is less than 0.5 we return zero. // This happens when `x <= (log(1e-18) * 1e18) ~ -4.15e19`. if (x <= -41446531673892822313) return r; /// @solidity memory-safe-assembly assembly { // When the result is greater than `(2**255 - 1) / 1e18` we can not represent it as // an int. This happens when `x >= floor(log((2**255 - 1) / 1e18) * 1e18) ≈ 135`. if iszero(slt(x, 135305999368893231589)) { mstore(0x00, 0xa37bfec9) // `ExpOverflow()`. revert(0x1c, 0x04) } } // `x` is now in the range `(-42, 136) * 1e18`. Convert to `(-42, 136) * 2**96` // for more intermediate precision and a binary basis. This base conversion // is a multiplication by 1e18 / 2**96 = 5**18 / 2**78. x = (x << 78) / 5 ** 18; // Reduce range of x to (-½ ln 2, ½ ln 2) * 2**96 by factoring out powers // of two such that exp(x) = exp(x') * 2**k, where k is an integer. // Solving this gives k = round(x / log(2)) and x' = x - k * log(2). int256 k = ((x << 96) / 54916777467707473351141471128 + 2 ** 95) >> 96; x = x - k * 54916777467707473351141471128; // `k` is in the range `[-61, 195]`. // Evaluate using a (6, 7)-term rational approximation. // `p` is made monic, we'll multiply by a scale factor later. int256 y = x + 1346386616545796478920950773328; y = ((y * x) >> 96) + 57155421227552351082224309758442; int256 p = y + x - 94201549194550492254356042504812; p = ((p * y) >> 96) + 28719021644029726153956944680412240; p = p * x + (4385272521454847904659076985693276 << 96); // We leave `p` in `2**192` basis so we don't need to scale it back up for the division. int256 q = x - 2855989394907223263936484059900; q = ((q * x) >> 96) + 50020603652535783019961831881945; q = ((q * x) >> 96) - 533845033583426703283633433725380; q = ((q * x) >> 96) + 3604857256930695427073651918091429; q = ((q * x) >> 96) - 14423608567350463180887372962807573; q = ((q * x) >> 96) + 26449188498355588339934803723976023; /// @solidity memory-safe-assembly assembly { // Div in assembly because solidity adds a zero check despite the unchecked. // The q polynomial won't have zeros in the domain as all its roots are complex. // No scaling is necessary because p is already `2**96` too large. r := sdiv(p, q) } // r should be in the range `(0.09, 0.25) * 2**96`. // We now need to multiply r by: // - The scale factor `s ≈ 6.031367120`. // - The `2**k` factor from the range reduction. // - The `1e18 / 2**96` factor for base conversion. // We do this all at once, with an intermediate result in `2**213` // basis, so the final right shift is always by a positive amount. r = int256( (uint256(r) * 3822833074963236453042738258902158003155416615667) >> uint256(195 - k) ); } } /// @dev Returns `ln(x)`, denominated in `WAD`. /// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln function lnWad(int256 x) internal pure returns (int256 r) { /// @solidity memory-safe-assembly assembly { // We want to convert `x` from `10**18` fixed point to `2**96` fixed point. // We do this by multiplying by `2**96 / 10**18`. But since // `ln(x * C) = ln(x) + ln(C)`, we can simply do nothing here // and add `ln(2**96 / 10**18)` at the end. // Compute `k = log2(x) - 96`, `r = 159 - k = 255 - log2(x) = 255 ^ log2(x)`. r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x)) r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x)))) r := or(r, shl(5, lt(0xffffffff, shr(r, x)))) r := or(r, shl(4, lt(0xffff, shr(r, x)))) r := or(r, shl(3, lt(0xff, shr(r, x)))) // We place the check here for more optimal stack operations. if iszero(sgt(x, 0)) { mstore(0x00, 0x1615e638) // `LnWadUndefined()`. revert(0x1c, 0x04) } // forgefmt: disable-next-item r := xor(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)), 0xf8f9f9faf9fdfafbf9fdfcfdfafbfcfef9fafdfafcfcfbfefafafcfbffffffff)) // Reduce range of x to (1, 2) * 2**96 // ln(2^k * x) = k * ln(2) + ln(x) x := shr(159, shl(r, x)) // Evaluate using a (8, 8)-term rational approximation. // `p` is made monic, we will multiply by a scale factor later. // forgefmt: disable-next-item let p := sub( // This heavily nested expression is to avoid stack-too-deep for via-ir. sar(96, mul(add(43456485725739037958740375743393, sar(96, mul(add(24828157081833163892658089445524, sar(96, mul(add(3273285459638523848632254066296, x), x))), x))), x)), 11111509109440967052023855526967) p := sub(sar(96, mul(p, x)), 45023709667254063763336534515857) p := sub(sar(96, mul(p, x)), 14706773417378608786704636184526) p := sub(mul(p, x), shl(96, 795164235651350426258249787498)) // We leave `p` in `2**192` basis so we don't need to scale it back up for the division. // `q` is monic by convention. let q := add(5573035233440673466300451813936, x) q := add(71694874799317883764090561454958, sar(96, mul(x, q))) q := add(283447036172924575727196451306956, sar(96, mul(x, q))) q := add(401686690394027663651624208769553, sar(96, mul(x, q))) q := add(204048457590392012362485061816622, sar(96, mul(x, q))) q := add(31853899698501571402653359427138, sar(96, mul(x, q))) q := add(909429971244387300277376558375, sar(96, mul(x, q))) // `p / q` is in the range `(0, 0.125) * 2**96`. // Finalization, we need to: // - Multiply by the scale factor `s = 5.549…`. // - Add `ln(2**96 / 10**18)`. // - Add `k * ln(2)`. // - Multiply by `10**18 / 2**96 = 5**18 >> 78`. // The q polynomial is known not to have zeros in the domain. // No scaling required because p is already `2**96` too large. p := sdiv(p, q) // Multiply by the scaling factor: `s * 5**18 * 2**96`, base is now `5**18 * 2**192`. p := mul(1677202110996718588342820967067443963516166, p) // Add `ln(2) * k * 5**18 * 2**192`. // forgefmt: disable-next-item p := add(mul(16597577552685614221487285958193947469193820559219878177908093499208371, sub(159, r)), p) // Add `ln(2**96 / 10**18) * 5**18 * 2**192`. p := add(600920179829731861736702779321621459595472258049074101567377883020018308, p) // Base conversion: mul `2**18 / 2**192`. r := sar(174, p) } } /// @dev Returns `W_0(x)`, denominated in `WAD`. /// See: https://en.wikipedia.org/wiki/Lambert_W_function /// a.k.a. Product log function. This is an approximation of the principal branch. function lambertW0Wad(int256 x) internal pure returns (int256 w) { // forgefmt: disable-next-item unchecked { if ((w = x) <= -367879441171442322) revert OutOfDomain(); // `x` less than `-1/e`. int256 wad = int256(WAD); int256 p = x; uint256 c; // Whether we need to avoid catastrophic cancellation. uint256 i = 4; // Number of iterations. if (w <= 0x1ffffffffffff) { if (-0x4000000000000 <= w) { i = 1; // Inputs near zero only take one step to converge. } else if (w <= -0x3ffffffffffffff) { i = 32; // Inputs near `-1/e` take very long to converge. } } else if (w >> 63 == 0) { /// @solidity memory-safe-assembly assembly { // Inline log2 for more performance, since the range is small. let v := shr(49, w) let l := shl(3, lt(0xff, v)) l := add(or(l, byte(and(0x1f, shr(shr(l, v), 0x8421084210842108cc6318c6db6d54be)), 0x0706060506020504060203020504030106050205030304010505030400000000)), 49) w := sdiv(shl(l, 7), byte(sub(l, 31), 0x0303030303030303040506080c13)) c := gt(l, 60) i := add(2, add(gt(l, 53), c)) } } else { int256 ll = lnWad(w = lnWad(w)); /// @solidity memory-safe-assembly assembly { // `w = ln(x) - ln(ln(x)) + b * ln(ln(x)) / ln(x)`. w := add(sdiv(mul(ll, 1023715080943847266), w), sub(w, ll)) i := add(3, iszero(shr(68, x))) c := iszero(shr(143, x)) } if (c == 0) { do { // If `x` is big, use Newton's so that intermediate values won't overflow. int256 e = expWad(w); /// @solidity memory-safe-assembly assembly { let t := mul(w, div(e, wad)) w := sub(w, sdiv(sub(t, x), div(add(e, t), wad))) } if (p <= w) break; p = w; } while (--i != 0); /// @solidity memory-safe-assembly assembly { w := sub(w, sgt(w, 2)) } return w; } } do { // Otherwise, use Halley's for faster convergence. int256 e = expWad(w); /// @solidity memory-safe-assembly assembly { let t := add(w, wad) let s := sub(mul(w, e), mul(x, wad)) w := sub(w, sdiv(mul(s, wad), sub(mul(e, t), sdiv(mul(add(t, wad), s), add(t, t))))) } if (p <= w) break; p = w; } while (--i != c); /// @solidity memory-safe-assembly assembly { w := sub(w, sgt(w, 2)) } // For certain ranges of `x`, we'll use the quadratic-rate recursive formula of // R. Iacono and J.P. Boyd for the last iteration, to avoid catastrophic cancellation. if (c != 0) { int256 t = w | 1; /// @solidity memory-safe-assembly assembly { x := sdiv(mul(x, wad), t) } x = (t * (wad + lnWad(x))); /// @solidity memory-safe-assembly assembly { w := sdiv(x, add(wad, t)) } } } } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* GENERAL NUMBER UTILITIES */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Calculates `floor(x * y / d)` with full precision. /// Throws if result overflows a uint256 or when `d` is zero. /// Credit to Remco Bloemen under MIT license: https://2π.com/21/muldiv function fullMulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 result) { /// @solidity memory-safe-assembly assembly { for {} 1 {} { // 512-bit multiply `[p1 p0] = x * y`. // Compute the product mod `2**256` and mod `2**256 - 1` // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that `product = p1 * 2**256 + p0`. // Least significant 256 bits of the product. result := mul(x, y) // Temporarily use `result` as `p0` to save gas. let mm := mulmod(x, y, not(0)) // Most significant 256 bits of the product. let p1 := sub(mm, add(result, lt(mm, result))) // Handle non-overflow cases, 256 by 256 division. if iszero(p1) { if iszero(d) { mstore(0x00, 0xae47f702) // `FullMulDivFailed()`. revert(0x1c, 0x04) } result := div(result, d) break } // Make sure the result is less than `2**256`. Also prevents `d == 0`. if iszero(gt(d, p1)) { mstore(0x00, 0xae47f702) // `FullMulDivFailed()`. revert(0x1c, 0x04) } /*------------------- 512 by 256 division --------------------*/ // Make division exact by subtracting the remainder from `[p1 p0]`. // Compute remainder using mulmod. let r := mulmod(x, y, d) // `t` is the least significant bit of `d`. // Always greater or equal to 1. let t := and(d, sub(0, d)) // Divide `d` by `t`, which is a power of two. d := div(d, t) // Invert `d mod 2**256` // Now that `d` is an odd number, it has an inverse // modulo `2**256` such that `d * inv = 1 mod 2**256`. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, `d * inv = 1 mod 2**4`. let inv := xor(2, mul(3, d)) // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**8 inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**16 inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**32 inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**64 inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**128 result := mul( // Divide [p1 p0] by the factors of two. // Shift in bits from `p1` into `p0`. For this we need // to flip `t` such that it is `2**256 / t`. or( mul(sub(p1, gt(r, result)), add(div(sub(0, t), t), 1)), div(sub(result, r), t) ), // inverse mod 2**256 mul(inv, sub(2, mul(d, inv))) ) break } } } /// @dev Calculates `floor(x * y / d)` with full precision, rounded up. /// Throws if result overflows a uint256 or when `d` is zero. /// Credit to Uniswap-v3-core under MIT license: /// https://github.com/Uniswap/v3-core/blob/main/contracts/libraries/FullMath.sol function fullMulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 result) { result = fullMulDiv(x, y, d); /// @solidity memory-safe-assembly assembly { if mulmod(x, y, d) { result := add(result, 1) if iszero(result) { mstore(0x00, 0xae47f702) // `FullMulDivFailed()`. revert(0x1c, 0x04) } } } } /// @dev Returns `floor(x * y / d)`. /// Reverts if `x * y` overflows, or `d` is zero. function mulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { // Equivalent to require(d != 0 && (y == 0 || x <= type(uint256).max / y)) if iszero(mul(d, iszero(mul(y, gt(x, div(not(0), y)))))) { mstore(0x00, 0xad251c27) // `MulDivFailed()`. revert(0x1c, 0x04) } z := div(mul(x, y), d) } } /// @dev Returns `ceil(x * y / d)`. /// Reverts if `x * y` overflows, or `d` is zero. function mulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { // Equivalent to require(d != 0 && (y == 0 || x <= type(uint256).max / y)) if iszero(mul(d, iszero(mul(y, gt(x, div(not(0), y)))))) { mstore(0x00, 0xad251c27) // `MulDivFailed()`. revert(0x1c, 0x04) } z := add(iszero(iszero(mod(mul(x, y), d))), div(mul(x, y), d)) } } /// @dev Returns `ceil(x / d)`. /// Reverts if `d` is zero. function divUp(uint256 x, uint256 d) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { if iszero(d) { mstore(0x00, 0x65244e4e) // `DivFailed()`. revert(0x1c, 0x04) } z := add(iszero(iszero(mod(x, d))), div(x, d)) } } /// @dev Returns `max(0, x - y)`. function zeroFloorSub(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := mul(gt(x, y), sub(x, y)) } } /// @dev Exponentiate `x` to `y` by squaring, denominated in base `b`. /// Reverts if the computation overflows. function rpow(uint256 x, uint256 y, uint256 b) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := mul(b, iszero(y)) // `0 ** 0 = 1`. Otherwise, `0 ** n = 0`. if x { z := xor(b, mul(xor(b, x), and(y, 1))) // `z = isEven(y) ? scale : x` let half := shr(1, b) // Divide `b` by 2. // Divide `y` by 2 every iteration. for { y := shr(1, y) } y { y := shr(1, y) } { let xx := mul(x, x) // Store x squared. let xxRound := add(xx, half) // Round to the nearest number. // Revert if `xx + half` overflowed, or if `x ** 2` overflows. if or(lt(xxRound, xx), shr(128, x)) { mstore(0x00, 0x49f7642b) // `RPowOverflow()`. revert(0x1c, 0x04) } x := div(xxRound, b) // Set `x` to scaled `xxRound`. // If `y` is odd: if and(y, 1) { let zx := mul(z, x) // Compute `z * x`. let zxRound := add(zx, half) // Round to the nearest number. // If `z * x` overflowed or `zx + half` overflowed: if or(xor(div(zx, x), z), lt(zxRound, zx)) { // Revert if `x` is non-zero. if iszero(iszero(x)) { mstore(0x00, 0x49f7642b) // `RPowOverflow()`. revert(0x1c, 0x04) } } z := div(zxRound, b) // Return properly scaled `zxRound`. } } } } } /// @dev Returns the square root of `x`. function sqrt(uint256 x) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { // `floor(sqrt(2**15)) = 181`. `sqrt(2**15) - 181 = 2.84`. z := 181 // The "correct" value is 1, but this saves a multiplication later. // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically. // Let `y = x / 2**r`. We check `y >= 2**(k + 8)` // but shift right by `k` bits to ensure that if `x >= 256`, then `y >= 256`. let r := shl(7, lt(0xffffffffffffffffffffffffffffffffff, x)) r := or(r, shl(6, lt(0xffffffffffffffffff, shr(r, x)))) r := or(r, shl(5, lt(0xffffffffff, shr(r, x)))) r := or(r, shl(4, lt(0xffffff, shr(r, x)))) z := shl(shr(1, r), z) // Goal was to get `z*z*y` within a small factor of `x`. More iterations could // get y in a tighter range. Currently, we will have y in `[256, 256*(2**16))`. // We ensured `y >= 256` so that the relative difference between `y` and `y+1` is small. // That's not possible if `x < 256` but we can just verify those cases exhaustively. // Now, `z*z*y <= x < z*z*(y+1)`, and `y <= 2**(16+8)`, and either `y >= 256`, or `x < 256`. // Correctness can be checked exhaustively for `x < 256`, so we assume `y >= 256`. // Then `z*sqrt(y)` is within `sqrt(257)/sqrt(256)` of `sqrt(x)`, or about 20bps. // For `s` in the range `[1/256, 256]`, the estimate `f(s) = (181/1024) * (s+1)` // is in the range `(1/2.84 * sqrt(s), 2.84 * sqrt(s))`, // with largest error when `s = 1` and when `s = 256` or `1/256`. // Since `y` is in `[256, 256*(2**16))`, let `a = y/65536`, so that `a` is in `[1/256, 256)`. // Then we can estimate `sqrt(y)` using // `sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2**18`. // There is no overflow risk here since `y < 2**136` after the first branch above. z := shr(18, mul(z, add(shr(r, x), 65536))) // A `mul()` is saved from starting `z` at 181. // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough. z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) // If `x+1` is a perfect square, the Babylonian method cycles between // `floor(sqrt(x))` and `ceil(sqrt(x))`. This statement ensures we return floor. // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division z := sub(z, lt(div(x, z), z)) } } /// @dev Returns the cube root of `x`. /// Credit to bout3fiddy and pcaversaccio under AGPLv3 license: /// https://github.com/pcaversaccio/snekmate/blob/main/src/utils/Math.vy function cbrt(uint256 x) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { let r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x)) r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x)))) r := or(r, shl(5, lt(0xffffffff, shr(r, x)))) r := or(r, shl(4, lt(0xffff, shr(r, x)))) r := or(r, shl(3, lt(0xff, shr(r, x)))) z := div(shl(div(r, 3), shl(lt(0xf, shr(r, x)), 0xf)), xor(7, mod(r, 3))) z := div(add(add(div(x, mul(z, z)), z), z), 3) z := div(add(add(div(x, mul(z, z)), z), z), 3) z := div(add(add(div(x, mul(z, z)), z), z), 3) z := div(add(add(div(x, mul(z, z)), z), z), 3) z := div(add(add(div(x, mul(z, z)), z), z), 3) z := div(add(add(div(x, mul(z, z)), z), z), 3) z := div(add(add(div(x, mul(z, z)), z), z), 3) z := sub(z, lt(div(x, mul(z, z)), z)) } } /// @dev Returns the square root of `x`, denominated in `WAD`. function sqrtWad(uint256 x) internal pure returns (uint256 z) { unchecked { z = 10 ** 9; if (x <= type(uint256).max / 10 ** 36 - 1) { x *= 10 ** 18; z = 1; } z *= sqrt(x); } } /// @dev Returns the cube root of `x`, denominated in `WAD`. function cbrtWad(uint256 x) internal pure returns (uint256 z) { unchecked { z = 10 ** 12; if (x <= (type(uint256).max / 10 ** 36) * 10 ** 18 - 1) { if (x >= type(uint256).max / 10 ** 36) { x *= 10 ** 18; z = 10 ** 6; } else { x *= 10 ** 36; z = 1; } } z *= cbrt(x); } } /// @dev Returns the factorial of `x`. function factorial(uint256 x) internal pure returns (uint256 result) { /// @solidity memory-safe-assembly assembly { if iszero(lt(x, 58)) { mstore(0x00, 0xaba0f2a2) // `FactorialOverflow()`. revert(0x1c, 0x04) } for { result := 1 } x { x := sub(x, 1) } { result := mul(result, x) } } } /// @dev Returns the log2 of `x`. /// Equivalent to computing the index of the most significant bit (MSB) of `x`. /// Returns 0 if `x` is zero. function log2(uint256 x) internal pure returns (uint256 r) { /// @solidity memory-safe-assembly assembly { r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x)) r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x)))) r := or(r, shl(5, lt(0xffffffff, shr(r, x)))) r := or(r, shl(4, lt(0xffff, shr(r, x)))) r := or(r, shl(3, lt(0xff, shr(r, x)))) // forgefmt: disable-next-item r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)), 0x0706060506020504060203020504030106050205030304010505030400000000)) } } /// @dev Returns the log2 of `x`, rounded up. /// Returns 0 if `x` is zero. function log2Up(uint256 x) internal pure returns (uint256 r) { r = log2(x); /// @solidity memory-safe-assembly assembly { r := add(r, lt(shl(r, 1), x)) } } /// @dev Returns the log10 of `x`. /// Returns 0 if `x` is zero. function log10(uint256 x) internal pure returns (uint256 r) { /// @solidity memory-safe-assembly assembly { if iszero(lt(x, 100000000000000000000000000000000000000)) { x := div(x, 100000000000000000000000000000000000000) r := 38 } if iszero(lt(x, 100000000000000000000)) { x := div(x, 100000000000000000000) r := add(r, 20) } if iszero(lt(x, 10000000000)) { x := div(x, 10000000000) r := add(r, 10) } if iszero(lt(x, 100000)) { x := div(x, 100000) r := add(r, 5) } r := add(r, add(gt(x, 9), add(gt(x, 99), add(gt(x, 999), gt(x, 9999))))) } } /// @dev Returns the log10 of `x`, rounded up. /// Returns 0 if `x` is zero. function log10Up(uint256 x) internal pure returns (uint256 r) { r = log10(x); /// @solidity memory-safe-assembly assembly { r := add(r, lt(exp(10, r), x)) } } /// @dev Returns the log256 of `x`. /// Returns 0 if `x` is zero. function log256(uint256 x) internal pure returns (uint256 r) { /// @solidity memory-safe-assembly assembly { r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x)) r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x)))) r := or(r, shl(5, lt(0xffffffff, shr(r, x)))) r := or(r, shl(4, lt(0xffff, shr(r, x)))) r := or(shr(3, r), lt(0xff, shr(r, x))) } } /// @dev Returns the log256 of `x`, rounded up. /// Returns 0 if `x` is zero. function log256Up(uint256 x) internal pure returns (uint256 r) { r = log256(x); /// @solidity memory-safe-assembly assembly { r := add(r, lt(shl(shl(3, r), 1), x)) } } /// @dev Returns the scientific notation format `mantissa * 10 ** exponent` of `x`. /// Useful for compressing prices (e.g. using 25 bit mantissa and 7 bit exponent). function sci(uint256 x) internal pure returns (uint256 mantissa, uint256 exponent) { /// @solidity memory-safe-assembly assembly { mantissa := x if mantissa { if iszero(mod(mantissa, 1000000000000000000000000000000000)) { mantissa := div(mantissa, 1000000000000000000000000000000000) exponent := 33 } if iszero(mod(mantissa, 10000000000000000000)) { mantissa := div(mantissa, 10000000000000000000) exponent := add(exponent, 19) } if iszero(mod(mantissa, 1000000000000)) { mantissa := div(mantissa, 1000000000000) exponent := add(exponent, 12) } if iszero(mod(mantissa, 1000000)) { mantissa := div(mantissa, 1000000) exponent := add(exponent, 6) } if iszero(mod(mantissa, 10000)) { mantissa := div(mantissa, 10000) exponent := add(exponent, 4) } if iszero(mod(mantissa, 100)) { mantissa := div(mantissa, 100) exponent := add(exponent, 2) } if iszero(mod(mantissa, 10)) { mantissa := div(mantissa, 10) exponent := add(exponent, 1) } } } } /// @dev Convenience function for packing `x` into a smaller number using `sci`. /// The `mantissa` will be in bits [7..255] (the upper 249 bits). /// The `exponent` will be in bits [0..6] (the lower 7 bits). /// Use `SafeCastLib` to safely ensure that the `packed` number is small /// enough to fit in the desired unsigned integer type: /// ``` /// uint32 packed = SafeCastLib.toUint32(FixedPointMathLib.packSci(777 ether)); /// ``` function packSci(uint256 x) internal pure returns (uint256 packed) { (x, packed) = sci(x); // Reuse for `mantissa` and `exponent`. /// @solidity memory-safe-assembly assembly { if shr(249, x) { mstore(0x00, 0xce30380c) // `MantissaOverflow()`. revert(0x1c, 0x04) } packed := or(shl(7, x), packed) } } /// @dev Convenience function for unpacking a packed number from `packSci`. function unpackSci(uint256 packed) internal pure returns (uint256 unpacked) { unchecked { unpacked = (packed >> 7) * 10 ** (packed & 0x7f); } } /// @dev Returns the average of `x` and `y`. function avg(uint256 x, uint256 y) internal pure returns (uint256 z) { unchecked { z = (x & y) + ((x ^ y) >> 1); } } /// @dev Returns the average of `x` and `y`. function avg(int256 x, int256 y) internal pure returns (int256 z) { unchecked { z = (x >> 1) + (y >> 1) + (x & y & 1); } } /// @dev Returns the absolute value of `x`. function abs(int256 x) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := xor(sub(0, shr(255, x)), add(sub(0, shr(255, x)), x)) } } /// @dev Returns the absolute distance between `x` and `y`. function dist(int256 x, int256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := xor(mul(xor(sub(y, x), sub(x, y)), sgt(x, y)), sub(y, x)) } } /// @dev Returns the minimum of `x` and `y`. function min(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := xor(x, mul(xor(x, y), lt(y, x))) } } /// @dev Returns the minimum of `x` and `y`. function min(int256 x, int256 y) internal pure returns (int256 z) { /// @solidity memory-safe-assembly assembly { z := xor(x, mul(xor(x, y), slt(y, x))) } } /// @dev Returns the maximum of `x` and `y`. function max(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := xor(x, mul(xor(x, y), gt(y, x))) } } /// @dev Returns the maximum of `x` and `y`. function max(int256 x, int256 y) internal pure returns (int256 z) { /// @solidity memory-safe-assembly assembly { z := xor(x, mul(xor(x, y), sgt(y, x))) } } /// @dev Returns `x`, bounded to `minValue` and `maxValue`. function clamp(uint256 x, uint256 minValue, uint256 maxValue) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := xor(x, mul(xor(x, minValue), gt(minValue, x))) z := xor(z, mul(xor(z, maxValue), lt(maxValue, z))) } } /// @dev Returns `x`, bounded to `minValue` and `maxValue`. function clamp(int256 x, int256 minValue, int256 maxValue) internal pure returns (int256 z) { /// @solidity memory-safe-assembly assembly { z := xor(x, mul(xor(x, minValue), sgt(minValue, x))) z := xor(z, mul(xor(z, maxValue), slt(maxValue, z))) } } /// @dev Returns greatest common divisor of `x` and `y`. function gcd(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { for { z := x } y {} { let t := y y := mod(z, y) z := t } } } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* RAW NUMBER OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Returns `x + y`, without checking for overflow. function rawAdd(uint256 x, uint256 y) internal pure returns (uint256 z) { unchecked { z = x + y; } } /// @dev Returns `x + y`, without checking for overflow. function rawAdd(int256 x, int256 y) internal pure returns (int256 z) { unchecked { z = x + y; } } /// @dev Returns `x - y`, without checking for underflow. function rawSub(uint256 x, uint256 y) internal pure returns (uint256 z) { unchecked { z = x - y; } } /// @dev Returns `x - y`, without checking for underflow. function rawSub(int256 x, int256 y) internal pure returns (int256 z) { unchecked { z = x - y; } } /// @dev Returns `x * y`, without checking for overflow. function rawMul(uint256 x, uint256 y) internal pure returns (uint256 z) { unchecked { z = x * y; } } /// @dev Returns `x * y`, without checking for overflow. function rawMul(int256 x, int256 y) internal pure returns (int256 z) { unchecked { z = x * y; } } /// @dev Returns `x / y`, returning 0 if `y` is zero. function rawDiv(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := div(x, y) } } /// @dev Returns `x / y`, returning 0 if `y` is zero. function rawSDiv(int256 x, int256 y) internal pure returns (int256 z) { /// @solidity memory-safe-assembly assembly { z := sdiv(x, y) } } /// @dev Returns `x % y`, returning 0 if `y` is zero. function rawMod(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := mod(x, y) } } /// @dev Returns `x % y`, returning 0 if `y` is zero. function rawSMod(int256 x, int256 y) internal pure returns (int256 z) { /// @solidity memory-safe-assembly assembly { z := smod(x, y) } } /// @dev Returns `(x + y) % d`, return 0 if `d` if zero. function rawAddMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := addmod(x, y, d) } } /// @dev Returns `(x * y) % d`, return 0 if `d` if zero. function rawMulMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := mulmod(x, y, d) } } }
{ "evmVersion": "paris", "libraries": {}, "metadata": { "bytecodeHash": "ipfs", "useLiteralContent": true }, "optimizer": { "enabled": true, "runs": 50 }, "remappings": [], "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } } }
Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
Contract ABI
API[{"inputs":[{"internalType":"address","name":"protocolGovernor_","type":"address"},{"components":[{"internalType":"address","name":"juiceAccount","type":"address"},{"internalType":"address","name":"blastPointsOperator","type":"address"},{"internalType":"bool","name":"isAutoCompounding","type":"bool"},{"internalType":"address","name":"liquidationReceiver","type":"address"},{"internalType":"address","name":"weth","type":"address"},{"internalType":"UD60x18","name":"maxLtv","type":"uint256"},{"internalType":"UD60x18","name":"liquidationThreshold","type":"uint256"},{"internalType":"string","name":"name","type":"string"},{"internalType":"string","name":"symbol","type":"string"},{"internalType":"uint8","name":"decimals","type":"uint8"}],"internalType":"struct JuiceAccountManager.InitParams","name":"params","type":"tuple"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"AccountBeingLiquidated","type":"error"},{"inputs":[],"name":"AccountHealthy","type":"error"},{"inputs":[],"name":"AccountInsolvent","type":"error"},{"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"AddressEmptyCode","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"AddressInsufficientBalance","type":"error"},{"inputs":[],"name":"AllowanceOverflow","type":"error"},{"inputs":[],"name":"AllowanceUnderflow","type":"error"},{"inputs":[],"name":"ContractDoesNotExist","type":"error"},{"inputs":[],"name":"ERC1167FailedCreateClone","type":"error"},{"inputs":[],"name":"FailedInnerCall","type":"error"},{"inputs":[],"name":"InsufficientAllowance","type":"error"},{"inputs":[],"name":"InsufficientBalance","type":"error"},{"inputs":[],"name":"InvalidParams","type":"error"},{"inputs":[],"name":"InvalidPermit","type":"error"},{"inputs":[],"name":"NotClaimableProfit","type":"error"},{"inputs":[{"internalType":"uint256","name":"x","type":"uint256"},{"internalType":"uint256","name":"y","type":"uint256"}],"name":"PRBMath_MulDiv18_Overflow","type":"error"},{"inputs":[{"internalType":"uint256","name":"x","type":"uint256"},{"internalType":"uint256","name":"y","type":"uint256"},{"internalType":"uint256","name":"denominator","type":"uint256"}],"name":"PRBMath_MulDiv_Overflow","type":"error"},{"inputs":[],"name":"PermitExpired","type":"error"},{"inputs":[],"name":"ReentrancyGuardReentrantCall","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"inputs":[],"name":"StrategyNotApproved","type":"error"},{"inputs":[],"name":"TotalSupplyOverflow","type":"error"},{"inputs":[],"name":"TransferDisabled","type":"error"},{"inputs":[],"name":"Unauthorized","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"string","name":"role","type":"string"}],"name":"UnauthorizedRole","type":"error"},{"inputs":[],"name":"ZeroAddress","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"AccountBorrowed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"AccountClaimed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"AccountCreated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","type":"address"}],"name":"AccountLiquidationCompleted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","type":"address"}],"name":"AccountLiquidationStarted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"AccountRepaid","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":false,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"CollateralDeposit","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"uint256","name":"collateralAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"bonusCollateral","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"debtAmountNeeded","type":"uint256"}],"name":"CollateralLiquidation","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":false,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"CollateralWithdrawal","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"FeesCharged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"gasClaimed","type":"uint256"}],"name":"GasRefundClaimed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"feeCollector","type":"address"},{"indexed":true,"internalType":"address","name":"liquidator","type":"address"},{"indexed":false,"internalType":"uint256","name":"protocolShare","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"liquidatorShare","type":"uint256"}],"name":"LiquidationFeesTaken","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"liquidationFeeTo","type":"address"},{"indexed":false,"internalType":"address","name":"liquidationReceiver","type":"address"}],"name":"LiquidationReceiverCreated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"UD60x18","name":"tolerance","type":"uint256"}],"name":"MaximumSlippageToleranceUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"operator","type":"address"}],"name":"PointsOperatorConfigured","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"strategy","type":"address"}],"name":"StrategyActivated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"strategy","type":"address"}],"name":"StrategyDeactivated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"strategy","type":"address"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"StrategyDeposit","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"strategy","type":"address"},{"indexed":false,"internalType":"bool","name":"approval","type":"bool"}],"name":"StrategyUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"strategy","type":"address"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"StrategyWithdrawal","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"YieldAccrued","type":"event"},{"inputs":[],"name":"DOMAIN_SEPARATOR","outputs":[{"internalType":"bytes32","name":"result","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"LIQUIDATION_BONUS","outputs":[{"internalType":"UD60x18","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MINIMUM_COMPOUND_AMOUNT","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"uint256","name":"borrowed","type":"uint256"}],"name":"_afterBorrow","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"_afterLiquidationCompleted","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"_afterLiquidationStarted","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"uint256","name":"","type":"uint256"}],"name":"_afterRepay","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"_completeLiquidation","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"accountOwner","type":"address"},{"internalType":"uint256","name":"debtAmount","type":"uint256"},{"internalType":"uint256","name":"debtToCover","type":"uint256"}],"name":"_simulateCollateralLiquidation","outputs":[{"components":[{"internalType":"uint256","name":"actualDebtToLiquidate","type":"uint256"},{"internalType":"uint256","name":"collateralAmount","type":"uint256"},{"internalType":"uint256","name":"bonusCollateral","type":"uint256"}],"internalType":"struct AccountLib.CollateralLiquidation","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"accountCount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"result","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"approvedStrategies","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"result","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOfAssets","outputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"bytes[]","name":"pythPriceUpdates","type":"bytes[]"}],"name":"borrow","outputs":[{"internalType":"uint256","name":"borrowed","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"borrow","outputs":[{"internalType":"uint256","name":"borrowed","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"}],"name":"claim","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"claimMaxGas","outputs":[{"internalType":"uint256","name":"gasClaimed","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"compound","outputs":[{"internalType":"uint256","name":"earned","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"createAccount","outputs":[{"internalType":"address payable","name":"account","type":"address"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"}],"name":"deposit","outputs":[{"internalType":"uint256","name":"updatedAssets","type":"uint256"},{"internalType":"uint256","name":"shares","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"feeCollector_","type":"address"},{"internalType":"address","name":"liquidationFeeTo","type":"address"},{"internalType":"uint256","name":"protocolShare","type":"uint256"},{"internalType":"uint256","name":"liquidatorShare","type":"uint256"}],"name":"emitLiquidationFeeEvent","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner_","type":"address"}],"name":"getAccount","outputs":[{"internalType":"address","name":"account","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"getAccountHealth","outputs":[{"components":[{"internalType":"uint256","name":"debtAmount","type":"uint256"},{"internalType":"uint256","name":"collateralValue","type":"uint256"},{"internalType":"uint256","name":"investmentValue","type":"uint256"},{"internalType":"bool","name":"isLiquidatable","type":"bool"},{"internalType":"bool","name":"hasBadDebt","type":"bool"}],"internalType":"struct AccountLib.Health","name":"health","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"getAccountLiquidationSlippageTolerance","outputs":[{"internalType":"UD60x18","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"getAccountLiquidationStatus","outputs":[{"components":[{"internalType":"bool","name":"isLiquidating","type":"bool"},{"internalType":"uint256","name":"liquidationStartTime","type":"uint256"}],"internalType":"struct AccountLib.LiquidationStatus","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"getAccountLoan","outputs":[{"components":[{"internalType":"uint256","name":"debtAmount","type":"uint256"},{"internalType":"uint256","name":"collateralValue","type":"uint256"},{"internalType":"UD60x18","name":"ltv","type":"uint256"},{"internalType":"UD60x18","name":"maxLtv","type":"uint256"}],"internalType":"struct AccountLib.Loan","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"uint256","name":"index","type":"uint256"}],"name":"getActiveStrategy","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"getActiveStrategyCount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"getDebtAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getFeeCollector","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getLendAsset","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getLiquidationFee","outputs":[{"components":[{"internalType":"UD60x18","name":"protocolShare","type":"uint256"},{"internalType":"UD60x18","name":"liquidatorShare","type":"uint256"}],"internalType":"struct AccountLib.LiquidationFee","name":"fee","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"address","name":"liquidationFeeTo","type":"address"}],"name":"getLiquidationReceiver","outputs":[{"internalType":"contract ILiquidationReceiver","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getProtocolGovernor","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"getTotalAccountValue","outputs":[{"internalType":"uint256","name":"totalValue","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"getTotalCollateralValue","outputs":[{"internalType":"uint256","name":"totalValue","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"strategy","type":"address"}],"name":"isApprovedStrategy","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"isAutoCompounding","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"isCreatedAccount","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"receiver","type":"address"}],"name":"isLiquidationReceiver","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"juiceAccountImplementation","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lendingPool","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"address","name":"liquidationFeeTo","type":"address"}],"name":"liquidate","outputs":[{"internalType":"contract ILiquidationReceiver","name":"liquidationReceiver_","type":"address"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"uint256","name":"debtToCover","type":"uint256"},{"internalType":"address","name":"liquidationFeeTo","type":"address"}],"name":"liquidateCollateral","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"address","name":"liquidationFeeTo","type":"address"},{"internalType":"address","name":"strategy","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"liquidateStrategy","outputs":[{"internalType":"contract ILiquidationReceiver","name":"liquidationReceiver_","type":"address"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"}],"name":"liquidationReceiver","outputs":[{"internalType":"contract ILiquidationReceiver","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"liquidationThreshold","outputs":[{"internalType":"UD60x18","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxLtv","outputs":[{"internalType":"UD60x18","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"nonces","outputs":[{"internalType":"uint256","name":"result","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"pauseAccount","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"permit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"name":"previewDeposit","outputs":[{"internalType":"uint256","name":"updatedAssets","type":"uint256"},{"internalType":"uint256","name":"shares","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"name":"previewWithdraw","outputs":[{"internalType":"uint256","name":"assets","type":"uint256"},{"internalType":"uint256","name":"updatedShares","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"repay","outputs":[{"internalType":"uint256","name":"repaid","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"uint256","name":"debtToCover","type":"uint256"}],"name":"simulateCollateralLiquidation","outputs":[{"components":[{"internalType":"uint256","name":"actualDebtToLiquidate","type":"uint256"},{"internalType":"uint256","name":"collateralAmount","type":"uint256"},{"internalType":"uint256","name":"bonusCollateral","type":"uint256"}],"internalType":"struct AccountLib.CollateralLiquidation","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"strategy","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"strategyDeposit","outputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"strategy","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"},{"internalType":"bytes[]","name":"pythPriceUpdates","type":"bytes[]"}],"name":"strategyDeposit","outputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"strategy","type":"address"},{"internalType":"uint256","name":"assets","type":"uint256"},{"internalType":"bytes[]","name":"pythPriceUpdates","type":"bytes[]"}],"name":"strategyWithdrawal","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"strategy","type":"address"},{"internalType":"uint256","name":"assets","type":"uint256"}],"name":"strategyWithdrawal","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"toggleAutoCompounding","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"totalAssets","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"result","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"unpauseAccount","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"UD60x18","name":"maxLtv_","type":"uint256"},{"internalType":"UD60x18","name":"liquidationThreshold_","type":"uint256"}],"name":"updateLiquidationParameters","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes[]","name":"updateData","type":"bytes[]"}],"name":"updatePythPriceFeeds","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"strategy","type":"address"},{"internalType":"bool","name":"approval","type":"bool"}],"name":"updateStrategyApproval","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"}],"name":"withdraw","outputs":[{"internalType":"uint256","name":"updatedAssets","type":"uint256"},{"internalType":"uint256","name":"updatedShares","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"},{"internalType":"bytes[]","name":"pythPriceUpdates","type":"bytes[]"}],"name":"withdraw","outputs":[{"internalType":"uint256","name":"updatedAssets","type":"uint256"},{"internalType":"uint256","name":"updatedShares","type":"uint256"}],"stateMutability":"payable","type":"function"}]
Contract Creation Code
610180604052620f4240600f553480156200001957600080fd5b506040516200601b3803806200601b8339810160408190526200003c91620009f7565b602081015160808083015160e084015161010085015161012086015160608701516001600160a01b038916909552600160005587959486949392919085908190819081816200008a62000716565b6001600160a01b038116620000b25760405163d92e233d60e01b815260040160405180910390fd5b6001600160a01b0381163b620000db57604051630b0f2dd560e31b815260040160405180910390fd5b620000e5620007da565b6001600160a01b0381166200010d5760405163d92e233d60e01b815260040160405180910390fd5b6001600160a01b0381163b6200013657604051630b0f2dd560e31b815260040160405180910390fd5b6001600160a01b03831660e0526200014d620007da565b6001600160a01b031660a052620001636200081e565b6001600160a01b031660c05250600092506200018191505062000860565b6001600160a01b031603620002025760405162461bcd60e51b815260206004820152603660248201527f53747261746567794163636f756e744d616e616765723a20736c69707061676560448201527f206d6f64656c206973207a65726f206164647265737300000000000000000000606482015260840160405180910390fd5b5050806001600160a01b031663c824e1576040516020016200023c906020808252600490820152630a0b2a8960e31b604082015260600190565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b81526004016200027191815260200190565b602060405180830381865afa1580156200028f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620002b5919062000b34565b6001600160a01b03908116610100528291508116620002e75760405163d92e233d60e01b815260040160405180910390fd5b6001600160a01b0381163b6200031057604051630b0f2dd560e31b815260040160405180910390fd5b50600980546001600160a01b0319166001600160a01b03928316179055849081166200034f5760405163d92e233d60e01b815260040160405180910390fd5b6001600160a01b0381163b6200037857604051630b0f2dd560e31b815260040160405180910390fd5b6001600160a01b0385166101205260ff821661014052600b6200039c858262000bea565b50600c620003ab848262000bea565b5050600d80546001600160a01b0387166001600160a01b031990911681179091556040516000955090935063c824e157925062000405915060200160208082526005908201526410931054d560da1b604082015260600190565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b81526004016200043a91815260200190565b602060405180830381865afa15801562000458573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906200047e919062000b34565b9050806001600160a01b0316634e606c476040518163ffffffff1660e01b8152600401600060405180830381600087803b158015620004bc57600080fd5b505af1158015620004d1573d6000803e3d6000fd5b5050600e80546001600160a01b0388166001600160a01b031990911681179091556040516000955090935063c824e15792506200053291506020016020808252600c908201526b424c4153545f504f494e545360a01b604082015260600190565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b81526004016200056791815260200190565b602060405180830381865afa15801562000585573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620005ab919062000b34565b6040516336b91f2b60e01b81526001600160a01b038481166004830152919250908216906336b91f2b90602401600060405180830381600087803b158015620005f357600080fd5b505af115801562000608573d6000803e3d6000fd5b505085519450506001600160a01b03841692506200063c9150505760405163d92e233d60e01b815260040160405180910390fd5b6001600160a01b0381163b6200066557604051630b0f2dd560e31b815260040160405180910390fd5b81516001600160a01b039081166101605260a083015160105560c08301516011556080830151604051631a33757d60e01b8152911690631a33757d90620006b29060029060040162000cb6565b6020604051808303816000875af1158015620006d2573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620006f8919062000cdf565b5050604001516013805460ff19169115159190911790555062000cf9565b60006080516001600160a01b03166321f8a7216040516020016200075c906020808252600e908201526d282924a1a2afa82927ab24a222a960911b604082015260600190565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b81526004016200079191815260200190565b602060405180830381865afa158015620007af573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620007d5919062000b34565b905090565b60006080516001600160a01b031663c824e1576040516020016200075c906020808252600c908201526b13115391125391d7d413d3d360a21b604082015260600190565b60006080516001600160a01b031663c824e1576040516020016200075c906020808252600a90820152691311539117d054d4d15560b21b604082015260600190565b60006080516001600160a01b03166321f8a7216040516020016200075c9060208082526017908201527f53545241544547595f534c4950504147455f4d4f44454c000000000000000000604082015260600190565b80516001600160a01b0381168114620008cd57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60405161014081016001600160401b03811182821017156200090e576200090e620008d2565b60405290565b604051601f8201601f191681016001600160401b03811182821017156200093f576200093f620008d2565b604052919050565b80518015158114620008cd57600080fd5b600082601f8301126200096a57600080fd5b81516001600160401b03811115620009865762000986620008d2565b60206200099c601f8301601f1916820162000914565b8281528582848701011115620009b157600080fd5b60005b83811015620009d1578581018301518282018401528201620009b4565b506000928101909101919091529392505050565b805160ff81168114620008cd57600080fd5b6000806040838503121562000a0b57600080fd5b62000a1683620008b5565b60208401519092506001600160401b038082111562000a3457600080fd5b90840190610140828703121562000a4a57600080fd5b62000a54620008e8565b62000a5f83620008b5565b815262000a6f60208401620008b5565b602082015262000a826040840162000947565b604082015262000a9560608401620008b5565b606082015262000aa860808401620008b5565b608082015260a083015160a082015260c083015160c082015260e08301518281111562000ad457600080fd5b62000ae28882860162000958565b60e083015250610100808401518381111562000afd57600080fd5b62000b0b8982870162000958565b828401525050610120915062000b23828401620009e5565b828201528093505050509250929050565b60006020828403121562000b4757600080fd5b62000b5282620008b5565b9392505050565b600181811c9082168062000b6e57607f821691505b60208210810362000b8f57634e487b7160e01b600052602260045260246000fd5b50919050565b601f82111562000be5576000816000526020600020601f850160051c8101602086101562000bc05750805b601f850160051c820191505b8181101562000be15782815560010162000bcc565b5050505b505050565b81516001600160401b0381111562000c065762000c06620008d2565b62000c1e8162000c17845462000b59565b8462000b95565b602080601f83116001811462000c56576000841562000c3d5750858301515b600019600386901b1c1916600185901b17855562000be1565b600085815260208120601f198616915b8281101562000c875788860151825594840194600190910190840162000c66565b508582101562000ca65787850151600019600388901b60f8161c191681555b5050505050600190811b01905550565b602081016003831062000cd957634e487b7160e01b600052602160045260246000fd5b91905290565b60006020828403121562000cf257600080fd5b5051919050565b60805160a05160c05160e051610100516101205161014051610160516151ea62000e3160003960008181610b1a01528181611c540152612e970152600081816105e801526118d7015260008181610edc0152818161185401528181612abc01528181612b7501528181613b7901528181613ef6015281816140a90152614207015260008181610f850152610fff01526000818161174001526137a801526000818161109b01528181612802015281816128a501528181612d89015281816138090152818161395b015281816139de0152613a73015260008181610a89015281816113de01528181611dc801528181611e8f01526132c10152600081816108f80152818161303e015281816130d9015281816133f501528181613d2301528181613da001528181613f21015261400501526151ea6000f3fe6080604052600436106103bb5760003560e01c80639159b206116101f4578063c62e8d3a1161010e578063e4af29fc116100a6578063e4af29fc14610cec578063e59e801814610d02578063ef48644614610d68578063ef8b30f714610d88578063f2468d8714610da8578063f69e204614610dc8578063f9566d8214610ddd578063fbcbc0f114610dfd578063fbf4198414610e1d578063ffc5ab1614610e4d57600080fd5b8063c62e8d3a14610be9578063ca8bcd6614610876578063d505accf14610bfc578063d610dc2a14610c1c578063d8cab31814610c3c578063dd62ed3e14610c56578063dd76401714610c8c578063ddd5e1b214610cac578063e1d5c06414610ccc57600080fd5b8063a612ce2b1161018c578063a612ce2b14610aad578063a8e8f9eb14610acd578063a9059cbb14610aed578063b0cb805514610b08578063b17e32f914610b3c578063b2b8c93f14610b51578063b3c0a0b314610b66578063bacd4c2814610b79578063c5ebeaec14610b99578063c613aec014610bb957600080fd5b80639159b2061461093c57806394408b9a1461095c57806395d89b411461097c578063971d6c9514610991578063985d28aa146109b157806399f8148e146109ea5780639d919c6314610a235780639dca362f14610a65578063a59a997314610a7a57600080fd5b80634031234c116102e55780636c648fc41161027d5780636c648fc4146107dd5780636e553f65146107fd57806370a082311461081d578063713fa6de146108505780637af0bdfd146108635780637b91c265146108765780637ecebe001461089657806386b9d81f146108c957806389dbb857146108e957806390401a7a1461091c57600080fd5b80634031234c14610659578063410051a51461066f57806347a873cb146106c257806347e41a89146106e2578063484d1ad61461075f5780635a287cb21461077f57806363b527f01461079f5780636856728e146107b25780636a11d0b2146107c757600080fd5b80631534a277116103585780631534a2771461051657806318160ddd146105575780631e8a84b11461057457806322867d781461059457806323b872dd146105b4578063313ce567146105d45780633574d4c4146106125780633644e5151461062e5780633a12c6da1461064357600080fd5b8062f714ce146103c057806301e1d114146103fa578063032e9c761461041d5780630674fa411461043257806306fdde03146104525780630914b18f14610474578063095ea7b3146104b45780630a28a477146104d457806312fde4b7146104f4575b600080fd5b3480156103cc57600080fd5b506103e06103db36600461472e565b610e60565b604080519283526020830191909152015b60405180910390f35b34801561040657600080fd5b5061040f610ec2565b6040519081526020016103f1565b61043061042b3660046148b1565b610f64565b005b34801561043e57600080fd5b5061040f61044d3660046148e5565b611081565b34801561045e57600080fd5b506104676111e6565b6040516103f19190614952565b34801561048057600080fd5b506104a461048f3660046148e5565b60016020526000908152604090205460ff1681565b60405190151581526020016103f1565b3480156104c057600080fd5b506104a46104cf366004614965565b611278565b3480156104e057600080fd5b506103e06104ef366004614991565b6112cc565b34801561050057600080fd5b506105096112de565b6040516103f191906149aa565b34801561052257600080fd5b506105096105313660046149be565b60046020908152600092835260408084209091529082529020546001600160a01b031681565b34801561056357600080fd5b506805345cdf77eb68f44c5461040f565b34801561058057600080fd5b5061043061058f3660046149fa565b6112e8565b3480156105a057600080fd5b5061040f6105af366004614965565b6113a8565b3480156105c057600080fd5b506104a46105cf366004614a28565b611502565b3480156105e057600080fd5b5060405160ff7f00000000000000000000000000000000000000000000000000000000000000001681526020016103f1565b34801561061e57600080fd5b5061040f670e92596fd629000081565b34801561063a57600080fd5b5061040f61151d565b34801561064f57600080fd5b5061040f60105481565b34801561066557600080fd5b5061040f60115481565b34801561067b57600080fd5b5061068f61068a3660046148e5565b61159a565b6040516103f191908151815260208083015190820152604080830151908201526060918201519181019190915260800190565b3480156106ce57600080fd5b506104306106dd366004614965565b611627565b3480156106ee57600080fd5b506107426106fd3660046148e5565b60408051808201825260008082526020918201819052825180840184526001600160a01b03949094168082526003808452938220548015158652915291815282015290565b6040805182511515815260209283015192810192909252016103f1565b34801561076b57600080fd5b5061043061077a3660046148e5565b6116c7565b34801561078b57600080fd5b5061050961079a3660046149be565b611739565b61040f6107ad366004614a69565b611794565b3480156107be57600080fd5b506104306117ea565b3480156107d357600080fd5b5061040f600f5481565b3480156107e957600080fd5b5061040f6107f83660046148e5565b611811565b34801561080957600080fd5b506103e061081836600461472e565b61191a565b34801561082957600080fd5b5061040f6108383660046148e5565b6387a211a2600c908152600091909152602090205490565b61043061085e366004614aaf565b61199e565b61040f610871366004614b1a565b6119fa565b34801561088257600080fd5b506104306108913660046148e5565b611a52565b3480156108a257600080fd5b5061040f6108b13660046148e5565b6338377508600c908152600091909152602090205490565b3480156108d557600080fd5b506105096108e43660046149be565b611a74565b3480156108f557600080fd5b507f0000000000000000000000000000000000000000000000000000000000000000610509565b34801561092857600080fd5b50610509610937366004614965565b611a80565b34801561094857600080fd5b5061040f6109573660046148e5565b611aa2565b34801561096857600080fd5b506104306109773660046148e5565b611ac0565b34801561098857600080fd5b50610467611b0e565b34801561099d57600080fd5b506104306109ac366004614b79565b611b1d565b3480156109bd57600080fd5b506104a46109cc3660046148e5565b6001600160a01b031660009081526007602052604090205460ff1690565b3480156109f657600080fd5b506104a4610a053660046148e5565b6001600160a01b031660009081526005602052604090205460ff1690565b348015610a2f57600080fd5b50610a43610a3e366004614bbf565b611ba8565b60408051825181526020808401519082015291810151908201526060016103f1565b348015610a7157600080fd5b50610509611c14565b348015610a8657600080fd5b507f0000000000000000000000000000000000000000000000000000000000000000610509565b348015610ab957600080fd5b5061040f610ac83660046148e5565b611dae565b348015610ad957600080fd5b50610430610ae8366004614a28565b611e3e565b348015610af957600080fd5b506104a46105cf366004614965565b348015610b1457600080fd5b506105097f000000000000000000000000000000000000000000000000000000000000000081565b348015610b4857600080fd5b50610509611e8b565b348015610b5d57600080fd5b5061040f611f0f565b610509610b74366004614bf4565b612124565b348015610b8557600080fd5b5061040f610b943660046148e5565b6123a2565b348015610ba557600080fd5b5061040f610bb4366004614991565b612438565b348015610bc557600080fd5b506104a4610bd43660046148e5565b60076020526000908152604090205460ff1681565b61040f610bf7366004614c50565b61248a565b348015610c0857600080fd5b50610430610c17366004614ce2565b6124e3565b348015610c2857600080fd5b50610430610c37366004614d59565b61266c565b348015610c4857600080fd5b506013546104a49060ff1681565b348015610c6257600080fd5b5061040f610c713660046149be565b602052637f5e9f20600c908152600091909152603490205490565b348015610c9857600080fd5b50610430610ca73660046148e5565b6126ab565b348015610cb857600080fd5b50610430610cc736600461472e565b61274b565b348015610cd857600080fd5b5061040f610ce73660046148e5565b612927565b348015610cf857600080fd5b5061040f60065481565b348015610d0e57600080fd5b50610d22610d1d3660046148e5565b612948565b6040516103f19190600060a08201905082518252602083015160208301526040830151604083015260608301511515606083015260808301511515608083015292915050565b348015610d7457600080fd5b50610430610d83366004614965565b612a2a565b348015610d9457600080fd5b506103e0610da3366004614991565b612a50565b348015610db457600080fd5b50610a43610dc3366004614965565b612a6e565b348015610dd457600080fd5b5061040f612aaa565b348015610de957600080fd5b50610430610df8366004614d7b565b612c2f565b348015610e0957600080fd5b50610509610e183660046148e5565b612e72565b348015610e2957600080fd5b50610e32612ec4565b604080518251815260209283015192810192909252016103f1565b6103e0610e5b366004614dbd565b612ef2565b600080610e6b612f20565b610eac3384866000604051908082528060200260200182016040528015610ea657816020015b6060815260200190600190039081610e915790505b50612f4a565b9092509050610ebb6001600055565b9250929050565b60405163e12f3a6160e01b81526000906001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063e12f3a6190610f119030906004016149aa565b602060405180830381865afa158015610f2e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f529190614e15565b600a54610f5f9190614e44565b905090565b80511561107e5760405163d47eed4560e01b81526000906001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063d47eed4590610fba908590600401614e57565b602060405180830381865afa158015610fd7573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ffb9190614e15565b90507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663ef9e5e2882846040518363ffffffff1660e01b815260040161104a9190614e57565b6000604051808303818588803b15801561106357600080fd5b505af1158015611077573d6000803e3d6000fd5b5050505050505b50565b6040516370a0823160e01b81526000906001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906370a08231906110d09085906004016149aa565b602060405180830381865afa1580156110ed573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111119190614e15565b905060005b6001600160a01b038316600090815260086020526040902061113790612fe0565b8110156111e0576001600160a01b03831660009081526008602052604090206111609082612fea565b6001600160a01b0316631c083f6a846040518263ffffffff1660e01b815260040161118b91906149aa565b602060405180830381865afa1580156111a8573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111cc9190614e15565b6111d69083614e44565b9150600101611116565b50919050565b6060600b80546111f590614ebb565b80601f016020809104026020016040519081016040528092919081815260200182805461122190614ebb565b801561126e5780601f106112435761010080835404028352916020019161126e565b820191906000526020600020905b81548152906001019060200180831161125157829003601f168201915b5050505050905090565b600082602052637f5e9f20600c5233600052816034600c205581600052602c5160601c337f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92560206000a35060015b92915050565b6000806112d883612ff6565b93915050565b6000610f5f61303a565b6112f1336130cb565b61134557335b60408051637974da6f60e01b81526001600160a01b0390921660048301526024820152600e60448201526d282927aa27a1a7a62fa0a226a4a760911b60648201526084015b60405180910390fd5b6001600160a01b038216600081815260076020908152604091829020805460ff19168515159081179091558251938452908301527ffc2e7375e815d084de88de8e8e356e71102275019b06a1b529eee0c8ab57cd34910160405180910390a15050565b60006113b2612f20565b60405163c883b2e560e01b8152600481018390526001600160a01b0384811660248301523360448301527f0000000000000000000000000000000000000000000000000000000000000000169063c883b2e5906064016020604051808303816000875af1158015611427573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061144b9190614e15565b6001600160a01b0384811660008181526002602090815260409182902054915185815294955091939216917fa42e379bd7db0adade1690b7b2b3b81c2419c87c3c9f0c4f4f5a4da3ce8a8966910160405180910390a36040516347a873cb60e01b815230906347a873cb906114c69086908590600401614eef565b600060405180830381600087803b1580156114e057600080fd5b505af11580156114f4573d6000803e3d6000fd5b505050506112c66001600055565b600060405163a24e573d60e01b815260040160405180910390fd5b6000806115286111e6565b8051906020012090506040517f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f81528160208201527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6604082015246606082015230608082015260a081209250505090565b6115c56040518060800160405280600081526020016000815260200160008152602001600081525090565b60006115d083611811565b905060006115dd84611dae565b9050600082156115f6576115f383835b90613177565b90505b604051806080016040528083815260200184815260200182815260200161161c60105490565b905295945050505050565b3330146116495733604051637974da6f60e01b815260040161133c9190614f08565b600061165483612948565b6001600160a01b0384166000908152600360205260409020549091501580159061168057508060600151155b156116c25760405163dd76401760e01b8152309063dd764017906116a89086906004016149aa565b600060405180830381600087803b15801561106357600080fd5b505050565b6116d0336130cb565b6116da57336112f7565b6116e38161318f565b806001600160a01b0316638456cb596040518163ffffffff1660e01b8152600401600060405180830381600087803b15801561171e57600080fd5b505af1158015611732573d6000803e3d6000fd5b5050505050565b600061178d7f00000000000000000000000000000000000000000000000000000000000000008484604051602001611772929190614f38565b60405160208183030381529060405280519060200120613238565b9392505050565b3360009081526001602052604081205460ff166117c3576040516282b42960e81b815260040160405180910390fd5b6117cb612f20565b6117d482610f64565b6117de3384613298565b90506112c66001600055565b6117f3336130cb565b6117fd57336112f7565b6013805460ff19811660ff90911615179055565b6001600160a01b038082166000908152600260205260408120549091168161183882611aa2565b905060006118446133f1565b6001600160a01b031663b3596f077f00000000000000000000000000000000000000000000000000000000000000006040518263ffffffff1660e01b815260040161188f91906149aa565b602060405180830381865afa1580156118ac573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118d09190614e15565b90506118fd7f0000000000000000000000000000000000000000000000000000000000000000600a615036565b6119078284615045565b6119119190615072565b95945050505050565b600080611925612f20565b60135460ff161561193a57611938612aaa565b505b6119448484613454565b90925090506001600160a01b0383167f85a75ad7f484e83157db3f52d6bfcf613d65995bd6546c2ed0d55ee07a51170a61197d85612e72565b8660405161198c929190614eef565b60405180910390a2610ebb6001600055565b3360009081526001602052604090205460ff166119cd576040516282b42960e81b815260040160405180910390fd5b6119d5612f20565b6119de81610f64565b6119ea3385858561346d565b6119f46001600055565b50505050565b3360009081526001602052604081205460ff16611a29576040516282b42960e81b815260040160405180910390fd5b611a31612f20565b611a3e33868686866135c2565b9050611a4a6001600055565b949350505050565b33301461107e5733604051637974da6f60e01b815260040161133c9190614f08565b600061178d8383613744565b6001600160a01b038216600090815260086020526040812061178d9083612fea565b6387a211a2600c90815260008281526020909120546112c690612ff6565b611ac9336130cb565b611ad357336112f7565b806001600160a01b0316633f4ba83a6040518163ffffffff1660e01b8152600401600060405180830381600087803b15801561171e57600080fd5b6060600c80546111f590614ebb565b3360009081526005602052604090205460ff16611b4c576040516282b42960e81b815260040160405180910390fd5b826001600160a01b0316846001600160a01b03167fb15b5161080eeb6130c6088d7b1e8eceb1092d2a15836c769bd094d9a68c8c6b8484604051611b9a929190918252602082015260400190565b60405180910390a350505050565b611bb06146f8565b6000838311611bbf5782611bc1565b835b90506000611bce86611aa2565b90506000806000611bdf8585613b58565b92509250925084811015611bf1578094505b506040805160608101825294855260208501929092529083015250949350505050565b6000611c1e612f20565b3360008181526001602052604090205460ff1615611c4f57604051635435b28960e11b815260040160405180910390fd5b611c817f0000000000000000000000000000000000000000000000000000000000000000611c7c83613c6d565b613cb1565b6001600160a01b038082166000818152600160208181526040808420805460ff1916841790559487168084526012825285842080546001600160a01b0319908116871790915594845260029091529382208054909316909317909155600680549395509192611cf1908490614e44565b92505081905550806001600160a01b03167fac631f3001b55ea1509cf3d7e74898f85392a61a76e8149181ae1259622dabc883604051611d3191906149aa565b60405180910390a2816001600160a01b031663485cc95582611d51613d1f565b6040518363ffffffff1660e01b8152600401611d6e929190614f38565b600060405180830381600087803b158015611d8857600080fd5b505af1158015611d9c573d6000803e3d6000fd5b5050505050611dab6001600055565b90565b60405163a612ce2b60e01b81526000906001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063a612ce2b90611dfd9085906004016149aa565b602060405180830381865afa158015611e1a573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112c69190614e15565b3360009081526001602052604090205460ff16611e6d576040516282b42960e81b815260040160405180910390fd5b611e75612f20565b611e813384848461346d565b6116c26001600055565b60007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316635c222bad6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611eeb573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f5f9190615094565b600d5460405160009182916001600160a01b039091169063c824e15790611f529060200160208082526005908201526410931054d560da1b604082015260600190565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b8152600401611f8691815260200190565b602060405180830381865afa158015611fa3573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611fc79190615094565b600d546040519192506000916001600160a01b03909116906321f8a72190611ff1906020016150b1565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b815260040161202591815260200190565b602060405180830381865afa158015612042573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906120669190615094565b60405163662aa11d60e01b81529091506001600160a01b0383169063662aa11d906120979030908590600401614f38565b6020604051808303816000875af11580156120b6573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906120da9190614e15565b9250806001600160a01b03167f9c3c39d0eedd3d18612a0e8e76cc7bc873815d3e19206dbbf9825989b1c95e6b8460405161211791815260200190565b60405180910390a2505090565b60006121308585613744565b905060006001600160a01b0384161561223f576040516370a0823160e01b81526000906001600160a01b03861690630a28a4779082906370a082319061217a908c906004016149aa565b602060405180830381865afa158015612197573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906121bb9190614e15565b6040518263ffffffff1660e01b81526004016121d991815260200190565b602060405180830381865afa1580156121f6573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061221a9190614e15565b9050612231611dab8261222c8a6123a2565b613d78565b61223b90826150d8565b9150505b604051639035268760e01b81526001600160a01b038716906390352687903490612273908890879087908a906004016150eb565b6000604051808303818588803b15801561228c57600080fd5b505af11580156122a0573d6000803e3d6000fd5b50505050506001600160a01b038416158015906123275750604051630e041fb560e11b81526001600160a01b03851690631c083f6a906122e49089906004016149aa565b602060405180830381865afa158015612301573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906123259190614e15565b155b15612399576001600160a01b038616600090815260086020526040902061234e9085613d87565b506001600160a01b038681166000818152600260205260408082205490518489169491909116917f9910e38adb465481c843222dba5590cfcb99a51e28f2fc633b66289ef06ba4e291a45b50949350505050565b6001600160a01b038116600090815260036020526040812054428181039110026123ca613d9c565b6001600160a01b0316635628570c826040518263ffffffff1660e01b81526004016123f791815260200190565b602060405180830381865afa158015612414573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061178d9190614e15565b3360009081526001602052604081205460ff16612467576040516282b42960e81b815260040160405180910390fd5b61246f612f20565b6124793383613298565b90506124856001600055565b919050565b3360009081526001602052604081205460ff166124b9576040516282b42960e81b815260040160405180910390fd5b6124c1612f20565b6124ca82610f64565b6124d733878787876135c2565b90506119116001600055565b60006124ed6111e6565b8051906020012090508442111561250c57631a15a3cc6000526004601cfd5b6040518860601b60601c98508760601b60601c975065383775081901600e52886000526020600c2080547f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f83528360208401527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6604084015246606084015230608084015260a08320602e527f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c983528a60208401528960408401528860608401528060808401528760a084015260c08320604e526042602c206000528660ff1660205285604052846060526020806080600060015afa8b3d51146126185763ddafbaef6000526004601cfd5b0190556303faf4f960a51b88176040526034602c2087905587897f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925602060608501a360405250506000606052505050505050565b612675336130cb565b61267f57336112f7565b808210156126a057604051635435b28960e11b815260040160405180910390fd5b601091909155601155565b3330146126cd5733604051637974da6f60e01b815260040161133c9190614f08565b6001600160a01b038116600081815260036020526040808220829055517fccfc0aeacebc685763eb86a3e35dfeac830fd983f2f597b3f142ee667d28acc49190a2604051637b91c26560e01b81523090637b91c265906127319084906004016149aa565b600060405180830381600087803b15801561171e57600080fd5b806001600160a01b0381166127735760405163d92e233d60e01b815260040160405180910390fd5b3360009081526001602052604090205460ff166127a2576040516282b42960e81b815260040160405180910390fd5b6127aa612f20565b33600090815260036020526040902054156127d857604051635e3b451760e11b815260040160405180910390fd5b6127e133611dae565b15158061287a57506040516370a0823160e01b815283906001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906370a08231906128379033906004016149aa565b602060405180830381865afa158015612854573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906128789190614e15565b105b156128985760405163e44069c960e01b815260040160405180910390fd5b6128cd6001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016338486613e08565b336000818152600260209081526040918290205491518681526001600160a01b03909216917f01bfef2bf622406285ca1a4057a39432c0ba15e2069c29ae6098c22affdeaf45910160405180910390a36116c26001600055565b6001600160a01b03811660009081526008602052604081206112c690612fe0565b61297e6040518060a001604052806000815260200160008152602001600081526020016000151581526020016000151581525090565b600061298983611081565b9050600061299684611811565b905060006129a385611dae565b905060006129b18484614e44565b6040805160a0810182528481526020810186905290810186905260006060820181905260808201529550905081158015906129ec5750600081115b15612a1357612a07611dab601154612a018590565b90613d78565b81106060860152612a21565b8115612a2157600160808601525b50505050919050565b333014612a4c5733604051637974da6f60e01b815260040161133c9190614f08565b5050565b600080612a5c83613e6f565b9050612a6781612ff6565b9150915091565b612a766146f8565b6001600160a01b0380841660009081526002602052604081205490911690612a9d85611dae565b9050611911828286611ba8565b60405163e12f3a6160e01b81526000907f0000000000000000000000000000000000000000000000000000000000000000906001600160a01b0382169063e12f3a6190612afb9030906004016149aa565b602060405180830381865afa158015612b18573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612b3c9190614e15565b9150600f548210612c2b5781600a6000828254612b599190614e44565b9091555050604051635569f64b60e11b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063aad3ec9690612bac9030908690600401614eef565b6020604051808303816000875af1158015612bcb573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612bef9190614e15565b91507f3b6bc0ba304eaa17cdca1b053baac859e721c7a775cddefc825f6286641311fc82604051612c2291815260200190565b60405180910390a15b5090565b6000612c3a84612948565b90508060600151612c5e57604051636caa790760e01b815260040160405180910390fd5b6001600160a01b0384166000908152600360205260408120549003612d14576001600160a01b038416600081815260036020526040808220429055517fdcd8b95bdfd2ffcc332acd69f71c9319a5a1006ca18c94d83d854e591cb6e0439190a2604051636545e6b360e11b8152309063ca8bcd6690612ce19087906004016149aa565b600060405180830381600087803b158015612cfb57600080fd5b505af1158015612d0f573d6000803e3d6000fd5b505050505b6001600160a01b0380851660009081526002602052604081205490911690612d3b86611dae565b90506000612d4a838388611ba8565b9050612d6a833383604001518460200151612d6591906150d8565b613e9f565b612d7983868360400151613e9f565b8051612db3906001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169033908a90613e08565b8051604051631b8fec7360e11b815260048101919091526001600160a01b0388169063371fd8e690602401600060405180830381600087803b158015612df857600080fd5b505af1158015612e0c573d6000803e3d6000fd5b505050602080830151604080850151855182516001600160a01b038e168152948501939093529083015260608201527fe32ec3ea3154879f27d5367898ab3a5ac6b68bf921d7cc610720f417c5cb243c915060800160405180910390a150505050505050565b6001600160a01b038082166000908152601260205260409020541680612485576112c67f0000000000000000000000000000000000000000000000000000000000000000612ebf84613c6d565b613238565b6040805180820190915260008082526020820152612ee0613f1d565b8152612eea614001565b602082015290565b600080612efd612f20565b612f0933858786612f4a565b9092509050612f186001600055565b935093915050565b600260005403612f4357604051633ee5aeb560e01b815260040160405180910390fd5b6002600055565b601354600090819060ff1615612f6457612f62612aaa565b505b612f6f868686614066565b90925090506000612f7f87612e72565b9050612f8a84610f64565b612f938161318f565b866001600160a01b03167f2514892efd9b8bb8666eb8f78a0f6dc59add738ad886bd36912de7b811e0c9808785604051612fce929190614eef565b60405180910390a25094509492505050565b60006112c6825490565b600061178d83836140d0565b60006130096805345cdf77eb68f44c5490565b15612c2b576805345cdf77eb68f44c54613021610ec2565b61302b9084615045565b6130359190615072565b6112c6565b60007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166321f8a72160405160200161307a906150b1565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b81526004016130ae91815260200190565b602060405180830381865afa158015611eeb573d6000803e3d6000fd5b6000816001600160a01b03167f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663893d20e86040518163ffffffff1660e01b8152600401602060405180830381865afa158015613135573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906131599190615094565b6001600160a01b03161461316f57506000919050565b506001919050565b600061178d611dab84670de0b6b3a7640000856140fa565b6001600160a01b038116600090815260036020526040902054156131c657604051635e3b451760e11b815260040160405180910390fd5b60006131d182612948565b905060006131ee611dab6131e460105490565b6020850151612a01565b90508082600001511115613215576040516334b3313560e11b815260040160405180910390fd5b8160600151156116c2576040516334b3313560e11b815260040160405180910390fd5b6040513060388201526f5af43d82803e903d91602b57fd5bf3ff602482015260148101839052733d602d80600a3d3981f3363d3d373d3d3d363d738152605881018290526037600c8201206078820152605560439091012060009061178d565b604051630967fa2960e31b8152600481018290526001600160a01b0383811660248301526000917f000000000000000000000000000000000000000000000000000000000000000090911690634b3fd148906044016020604051808303816000875af115801561330c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906133309190614e15565b905061333b8361318f565b6001600160a01b0380841660008181526002602052604090819020549051919216907f44dd1331990f12a8382e7da57756538a810f52fa13c1bb0d0ca6b14225be6d339061338c9085815260200190565b60405180910390a36040516377a4322360e11b8152309063ef486446906133b99086908590600401614eef565b600060405180830381600087803b1580156133d357600080fd5b505af11580156133e7573d6000803e3d6000fd5b5050505092915050565b60007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166321f8a72160405160200161307a906020808252600e908201526d282924a1a2afa82927ab24a222a960911b604082015260600190565b6000806134623384866141ce565b909590945092505050565b836001600160a01b0316826001600160a01b0316846001600160a01b03167f44afc4b038b803a70a242636bdd48bded871bf13df04e3613998f5ef1915ca8b846040516134bc91815260200190565b60405180910390a46001600160a01b038216158015906135465750604051630e041fb560e11b81526001600160a01b03831690631c083f6a906135039087906004016149aa565b602060405180830381865afa158015613520573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906135449190614e15565b155b156135b9576001600160a01b038416600090815260086020526040902061356d9083613d87565b50816001600160a01b0316846001600160a01b0316846001600160a01b03167f9910e38adb465481c843222dba5590cfcb99a51e28f2fc633b66289ef06ba4e260405160405180910390a45b6119f48461318f565b6001600160a01b03831660009081526007602052604081205460ff166135fb57604051631a22ce4f60e11b815260040160405180910390fd5b6001600160a01b038616600090815260086020526040902061361d9085614239565b1561366d57836001600160a01b0316866001600160a01b0316866001600160a01b03167ff6fa2840bdce616f9e9bbe7d65ca8bcca0532f1c4aa348c65c79c2cbf6ebf1f960405160405180910390a45b604051634b18bb2360e11b81526001600160a01b03851690639631764690349061369f90879087908c9060040161511e565b60206040518083038185885af11580156136bd573d6000803e3d6000fd5b50505050506040513d601f19601f820116820180604052508101906136e29190614e15565b9050856001600160a01b0316846001600160a01b0316866001600160a01b03167fcc3d99ef3608eafdfce86498089694111f40a0dd5b2841cba24bf2dfde1cc16c8660405161373391815260200190565b60405180910390a46119118661318f565b60008061375084612948565b9050806060015161377457604051636caa790760e01b815260040160405180910390fd5b6001600160a01b038085166000908152600460209081526040808320878516845290915290205416915081613941576137f57f000000000000000000000000000000000000000000000000000000000000000085856040516020016137da929190614f38565b60405160208183030381529060405280519060200120613cb1565b604080516080810182526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000811682523060208301908152888216838501908152888316606085019081529451630415cc1560e01b81529351831660048501529051821660248401525181166044830152915182166064820152919350831690630415cc1590608401600060405180830381600087803b15801561389f57600080fd5b505af11580156138b3573d6000803e3d6000fd5b505050506001600160a01b03848116600081815260046020908152604080832088861680855290835281842080546001600160a01b0319169689169687179055948352600590915290819020805460ff19166001179055517f39ee3b3ae7d535f7a027ce37245120586dd668f09e21538a7e0e8d7d5b3f1637906139389086906149aa565b60405180910390a35b6040516370a0823160e01b81526000906001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906370a08231906139909088906004016149aa565b602060405180830381865afa1580156139ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906139d19190614e15565b1115613a9b57613a9b84837f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166370a08231886040518263ffffffff1660e01b8152600401613a2891906149aa565b602060405180830381865afa158015613a45573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613a699190614e15565b6001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016929190613e08565b6001600160a01b0384166000908152600360205260408120549003613b51576001600160a01b038416600081815260036020526040808220429055517fdcd8b95bdfd2ffcc332acd69f71c9319a5a1006ca18c94d83d854e591cb6e0439190a2604051636545e6b360e11b8152309063ca8bcd6690613b1e9087906004016149aa565b600060405180830381600087803b158015613b3857600080fd5b505af1158015613b4c573d6000803e3d6000fd5b505050505b5092915050565b600080600080613bf5613b696133f1565b6001600160a01b031663b3596f077f00000000000000000000000000000000000000000000000000000000000000006040518263ffffffff1660e01b8152600401613bb491906149aa565b602060405180830381865afa158015613bd1573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611dab9190614e15565b90506000613c12611dab836115ed670e92596fd62900008b612a01565b905085811115613c3f57859450613c38611dab670e92596fd62900006115ed8589613d78565b9250613c46565b8094508692505b6000613c5283856115ed565b9050613c61611dab878361424e565b94505050509250925092565b6040516001600160601b0319606083811b8216602084015230901b166034820152600090604801604051602081830303815290604052805190602001209050919050565b6000763d602d80600a3d3981f3363d3d373d3d3d363d730000008360601b60e81c176000526e5af43d82803e903d91602b57fd5bf38360781b1760205281603760096000f590506001600160a01b0381166112c6576040516330be1a3d60e21b815260040160405180910390fd5b60007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663c824e15760405160200161307a906020808252600490820152630a0b2a8960e31b604082015260600190565b600061178d611dab848461425d565b600061178d836001600160a01b038416614313565b60007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166321f8a72160405160200161307a9060208082526017908201527614d51490551151d657d4d31254141051d157d353d11153604a1b604082015260600190565b6040516001600160a01b0384811660248301528381166044830152606482018390526119f49186918216906323b872dd906084015b604051602081830303815290604052915060e01b6020820180516001600160e01b038381831617835250505050614406565b6000613e826805345cdf77eb68f44c5490565b15612c2b57613e8f610ec2565b6805345cdf77eb68f44c54613021565b6000613ec5613eb56805345cdf77eb68f44c5490565b613ebd610ec2565b849190614460565b905081600a6000828254613ed991906150d8565b90915550613ee99050848261448f565b6119f46001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000168484614506565b60007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663e5f3d3a5604051602001613f8c906020808252601a908201527950524f544f434f4c5f4c49515549444154494f4e5f534841524560301b604082015260600190565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b8152600401613fc091815260200190565b602060405180830381865afa158015613fdd573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f5f9190614e15565b60007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663e5f3d3a5604051602001613f8c9060208082526010908201526f4c495155494441544f525f534841524560801b604082015260600190565b600080614072836112cc565b809250819350505081600a600082825461408c91906150d8565b9091555061409c9050858261448f565b612f186001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000168584614506565b60008260000182815481106140e7576140e761514f565b9060005260206000200154905092915050565b60008080600019858709858702925082811083820303915050806000036141345783828161412a5761412a61505c565b049250505061178d565b83811061416557604051630c740aef60e31b815260048101879052602481018690526044810185905260640161133c565b60008486880960026001871981018816978890046003810283188082028403028082028403028082028403028082028403028082028403029081029092039091026000889003889004909101858311909403939093029303949094049190911702949350505050565b6000806141da83612a50565b809250819350505081600a60008282546141f49190614e44565b9091555061422f90506001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016863085613e08565b612f18848261452c565b600061178d836001600160a01b0384166145ab565b600061178d611dab83856150d8565b60008080600019848609848602925082811083820303915050806000036142915750670de0b6b3a7640000900490506112c6565b670de0b6b3a764000081106142c357604051635173648d60e01b8152600481018690526024810185905260440161133c565b6000670de0b6b3a764000085870962040000818503049310909103600160ee1b02919091177faccb18165bd6fe31ae1cf318dc5b51eee0e1ba569b88cd74c1773b91fac106690291505092915050565b600081815260018301602052604081205480156143fc5760006143376001836150d8565b855490915060009061434b906001906150d8565b90508082146143b057600086600001828154811061436b5761436b61514f565b906000526020600020015490508087600001848154811061438e5761438e61514f565b6000918252602080832090910192909255918252600188019052604090208390555b85548690806143c1576143c1615165565b6001900381819060005260206000200160009055905585600101600086815260200190815260200160002060009055600193505050506112c6565b60009150506112c6565b600061441b6001600160a01b038416836145fa565b9050805160001415801561444057508080602001905181019061443e919061517b565b155b156116c25782604051635274afe760e01b815260040161133c91906149aa565b60008260001904841183021582026144805763ad251c276000526004601cfd5b50910281810615159190040190565b6387a211a2600c52816000526020600c208054808311156144b85763f4d678b86000526004601cfd5b82900390556805345cdf77eb68f44c8054829003905560008181526001600160a01b0383167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef602083a35050565b6116c283846001600160a01b031663a9059cbb8585604051602401613e3d929190614eef565b6805345cdf77eb68f44c54818101818110156145505763e5cfe9576000526004601cfd5b806805345cdf77eb68f44c5550506387a211a2600c52816000526020600c208181540181555080602052600c5160601c60007fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef602080a35050565b60008181526001830160205260408120546145f2575081546001818101845560008481526020808220909301849055845484825282860190935260409020919091556112c6565b5060006112c6565b606061178d8383600084600080856001600160a01b031684866040516146209190615198565b60006040518083038185875af1925050503d806000811461465d576040519150601f19603f3d011682016040523d82523d6000602084013e614662565b606091505b509150915061467286838361467c565b9695505050505050565b6060826146915761468c826146cf565b61178d565b81511580156146a857506001600160a01b0384163b155b156146c85783604051639996b31560e01b815260040161133c91906149aa565b508061178d565b8051156146df5780518082602001fd5b604051630a12f52160e11b815260040160405180910390fd5b60405180606001604052806000815260200160008152602001600081525090565b6001600160a01b038116811461107e57600080fd5b6000806040838503121561474157600080fd5b82359150602083013561475381614719565b809150509250929050565b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f191681016001600160401b038111828210171561479c5761479c61475e565b604052919050565b600082601f8301126147b557600080fd5b81356001600160401b038111156147ce576147ce61475e565b6147e1601f8201601f1916602001614774565b8181528460208386010111156147f657600080fd5b816020850160208301376000918101602001919091529392505050565b600082601f83011261482457600080fd5b813560206001600160401b03808311156148405761484061475e565b8260051b61484f838201614774565b938452858101830193838101908886111561486957600080fd5b84880192505b858310156148a5578235848111156148875760008081fd5b6148958a87838c01016147a4565b835250918401919084019061486f565b98975050505050505050565b6000602082840312156148c357600080fd5b81356001600160401b038111156148d957600080fd5b611a4a84828501614813565b6000602082840312156148f757600080fd5b813561178d81614719565b60005b8381101561491d578181015183820152602001614905565b50506000910152565b6000815180845261493e816020860160208601614902565b601f01601f19169290920160200192915050565b60208152600061178d6020830184614926565b6000806040838503121561497857600080fd5b823561498381614719565b946020939093013593505050565b6000602082840312156149a357600080fd5b5035919050565b6001600160a01b0391909116815260200190565b600080604083850312156149d157600080fd5b82356149dc81614719565b9150602083013561475381614719565b801515811461107e57600080fd5b60008060408385031215614a0d57600080fd5b8235614a1881614719565b91506020830135614753816149ec565b600080600060608486031215614a3d57600080fd5b8335614a4881614719565b92506020840135614a5881614719565b929592945050506040919091013590565b60008060408385031215614a7c57600080fd5b8235915060208301356001600160401b03811115614a9957600080fd5b614aa585828601614813565b9150509250929050565b60008060008060808587031215614ac557600080fd5b8435614ad081614719565b93506020850135614ae081614719565b92506040850135915060608501356001600160401b03811115614b0257600080fd5b614b0e87828801614813565b91505092959194509250565b60008060008060808587031215614b3057600080fd5b8435614b3b81614719565b93506020850135614b4b81614719565b92506040850135915060608501356001600160401b03811115614b6d57600080fd5b614b0e878288016147a4565b60008060008060808587031215614b8f57600080fd5b8435614b9a81614719565b93506020850135614baa81614719565b93969395505050506040820135916060013590565b600080600060608486031215614bd457600080fd5b8335614bdf81614719565b95602085013595506040909401359392505050565b60008060008060808587031215614c0a57600080fd5b8435614c1581614719565b93506020850135614c2581614719565b92506040850135614c3581614719565b915060608501356001600160401b03811115614b6d57600080fd5b600080600080600060a08688031215614c6857600080fd5b8535614c7381614719565b94506020860135614c8381614719565b93506040860135925060608601356001600160401b0380821115614ca657600080fd5b614cb289838a016147a4565b93506080880135915080821115614cc857600080fd5b50614cd588828901614813565b9150509295509295909350565b600080600080600080600060e0888a031215614cfd57600080fd5b8735614d0881614719565b96506020880135614d1881614719565b95506040880135945060608801359350608088013560ff81168114614d3c57600080fd5b9699959850939692959460a0840135945060c09093013592915050565b60008060408385031215614d6c57600080fd5b50508035926020909101359150565b600080600060608486031215614d9057600080fd5b8335614d9b81614719565b9250602084013591506040840135614db281614719565b809150509250925092565b600080600060608486031215614dd257600080fd5b833592506020840135614de481614719565b915060408401356001600160401b03811115614dff57600080fd5b614e0b86828701614813565b9150509250925092565b600060208284031215614e2757600080fd5b5051919050565b634e487b7160e01b600052601160045260246000fd5b808201808211156112c6576112c6614e2e565b600060208083016020845280855180835260408601915060408160051b87010192506020870160005b82811015614eae57603f19888603018452614e9c858351614926565b94509285019290850190600101614e80565b5092979650505050505050565b600181811c90821680614ecf57607f821691505b6020821081036111e057634e487b7160e01b600052602260045260246000fd5b6001600160a01b03929092168252602082015260400190565b6001600160a01b039190911681526040602082018190526004908201526329a2a62360e11b606082015260800190565b6001600160a01b0392831681529116602082015260400190565b600181815b80851115614f8d578160001904821115614f7357614f73614e2e565b80851615614f8057918102915b93841c9390800290614f57565b509250929050565b600082614fa4575060016112c6565b81614fb1575060006112c6565b8160018114614fc75760028114614fd157614fed565b60019150506112c6565b60ff841115614fe257614fe2614e2e565b50506001821b6112c6565b5060208310610133831016604e8410600b8410161715615010575081810a6112c6565b61501a8383614f52565b806000190482111561502e5761502e614e2e565b029392505050565b600061178d60ff841683614f95565b80820281158282048414176112c6576112c6614e2e565b634e487b7160e01b600052601260045260246000fd5b60008261508f57634e487b7160e01b600052601260045260246000fd5b500490565b6000602082840312156150a657600080fd5b815161178d81614719565b6020808252600d908201526c2322a2afa1a7a62622a1aa27a960991b604082015260600190565b818103818111156112c6576112c6614e2e565b6001600160a01b038581168252841660208201526040810183905260806060820181905260009061467290830184614926565b8381526060602082015260006151376060830185614926565b905060018060a01b0383166040830152949350505050565b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052603160045260246000fd5b60006020828403121561518d57600080fd5b815161178d816149ec565b600082516151aa818460208701614902565b919091019291505056fea2646970667358221220646ac1b56870a7cbc74f8651fa212c9861e368f4e8c7b29ba389a3662e99159b64736f6c634300081800330000000000000000000000005bbc51eda8508f598e01eecd1ea129e741bcc25a000000000000000000000000000000000000000000000000000000000000004000000000000000000000000044aeb27b159015d4956b01d0e1704c6bb806717f00000000000000000000000002f6eeb4e33bba64bcbea18bd149b9031c2735f70000000000000000000000000000000000000000000000000000000000000001000000000000000000000000dce39f0d5d4c39dc2c263a7356478c73db8014dd000000000000000000000000430000000000000000000000000000000000000400000000000000000000000000000000000000000000000029a2241af62c00000000000000000000000000000000000000000000000000001158e460913d0000000000000000000000000000000000000000000000000000000000000000014000000000000000000000000000000000000000000000000000000000000001a0000000000000000000000000000000000000000000000000000000000000001200000000000000000000000000000000000000000000000000000000000000234a756963652046696e616e6365205745544820436f6c6c61746572616c205661756c74000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000076a63765745544800000000000000000000000000000000000000000000000000
Deployed Bytecode
0x6080604052600436106103bb5760003560e01c80639159b206116101f4578063c62e8d3a1161010e578063e4af29fc116100a6578063e4af29fc14610cec578063e59e801814610d02578063ef48644614610d68578063ef8b30f714610d88578063f2468d8714610da8578063f69e204614610dc8578063f9566d8214610ddd578063fbcbc0f114610dfd578063fbf4198414610e1d578063ffc5ab1614610e4d57600080fd5b8063c62e8d3a14610be9578063ca8bcd6614610876578063d505accf14610bfc578063d610dc2a14610c1c578063d8cab31814610c3c578063dd62ed3e14610c56578063dd76401714610c8c578063ddd5e1b214610cac578063e1d5c06414610ccc57600080fd5b8063a612ce2b1161018c578063a612ce2b14610aad578063a8e8f9eb14610acd578063a9059cbb14610aed578063b0cb805514610b08578063b17e32f914610b3c578063b2b8c93f14610b51578063b3c0a0b314610b66578063bacd4c2814610b79578063c5ebeaec14610b99578063c613aec014610bb957600080fd5b80639159b2061461093c57806394408b9a1461095c57806395d89b411461097c578063971d6c9514610991578063985d28aa146109b157806399f8148e146109ea5780639d919c6314610a235780639dca362f14610a65578063a59a997314610a7a57600080fd5b80634031234c116102e55780636c648fc41161027d5780636c648fc4146107dd5780636e553f65146107fd57806370a082311461081d578063713fa6de146108505780637af0bdfd146108635780637b91c265146108765780637ecebe001461089657806386b9d81f146108c957806389dbb857146108e957806390401a7a1461091c57600080fd5b80634031234c14610659578063410051a51461066f57806347a873cb146106c257806347e41a89146106e2578063484d1ad61461075f5780635a287cb21461077f57806363b527f01461079f5780636856728e146107b25780636a11d0b2146107c757600080fd5b80631534a277116103585780631534a2771461051657806318160ddd146105575780631e8a84b11461057457806322867d781461059457806323b872dd146105b4578063313ce567146105d45780633574d4c4146106125780633644e5151461062e5780633a12c6da1461064357600080fd5b8062f714ce146103c057806301e1d114146103fa578063032e9c761461041d5780630674fa411461043257806306fdde03146104525780630914b18f14610474578063095ea7b3146104b45780630a28a477146104d457806312fde4b7146104f4575b600080fd5b3480156103cc57600080fd5b506103e06103db36600461472e565b610e60565b604080519283526020830191909152015b60405180910390f35b34801561040657600080fd5b5061040f610ec2565b6040519081526020016103f1565b61043061042b3660046148b1565b610f64565b005b34801561043e57600080fd5b5061040f61044d3660046148e5565b611081565b34801561045e57600080fd5b506104676111e6565b6040516103f19190614952565b34801561048057600080fd5b506104a461048f3660046148e5565b60016020526000908152604090205460ff1681565b60405190151581526020016103f1565b3480156104c057600080fd5b506104a46104cf366004614965565b611278565b3480156104e057600080fd5b506103e06104ef366004614991565b6112cc565b34801561050057600080fd5b506105096112de565b6040516103f191906149aa565b34801561052257600080fd5b506105096105313660046149be565b60046020908152600092835260408084209091529082529020546001600160a01b031681565b34801561056357600080fd5b506805345cdf77eb68f44c5461040f565b34801561058057600080fd5b5061043061058f3660046149fa565b6112e8565b3480156105a057600080fd5b5061040f6105af366004614965565b6113a8565b3480156105c057600080fd5b506104a46105cf366004614a28565b611502565b3480156105e057600080fd5b5060405160ff7f00000000000000000000000000000000000000000000000000000000000000121681526020016103f1565b34801561061e57600080fd5b5061040f670e92596fd629000081565b34801561063a57600080fd5b5061040f61151d565b34801561064f57600080fd5b5061040f60105481565b34801561066557600080fd5b5061040f60115481565b34801561067b57600080fd5b5061068f61068a3660046148e5565b61159a565b6040516103f191908151815260208083015190820152604080830151908201526060918201519181019190915260800190565b3480156106ce57600080fd5b506104306106dd366004614965565b611627565b3480156106ee57600080fd5b506107426106fd3660046148e5565b60408051808201825260008082526020918201819052825180840184526001600160a01b03949094168082526003808452938220548015158652915291815282015290565b6040805182511515815260209283015192810192909252016103f1565b34801561076b57600080fd5b5061043061077a3660046148e5565b6116c7565b34801561078b57600080fd5b5061050961079a3660046149be565b611739565b61040f6107ad366004614a69565b611794565b3480156107be57600080fd5b506104306117ea565b3480156107d357600080fd5b5061040f600f5481565b3480156107e957600080fd5b5061040f6107f83660046148e5565b611811565b34801561080957600080fd5b506103e061081836600461472e565b61191a565b34801561082957600080fd5b5061040f6108383660046148e5565b6387a211a2600c908152600091909152602090205490565b61043061085e366004614aaf565b61199e565b61040f610871366004614b1a565b6119fa565b34801561088257600080fd5b506104306108913660046148e5565b611a52565b3480156108a257600080fd5b5061040f6108b13660046148e5565b6338377508600c908152600091909152602090205490565b3480156108d557600080fd5b506105096108e43660046149be565b611a74565b3480156108f557600080fd5b507f0000000000000000000000005bbc51eda8508f598e01eecd1ea129e741bcc25a610509565b34801561092857600080fd5b50610509610937366004614965565b611a80565b34801561094857600080fd5b5061040f6109573660046148e5565b611aa2565b34801561096857600080fd5b506104306109773660046148e5565b611ac0565b34801561098857600080fd5b50610467611b0e565b34801561099d57600080fd5b506104306109ac366004614b79565b611b1d565b3480156109bd57600080fd5b506104a46109cc3660046148e5565b6001600160a01b031660009081526007602052604090205460ff1690565b3480156109f657600080fd5b506104a4610a053660046148e5565b6001600160a01b031660009081526005602052604090205460ff1690565b348015610a2f57600080fd5b50610a43610a3e366004614bbf565b611ba8565b60408051825181526020808401519082015291810151908201526060016103f1565b348015610a7157600080fd5b50610509611c14565b348015610a8657600080fd5b507f0000000000000000000000004a1d9220e11a47d8ab22ccd82da616740cf0920a610509565b348015610ab957600080fd5b5061040f610ac83660046148e5565b611dae565b348015610ad957600080fd5b50610430610ae8366004614a28565b611e3e565b348015610af957600080fd5b506104a46105cf366004614965565b348015610b1457600080fd5b506105097f00000000000000000000000044aeb27b159015d4956b01d0e1704c6bb806717f81565b348015610b4857600080fd5b50610509611e8b565b348015610b5d57600080fd5b5061040f611f0f565b610509610b74366004614bf4565b612124565b348015610b8557600080fd5b5061040f610b943660046148e5565b6123a2565b348015610ba557600080fd5b5061040f610bb4366004614991565b612438565b348015610bc557600080fd5b506104a4610bd43660046148e5565b60076020526000908152604090205460ff1681565b61040f610bf7366004614c50565b61248a565b348015610c0857600080fd5b50610430610c17366004614ce2565b6124e3565b348015610c2857600080fd5b50610430610c37366004614d59565b61266c565b348015610c4857600080fd5b506013546104a49060ff1681565b348015610c6257600080fd5b5061040f610c713660046149be565b602052637f5e9f20600c908152600091909152603490205490565b348015610c9857600080fd5b50610430610ca73660046148e5565b6126ab565b348015610cb857600080fd5b50610430610cc736600461472e565b61274b565b348015610cd857600080fd5b5061040f610ce73660046148e5565b612927565b348015610cf857600080fd5b5061040f60065481565b348015610d0e57600080fd5b50610d22610d1d3660046148e5565b612948565b6040516103f19190600060a08201905082518252602083015160208301526040830151604083015260608301511515606083015260808301511515608083015292915050565b348015610d7457600080fd5b50610430610d83366004614965565b612a2a565b348015610d9457600080fd5b506103e0610da3366004614991565b612a50565b348015610db457600080fd5b50610a43610dc3366004614965565b612a6e565b348015610dd457600080fd5b5061040f612aaa565b348015610de957600080fd5b50610430610df8366004614d7b565b612c2f565b348015610e0957600080fd5b50610509610e183660046148e5565b612e72565b348015610e2957600080fd5b50610e32612ec4565b604080518251815260209283015192810192909252016103f1565b6103e0610e5b366004614dbd565b612ef2565b600080610e6b612f20565b610eac3384866000604051908082528060200260200182016040528015610ea657816020015b6060815260200190600190039081610e915790505b50612f4a565b9092509050610ebb6001600055565b9250929050565b60405163e12f3a6160e01b81526000906001600160a01b037f0000000000000000000000004300000000000000000000000000000000000004169063e12f3a6190610f119030906004016149aa565b602060405180830381865afa158015610f2e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f529190614e15565b600a54610f5f9190614e44565b905090565b80511561107e5760405163d47eed4560e01b81526000906001600160a01b037f000000000000000000000000a2aa501b19aff244d90cc15a4cf739d2725b5729169063d47eed4590610fba908590600401614e57565b602060405180830381865afa158015610fd7573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ffb9190614e15565b90507f000000000000000000000000a2aa501b19aff244d90cc15a4cf739d2725b57296001600160a01b031663ef9e5e2882846040518363ffffffff1660e01b815260040161104a9190614e57565b6000604051808303818588803b15801561106357600080fd5b505af1158015611077573d6000803e3d6000fd5b5050505050505b50565b6040516370a0823160e01b81526000906001600160a01b037f000000000000000000000000430000000000000000000000000000000000000316906370a08231906110d09085906004016149aa565b602060405180830381865afa1580156110ed573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111119190614e15565b905060005b6001600160a01b038316600090815260086020526040902061113790612fe0565b8110156111e0576001600160a01b03831660009081526008602052604090206111609082612fea565b6001600160a01b0316631c083f6a846040518263ffffffff1660e01b815260040161118b91906149aa565b602060405180830381865afa1580156111a8573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111cc9190614e15565b6111d69083614e44565b9150600101611116565b50919050565b6060600b80546111f590614ebb565b80601f016020809104026020016040519081016040528092919081815260200182805461122190614ebb565b801561126e5780601f106112435761010080835404028352916020019161126e565b820191906000526020600020905b81548152906001019060200180831161125157829003601f168201915b5050505050905090565b600082602052637f5e9f20600c5233600052816034600c205581600052602c5160601c337f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92560206000a35060015b92915050565b6000806112d883612ff6565b93915050565b6000610f5f61303a565b6112f1336130cb565b61134557335b60408051637974da6f60e01b81526001600160a01b0390921660048301526024820152600e60448201526d282927aa27a1a7a62fa0a226a4a760911b60648201526084015b60405180910390fd5b6001600160a01b038216600081815260076020908152604091829020805460ff19168515159081179091558251938452908301527ffc2e7375e815d084de88de8e8e356e71102275019b06a1b529eee0c8ab57cd34910160405180910390a15050565b60006113b2612f20565b60405163c883b2e560e01b8152600481018390526001600160a01b0384811660248301523360448301527f0000000000000000000000004a1d9220e11a47d8ab22ccd82da616740cf0920a169063c883b2e5906064016020604051808303816000875af1158015611427573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061144b9190614e15565b6001600160a01b0384811660008181526002602090815260409182902054915185815294955091939216917fa42e379bd7db0adade1690b7b2b3b81c2419c87c3c9f0c4f4f5a4da3ce8a8966910160405180910390a36040516347a873cb60e01b815230906347a873cb906114c69086908590600401614eef565b600060405180830381600087803b1580156114e057600080fd5b505af11580156114f4573d6000803e3d6000fd5b505050506112c66001600055565b600060405163a24e573d60e01b815260040160405180910390fd5b6000806115286111e6565b8051906020012090506040517f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f81528160208201527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6604082015246606082015230608082015260a081209250505090565b6115c56040518060800160405280600081526020016000815260200160008152602001600081525090565b60006115d083611811565b905060006115dd84611dae565b9050600082156115f6576115f383835b90613177565b90505b604051806080016040528083815260200184815260200182815260200161161c60105490565b905295945050505050565b3330146116495733604051637974da6f60e01b815260040161133c9190614f08565b600061165483612948565b6001600160a01b0384166000908152600360205260409020549091501580159061168057508060600151155b156116c25760405163dd76401760e01b8152309063dd764017906116a89086906004016149aa565b600060405180830381600087803b15801561106357600080fd5b505050565b6116d0336130cb565b6116da57336112f7565b6116e38161318f565b806001600160a01b0316638456cb596040518163ffffffff1660e01b8152600401600060405180830381600087803b15801561171e57600080fd5b505af1158015611732573d6000803e3d6000fd5b5050505050565b600061178d7f000000000000000000000000dce39f0d5d4c39dc2c263a7356478c73db8014dd8484604051602001611772929190614f38565b60405160208183030381529060405280519060200120613238565b9392505050565b3360009081526001602052604081205460ff166117c3576040516282b42960e81b815260040160405180910390fd5b6117cb612f20565b6117d482610f64565b6117de3384613298565b90506112c66001600055565b6117f3336130cb565b6117fd57336112f7565b6013805460ff19811660ff90911615179055565b6001600160a01b038082166000908152600260205260408120549091168161183882611aa2565b905060006118446133f1565b6001600160a01b031663b3596f077f00000000000000000000000043000000000000000000000000000000000000046040518263ffffffff1660e01b815260040161188f91906149aa565b602060405180830381865afa1580156118ac573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118d09190614e15565b90506118fd7f0000000000000000000000000000000000000000000000000000000000000012600a615036565b6119078284615045565b6119119190615072565b95945050505050565b600080611925612f20565b60135460ff161561193a57611938612aaa565b505b6119448484613454565b90925090506001600160a01b0383167f85a75ad7f484e83157db3f52d6bfcf613d65995bd6546c2ed0d55ee07a51170a61197d85612e72565b8660405161198c929190614eef565b60405180910390a2610ebb6001600055565b3360009081526001602052604090205460ff166119cd576040516282b42960e81b815260040160405180910390fd5b6119d5612f20565b6119de81610f64565b6119ea3385858561346d565b6119f46001600055565b50505050565b3360009081526001602052604081205460ff16611a29576040516282b42960e81b815260040160405180910390fd5b611a31612f20565b611a3e33868686866135c2565b9050611a4a6001600055565b949350505050565b33301461107e5733604051637974da6f60e01b815260040161133c9190614f08565b600061178d8383613744565b6001600160a01b038216600090815260086020526040812061178d9083612fea565b6387a211a2600c90815260008281526020909120546112c690612ff6565b611ac9336130cb565b611ad357336112f7565b806001600160a01b0316633f4ba83a6040518163ffffffff1660e01b8152600401600060405180830381600087803b15801561171e57600080fd5b6060600c80546111f590614ebb565b3360009081526005602052604090205460ff16611b4c576040516282b42960e81b815260040160405180910390fd5b826001600160a01b0316846001600160a01b03167fb15b5161080eeb6130c6088d7b1e8eceb1092d2a15836c769bd094d9a68c8c6b8484604051611b9a929190918252602082015260400190565b60405180910390a350505050565b611bb06146f8565b6000838311611bbf5782611bc1565b835b90506000611bce86611aa2565b90506000806000611bdf8585613b58565b92509250925084811015611bf1578094505b506040805160608101825294855260208501929092529083015250949350505050565b6000611c1e612f20565b3360008181526001602052604090205460ff1615611c4f57604051635435b28960e11b815260040160405180910390fd5b611c817f00000000000000000000000044aeb27b159015d4956b01d0e1704c6bb806717f611c7c83613c6d565b613cb1565b6001600160a01b038082166000818152600160208181526040808420805460ff1916841790559487168084526012825285842080546001600160a01b0319908116871790915594845260029091529382208054909316909317909155600680549395509192611cf1908490614e44565b92505081905550806001600160a01b03167fac631f3001b55ea1509cf3d7e74898f85392a61a76e8149181ae1259622dabc883604051611d3191906149aa565b60405180910390a2816001600160a01b031663485cc95582611d51613d1f565b6040518363ffffffff1660e01b8152600401611d6e929190614f38565b600060405180830381600087803b158015611d8857600080fd5b505af1158015611d9c573d6000803e3d6000fd5b5050505050611dab6001600055565b90565b60405163a612ce2b60e01b81526000906001600160a01b037f0000000000000000000000004a1d9220e11a47d8ab22ccd82da616740cf0920a169063a612ce2b90611dfd9085906004016149aa565b602060405180830381865afa158015611e1a573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112c69190614e15565b3360009081526001602052604090205460ff16611e6d576040516282b42960e81b815260040160405180910390fd5b611e75612f20565b611e813384848461346d565b6116c26001600055565b60007f0000000000000000000000004a1d9220e11a47d8ab22ccd82da616740cf0920a6001600160a01b0316635c222bad6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611eeb573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f5f9190615094565b600d5460405160009182916001600160a01b039091169063c824e15790611f529060200160208082526005908201526410931054d560da1b604082015260600190565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b8152600401611f8691815260200190565b602060405180830381865afa158015611fa3573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611fc79190615094565b600d546040519192506000916001600160a01b03909116906321f8a72190611ff1906020016150b1565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b815260040161202591815260200190565b602060405180830381865afa158015612042573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906120669190615094565b60405163662aa11d60e01b81529091506001600160a01b0383169063662aa11d906120979030908590600401614f38565b6020604051808303816000875af11580156120b6573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906120da9190614e15565b9250806001600160a01b03167f9c3c39d0eedd3d18612a0e8e76cc7bc873815d3e19206dbbf9825989b1c95e6b8460405161211791815260200190565b60405180910390a2505090565b60006121308585613744565b905060006001600160a01b0384161561223f576040516370a0823160e01b81526000906001600160a01b03861690630a28a4779082906370a082319061217a908c906004016149aa565b602060405180830381865afa158015612197573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906121bb9190614e15565b6040518263ffffffff1660e01b81526004016121d991815260200190565b602060405180830381865afa1580156121f6573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061221a9190614e15565b9050612231611dab8261222c8a6123a2565b613d78565b61223b90826150d8565b9150505b604051639035268760e01b81526001600160a01b038716906390352687903490612273908890879087908a906004016150eb565b6000604051808303818588803b15801561228c57600080fd5b505af11580156122a0573d6000803e3d6000fd5b50505050506001600160a01b038416158015906123275750604051630e041fb560e11b81526001600160a01b03851690631c083f6a906122e49089906004016149aa565b602060405180830381865afa158015612301573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906123259190614e15565b155b15612399576001600160a01b038616600090815260086020526040902061234e9085613d87565b506001600160a01b038681166000818152600260205260408082205490518489169491909116917f9910e38adb465481c843222dba5590cfcb99a51e28f2fc633b66289ef06ba4e291a45b50949350505050565b6001600160a01b038116600090815260036020526040812054428181039110026123ca613d9c565b6001600160a01b0316635628570c826040518263ffffffff1660e01b81526004016123f791815260200190565b602060405180830381865afa158015612414573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061178d9190614e15565b3360009081526001602052604081205460ff16612467576040516282b42960e81b815260040160405180910390fd5b61246f612f20565b6124793383613298565b90506124856001600055565b919050565b3360009081526001602052604081205460ff166124b9576040516282b42960e81b815260040160405180910390fd5b6124c1612f20565b6124ca82610f64565b6124d733878787876135c2565b90506119116001600055565b60006124ed6111e6565b8051906020012090508442111561250c57631a15a3cc6000526004601cfd5b6040518860601b60601c98508760601b60601c975065383775081901600e52886000526020600c2080547f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f83528360208401527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6604084015246606084015230608084015260a08320602e527f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c983528a60208401528960408401528860608401528060808401528760a084015260c08320604e526042602c206000528660ff1660205285604052846060526020806080600060015afa8b3d51146126185763ddafbaef6000526004601cfd5b0190556303faf4f960a51b88176040526034602c2087905587897f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925602060608501a360405250506000606052505050505050565b612675336130cb565b61267f57336112f7565b808210156126a057604051635435b28960e11b815260040160405180910390fd5b601091909155601155565b3330146126cd5733604051637974da6f60e01b815260040161133c9190614f08565b6001600160a01b038116600081815260036020526040808220829055517fccfc0aeacebc685763eb86a3e35dfeac830fd983f2f597b3f142ee667d28acc49190a2604051637b91c26560e01b81523090637b91c265906127319084906004016149aa565b600060405180830381600087803b15801561171e57600080fd5b806001600160a01b0381166127735760405163d92e233d60e01b815260040160405180910390fd5b3360009081526001602052604090205460ff166127a2576040516282b42960e81b815260040160405180910390fd5b6127aa612f20565b33600090815260036020526040902054156127d857604051635e3b451760e11b815260040160405180910390fd5b6127e133611dae565b15158061287a57506040516370a0823160e01b815283906001600160a01b037f000000000000000000000000430000000000000000000000000000000000000316906370a08231906128379033906004016149aa565b602060405180830381865afa158015612854573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906128789190614e15565b105b156128985760405163e44069c960e01b815260040160405180910390fd5b6128cd6001600160a01b037f000000000000000000000000430000000000000000000000000000000000000316338486613e08565b336000818152600260209081526040918290205491518681526001600160a01b03909216917f01bfef2bf622406285ca1a4057a39432c0ba15e2069c29ae6098c22affdeaf45910160405180910390a36116c26001600055565b6001600160a01b03811660009081526008602052604081206112c690612fe0565b61297e6040518060a001604052806000815260200160008152602001600081526020016000151581526020016000151581525090565b600061298983611081565b9050600061299684611811565b905060006129a385611dae565b905060006129b18484614e44565b6040805160a0810182528481526020810186905290810186905260006060820181905260808201529550905081158015906129ec5750600081115b15612a1357612a07611dab601154612a018590565b90613d78565b81106060860152612a21565b8115612a2157600160808601525b50505050919050565b333014612a4c5733604051637974da6f60e01b815260040161133c9190614f08565b5050565b600080612a5c83613e6f565b9050612a6781612ff6565b9150915091565b612a766146f8565b6001600160a01b0380841660009081526002602052604081205490911690612a9d85611dae565b9050611911828286611ba8565b60405163e12f3a6160e01b81526000907f0000000000000000000000004300000000000000000000000000000000000004906001600160a01b0382169063e12f3a6190612afb9030906004016149aa565b602060405180830381865afa158015612b18573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612b3c9190614e15565b9150600f548210612c2b5781600a6000828254612b599190614e44565b9091555050604051635569f64b60e11b81526001600160a01b037f0000000000000000000000004300000000000000000000000000000000000004169063aad3ec9690612bac9030908690600401614eef565b6020604051808303816000875af1158015612bcb573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612bef9190614e15565b91507f3b6bc0ba304eaa17cdca1b053baac859e721c7a775cddefc825f6286641311fc82604051612c2291815260200190565b60405180910390a15b5090565b6000612c3a84612948565b90508060600151612c5e57604051636caa790760e01b815260040160405180910390fd5b6001600160a01b0384166000908152600360205260408120549003612d14576001600160a01b038416600081815260036020526040808220429055517fdcd8b95bdfd2ffcc332acd69f71c9319a5a1006ca18c94d83d854e591cb6e0439190a2604051636545e6b360e11b8152309063ca8bcd6690612ce19087906004016149aa565b600060405180830381600087803b158015612cfb57600080fd5b505af1158015612d0f573d6000803e3d6000fd5b505050505b6001600160a01b0380851660009081526002602052604081205490911690612d3b86611dae565b90506000612d4a838388611ba8565b9050612d6a833383604001518460200151612d6591906150d8565b613e9f565b612d7983868360400151613e9f565b8051612db3906001600160a01b037f0000000000000000000000004300000000000000000000000000000000000003169033908a90613e08565b8051604051631b8fec7360e11b815260048101919091526001600160a01b0388169063371fd8e690602401600060405180830381600087803b158015612df857600080fd5b505af1158015612e0c573d6000803e3d6000fd5b505050602080830151604080850151855182516001600160a01b038e168152948501939093529083015260608201527fe32ec3ea3154879f27d5367898ab3a5ac6b68bf921d7cc610720f417c5cb243c915060800160405180910390a150505050505050565b6001600160a01b038082166000908152601260205260409020541680612485576112c67f00000000000000000000000044aeb27b159015d4956b01d0e1704c6bb806717f612ebf84613c6d565b613238565b6040805180820190915260008082526020820152612ee0613f1d565b8152612eea614001565b602082015290565b600080612efd612f20565b612f0933858786612f4a565b9092509050612f186001600055565b935093915050565b600260005403612f4357604051633ee5aeb560e01b815260040160405180910390fd5b6002600055565b601354600090819060ff1615612f6457612f62612aaa565b505b612f6f868686614066565b90925090506000612f7f87612e72565b9050612f8a84610f64565b612f938161318f565b866001600160a01b03167f2514892efd9b8bb8666eb8f78a0f6dc59add738ad886bd36912de7b811e0c9808785604051612fce929190614eef565b60405180910390a25094509492505050565b60006112c6825490565b600061178d83836140d0565b60006130096805345cdf77eb68f44c5490565b15612c2b576805345cdf77eb68f44c54613021610ec2565b61302b9084615045565b6130359190615072565b6112c6565b60007f0000000000000000000000005bbc51eda8508f598e01eecd1ea129e741bcc25a6001600160a01b03166321f8a72160405160200161307a906150b1565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b81526004016130ae91815260200190565b602060405180830381865afa158015611eeb573d6000803e3d6000fd5b6000816001600160a01b03167f0000000000000000000000005bbc51eda8508f598e01eecd1ea129e741bcc25a6001600160a01b031663893d20e86040518163ffffffff1660e01b8152600401602060405180830381865afa158015613135573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906131599190615094565b6001600160a01b03161461316f57506000919050565b506001919050565b600061178d611dab84670de0b6b3a7640000856140fa565b6001600160a01b038116600090815260036020526040902054156131c657604051635e3b451760e11b815260040160405180910390fd5b60006131d182612948565b905060006131ee611dab6131e460105490565b6020850151612a01565b90508082600001511115613215576040516334b3313560e11b815260040160405180910390fd5b8160600151156116c2576040516334b3313560e11b815260040160405180910390fd5b6040513060388201526f5af43d82803e903d91602b57fd5bf3ff602482015260148101839052733d602d80600a3d3981f3363d3d373d3d3d363d738152605881018290526037600c8201206078820152605560439091012060009061178d565b604051630967fa2960e31b8152600481018290526001600160a01b0383811660248301526000917f0000000000000000000000004a1d9220e11a47d8ab22ccd82da616740cf0920a90911690634b3fd148906044016020604051808303816000875af115801561330c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906133309190614e15565b905061333b8361318f565b6001600160a01b0380841660008181526002602052604090819020549051919216907f44dd1331990f12a8382e7da57756538a810f52fa13c1bb0d0ca6b14225be6d339061338c9085815260200190565b60405180910390a36040516377a4322360e11b8152309063ef486446906133b99086908590600401614eef565b600060405180830381600087803b1580156133d357600080fd5b505af11580156133e7573d6000803e3d6000fd5b5050505092915050565b60007f0000000000000000000000005bbc51eda8508f598e01eecd1ea129e741bcc25a6001600160a01b03166321f8a72160405160200161307a906020808252600e908201526d282924a1a2afa82927ab24a222a960911b604082015260600190565b6000806134623384866141ce565b909590945092505050565b836001600160a01b0316826001600160a01b0316846001600160a01b03167f44afc4b038b803a70a242636bdd48bded871bf13df04e3613998f5ef1915ca8b846040516134bc91815260200190565b60405180910390a46001600160a01b038216158015906135465750604051630e041fb560e11b81526001600160a01b03831690631c083f6a906135039087906004016149aa565b602060405180830381865afa158015613520573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906135449190614e15565b155b156135b9576001600160a01b038416600090815260086020526040902061356d9083613d87565b50816001600160a01b0316846001600160a01b0316846001600160a01b03167f9910e38adb465481c843222dba5590cfcb99a51e28f2fc633b66289ef06ba4e260405160405180910390a45b6119f48461318f565b6001600160a01b03831660009081526007602052604081205460ff166135fb57604051631a22ce4f60e11b815260040160405180910390fd5b6001600160a01b038616600090815260086020526040902061361d9085614239565b1561366d57836001600160a01b0316866001600160a01b0316866001600160a01b03167ff6fa2840bdce616f9e9bbe7d65ca8bcca0532f1c4aa348c65c79c2cbf6ebf1f960405160405180910390a45b604051634b18bb2360e11b81526001600160a01b03851690639631764690349061369f90879087908c9060040161511e565b60206040518083038185885af11580156136bd573d6000803e3d6000fd5b50505050506040513d601f19601f820116820180604052508101906136e29190614e15565b9050856001600160a01b0316846001600160a01b0316866001600160a01b03167fcc3d99ef3608eafdfce86498089694111f40a0dd5b2841cba24bf2dfde1cc16c8660405161373391815260200190565b60405180910390a46119118661318f565b60008061375084612948565b9050806060015161377457604051636caa790760e01b815260040160405180910390fd5b6001600160a01b038085166000908152600460209081526040808320878516845290915290205416915081613941576137f57f000000000000000000000000dce39f0d5d4c39dc2c263a7356478c73db8014dd85856040516020016137da929190614f38565b60405160208183030381529060405280519060200120613cb1565b604080516080810182526001600160a01b037f0000000000000000000000004300000000000000000000000000000000000003811682523060208301908152888216838501908152888316606085019081529451630415cc1560e01b81529351831660048501529051821660248401525181166044830152915182166064820152919350831690630415cc1590608401600060405180830381600087803b15801561389f57600080fd5b505af11580156138b3573d6000803e3d6000fd5b505050506001600160a01b03848116600081815260046020908152604080832088861680855290835281842080546001600160a01b0319169689169687179055948352600590915290819020805460ff19166001179055517f39ee3b3ae7d535f7a027ce37245120586dd668f09e21538a7e0e8d7d5b3f1637906139389086906149aa565b60405180910390a35b6040516370a0823160e01b81526000906001600160a01b037f000000000000000000000000430000000000000000000000000000000000000316906370a08231906139909088906004016149aa565b602060405180830381865afa1580156139ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906139d19190614e15565b1115613a9b57613a9b84837f00000000000000000000000043000000000000000000000000000000000000036001600160a01b03166370a08231886040518263ffffffff1660e01b8152600401613a2891906149aa565b602060405180830381865afa158015613a45573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613a699190614e15565b6001600160a01b037f000000000000000000000000430000000000000000000000000000000000000316929190613e08565b6001600160a01b0384166000908152600360205260408120549003613b51576001600160a01b038416600081815260036020526040808220429055517fdcd8b95bdfd2ffcc332acd69f71c9319a5a1006ca18c94d83d854e591cb6e0439190a2604051636545e6b360e11b8152309063ca8bcd6690613b1e9087906004016149aa565b600060405180830381600087803b158015613b3857600080fd5b505af1158015613b4c573d6000803e3d6000fd5b505050505b5092915050565b600080600080613bf5613b696133f1565b6001600160a01b031663b3596f077f00000000000000000000000043000000000000000000000000000000000000046040518263ffffffff1660e01b8152600401613bb491906149aa565b602060405180830381865afa158015613bd1573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611dab9190614e15565b90506000613c12611dab836115ed670e92596fd62900008b612a01565b905085811115613c3f57859450613c38611dab670e92596fd62900006115ed8589613d78565b9250613c46565b8094508692505b6000613c5283856115ed565b9050613c61611dab878361424e565b94505050509250925092565b6040516001600160601b0319606083811b8216602084015230901b166034820152600090604801604051602081830303815290604052805190602001209050919050565b6000763d602d80600a3d3981f3363d3d373d3d3d363d730000008360601b60e81c176000526e5af43d82803e903d91602b57fd5bf38360781b1760205281603760096000f590506001600160a01b0381166112c6576040516330be1a3d60e21b815260040160405180910390fd5b60007f0000000000000000000000005bbc51eda8508f598e01eecd1ea129e741bcc25a6001600160a01b031663c824e15760405160200161307a906020808252600490820152630a0b2a8960e31b604082015260600190565b600061178d611dab848461425d565b600061178d836001600160a01b038416614313565b60007f0000000000000000000000005bbc51eda8508f598e01eecd1ea129e741bcc25a6001600160a01b03166321f8a72160405160200161307a9060208082526017908201527614d51490551151d657d4d31254141051d157d353d11153604a1b604082015260600190565b6040516001600160a01b0384811660248301528381166044830152606482018390526119f49186918216906323b872dd906084015b604051602081830303815290604052915060e01b6020820180516001600160e01b038381831617835250505050614406565b6000613e826805345cdf77eb68f44c5490565b15612c2b57613e8f610ec2565b6805345cdf77eb68f44c54613021565b6000613ec5613eb56805345cdf77eb68f44c5490565b613ebd610ec2565b849190614460565b905081600a6000828254613ed991906150d8565b90915550613ee99050848261448f565b6119f46001600160a01b037f0000000000000000000000004300000000000000000000000000000000000004168484614506565b60007f0000000000000000000000005bbc51eda8508f598e01eecd1ea129e741bcc25a6001600160a01b031663e5f3d3a5604051602001613f8c906020808252601a908201527950524f544f434f4c5f4c49515549444154494f4e5f534841524560301b604082015260600190565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b8152600401613fc091815260200190565b602060405180830381865afa158015613fdd573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f5f9190614e15565b60007f0000000000000000000000005bbc51eda8508f598e01eecd1ea129e741bcc25a6001600160a01b031663e5f3d3a5604051602001613f8c9060208082526010908201526f4c495155494441544f525f534841524560801b604082015260600190565b600080614072836112cc565b809250819350505081600a600082825461408c91906150d8565b9091555061409c9050858261448f565b612f186001600160a01b037f0000000000000000000000004300000000000000000000000000000000000004168584614506565b60008260000182815481106140e7576140e761514f565b9060005260206000200154905092915050565b60008080600019858709858702925082811083820303915050806000036141345783828161412a5761412a61505c565b049250505061178d565b83811061416557604051630c740aef60e31b815260048101879052602481018690526044810185905260640161133c565b60008486880960026001871981018816978890046003810283188082028403028082028403028082028403028082028403028082028403029081029092039091026000889003889004909101858311909403939093029303949094049190911702949350505050565b6000806141da83612a50565b809250819350505081600a60008282546141f49190614e44565b9091555061422f90506001600160a01b037f000000000000000000000000430000000000000000000000000000000000000416863085613e08565b612f18848261452c565b600061178d836001600160a01b0384166145ab565b600061178d611dab83856150d8565b60008080600019848609848602925082811083820303915050806000036142915750670de0b6b3a7640000900490506112c6565b670de0b6b3a764000081106142c357604051635173648d60e01b8152600481018690526024810185905260440161133c565b6000670de0b6b3a764000085870962040000818503049310909103600160ee1b02919091177faccb18165bd6fe31ae1cf318dc5b51eee0e1ba569b88cd74c1773b91fac106690291505092915050565b600081815260018301602052604081205480156143fc5760006143376001836150d8565b855490915060009061434b906001906150d8565b90508082146143b057600086600001828154811061436b5761436b61514f565b906000526020600020015490508087600001848154811061438e5761438e61514f565b6000918252602080832090910192909255918252600188019052604090208390555b85548690806143c1576143c1615165565b6001900381819060005260206000200160009055905585600101600086815260200190815260200160002060009055600193505050506112c6565b60009150506112c6565b600061441b6001600160a01b038416836145fa565b9050805160001415801561444057508080602001905181019061443e919061517b565b155b156116c25782604051635274afe760e01b815260040161133c91906149aa565b60008260001904841183021582026144805763ad251c276000526004601cfd5b50910281810615159190040190565b6387a211a2600c52816000526020600c208054808311156144b85763f4d678b86000526004601cfd5b82900390556805345cdf77eb68f44c8054829003905560008181526001600160a01b0383167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef602083a35050565b6116c283846001600160a01b031663a9059cbb8585604051602401613e3d929190614eef565b6805345cdf77eb68f44c54818101818110156145505763e5cfe9576000526004601cfd5b806805345cdf77eb68f44c5550506387a211a2600c52816000526020600c208181540181555080602052600c5160601c60007fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef602080a35050565b60008181526001830160205260408120546145f2575081546001818101845560008481526020808220909301849055845484825282860190935260409020919091556112c6565b5060006112c6565b606061178d8383600084600080856001600160a01b031684866040516146209190615198565b60006040518083038185875af1925050503d806000811461465d576040519150601f19603f3d011682016040523d82523d6000602084013e614662565b606091505b509150915061467286838361467c565b9695505050505050565b6060826146915761468c826146cf565b61178d565b81511580156146a857506001600160a01b0384163b155b156146c85783604051639996b31560e01b815260040161133c91906149aa565b508061178d565b8051156146df5780518082602001fd5b604051630a12f52160e11b815260040160405180910390fd5b60405180606001604052806000815260200160008152602001600081525090565b6001600160a01b038116811461107e57600080fd5b6000806040838503121561474157600080fd5b82359150602083013561475381614719565b809150509250929050565b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f191681016001600160401b038111828210171561479c5761479c61475e565b604052919050565b600082601f8301126147b557600080fd5b81356001600160401b038111156147ce576147ce61475e565b6147e1601f8201601f1916602001614774565b8181528460208386010111156147f657600080fd5b816020850160208301376000918101602001919091529392505050565b600082601f83011261482457600080fd5b813560206001600160401b03808311156148405761484061475e565b8260051b61484f838201614774565b938452858101830193838101908886111561486957600080fd5b84880192505b858310156148a5578235848111156148875760008081fd5b6148958a87838c01016147a4565b835250918401919084019061486f565b98975050505050505050565b6000602082840312156148c357600080fd5b81356001600160401b038111156148d957600080fd5b611a4a84828501614813565b6000602082840312156148f757600080fd5b813561178d81614719565b60005b8381101561491d578181015183820152602001614905565b50506000910152565b6000815180845261493e816020860160208601614902565b601f01601f19169290920160200192915050565b60208152600061178d6020830184614926565b6000806040838503121561497857600080fd5b823561498381614719565b946020939093013593505050565b6000602082840312156149a357600080fd5b5035919050565b6001600160a01b0391909116815260200190565b600080604083850312156149d157600080fd5b82356149dc81614719565b9150602083013561475381614719565b801515811461107e57600080fd5b60008060408385031215614a0d57600080fd5b8235614a1881614719565b91506020830135614753816149ec565b600080600060608486031215614a3d57600080fd5b8335614a4881614719565b92506020840135614a5881614719565b929592945050506040919091013590565b60008060408385031215614a7c57600080fd5b8235915060208301356001600160401b03811115614a9957600080fd5b614aa585828601614813565b9150509250929050565b60008060008060808587031215614ac557600080fd5b8435614ad081614719565b93506020850135614ae081614719565b92506040850135915060608501356001600160401b03811115614b0257600080fd5b614b0e87828801614813565b91505092959194509250565b60008060008060808587031215614b3057600080fd5b8435614b3b81614719565b93506020850135614b4b81614719565b92506040850135915060608501356001600160401b03811115614b6d57600080fd5b614b0e878288016147a4565b60008060008060808587031215614b8f57600080fd5b8435614b9a81614719565b93506020850135614baa81614719565b93969395505050506040820135916060013590565b600080600060608486031215614bd457600080fd5b8335614bdf81614719565b95602085013595506040909401359392505050565b60008060008060808587031215614c0a57600080fd5b8435614c1581614719565b93506020850135614c2581614719565b92506040850135614c3581614719565b915060608501356001600160401b03811115614b6d57600080fd5b600080600080600060a08688031215614c6857600080fd5b8535614c7381614719565b94506020860135614c8381614719565b93506040860135925060608601356001600160401b0380821115614ca657600080fd5b614cb289838a016147a4565b93506080880135915080821115614cc857600080fd5b50614cd588828901614813565b9150509295509295909350565b600080600080600080600060e0888a031215614cfd57600080fd5b8735614d0881614719565b96506020880135614d1881614719565b95506040880135945060608801359350608088013560ff81168114614d3c57600080fd5b9699959850939692959460a0840135945060c09093013592915050565b60008060408385031215614d6c57600080fd5b50508035926020909101359150565b600080600060608486031215614d9057600080fd5b8335614d9b81614719565b9250602084013591506040840135614db281614719565b809150509250925092565b600080600060608486031215614dd257600080fd5b833592506020840135614de481614719565b915060408401356001600160401b03811115614dff57600080fd5b614e0b86828701614813565b9150509250925092565b600060208284031215614e2757600080fd5b5051919050565b634e487b7160e01b600052601160045260246000fd5b808201808211156112c6576112c6614e2e565b600060208083016020845280855180835260408601915060408160051b87010192506020870160005b82811015614eae57603f19888603018452614e9c858351614926565b94509285019290850190600101614e80565b5092979650505050505050565b600181811c90821680614ecf57607f821691505b6020821081036111e057634e487b7160e01b600052602260045260246000fd5b6001600160a01b03929092168252602082015260400190565b6001600160a01b039190911681526040602082018190526004908201526329a2a62360e11b606082015260800190565b6001600160a01b0392831681529116602082015260400190565b600181815b80851115614f8d578160001904821115614f7357614f73614e2e565b80851615614f8057918102915b93841c9390800290614f57565b509250929050565b600082614fa4575060016112c6565b81614fb1575060006112c6565b8160018114614fc75760028114614fd157614fed565b60019150506112c6565b60ff841115614fe257614fe2614e2e565b50506001821b6112c6565b5060208310610133831016604e8410600b8410161715615010575081810a6112c6565b61501a8383614f52565b806000190482111561502e5761502e614e2e565b029392505050565b600061178d60ff841683614f95565b80820281158282048414176112c6576112c6614e2e565b634e487b7160e01b600052601260045260246000fd5b60008261508f57634e487b7160e01b600052601260045260246000fd5b500490565b6000602082840312156150a657600080fd5b815161178d81614719565b6020808252600d908201526c2322a2afa1a7a62622a1aa27a960991b604082015260600190565b818103818111156112c6576112c6614e2e565b6001600160a01b038581168252841660208201526040810183905260806060820181905260009061467290830184614926565b8381526060602082015260006151376060830185614926565b905060018060a01b0383166040830152949350505050565b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052603160045260246000fd5b60006020828403121561518d57600080fd5b815161178d816149ec565b600082516151aa818460208701614902565b919091019291505056fea2646970667358221220646ac1b56870a7cbc74f8651fa212c9861e368f4e8c7b29ba389a3662e99159b64736f6c63430008180033
Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)
0000000000000000000000005bbc51eda8508f598e01eecd1ea129e741bcc25a000000000000000000000000000000000000000000000000000000000000004000000000000000000000000044aeb27b159015d4956b01d0e1704c6bb806717f00000000000000000000000002f6eeb4e33bba64bcbea18bd149b9031c2735f70000000000000000000000000000000000000000000000000000000000000001000000000000000000000000dce39f0d5d4c39dc2c263a7356478c73db8014dd000000000000000000000000430000000000000000000000000000000000000400000000000000000000000000000000000000000000000029a2241af62c00000000000000000000000000000000000000000000000000001158e460913d0000000000000000000000000000000000000000000000000000000000000000014000000000000000000000000000000000000000000000000000000000000001a0000000000000000000000000000000000000000000000000000000000000001200000000000000000000000000000000000000000000000000000000000000234a756963652046696e616e6365205745544820436f6c6c61746572616c205661756c74000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000076a63765745544800000000000000000000000000000000000000000000000000
-----Decoded View---------------
Arg [0] : protocolGovernor_ (address): 0x5bbc51EdA8508F598E01eeCd1EA129E741bCc25a
Arg [1] : params (tuple): System.Collections.Generic.List`1[Nethereum.ABI.FunctionEncoding.ParameterOutput]
-----Encoded View---------------
17 Constructor Arguments found :
Arg [0] : 0000000000000000000000005bbc51eda8508f598e01eecd1ea129e741bcc25a
Arg [1] : 0000000000000000000000000000000000000000000000000000000000000040
Arg [2] : 00000000000000000000000044aeb27b159015d4956b01d0e1704c6bb806717f
Arg [3] : 00000000000000000000000002f6eeb4e33bba64bcbea18bd149b9031c2735f7
Arg [4] : 0000000000000000000000000000000000000000000000000000000000000001
Arg [5] : 000000000000000000000000dce39f0d5d4c39dc2c263a7356478c73db8014dd
Arg [6] : 0000000000000000000000004300000000000000000000000000000000000004
Arg [7] : 00000000000000000000000000000000000000000000000029a2241af62c0000
Arg [8] : 0000000000000000000000000000000000000000000000001158e460913d0000
Arg [9] : 0000000000000000000000000000000000000000000000000000000000000140
Arg [10] : 00000000000000000000000000000000000000000000000000000000000001a0
Arg [11] : 0000000000000000000000000000000000000000000000000000000000000012
Arg [12] : 0000000000000000000000000000000000000000000000000000000000000023
Arg [13] : 4a756963652046696e616e6365205745544820436f6c6c61746572616c205661
Arg [14] : 756c740000000000000000000000000000000000000000000000000000000000
Arg [15] : 0000000000000000000000000000000000000000000000000000000000000007
Arg [16] : 6a63765745544800000000000000000000000000000000000000000000000000
Loading...
Loading
Loading...
Loading
Multichain Portfolio | 34 Chains
Chain | Token | Portfolio % | Price | Amount | Value |
---|---|---|---|---|---|
BLAST | 100.00% | $1,785.44 | 27.9916 | $49,977.3 |
Loading...
Loading
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.