More Info
Private Name Tags
ContractCreator
TokenTracker
Latest 25 from a total of 95,111 transactions
| Transaction Hash |
|
Block
|
From
|
To
|
|||||
|---|---|---|---|---|---|---|---|---|---|
| Liquidate Strate... | 30080513 | 3 days ago | IN | 0 ETH | 0.00000027 | ||||
| Liquidate | 30080511 | 3 days ago | IN | 0 ETH | 0.00000022 | ||||
| Liquidate | 29977917 | 5 days ago | IN | 0 ETH | 0.00000005 | ||||
| Liquidate | 29977015 | 5 days ago | IN | 0 ETH | 0.00000004 | ||||
| Liquidate Strate... | 29965326 | 5 days ago | IN | 0 ETH | 0.00000008 | ||||
| Liquidate | 29965322 | 5 days ago | IN | 0 ETH | 0.00000006 | ||||
| Liquidate | 29954507 | 6 days ago | IN | 0 ETH | 0.00000004 | ||||
| Transfer | 29905122 | 7 days ago | IN | 0 ETH | 0.00000006 | ||||
| Withdraw | 29890522 | 7 days ago | IN | 0 ETH | 0.00000061 | ||||
| Withdraw | 29890501 | 7 days ago | IN | 0 ETH | 0.00000088 | ||||
| Withdraw | 29854989 | 8 days ago | IN | 0 ETH | 0.00000012 | ||||
| Liquidate Strate... | 29853701 | 8 days ago | IN | 0 ETH | 0.00000028 | ||||
| Liquidate | 29853697 | 8 days ago | IN | 0 ETH | 0.00000022 | ||||
| Withdraw | 29850980 | 8 days ago | IN | 0 ETH | 0.00000084 | ||||
| Liquidate | 29850120 | 8 days ago | IN | 0 ETH | 0.00000037 | ||||
| Liquidate | 29849663 | 8 days ago | IN | 0 ETH | 0.00000107 | ||||
| Liquidate | 29841115 | 8 days ago | IN | 0 ETH | 0.0007086 | ||||
| Liquidate Strate... | 29835261 | 8 days ago | IN | 0 ETH | 0.00000383 | ||||
| Liquidate | 29835257 | 8 days ago | IN | 0 ETH | 0.00000358 | ||||
| Liquidate Strate... | 29833454 | 9 days ago | IN | 0 ETH | 0.00000305 | ||||
| Liquidate | 29833452 | 9 days ago | IN | 0 ETH | 0.00000235 | ||||
| Liquidate | 29807797 | 9 days ago | IN | 0 ETH | 0.00000061 | ||||
| Withdraw | 29790484 | 10 days ago | IN | 0 ETH | 0.00000077 | ||||
| Liquidate | 29788922 | 10 days ago | IN | 0 ETH | 0.00000102 | ||||
| Liquidate | 29761046 | 10 days ago | IN | 0 ETH | 0.00000432 |
Latest 25 internal transactions (View All)
Advanced mode:
Cross-Chain Transactions
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 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/IAssetPriceProvider.sol";
import "../libraries/accounts/AccountLib.sol";
import "../libraries/Errors.sol";
import "./JuiceModule.sol";
import "./JuiceAccount.sol";
import "../managers/CollateralAccountManager.sol";
import "./periphery/BlastGas.sol";
import "./periphery/BlastPoints.sol";
import "../periphery/PythPusher.sol";
abstract contract JuiceAccountManagerEvents {
/// @notice When yield is accrued
event YieldAccrued(uint256 amount);
event AutoCompoundingToggled(bool isAutoCompounding);
}
/// @title JuiceAccountManager supports one account implementation
/// @dev Facilitates collateralization of WETH.
/// @notice The AccountManager contract deploys Account contracts.
contract JuiceAccountManager is
CollateralAccountManager,
PythPusher,
JuiceModule,
JuiceAccountManagerEvents,
BlastGas,
BlastPoints
{
using EnumerableSet for EnumerableSet.AddressSet;
using SafeERC20 for IERC20;
using Address for address;
uint256 public constant MINIMUM_COMPOUND_AMOUNT = 1e6;
bool public isAutoCompounding;
/// @notice Constructs the factory
/// @param params The parameters for the JuiceAccountManager
constructor(
address protocolGovernor_,
address pointsOperator_,
bool isAutoCompounding_,
InitParams memory params
)
JuiceModule(protocolGovernor_)
BlastPoints(protocolGovernor_, pointsOperator_)
BlastGas(protocolGovernor_)
CollateralAccountManager(protocolGovernor_, params)
{
_initializePyth(protocolGovernor_);
IERC20Rebasing(address(params.collateral)).configure(YieldMode.CLAIMABLE);
isAutoCompounding = isAutoCompounding_;
}
function toggleAutoCompounding() public onlyOwner {
isAutoCompounding = !isAutoCompounding;
}
/// @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) = _deposit(assets, msg.sender, receiver);
}
/// @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)
{
if (isAutoCompounding) {
compound();
}
(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)
{
(updatedAssets, updatedShares) = _withdraw(caller, receiver, shares);
updatePythPriceFeeds(pythPricesUpdates);
}
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 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 totalAssets() public view virtual override returns (uint256) {
return _totalCollateralAssets + IERC20Rebasing(address(_collateral)).getClaimableAmount(address(this));
}
}// 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) (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.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/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 { Pausable } from "@openzeppelin/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts/utils/Context.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 { Address } from "@openzeppelin/contracts/utils/Address.sol";
import "../interfaces/ILendingPool.sol";
import "../libraries/Errors.sol";
import "../periphery/Multicall.sol";
/// @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 Multicall, IAccount, AddressCheckerTrait, Initializable, Pausable {
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() {
_disableInitializers();
}
/// @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 (_msgSender() != 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() {
bool isLiquidationReceiver = false;
try _manager.isLiquidationReceiver(_msgSender()) returns (bool _isLiquidationReceiver) {
isLiquidationReceiver = _isLiquidationReceiver;
} catch {
isLiquidationReceiver = false;
}
if (_msgSender() == owner || _msgSender() == address(_manager) || isLiquidationReceiver) {
_;
} else {
revert Errors.Unauthorized();
}
}
///////////////////////
// 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();
}
function multicall(bytes[] calldata data)
public
payable
override
onlyOwner
whenNotPaused
returns (bytes[] memory results)
{
results = super.multicall(data);
}
//////////////////////////
// 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 payable virtual onlyOwner whenNotPaused {
// Borrow funds
_manager.borrow(amount);
}
/// @notice Repay the lending pool
/// @param amount The amount to repay
function repay(uint256 amount) external payable virtual onlyRepayer {
_manager.repay(address(this), amount);
}
/// @notice Repay the lending pool
/// @param amountFrom Additional amount to pull from owner before repayment
function repayFrom(uint256 amountFrom) external payable virtual onlyOwner {
asset.safeTransferFrom(_msgSender(), address(this), amountFrom);
_manager.repay(address(this), asset.balanceOf(address(this)));
}
////////////////////
// Views
////////////////////
/// @notice Returns the AccountManager that created this Account.
function getManager() external view returns (IAccountManager) {
return _manager;
}
function claim(uint256 amount) external payable onlyOwner whenNotPaused {
_manager.claim(amount, _msgSender());
}
function claim(uint256 amount, address recipient) external payable onlyOwner whenNotPaused {
_manager.claim(amount, recipient);
}
}// 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 payable override onlyOwner whenNotPaused {
uint256 amountBorrowed = _manager.borrow(amount);
asset.safeTransfer(_msgSender(), amountBorrowed);
}
/// @notice Repay the lending pool
/// @param amount The amount to repay
function repay(uint256 amount) external payable override whenNotPaused {
_manager.repay(address(this), amount);
}
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";
/// @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 {
using SafeERC20 for IERC20;
/// @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);
uint256 executionGasLimit = 0;
if (strategy != address(0)) {
executionGasLimit = IStrategyVault(strategy).estimateExecuteDepositGasLimit();
}
uint256 executionFee = 0;
if (executionGasLimit > 0) {
executionFee = executionGasLimit * tx.gasprice;
}
receivedShares = _manager.strategyDeposit{ value: executionFee }(owner, strategy, amount, data);
}
/// @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 = _strategyWithdraw(strategy, shares, data);
_manager.strategyWithdrawal(owner, strategy, receivedAssets, false);
}
function strategyWithdrawAndRepay(
address strategy,
uint256 shares,
bytes memory data
)
external
payable
onlyOwner
whenNotPaused
returns (uint256 receivedAssets)
{
_manager.snapshotAccountHealthFactor();
receivedAssets = _strategyWithdraw(strategy, shares, data);
_manager.repay(address(this), receivedAssets);
_manager.strategyWithdrawal(owner, strategy, receivedAssets, true);
}
function _strategyWithdraw(
address strategy,
uint256 shares,
bytes memory data
)
internal
returns (uint256 receivedAssets)
{
uint256 executionGasLimit = 0;
if (strategy != address(0)) {
executionGasLimit = IStrategyVault(strategy).estimateExecuteWithdrawalGasLimit();
}
uint256 executionFee = 0;
if (executionGasLimit > 0) {
executionFee = executionGasLimit * tx.gasprice;
}
receivedAssets = IStrategyVault(strategy).withdraw{ value: executionFee }(shares, data);
}
//////////////////////////
// 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 recipient,
uint256 expectedReceived,
uint256 amountBefore
)
internal
view
{
if (asset.balanceOf(address(recipient)) < (expectedReceived + amountBefore)) {
revert Errors.WithdrawnAssetsNotReceived();
}
}
function liquidateStrategy(
address strategy,
address recipient,
uint256 minAmount,
bytes memory data
)
external
payable
onlyAccountManager
{
uint256 amountBefore = _preStrategyLiquidation(recipient);
uint256 receivedAssets = 0;
uint256 executionGasLimit = 0;
if (strategy != address(0)) {
executionGasLimit = IStrategyVault(strategy).estimateExecuteDepositGasLimit();
}
uint256 executionFee = 0;
if (executionGasLimit > 0) {
executionFee = executionGasLimit * tx.gasprice;
}
if (strategy != address(0)) {
receivedAssets = IStrategyVault(strategy).liquidate{ value: executionFee }(recipient, minAmount, data);
_postStrategyLiquidation(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;
function configurePointsOperatorOnBehalf(address operator, address contractAddress) external;
function operators(address contractAddress) external view returns (address);
function readStatus(address contractAddress) external view returns (address, bool, uint256);
}
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);
function getConfiguration(address contractAddress) external view returns (uint8);
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.24;
/// @title Multicall interface
/// @notice Enables calling multiple methods in a single call to the contract
interface IMulticall {
/// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed
/// @dev The `msg.value` should not be trusted for any method callable from multicall.
/// @param data The encoded function data for each of the calls to make to this contract
/// @return results The results from each of the calls passed in via data
function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);
}// 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 {
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 payable;
function repay(uint256 amount) external payable;
function claim(uint256 amount) external payable;
function claim(uint256 amount, address recipient) 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 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);
function getAccountOwner(address account) external returns (address owner);
// 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, bool didRepay) external;
function snapshotAccountHealthFactor() external;
function setAllowedAccountsMode(bool status) external;
function setAllowedAccountStatus(address account, bool status) 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);
}// 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
* @param asset the address of the asset
* @return price of the asset
*
*/
function getAssetPrice(address asset) external view returns (uint256);
}// 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 { 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 setInterestRateStrategy(address newStrategy) 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 setFee(bytes32 id, UD60x18 newFee) external;
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;
import { UD60x18 } from "@prb/math/src/UD60x18.sol";
/// @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 {
function setTotalDepositCap(uint256 newDepositCap) external;
function setMaxDepositPerAccount(uint256 newMaxDeposit) external;
function setDepositFee(UD60x18 newDepositFee) external;
function setWithdrawalFee(UD60x18 newWithdrawalFee) external;
/// @notice Estimate the ETH execution fee needed for this withdrawal
function estimateExecuteDepositGasLimit() external view returns (uint256);
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);
function previewDepositOffchain(uint256 assetAmount) external returns (uint256);
function previewWithdrawOffchain(uint256 shareAmount) external 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 { 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 "../periphery/PythPusher.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, PythPusher {
using SafeERC20 for IERC20;
/// @notice Initialize this permissioned account
/// @param owner_ The borrower that owns this account
function initialize(address owner_) public virtual override initializer {
_initialize(owner_);
address _protocolGovernor = ProtocolModule(msg.sender).getProtocolGovernor();
_initializePyth(_protocolGovernor);
// Configure Blast Points
IBlastPoints blast =
IBlastPoints(IProtocolGovernor(_protocolGovernor).getImmutableAddress(GovernorLib.BLAST_POINTS));
address operator_ =
IProtocolGovernor(_protocolGovernor).getAddress(GovernorLib.BLAST_POINTS_JUICE_ACCOUNTS_OPERATOR);
if (operator_ == address(0)) {
revert Errors.InvalidParams();
} else {
blast.configurePointsOperator(operator_);
}
}
function getKind() external pure override returns (bytes32) {
return keccak256(abi.encode("JUICE_INVESTMENT_ACCOUNT"));
}
}// 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);
// Particle
error ExistingPosition();
error NoPosition();
}// 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"));
/// @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"));
bytes32 public constant BLAST_POINTS_JUICE_ACCOUNTS_OPERATOR =
keccak256(abi.encode("BLAST_POINTS_JUICE_ACCOUNTS_OPERATOR"));
/// @dev Currently unused. Was meant to allow Accounts to redirect yield from idle borrow back to Lending Pool.
bytes32 public constant BLAST_LENDER_YIELD_SINK = keccak256(abi.encode("BLAST_LENDER_YIELD_SINK"));
///////////////
// 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"));
/// @notice Protocol maintainer
/// @dev A trusted address that can perform maintenance tasks. This will likely be a hot wallet.
bytes32 public constant PROTOCOL_MAINTAINER = keccak256(abi.encode("PROTOCOL_MAINTAINER"));
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;
UD60x18 healthFactor;
bool isLiquidatable;
bool isRisky;
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 "solady/src/utils/FixedPointMathLib.sol";
import { Pausable } from "@openzeppelin/contracts/utils/Pausable.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 { 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, Pausable, AccountManagerEvents, ProtocolModule, ReentrancyGuard {
using EnumerableSet for EnumerableSet.AddressSet;
using SafeERC20 for IERC20;
using Address for address;
using FixedPointMathLib for uint256;
error OldAccountDoesNotExist();
error HealthFactorSnapshotNotFound();
error RemainingDebtLeft();
/// @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;
bool public allowedAccountsMode;
mapping(address => bool) public isAccountAllowed;
/// @dev Used for storing the health factor of an account for comparison before and after some action.
mapping(address => UD60x18) internal _accountHealthFactorSnapshot;
// Account configurations
///////////////////////////
address immutable liquidationReceiverImpl;
modifier onlyAccount() {
if (!isCreatedAccount[msg.sender]) {
revert Errors.Unauthorized();
}
if (allowedAccountsMode && !isAccountAllowed[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())
nonZeroAddressAndContract(liquidationReceiverImpl_)
{
liquidationReceiverImpl = liquidationReceiverImpl_;
_lendingPool = ILendingPool(_getLendingPool());
_lendAsset = IERC20(_getLendAsset());
allowedAccountsMode = true;
}
//////////////////////////
// Account Administration
//////////////////////////
function setAllowedAccountsMode(bool status) external onlyOwner {
allowedAccountsMode = status;
}
function setAllowedAccountStatus(address account, bool status) external onlyOwner {
isAccountAllowed[account] = status;
}
function isLiquidationReceiver(address receiver) external view returns (bool) {
return _isLiquidationReceiver[receiver];
}
function getAccountOwner(address account) external view returns (address owner) {
owner = _accountOwnerCache[account];
}
/// @notice Let the owner pause deposits and borrows
function pause() external onlyOwner {
_pause();
}
/// @notice Let the owner unpause deposits and borrows
function unpause() external onlyOwner {
_unpause();
}
/// @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 {
_requireSolventCheckBorrow(account, true);
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 whenNotPaused returns (uint256 borrowed) {
borrowed = _lendingPool.borrow(amount, caller);
_requireSolventCheckBorrow(caller, true);
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 {
uint256 debtAmount = getDebtAmount(msg.sender);
if (debtAmount > 0) {
uint256 investmentValue = getTotalAccountValue(msg.sender);
uint256 profit = investmentValue.zeroFloorSub(debtAmount);
if (amount > profit) {
revert Errors.NotClaimableProfit();
}
_lendAsset.safeTransferFrom(msg.sender, recipient, amount);
_requireSolventCheckBorrow(msg.sender, true);
} else {
_lendAsset.safeTransferFrom(msg.sender, recipient, amount);
}
emit AccountClaimed(_accountOwnerCache[msg.sender], msg.sender, amount);
}
/// @dev Account cannot do any actions involving snapshots if it is being liquidated.
function snapshotAccountHealthFactor() external onlyAccount {
AccountLib.Health memory health = getAccountHealth(msg.sender);
if (health.isLiquidatable) revert Errors.AccountBeingLiquidated();
_accountHealthFactorSnapshot[msg.sender] = health.healthFactor;
}
/// @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);
}
/// @dev Used to get the health factor of an account at the current block number.
function _getLatestAccountHealthFactorSnapshot(address account) internal view returns (UD60x18 healthFactor) {
healthFactor = _accountHealthFactorSnapshot[account];
if (healthFactor == ZERO) revert HealthFactorSnapshotNotFound();
}
/////////////////////////
// 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 {
_requireSolventCheckBorrow(account, false);
}
function _requireSolventCheckBorrow(address account, bool checkBorrow) internal view {
// Actions depending on solvency cannot be performed during liquidation state.
if (_accountLiquidationStartTime[account] > 0) {
revert Errors.AccountBeingLiquidated();
}
// Only perform solvency check if Account has debt.
if (getDebtAmount(account) > 0) {
AccountLib.Health memory health = getAccountHealth(account);
if (checkBorrow) {
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 is at risk (this keeps it some % above
// the liquidation threshold).
if (health.isRisky) {
revert Errors.AccountInsolvent();
}
}
}
///////////////////
// HOOKS
///////////////////
function _afterRepay(address account, uint256) external virtual onlySelf {
if (_accountLiquidationStartTime[account] > 0) {
AccountLib.Health memory health = getAccountHealth(account);
if (!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 "../managers/StrategyAccountManager.sol";
import "../interfaces/IAssetPriceProvider.sol";
import "../libraries/accounts/AccountLib.sol";
import "../libraries/Errors.sol";
import "../system/ERC20CollateralVault.sol";
import "../system/ProtocolModule.sol";
abstract contract CollateralAccountManagerEvents {
/// @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, address sender, uint256 amount);
/// @notice A user has withdrawn WETH from the contract.
event CollateralWithdrawal(address indexed owner, address account, address receiver, uint256 amount);
/// @notice CollateralLiquidation
event CollateralLiquidation(
address account, uint256 collateralAmount, uint256 bonusCollateral, uint256 debtAmountNeeded
);
event LiquidationParametersUpdated(UD60x18 maxLtv, UD60x18 riskThreshold, UD60x18 liquidationThreshold);
}
/// @title CollateralAccountManager supports one account implementation
/// @notice The AccountManager contract deploys Account contracts.
abstract contract CollateralAccountManager is
StrategyAccountManager,
CollateralAccountManagerEvents,
ERC20CollateralVault
{
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%
/// @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 risk threshold for accounts
/// @dev (Investment value + Equity value) / Debt value > riskThreshold
UD60x18 public riskThreshold;
/// @notice The risk 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 accountImplementation;
mapping(address => address) internal _ownerAccountCache;
struct InitParams {
address account;
address liquidationReceiver;
address collateral;
UD60x18 maxLtv;
UD60x18 riskThreshold;
UD60x18 liquidationThreshold;
string name;
string symbol;
uint8 decimals;
}
/// @notice Constructs the factory
/// @param params The parameters
constructor(
address protocolGovernor_,
InitParams memory params
)
StrategyAccountManager(protocolGovernor_, params.liquidationReceiver)
ERC20CollateralVault(params.collateral, params.name, params.symbol, params.decimals)
nonZeroAddressAndContract(params.account)
{
accountImplementation = params.account;
_validateLiquidationParameters(params.maxLtv, params.riskThreshold, params.liquidationThreshold);
maxLtv = params.maxLtv;
riskThreshold = params.riskThreshold;
liquidationThreshold = params.liquidationThreshold;
}
function _validateLiquidationParameters(
UD60x18 maxLtv_,
UD60x18 riskThreshold_,
UD60x18 liquidationThreshold_
)
internal
pure
{
if (riskThreshold_ > maxLtv_ || liquidationThreshold_ > maxLtv_ || liquidationThreshold_ > riskThreshold_) {
revert Errors.InvalidParams();
}
}
/// @dev Updates maxLtv and riskThreshold.
/// riskThreshold must always be less than maxLtv.
function updateLiquidationParameters(
UD60x18 maxLtv_,
UD60x18 riskThreshold_,
UD60x18 liquidationThreshold_
)
external
onlyOwner
{
_validateLiquidationParameters(maxLtv_, riskThreshold_, liquidationThreshold);
maxLtv = maxLtv_;
riskThreshold = riskThreshold_;
liquidationThreshold = liquidationThreshold_;
emit LiquidationParametersUpdated(maxLtv, riskThreshold, liquidationThreshold);
}
/// @dev This call requires that this contract is the account manager on the lending pool
function createAccount() public nonReentrant returns (address payable account) {
account = _createAccount(msg.sender);
}
function _createAccount(address caller) internal returns (address payable account) {
address owner = caller;
if (_ownerAccountCache[owner] != address(0)) {
revert Errors.InvalidParams();
}
account = payable(Clones.cloneDeterministic(accountImplementation, _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
IAccount(account).initialize(owner);
}
/// @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
virtual
override
nonReentrant
returns (uint256 updatedAssets, uint256 shares)
{
(updatedAssets, shares) = _deposit(assets, msg.sender, receiver);
}
function _deposit(
uint256 assets,
address caller,
address receiver
)
internal
returns (uint256 updatedAssets, uint256 shares)
{
address _receiverAccount = getAccount(receiver);
if (!isCreatedAccount[_receiverAccount]) {
revert Errors.InvalidParams();
}
(updatedAssets, shares) = super.deposit(assets, receiver);
emit CollateralDeposit(receiver, _receiverAccount, caller, updatedAssets);
}
/// @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
virtual
override
nonReentrant
returns (uint256 updatedAssets, uint256 updatedShares)
{
(updatedAssets, updatedShares) = _withdraw(msg.sender, receiver, shares);
}
function _withdraw(
address caller,
address receiver,
uint256 shares
)
internal
override
returns (uint256 updatedAssets, uint256 updatedShares)
{
(updatedAssets, updatedShares) = super._withdraw(caller, receiver, shares);
address account = getAccount(caller);
_requireSolventCheckBorrow(account, true);
emit CollateralWithdrawal(caller, getAccount(caller), receiver, updatedAssets);
}
///////////////////////////
// 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;
}
/////////////////////////
// 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(accountImplementation, _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,
isRisky: false,
hasBadDebt: false,
healthFactor: ZERO,
debtAmount: debtAmount,
collateralValue: collateralValue,
investmentValue: investmentValue
});
if (debtAmount > 0 && equity > 0) {
health.healthFactor = ud(equity).div(ud(debtAmount));
health.isRisky = health.healthFactor < riskThreshold;
health.isLiquidatable = health.healthFactor < liquidationThreshold;
} 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: 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_)
{ }
/// @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);
}
uint256 executionGasLimit = 0;
if (strategy != address(0)) {
executionGasLimit = IStrategyVault(strategy).estimateExecuteDepositGasLimit();
}
uint256 executionFee = 0;
if (executionGasLimit > 0) {
executionFee = executionGasLimit * tx.gasprice;
}
shares = IStrategyVault(strategy).deposit{ value: executionFee }(amount, data, caller);
emit StrategyDeposit(owner, strategy, caller, amount);
_requireSolventCheckBorrow(caller, true);
}
function strategyWithdrawal(
address owner,
address strategy,
uint256 assets,
bool didRepay
)
external
virtual
onlyAccount
nonReentrant
{
_strategyWithdrawal(msg.sender, owner, strategy, assets, didRepay);
}
function _strategyWithdrawal(
address caller,
address owner,
address strategy,
uint256 assets,
bool didRepay
)
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);
}
// Caller repaid with strategy withdrawal, skip solvency check and make sure their health factor improved.
// They should have requested for a snapshot to be taken earlier.
if (didRepay) {
UD60x18 lastHealthFactor = _getLatestAccountHealthFactorSnapshot(caller);
UD60x18 currentHealthFactor = getAccountHealth(caller).healthFactor;
if (lastHealthFactor > currentHealthFactor) {
revert Errors.AccountInsolvent();
}
_accountHealthFactorSnapshot[caller] = ZERO;
} else {
_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);
// We calculate this as the strategy level now. Leftover for backwards compatibility.
uint256 minAmountAfterSlippage = 0;
uint256 executionGasLimit = 0;
if (strategy != address(0)) {
executionGasLimit = IStrategyVault(strategy).estimateExecuteWithdrawalGasLimit();
}
uint256 executionFee = 0;
if (executionGasLimit > 0) {
executionFee = executionGasLimit * tx.gasprice;
}
IInternalAccount(account).liquidateStrategy{ value: executionFee }(
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 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 "../external/uniswap/interfaces/IMulticall.sol";
/// @title Multicall
/// @notice Enables calling multiple methods in a single call to the contract
abstract contract Multicall is IMulticall {
/// @inheritdoc IMulticall
function multicall(bytes[] calldata data) public payable virtual override returns (bytes[] memory results) {
results = new bytes[](data.length);
for (uint256 i = 0; i < data.length; i++) {
(bool success, bytes memory result) = address(this).delegatecall(data[i]);
if (!success) {
// Next 5 lines from https://ethereum.stackexchange.com/a/83577
if (result.length < 68) revert();
assembly {
result := add(result, 0x04)
}
revert(abi.decode(result, (string)));
}
results[i] = result;
}
}
}// 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.
abstract contract PythPusher {
IPyth pyth;
function _initializePyth(address protocolGovernor_) internal {
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 "../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 { 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);
event ProtocolDeprecatedStatusSet(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;
emit ProtocolDeprecatedStatusSet(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");
_;
}
modifier onlyProtocolMaintainer() {
_protocolGovernor._validateRole(msg.sender, Roles.PROTOCOL_MAINTAINER, "PROTOCOL_MAINTAINER");
_;
}
/**
* @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);
}
// 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"},{"internalType":"address","name":"pointsOperator_","type":"address"},{"internalType":"bool","name":"isAutoCompounding_","type":"bool"},{"components":[{"internalType":"address","name":"account","type":"address"},{"internalType":"address","name":"liquidationReceiver","type":"address"},{"internalType":"address","name":"collateral","type":"address"},{"internalType":"UD60x18","name":"maxLtv","type":"uint256"},{"internalType":"UD60x18","name":"riskThreshold","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 CollateralAccountManager.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":"EnforcedPause","type":"error"},{"inputs":[],"name":"ExpectedPause","type":"error"},{"inputs":[],"name":"FailedInnerCall","type":"error"},{"inputs":[],"name":"HealthFactorSnapshotNotFound","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":[],"name":"OldAccountDoesNotExist","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":[],"name":"RemainingDebtLeft","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":false,"internalType":"bool","name":"isAutoCompounding","type":"bool"}],"name":"AutoCompoundingToggled","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":false,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"address","name":"sender","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":"address","name":"receiver","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":false,"internalType":"UD60x18","name":"maxLtv","type":"uint256"},{"indexed":false,"internalType":"UD60x18","name":"riskThreshold","type":"uint256"},{"indexed":false,"internalType":"UD60x18","name":"liquidationThreshold","type":"uint256"}],"name":"LiquidationParametersUpdated","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":false,"internalType":"address","name":"account","type":"address"}],"name":"Paused","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":"address","name":"account","type":"address"}],"name":"Unpaused","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":[],"name":"accountImplementation","outputs":[{"internalType":"address","name":"","type":"address"}],"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":[],"name":"allowedAccountsMode","outputs":[{"internalType":"bool","name":"","type":"bool"}],"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"}],"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":"UD60x18","name":"healthFactor","type":"uint256"},{"internalType":"bool","name":"isLiquidatable","type":"bool"},{"internalType":"bool","name":"isRisky","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":"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"}],"name":"getAccountOwner","outputs":[{"internalType":"address","name":"owner","type":"address"}],"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":"","type":"address"}],"name":"isAccountAllowed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"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":"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":[],"name":"pause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"pauseAccount","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"paused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","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":[],"name":"riskThreshold","outputs":[{"internalType":"UD60x18","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"bool","name":"status","type":"bool"}],"name":"setAllowedAccountStatus","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bool","name":"status","type":"bool"}],"name":"setAllowedAccountsMode","outputs":[],"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":[],"name":"snapshotAccountHealthFactor","outputs":[],"stateMutability":"nonpayable","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":"assets","type":"uint256"},{"internalType":"bool","name":"didRepay","type":"bool"}],"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":[],"name":"unpause","outputs":[],"stateMutability":"nonpayable","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":"riskThreshold_","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
6101606040523480156200001257600080fd5b50604051620062fd380380620062fd8339810160408190526200003591620009f1565b604081015160c082015160e083015161010084015160208501516000805460ff191690556001600160a01b03891660805260018055889488948694859485948a9493929190869081816200008862000665565b6001600160a01b038116620000b05760405163d92e233d60e01b815260040160405180910390fd5b6001600160a01b0381163b620000d957604051630b0f2dd560e31b815260040160405180910390fd5b620000e362000729565b6001600160a01b0381166200010b5760405163d92e233d60e01b815260040160405180910390fd5b6001600160a01b0381163b6200013457604051630b0f2dd560e31b815260040160405180910390fd5b826001600160a01b0381166200015d5760405163d92e233d60e01b815260040160405180910390fd5b6001600160a01b0381163b6200018657604051630b0f2dd560e31b815260040160405180910390fd5b6001600160a01b03841660e0526200019d62000729565b6001600160a01b031660a052620001b36200076d565b6001600160a01b0390811660c0526008805460ff191660011790558b975087169550620001f99450505050505760405163d92e233d60e01b815260040160405180910390fd5b6001600160a01b0381163b6200022257604051630b0f2dd560e31b815260040160405180910390fd5b6001600160a01b0385166101005260ff821661012052600e62000246858262000bcb565b50600f62000255848262000bcb565b505084519350506001600160a01b03831691506200028890505760405163d92e233d60e01b815260040160405180910390fd5b6001600160a01b0381163b620002b157604051630b0f2dd560e31b815260040160405180910390fd5b81516001600160a01b0316610140526060820151608083015160a0840151620002dc929190620007af565b506060810151601055608081015160115560a0015160125550806001600160a01b0381166200031e5760405163d92e233d60e01b815260040160405180910390fd5b6001600160a01b0381163b6200034757604051630b0f2dd560e31b815260040160405180910390fd5b50601580546001600160a01b039283166001600160a01b0319918216179091556016805492841692909116821790556040516000919063c824e15790620003aa9060200160208082526005908201526410931054d560da1b604082015260600190565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b8152600401620003df91815260200190565b602060405180830381865afa158015620003fd573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062000423919062000c97565b9050806001600160a01b0316634e606c476040518163ffffffff1660e01b8152600401600060405180830381600087803b1580156200046157600080fd5b505af115801562000476573d6000803e3d6000fd5b5050601780546001600160a01b0388166001600160a01b031990911681179091556040516000955090935063c824e1579250620004d791506020016020808252600c908201526b424c4153545f504f494e545360a01b604082015260600190565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b81526004016200050c91815260200190565b602060405180830381865afa1580156200052a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062000550919062000c97565b6040516336b91f2b60e01b81526001600160a01b038481166004830152919250908216906336b91f2b90602401600060405180830381600087803b1580156200059857600080fd5b505af1158015620005ad573d6000803e3d6000fd5b50505050505050620005c584620007ec60201b60201c565b80604001516001600160a01b0316631a33757d60026040518263ffffffff1660e01b8152600401620005f8919062000cbc565b6020604051808303816000875af115801562000618573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906200063e919062000ce5565b505060178054911515600160a01b0260ff60a01b199092169190911790555062000cff9050565b60006080516001600160a01b03166321f8a721604051602001620006ab906020808252600e908201526d282924a1a2afa82927ab24a222a960911b604082015260600190565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b8152600401620006e091815260200190565b602060405180830381865afa158015620006fe573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062000724919062000c97565b905090565b60006080516001600160a01b031663c824e157604051602001620006ab906020808252600c908201526b13115391125391d7d413d3d360a21b604082015260600190565b60006080516001600160a01b031663c824e157604051602001620006ab906020808252600a90820152691311539117d054d4d15560b21b604082015260600190565b81831080620007bd57508083105b80620007c857508082105b15620007e757604051635435b28960e11b815260040160405180910390fd5b505050565b806001600160a01b031663c824e15760405160200162000824906020808252600490820152630a0b2a8960e31b604082015260600190565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b81526004016200085991815260200190565b602060405180830381865afa15801562000877573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906200089d919062000c97565b601480546001600160a01b0319166001600160a01b039290921691909117905550565b80516001600160a01b0381168114620008d857600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60405161012081016001600160401b0381118282101715620009195762000919620008dd565b60405290565b604051601f8201601f191681016001600160401b03811182821017156200094a576200094a620008dd565b604052919050565b600082601f8301126200096457600080fd5b81516001600160401b03811115620009805762000980620008dd565b602062000996601f8301601f191682016200091f565b8281528582848701011115620009ab57600080fd5b60005b83811015620009cb578581018301518282018401528201620009ae565b506000928101909101919091529392505050565b805160ff81168114620008d857600080fd5b6000806000806080858703121562000a0857600080fd5b62000a1385620008c0565b935062000a2360208601620008c0565b92506040850151801515811462000a3957600080fd5b60608601519092506001600160401b038082111562000a5757600080fd5b90860190610120828903121562000a6d57600080fd5b62000a77620008f3565b62000a8283620008c0565b815262000a9260208401620008c0565b602082015262000aa560408401620008c0565b6040820152606083015160608201526080830151608082015260a083015160a082015260c08301518281111562000adb57600080fd5b62000ae98a82860162000952565b60c08301525060e08301518281111562000b0257600080fd5b62000b108a82860162000952565b60e083015250610100915062000b28828401620009df565b8282015280935050505092959194509250565b600181811c9082168062000b5057607f821691505b60208210810362000b7157634e487b7160e01b600052602260045260246000fd5b50919050565b601f821115620007e7576000816000526020600020601f850160051c8101602086101562000ba25750805b601f850160051c820191505b8181101562000bc35782815560010162000bae565b505050505050565b81516001600160401b0381111562000be75762000be7620008dd565b62000bff8162000bf8845462000b3b565b8462000b77565b602080601f83116001811462000c37576000841562000c1e5750858301515b600019600386901b1c1916600185901b17855562000bc3565b600085815260208120601f198616915b8281101562000c685788860151825594840194600190910190840162000c47565b508582101562000c875787850151600019600388901b60f8161c191681555b5050505050600190811b01905550565b60006020828403121562000caa57600080fd5b62000cb582620008c0565b9392505050565b602081016003831062000cdf57634e487b7160e01b600052602160045260246000fd5b91905290565b60006020828403121562000cf857600080fd5b5051919050565b60805160a05160c05160e0516101005161012051610140516154e662000e176000396000818161056201528181612e140152613c920152600081816106a80152611b2901526000818161102e01528181611aa601528181612a3801528181612af201528181613b5c015281816140670152818161473c0152614852015260008181611901015261378b0152600081816111b3015281816127b90152818161280001528181612d06015281816137ec0152818161393e015281816139c10152613a56015260008181610bf4015281816114f601528181611e4c01528181611ec60152613e56015260008181610a6301528181612f4901528181612fe4015281816133c8015281816140d601526141ba01526154e66000f3fe6080604052600436106103fd5760003560e01c80637ecebe0011610215578063bd1c5d7411610124578063e1d5c064116100b1578063e1d5c06414610ded578063e4af29fc14610e0d578063e59e801814610e23578063ef48644614610e9f578063ef8b30f714610ebf578063f2468d8714610edf578063f69e204614610eff578063f9566d8214610f14578063fbcbc0f114610f34578063fbf4198414610f54578063ffc5ab1614610f8457600080fd5b8063bd1c5d7414610ca6578063c5ebeaec14610cc6578063c613aec014610ce6578063ca8bcd66146109cc578063cb6c0c9a14610d16578063d505accf14610d36578063d8cab31814610d56578063dd62ed3e14610d77578063dd76401714610dad578063ddd5e1b214610dcd57600080fd5b806399f8148e116101a257806399f8148e14610b555780639d919c6314610b8e5780639dca362f14610bd0578063a59a997314610be5578063a612ce2b14610c18578063a9059cbb14610c38578063b17e32f914610c53578063b2b8c93f14610c68578063b3c0a0b314610c7d578063b43e6cb414610c9057600080fd5b80637ecebe00146109ec5780638456cb5914610a1f57806386b9d81f14610a3457806389dbb85714610a5457806390401a7a14610a875780639159b20614610aa757806394408b9a14610ac757806395d89b4114610ae7578063971d6c9514610afc578063985d28aa14610b1c57600080fd5b80633a12c6da116103115780635af451cc1161029e5780635af451cc146108cd5780635c975abb146108e25780636806eaab146108fa5780636856728e1461091a5780636a11d0b21461092f5780636c648fc4146109465780636e553f651461096657806370a08231146109865780637af0bdfd146109b95780637b91c265146109cc57600080fd5b80633a12c6da146107035780633f4ba83a146107195780634031234c1461072e578063410051a514610744578063442b172c1461079757806347a873cb146107d057806347e41a89146107f0578063484d1ad61461086d5780635507f5e91461088d5780635a287cb2146108ad57600080fd5b806312fde4b71161038f57806312fde4b7146105915780631534a277146105a657806318160ddd146105e75780631e8a84b1146106045780631fd9a8c61461062457806322867d781461065457806323b872dd14610674578063313ce567146106945780633574d4c4146106d25780633644e515146106ee57600080fd5b8062f714ce1461040257806301e1d1141461043c578063032e9c761461045f5780630674fa411461047457806306fdde03146104945780630914b18f146104b6578063095ea7b3146104f65780630a28a477146105165780630ba212ee1461053657806311464fbe14610550575b600080fd5b34801561040e57600080fd5b5061042261041d366004614ac3565b610f97565b604080519283526020830191909152015b60405180910390f35b34801561044857600080fd5b50610451611014565b604051908152602001610433565b61047261046d366004614c46565b6110b6565b005b34801561048057600080fd5b5061045161048f366004614c7a565b611199565b3480156104a057600080fd5b506104a96112fe565b6040516104339190614ce7565b3480156104c257600080fd5b506104e66104d1366004614c7a565b60026020526000908152604090205460ff1681565b6040519015158152602001610433565b34801561050257600080fd5b506104e6610511366004614cfa565b611390565b34801561052257600080fd5b50610422610531366004614d26565b6113e4565b34801561054257600080fd5b506008546104e69060ff1681565b34801561055c57600080fd5b506105847f000000000000000000000000000000000000000000000000000000000000000081565b6040516104339190614d3f565b34801561059d57600080fd5b506105846113f6565b3480156105b257600080fd5b506105846105c1366004614d53565b60056020908152600092835260408084209091529082529020546001600160a01b031681565b3480156105f357600080fd5b506805345cdf77eb68f44c54610451565b34801561061057600080fd5b5061047261061f366004614d8f565b611400565b34801561063057600080fd5b506104e661063f366004614c7a565b60096020526000908152604090205460ff1681565b34801561066057600080fd5b5061045161066f366004614cfa565b6114c0565b34801561068057600080fd5b506104e661068f366004614dbd565b611619565b3480156106a057600080fd5b5060405160ff7f0000000000000000000000000000000000000000000000000000000000000000168152602001610433565b3480156106de57600080fd5b50610451670e92596fd629000081565b3480156106fa57600080fd5b50610451611634565b34801561070f57600080fd5b5061045160105481565b34801561072557600080fd5b506104726116b1565b34801561073a57600080fd5b5061045160125481565b34801561075057600080fd5b5061076461075f366004614c7a565b6116ce565b60405161043391908151815260208083015190820152604080830151908201526060918201519181019190915260800190565b3480156107a357600080fd5b506105846107b2366004614c7a565b6001600160a01b039081166000908152600360205260409020541690565b3480156107dc57600080fd5b506104726107eb366004614cfa565b61175b565b3480156107fc57600080fd5b5061085061080b366004614c7a565b60408051808201825260008082526020918201819052825180840184526001600160a01b03949094168082526004808452938220548015158652915291815282015290565b604080518251151581526020928301519281019290925201610433565b34801561087957600080fd5b50610472610888366004614c7a565b6117f4565b34801561089957600080fd5b506104726108a8366004614dfe565b611868565b3480156108b957600080fd5b506105846108c8366004614d53565b6118fa565b3480156108d957600080fd5b50610472611955565b3480156108ee57600080fd5b5060005460ff166104e6565b34801561090657600080fd5b50610472610915366004614e51565b611a09565b34801561092657600080fd5b50610472611a2f565b34801561093b57600080fd5b50610451620f424081565b34801561095257600080fd5b50610451610961366004614c7a565b611a63565b34801561097257600080fd5b50610422610981366004614ac3565b611b6c565b34801561099257600080fd5b506104516109a1366004614c7a565b6387a211a2600c908152600091909152602090205490565b6104516109c7366004614e6e565b611b9e565b3480156109d857600080fd5b506104726109e7366004614c7a565b611c34565b3480156109f857600080fd5b50610451610a07366004614c7a565b6338377508600c908152600091909152602090205490565b348015610a2b57600080fd5b50610472611c56565b348015610a4057600080fd5b50610584610a4f366004614d53565b611c71565b348015610a6057600080fd5b507f0000000000000000000000000000000000000000000000000000000000000000610584565b348015610a9357600080fd5b50610584610aa2366004614cfa565b611c7d565b348015610ab357600080fd5b50610451610ac2366004614c7a565b611c9f565b348015610ad357600080fd5b50610472610ae2366004614c7a565b611cbd565b348015610af357600080fd5b506104a9611d0b565b348015610b0857600080fd5b50610472610b17366004614ed9565b611d1a565b348015610b2857600080fd5b506104e6610b37366004614c7a565b6001600160a01b03166000908152600b602052604090205460ff1690565b348015610b6157600080fd5b506104e6610b70366004614c7a565b6001600160a01b031660009081526006602052604090205460ff1690565b348015610b9a57600080fd5b50610bae610ba9366004614f1f565b611da5565b6040805182518152602080840151908201529181015190820152606001610433565b348015610bdc57600080fd5b50610584611e11565b348015610bf157600080fd5b507f0000000000000000000000000000000000000000000000000000000000000000610584565b348015610c2457600080fd5b50610451610c33366004614c7a565b611e32565b348015610c4457600080fd5b506104e661068f366004614cfa565b348015610c5f57600080fd5b50610584611ec2565b348015610c7457600080fd5b50610451611f46565b610584610c8b366004614f54565b61215b565b348015610c9c57600080fd5b5061045160115481565b348015610cb257600080fd5b50610472610cc1366004614fb0565b61235a565b348015610cd257600080fd5b50610451610ce1366004614d26565b6123cf565b348015610cf257600080fd5b506104e6610d01366004614c7a565b600b6020526000908152604090205460ff1681565b348015610d2257600080fd5b50610472610d31366004614d8f565b61245f565b348015610d4257600080fd5b50610472610d51366004614fdc565b61249d565b348015610d6257600080fd5b506017546104e690600160a01b900460ff1681565b348015610d8357600080fd5b50610451610d92366004614d53565b602052637f5e9f20600c908152600091909152603490205490565b348015610db957600080fd5b50610472610dc8366004614c7a565b612626565b348015610dd957600080fd5b50610472610de8366004614ac3565b6126c6565b348015610df957600080fd5b50610451610e08366004614c7a565b612882565b348015610e1957600080fd5b5061045160075481565b348015610e2f57600080fd5b50610e43610e3e366004614c7a565b6128a3565b6040516104339190600060e0820190508251825260208301516020830152604083015160408301526060830151606083015260808301511515608083015260a0830151151560a083015260c0830151151560c083015292915050565b348015610eab57600080fd5b50610472610eba366004614cfa565b6129aa565b348015610ecb57600080fd5b50610422610eda366004614d26565b6129cc565b348015610eeb57600080fd5b50610bae610efa366004614cfa565b6129ea565b348015610f0b57600080fd5b50610451612a26565b348015610f2057600080fd5b50610472610f2f366004615053565b612bac565b348015610f4057600080fd5b50610584610f4f366004614c7a565b612def565b348015610f6057600080fd5b50610f69612e41565b60408051825181526020928301519281019290925201610433565b610422610f92366004615095565b612e6f565b600080610fa2612e9c565b601754600160a01b900460ff1615610fbe57610fbc612a26565b505b610fff3384866000604051908082528060200260200182016040528015610ff957816020015b6060815260200190600190039081610fe45790505b50612ec6565b909250905061100d60018055565b9250929050565b60405163e12f3a6160e01b81526000906001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063e12f3a6190611063903090600401614d3f565b602060405180830381865afa158015611080573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110a491906150ed565b600d546110b1919061511c565b905090565b8051156111965760145460405163d47eed4560e01b81526000916001600160a01b03169063d47eed45906110ee90859060040161512f565b602060405180830381865afa15801561110b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061112f91906150ed565b601454604051631df3cbc560e31b81529192506001600160a01b03169063ef9e5e2890839061116290869060040161512f565b6000604051808303818588803b15801561117b57600080fd5b505af115801561118f573d6000803e3d6000fd5b5050505050505b50565b6040516370a0823160e01b81526000906001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906370a08231906111e8908590600401614d3f565b602060405180830381865afa158015611205573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061122991906150ed565b905060005b6001600160a01b0383166000908152600c6020526040902061124f90612eeb565b8110156112f8576001600160a01b0383166000908152600c602052604090206112789082612ef5565b6001600160a01b0316631c083f6a846040518263ffffffff1660e01b81526004016112a39190614d3f565b602060405180830381865afa1580156112c0573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112e491906150ed565b6112ee908361511c565b915060010161122e565b50919050565b6060600e805461130d90615193565b80601f016020809104026020016040519081016040528092919081815260200182805461133990615193565b80156113865780601f1061135b57610100808354040283529160200191611386565b820191906000526020600020905b81548152906001019060200180831161136957829003601f168201915b5050505050905090565b600082602052637f5e9f20600c5233600052816034600c205581600052602c5160601c337f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92560206000a35060015b92915050565b6000806113f083612f01565b93915050565b60006110b1612f45565b61140933612fd6565b61145d57335b60408051637974da6f60e01b81526001600160a01b0390921660048301526024820152600e60448201526d282927aa27a1a7a62fa0a226a4a760911b60648201526084015b60405180910390fd5b6001600160a01b0382166000818152600b6020908152604091829020805460ff19168515159081179091558251938452908301527ffc2e7375e815d084de88de8e8e356e71102275019b06a1b529eee0c8ab57cd34910160405180910390a15050565b60006114ca612e9c565b60405163c883b2e560e01b8152600481018390526001600160a01b0384811660248301523360448301527f0000000000000000000000000000000000000000000000000000000000000000169063c883b2e5906064016020604051808303816000875af115801561153f573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061156391906150ed565b6001600160a01b0384811660008181526003602090815260409182902054915185815294955091939216917fa42e379bd7db0adade1690b7b2b3b81c2419c87c3c9f0c4f4f5a4da3ce8a8966910160405180910390a36040516347a873cb60e01b815230906347a873cb906115de90869085906004016151c7565b600060405180830381600087803b1580156115f857600080fd5b505af115801561160c573d6000803e3d6000fd5b505050506113de60018055565b600060405163a24e573d60e01b815260040160405180910390fd5b60008061163f6112fe565b8051906020012090506040517f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f81528160208201527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6604082015246606082015230608082015260a081209250505090565b6116ba33612fd6565b6116c4573361140f565b6116cc613082565b565b6116f96040518060800160405280600081526020016000815260200160008152602001600081525090565b600061170483611a63565b9050600061171184611e32565b90506000821561172a5761172783835b906130ce565b90505b604051806080016040528083815260200184815260200182815260200161175060105490565b905295945050505050565b33301461177d5733604051637974da6f60e01b815260040161145491906151e0565b6001600160a01b038216600090815260046020526040902054156117f05760006117a6836128a3565b905080608001516117ee5760405163dd76401760e01b8152309063dd764017906117d4908690600401614d3f565b600060405180830381600087803b15801561117b57600080fd5b505b5050565b6117fd33612fd6565b611807573361140f565b6118128160016130e6565b806001600160a01b0316638456cb596040518163ffffffff1660e01b8152600401600060405180830381600087803b15801561184d57600080fd5b505af1158015611861573d6000803e3d6000fd5b5050505050565b3360009081526002602052604090205460ff16611897576040516282b42960e81b815260040160405180910390fd5b60085460ff1680156118b957503360009081526009602052604090205460ff16155b156118d6576040516282b42960e81b815260040160405180910390fd5b6118de612e9c565b6118eb33858585856131aa565b6118f460018055565b50505050565b600061194e7f00000000000000000000000000000000000000000000000000000000000000008484604051602001611933929190615210565b60405160208183030381529060405280519060200120613364565b9392505050565b3360009081526002602052604090205460ff16611984576040516282b42960e81b815260040160405180910390fd5b60085460ff1680156119a657503360009081526009602052604090205460ff16155b156119c3576040516282b42960e81b815260040160405180910390fd5b60006119ce336128a3565b90508060800151156119f357604051635e3b451760e11b815260040160405180910390fd5b60600151336000908152600a6020526040902055565b611a1233612fd6565b611a1c573361140f565b6008805460ff1916911515919091179055565b611a3833612fd6565b611a42573361140f565b6017805460ff60a01b198116600160a01b9182900460ff1615909102179055565b6001600160a01b0380821660009081526003602052604081205490911681611a8a82611c9f565b90506000611a966133c4565b6001600160a01b031663b3596f077f00000000000000000000000000000000000000000000000000000000000000006040518263ffffffff1660e01b8152600401611ae19190614d3f565b602060405180830381865afa158015611afe573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b2291906150ed565b9050611b4f7f0000000000000000000000000000000000000000000000000000000000000000600a61530e565b611b59828461531d565b611b63919061534a565b95945050505050565b600080611b77612e9c565b601754600160a01b900460ff1615611b9357611b91612a26565b505b610fff843385613427565b3360009081526002602052604081205460ff16611bcd576040516282b42960e81b815260040160405180910390fd5b60085460ff168015611bef57503360009081526009602052604090205460ff16155b15611c0c576040516282b42960e81b815260040160405180910390fd5b611c14612e9c565b611c2133868686866134d0565b9050611c2c60018055565b949350505050565b3330146111965733604051637974da6f60e01b815260040161145491906151e0565b611c5f33612fd6565b611c69573361140f565b6116cc6136ea565b600061194e8383613727565b6001600160a01b0382166000908152600c6020526040812061194e9083612ef5565b6387a211a2600c90815260008281526020909120546113de90612f01565b611cc633612fd6565b611cd0573361140f565b806001600160a01b0316633f4ba83a6040518163ffffffff1660e01b8152600401600060405180830381600087803b15801561184d57600080fd5b6060600f805461130d90615193565b3360009081526006602052604090205460ff16611d49576040516282b42960e81b815260040160405180910390fd5b826001600160a01b0316846001600160a01b03167fb15b5161080eeb6130c6088d7b1e8eceb1092d2a15836c769bd094d9a68c8c6b8484604051611d97929190918252602082015260400190565b60405180910390a350505050565b611dad614a8d565b6000838311611dbc5782611dbe565b835b90506000611dcb86611c9f565b90506000806000611ddc8585613b3b565b92509250925084811015611dee578094505b506040805160608101825294855260208501929092529083015250949350505050565b6000611e1b612e9c565b611e2433613c50565b9050611e2f60018055565b90565b60405163a612ce2b60e01b81526000906001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063a612ce2b90611e81908590600401614d3f565b602060405180830381865afa158015611e9e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113de91906150ed565b60007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316635c222bad6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611f22573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110b1919061536c565b60165460405160009182916001600160a01b039091169063c824e15790611f899060200160208082526005908201526410931054d560da1b604082015260600190565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b8152600401611fbd91815260200190565b602060405180830381865afa158015611fda573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611ffe919061536c565b6016546040519192506000916001600160a01b03909116906321f8a7219061202890602001615389565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b815260040161205c91815260200190565b602060405180830381865afa158015612079573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061209d919061536c565b60405163662aa11d60e01b81529091506001600160a01b0383169063662aa11d906120ce9030908590600401615210565b6020604051808303816000875af11580156120ed573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061211191906150ed565b9250806001600160a01b03167f9c3c39d0eedd3d18612a0e8e76cc7bc873815d3e19206dbbf9825989b1c95e6b8460405161214e91815260200190565b60405180910390a2505090565b60006121678585613727565b90506000806001600160a01b038516156121e057846001600160a01b031663ea2c58046040518163ffffffff1660e01b8152600401602060405180830381865afa1580156121b9573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906121dd91906150ed565b90505b600081156121f5576121f23a8361531d565b90505b604051639035268760e01b81526001600160a01b038916906390352687908390612229908a90899089908c906004016153b0565b6000604051808303818588803b15801561224257600080fd5b505af1158015612256573d6000803e3d6000fd5b50505050506001600160a01b038616158015906122dd5750604051630e041fb560e11b81526001600160a01b03871690631c083f6a9061229a908b90600401614d3f565b602060405180830381865afa1580156122b7573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906122db91906150ed565b155b1561234f576001600160a01b0388166000908152600c602052604090206123049087613ddc565b506001600160a01b03888116600081815260036020526040808220549051848b169491909116917f9910e38adb465481c843222dba5590cfcb99a51e28f2fc633b66289ef06ba4e291a45b505050949350505050565b61236333612fd6565b61236d573361140f565b61237a8383601254613df1565b60108390556011829055601281905560408051848152602081018490529081018290527fafabe1c7d6c2e86cbfc67a8ba53d25a7f8ef59b97d972dd4bf7d7525ba7fdddf9060600160405180910390a1505050565b3360009081526002602052604081205460ff166123fe576040516282b42960e81b815260040160405180910390fd5b60085460ff16801561242057503360009081526009602052604090205460ff16155b1561243d576040516282b42960e81b815260040160405180910390fd5b612445612e9c565b61244f3383613e26565b905061245a60018055565b919050565b61246833612fd6565b612472573361140f565b6001600160a01b03919091166000908152600960205260409020805460ff1916911515919091179055565b60006124a76112fe565b805190602001209050844211156124c657631a15a3cc6000526004601cfd5b6040518860601b60601c98508760601b60601c975065383775081901600e52886000526020600c2080547f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f83528360208401527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6604084015246606084015230608084015260a08320602e527f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c983528a60208401528960408401528860608401528060808401528760a084015260c08320604e526042602c206000528660ff1660205285604052846060526020806080600060015afa8b3d51146125d25763ddafbaef6000526004601cfd5b0190556303faf4f960a51b88176040526034602c2087905587897f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925602060608501a360405250506000606052505050505050565b3330146126485733604051637974da6f60e01b815260040161145491906151e0565b6001600160a01b038116600081815260046020526040808220829055517fccfc0aeacebc685763eb86a3e35dfeac830fd983f2f597b3f142ee667d28acc49190a2604051637b91c26560e01b81523090637b91c265906126ac908490600401614d3f565b600060405180830381600087803b15801561184d57600080fd5b806001600160a01b0381166126ee5760405163d92e233d60e01b815260040160405180910390fd5b3360009081526002602052604090205460ff1661271d576040516282b42960e81b815260040160405180910390fd5b60085460ff16801561273f57503360009081526009602052604090205460ff16155b1561275c576040516282b42960e81b815260040160405180910390fd5b612764612e9c565b600061276f33611e32565b905080156127f357600061278233611199565b905081811182820302808611156127ac5760405163e44069c960e01b815260040160405180910390fd5b6127e16001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016338789613f86565b6127ec3360016130e6565b5050612828565b6128286001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016338587613f86565b336000818152600360209081526040918290205491518781526001600160a01b03909216917f01bfef2bf622406285ca1a4057a39432c0ba15e2069c29ae6098c22affdeaf45910160405180910390a3506117ee60018055565b6001600160a01b0381166000908152600c602052604081206113de90612eeb565b6128e96040518060e00160405280600081526020016000815260200160008152602001600081526020016000151581526020016000151581526020016000151581525090565b60006128f483611199565b9050600061290184611a63565b9050600061290e85611e32565b9050600061291c848461511c565b6040805160e081018252848152602081018690529081018690526000606082018190526080820181905260a0820181905260c08201529550905081158015906129655750600081115b15612993576129748282611721565b60608601819052601154811060a08701526012541160808601526129a1565b81156129a157600160c08601525b50505050919050565b3330146117f05733604051637974da6f60e01b815260040161145491906151e0565b6000806129d883613fe0565b90506129e381612f01565b9150915091565b6129f2614a8d565b6001600160a01b0380841660009081526003602052604081205490911690612a1985611e32565b9050611b63828286611da5565b60405163e12f3a6160e01b81526000907f0000000000000000000000000000000000000000000000000000000000000000906001600160a01b0382169063e12f3a6190612a77903090600401614d3f565b602060405180830381865afa158015612a94573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612ab891906150ed565b9150620f42408210612ba85781600d6000828254612ad6919061511c565b9091555050604051635569f64b60e11b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063aad3ec9690612b2990309086906004016151c7565b6020604051808303816000875af1158015612b48573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612b6c91906150ed565b91507f3b6bc0ba304eaa17cdca1b053baac859e721c7a775cddefc825f6286641311fc82604051612b9f91815260200190565b60405180910390a15b5090565b6000612bb7846128a3565b90508060800151612bdb57604051636caa790760e01b815260040160405180910390fd5b6001600160a01b0384166000908152600460205260408120549003612c91576001600160a01b038416600081815260046020526040808220429055517fdcd8b95bdfd2ffcc332acd69f71c9319a5a1006ca18c94d83d854e591cb6e0439190a2604051636545e6b360e11b8152309063ca8bcd6690612c5e908790600401614d3f565b600060405180830381600087803b158015612c7857600080fd5b505af1158015612c8c573d6000803e3d6000fd5b505050505b6001600160a01b0380851660009081526003602052604081205490911690612cb886611e32565b90506000612cc7838388611da5565b9050612ce7833383604001518460200151612ce291906153e3565b614010565b612cf683868360400151614010565b8051612d30906001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169033908a90613f86565b8051604051631b8fec7360e11b815260048101919091526001600160a01b0388169063371fd8e690602401600060405180830381600087803b158015612d7557600080fd5b505af1158015612d89573d6000803e3d6000fd5b505050602080830151604080850151855182516001600160a01b038e168152948501939093529083015260608201527fe32ec3ea3154879f27d5367898ab3a5ac6b68bf921d7cc610720f417c5cb243c915060800160405180910390a150505050505050565b6001600160a01b03808216600090815260136020526040902054168061245a576113de7f0000000000000000000000000000000000000000000000000000000000000000612e3c8461408e565b613364565b6040805180820190915260008082526020820152612e5d6140d2565b8152612e676141b6565b602082015290565b600080612e7a612e9c565b612e8633858786612ec6565b9092509050612e9460018055565b935093915050565b600260015403612ebf57604051633ee5aeb560e01b815260040160405180910390fd5b6002600155565b600080612ed486868661421b565b9092509050612ee2836110b6565b94509492505050565b60006113de825490565b600061194e838361428b565b6000612f146805345cdf77eb68f44c5490565b15612ba8576805345cdf77eb68f44c54612f2c611014565b612f36908461531d565b612f40919061534a565b6113de565b60007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166321f8a721604051602001612f8590615389565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b8152600401612fb991815260200190565b602060405180830381865afa158015611f22573d6000803e3d6000fd5b6000816001600160a01b03167f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663893d20e86040518163ffffffff1660e01b8152600401602060405180830381865afa158015613040573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613064919061536c565b6001600160a01b03161461307a57506000919050565b506001919050565b61308a6142b5565b6000805460ff191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa335b6040516130c49190614d3f565b60405180910390a1565b600061194e611e2f84670de0b6b3a7640000856142d8565b6001600160a01b0382166000908152600460205260409020541561311d57604051635e3b451760e11b815260040160405180910390fd5b600061312883611e32565b11156117f0576000613139836128a3565b9050811561318757600061315e611e2f61315260105490565b60208501515b906143ac565b90508082600001511115613185576040516334b3313560e11b815260040160405180910390fd5b505b8060a00151156117ee576040516334b3313560e11b815260040160405180910390fd5b846001600160a01b0316836001600160a01b0316856001600160a01b03167f44afc4b038b803a70a242636bdd48bded871bf13df04e3613998f5ef1915ca8b856040516131f991815260200190565b60405180910390a46001600160a01b038316158015906132835750604051630e041fb560e11b81526001600160a01b03841690631c083f6a90613240908890600401614d3f565b602060405180830381865afa15801561325d573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061328191906150ed565b155b156132f6576001600160a01b0385166000908152600c602052604090206132aa9084613ddc565b50826001600160a01b0316856001600160a01b0316856001600160a01b03167f9910e38adb465481c843222dba5590cfcb99a51e28f2fc633b66289ef06ba4e260405160405180910390a45b801561335b576000613307866143bb565b90506000613314876128a3565b6060015190508181101561333b576040516334b3313560e11b815260040160405180910390fd5b50506001600160a01b0385166000908152600a6020526040812055611861565b611861856143f2565b6040513060388201526f5af43d82803e903d91602b57fd5bf3ff602482015260148101839052733d602d80600a3d3981f3363d3d373d3d3d363d738152605881018290526037600c8201206078820152605560439091012060009061194e565b60007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166321f8a721604051602001612f85906020808252600e908201526d282924a1a2afa82927ab24a222a960911b604082015260600190565b600080600061343584612def565b6001600160a01b03811660009081526002602052604090205490915060ff1661347157604051635435b28960e11b815260040160405180910390fd5b61347b86856143fd565b60405191945092506001600160a01b038516907fd88c5369d398bea6a7390a17ce98af43f4aacc78fd3587bc368993d98206a304906134bf908490899088906153f6565b60405180910390a250935093915050565b6001600160a01b0383166000908152600b602052604081205460ff1661350957604051631a22ce4f60e11b815260040160405180910390fd5b6001600160a01b0386166000908152600c6020526040902061352b9085614416565b1561357b57836001600160a01b0316866001600160a01b0316866001600160a01b03167ff6fa2840bdce616f9e9bbe7d65ca8bcca0532f1c4aa348c65c79c2cbf6ebf1f960405160405180910390a45b60006001600160a01b038516156135f157846001600160a01b0316638a7c32e16040518163ffffffff1660e01b8152600401602060405180830381865afa1580156135ca573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906135ee91906150ed565b90505b60008115613606576136033a8361531d565b90505b604051634b18bb2360e11b81526001600160a01b03871690639631764690839061363890899089908e9060040161541a565b60206040518083038185885af1158015613656573d6000803e3d6000fd5b50505050506040513d601f19601f8201168201806040525081019061367b91906150ed565b9250876001600160a01b0316866001600160a01b0316886001600160a01b03167fcc3d99ef3608eafdfce86498089694111f40a0dd5b2841cba24bf2dfde1cc16c886040516136cc91815260200190565b60405180910390a46136df8860016130e6565b505095945050505050565b6136f261442b565b6000805460ff191660011790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a2586130b73390565b600080613733846128a3565b9050806080015161375757604051636caa790760e01b815260040160405180910390fd5b6001600160a01b038085166000908152600560209081526040808320878516845290915290205416915081613924576137d87f000000000000000000000000000000000000000000000000000000000000000085856040516020016137bd929190615210565b6040516020818303038152906040528051906020012061444f565b604080516080810182526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000811682523060208301908152888216838501908152888316606085019081529451630415cc1560e01b81529351831660048501529051821660248401525181166044830152915182166064820152919350831690630415cc1590608401600060405180830381600087803b15801561388257600080fd5b505af1158015613896573d6000803e3d6000fd5b505050506001600160a01b03848116600081815260056020908152604080832088861680855290835281842080546001600160a01b0319169689169687179055948352600690915290819020805460ff19166001179055517f39ee3b3ae7d535f7a027ce37245120586dd668f09e21538a7e0e8d7d5b3f16379061391b908690614d3f565b60405180910390a35b6040516370a0823160e01b81526000906001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906370a0823190613973908890600401614d3f565b602060405180830381865afa158015613990573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906139b491906150ed565b1115613a7e57613a7e84837f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166370a08231886040518263ffffffff1660e01b8152600401613a0b9190614d3f565b602060405180830381865afa158015613a28573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613a4c91906150ed565b6001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016929190613f86565b6001600160a01b0384166000908152600460205260408120549003613b34576001600160a01b038416600081815260046020526040808220429055517fdcd8b95bdfd2ffcc332acd69f71c9319a5a1006ca18c94d83d854e591cb6e0439190a2604051636545e6b360e11b8152309063ca8bcd6690613b01908790600401614d3f565b600060405180830381600087803b158015613b1b57600080fd5b505af1158015613b2f573d6000803e3d6000fd5b505050505b5092915050565b600080600080613bd8613b4c6133c4565b6001600160a01b031663b3596f077f00000000000000000000000000000000000000000000000000000000000000006040518263ffffffff1660e01b8152600401613b979190614d3f565b602060405180830381865afa158015613bb4573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611e2f91906150ed565b90506000613bf5611e2f83611721670e92596fd62900008b613158565b905085811115613c2257859450613c1b611e2f670e92596fd629000061172185896143ac565b9250613c29565b8094508692505b6000613c358385611721565b9050613c44611e2f87836144bd565b94505050509250925092565b6001600160a01b03808216600090815260136020526040812054909183911615613c8d57604051635435b28960e11b815260040160405180910390fd5b613cbf7f0000000000000000000000000000000000000000000000000000000000000000613cba8361408e565b61444f565b6001600160a01b038082166000818152600260209081526040808320805460ff191660019081179091559487168084526013835281842080546001600160a01b0319908116871790915594845260039092528220805490931617909155600780549395509192613d3090849061511c565b92505081905550806001600160a01b03167fac631f3001b55ea1509cf3d7e74898f85392a61a76e8149181ae1259622dabc883604051613d709190614d3f565b60405180910390a260405163189acdbd60e31b81526001600160a01b0383169063c4d66de890613da4908490600401614d3f565b600060405180830381600087803b158015613dbe57600080fd5b505af1158015613dd2573d6000803e3d6000fd5b5050505050919050565b600061194e836001600160a01b0384166144cc565b81831080613dfe57508083105b80613e0857508082105b156117ee57604051635435b28960e11b815260040160405180910390fd5b6000613e3061442b565b604051630967fa2960e31b8152600481018390526001600160a01b0384811660248301527f00000000000000000000000000000000000000000000000000000000000000001690634b3fd148906044016020604051808303816000875af1158015613e9f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613ec391906150ed565b9050613ed08360016130e6565b6001600160a01b0380841660008181526003602052604090819020549051919216907f44dd1331990f12a8382e7da57756538a810f52fa13c1bb0d0ca6b14225be6d3390613f219085815260200190565b60405180910390a36040516377a4322360e11b8152309063ef48644690613f4e90869085906004016151c7565b600060405180830381600087803b158015613f6857600080fd5b505af1158015613f7c573d6000803e3d6000fd5b5050505092915050565b6118f484856001600160a01b03166323b872dd868686604051602401613fae939291906153f6565b604051602081830303815290604052915060e01b6020820180516001600160e01b0383818316178352505050506145bf565b6000613ff36805345cdf77eb68f44c5490565b15612ba857614000611014565b6805345cdf77eb68f44c54612f2c565b60006140366140266805345cdf77eb68f44c5490565b61402e611014565b849190614619565b905081600d600082825461404a91906153e3565b9091555061405a90508482614648565b6118f46001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001684846146d3565b6040516001600160601b0319606083811b8216602084015230901b166034820152600090604801604051602081830303815290604052805190602001209050919050565b60007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663e5f3d3a5604051602001614141906020808252601a908201527950524f544f434f4c5f4c49515549444154494f4e5f534841524560301b604082015260600190565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b815260040161417591815260200190565b602060405180830381865afa158015614192573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110b191906150ed565b60007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663e5f3d3a56040516020016141419060208082526010908201526f4c495155494441544f525f534841524560801b604082015260600190565b6000806142298585856146f9565b9092509050600061423986612def565b90506142468160016130e6565b856001600160a01b03167f0b260cc77140cab3405675836fc971314e656137208b77414be51fafd58ae34b61427a88612def565b87866040516134bf939291906153f6565b60008260000182815481106142a2576142a261544b565b9060005260206000200154905092915050565b60005460ff166116cc57604051638dfc202b60e01b815260040160405180910390fd5b60008080600019858709858702925082811083820303915050806000036143125783828161430857614308615334565b049250505061194e565b83811061434357604051630c740aef60e31b8152600481018790526024810186905260448101859052606401611454565b60008486880960026001871981018816978890046003810283188082028403028082028403028082028403028082028403028082028403029081029092039091026000889003889004909101858311909403939093029303949094049190911702949350505050565b600061194e611e2f8484614763565b6001600160a01b0381166000908152600a60205260409020548061245a57604051636571f87b60e11b815260040160405180910390fd5b6111968160006130e6565b60008061440b338486614819565b909590945092505050565b600061194e836001600160a01b038416614884565b60005460ff16156116cc5760405163d93c066560e01b815260040160405180910390fd5b6000763d602d80600a3d3981f3363d3d373d3d3d363d730000008360601b60e81c176000526e5af43d82803e903d91602b57fd5bf38360781b1760205281603760096000f590506001600160a01b0381166113de576040516330be1a3d60e21b815260040160405180910390fd5b600061194e611e2f83856153e3565b600081815260018301602052604081205480156145b55760006144f06001836153e3565b8554909150600090614504906001906153e3565b90508082146145695760008660000182815481106145245761452461544b565b90600052602060002001549050808760000184815481106145475761454761544b565b6000918252602080832090910192909255918252600188019052604090208390555b855486908061457a5761457a615461565b6001900381819060005260206000200160009055905585600101600086815260200190815260200160002060009055600193505050506113de565b60009150506113de565b60006145d46001600160a01b038416836148d3565b905080516000141580156145f95750808060200190518101906145f79190615477565b155b156117ee5782604051635274afe760e01b81526004016114549190614d3f565b60008260001904841183021582026146395763ad251c276000526004601cfd5b50910281810615159190040190565b614654826000836117ee565b6387a211a2600c52816000526020600c2080548083111561467d5763f4d678b86000526004601cfd5b82900390556805345cdf77eb68f44c8054829003905560008181526001600160a01b0383167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef602083a36117f0826000836117ee565b6117ee83846001600160a01b031663a9059cbb8585604051602401613fae9291906151c7565b600080614705836113e4565b809250819350505081600d600082825461471f91906153e3565b9091555061472f90508582614648565b612e946001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001685846146d3565b60008080600019848609848602925082811083820303915050806000036147975750670de0b6b3a7640000900490506113de565b670de0b6b3a764000081106147c957604051635173648d60e01b81526004810186905260248101859052604401611454565b6000670de0b6b3a764000085870962040000818503049310909103600160ee1b02919091177faccb18165bd6fe31ae1cf318dc5b51eee0e1ba569b88cd74c1773b91fac106690291505092915050565b600080614825836129cc565b809250819350505081600d600082825461483f919061511c565b9091555061487a90506001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016863085613f86565b612e9484826148e1565b60008181526001830160205260408120546148cb575081546001818101845560008481526020808220909301849055845484825282860190935260409020919091556113de565b5060006113de565b606061194e83836000614974565b6148ed600083836117ee565b6805345cdf77eb68f44c54818101818110156149115763e5cfe9576000526004601cfd5b806805345cdf77eb68f44c5550506387a211a2600c52816000526020600c208181540181555080602052600c5160601c60007fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef602080a36117f0600083836117ee565b606081471015614999573060405163cd78605960e01b81526004016114549190614d3f565b600080856001600160a01b031684866040516149b59190615494565b60006040518083038185875af1925050503d80600081146149f2576040519150601f19603f3d011682016040523d82523d6000602084013e6149f7565b606091505b5091509150614a07868383614a11565b9695505050505050565b606082614a2657614a2182614a64565b61194e565b8151158015614a3d57506001600160a01b0384163b155b15614a5d5783604051639996b31560e01b81526004016114549190614d3f565b508061194e565b805115614a745780518082602001fd5b604051630a12f52160e11b815260040160405180910390fd5b60405180606001604052806000815260200160008152602001600081525090565b6001600160a01b038116811461119657600080fd5b60008060408385031215614ad657600080fd5b823591506020830135614ae881614aae565b809150509250929050565b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f191681016001600160401b0381118282101715614b3157614b31614af3565b604052919050565b600082601f830112614b4a57600080fd5b81356001600160401b03811115614b6357614b63614af3565b614b76601f8201601f1916602001614b09565b818152846020838601011115614b8b57600080fd5b816020850160208301376000918101602001919091529392505050565b600082601f830112614bb957600080fd5b813560206001600160401b0380831115614bd557614bd5614af3565b8260051b614be4838201614b09565b9384528581018301938381019088861115614bfe57600080fd5b84880192505b85831015614c3a57823584811115614c1c5760008081fd5b614c2a8a87838c0101614b39565b8352509184019190840190614c04565b98975050505050505050565b600060208284031215614c5857600080fd5b81356001600160401b03811115614c6e57600080fd5b611c2c84828501614ba8565b600060208284031215614c8c57600080fd5b813561194e81614aae565b60005b83811015614cb2578181015183820152602001614c9a565b50506000910152565b60008151808452614cd3816020860160208601614c97565b601f01601f19169290920160200192915050565b60208152600061194e6020830184614cbb565b60008060408385031215614d0d57600080fd5b8235614d1881614aae565b946020939093013593505050565b600060208284031215614d3857600080fd5b5035919050565b6001600160a01b0391909116815260200190565b60008060408385031215614d6657600080fd5b8235614d7181614aae565b91506020830135614ae881614aae565b801515811461119657600080fd5b60008060408385031215614da257600080fd5b8235614dad81614aae565b91506020830135614ae881614d81565b600080600060608486031215614dd257600080fd5b8335614ddd81614aae565b92506020840135614ded81614aae565b929592945050506040919091013590565b60008060008060808587031215614e1457600080fd5b8435614e1f81614aae565b93506020850135614e2f81614aae565b9250604085013591506060850135614e4681614d81565b939692955090935050565b600060208284031215614e6357600080fd5b813561194e81614d81565b60008060008060808587031215614e8457600080fd5b8435614e8f81614aae565b93506020850135614e9f81614aae565b92506040850135915060608501356001600160401b03811115614ec157600080fd5b614ecd87828801614b39565b91505092959194509250565b60008060008060808587031215614eef57600080fd5b8435614efa81614aae565b93506020850135614f0a81614aae565b93969395505050506040820135916060013590565b600080600060608486031215614f3457600080fd5b8335614f3f81614aae565b95602085013595506040909401359392505050565b60008060008060808587031215614f6a57600080fd5b8435614f7581614aae565b93506020850135614f8581614aae565b92506040850135614f9581614aae565b915060608501356001600160401b03811115614ec157600080fd5b600080600060608486031215614fc557600080fd5b505081359360208301359350604090920135919050565b600080600080600080600060e0888a031215614ff757600080fd5b873561500281614aae565b9650602088013561501281614aae565b95506040880135945060608801359350608088013560ff8116811461503657600080fd5b9699959850939692959460a0840135945060c09093013592915050565b60008060006060848603121561506857600080fd5b833561507381614aae565b925060208401359150604084013561508a81614aae565b809150509250925092565b6000806000606084860312156150aa57600080fd5b8335925060208401356150bc81614aae565b915060408401356001600160401b038111156150d757600080fd5b6150e386828701614ba8565b9150509250925092565b6000602082840312156150ff57600080fd5b5051919050565b634e487b7160e01b600052601160045260246000fd5b808201808211156113de576113de615106565b600060208083016020845280855180835260408601915060408160051b87010192506020870160005b8281101561518657603f19888603018452615174858351614cbb565b94509285019290850190600101615158565b5092979650505050505050565b600181811c908216806151a757607f821691505b6020821081036112f857634e487b7160e01b600052602260045260246000fd5b6001600160a01b03929092168252602082015260400190565b6001600160a01b039190911681526040602082018190526004908201526329a2a62360e11b606082015260800190565b6001600160a01b0392831681529116602082015260400190565b600181815b8085111561526557816000190482111561524b5761524b615106565b8085161561525857918102915b93841c939080029061522f565b509250929050565b60008261527c575060016113de565b81615289575060006113de565b816001811461529f57600281146152a9576152c5565b60019150506113de565b60ff8411156152ba576152ba615106565b50506001821b6113de565b5060208310610133831016604e8410600b84101617156152e8575081810a6113de565b6152f2838361522a565b806000190482111561530657615306615106565b029392505050565b600061194e60ff84168361526d565b80820281158282048414176113de576113de615106565b634e487b7160e01b600052601260045260246000fd5b60008261536757634e487b7160e01b600052601260045260246000fd5b500490565b60006020828403121561537e57600080fd5b815161194e81614aae565b6020808252600d908201526c2322a2afa1a7a62622a1aa27a960991b604082015260600190565b6001600160a01b0385811682528416602082015260408101839052608060608201819052600090614a0790830184614cbb565b818103818111156113de576113de615106565b6001600160a01b039384168152919092166020820152604081019190915260600190565b8381526060602082015260006154336060830185614cbb565b905060018060a01b0383166040830152949350505050565b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052603160045260246000fd5b60006020828403121561548957600080fd5b815161194e81614d81565b600082516154a6818460208701614c97565b919091019291505056fea264697066735822122053854702facc4cc55a858530a74eee7473b9f534c50f8d3b3fd649a385e8687664736f6c6343000818003300000000000000000000000021d1887a5dd441dc8c01713713035dd171cd30d200000000000000000000000002f6eeb4e33bba64bcbea18bd149b9031c2735f70000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000008000000000000000000000000063a0a1d02336c0dc96a0b0da37eafb9eb7c07777000000000000000000000000287f1a4ee258f15e261558b9e50418b86d16b78f000000000000000000000000430000000000000000000000000000000000000400000000000000000000000000000000000000000000000029a2241af62c000000000000000000000000000000000000000000000000000010a741a4627800000000000000000000000000000000000000000000000000000ff59ee833b3000000000000000000000000000000000000000000000000000000000000000001200000000000000000000000000000000000000000000000000000000000000180000000000000000000000000000000000000000000000000000000000000001200000000000000000000000000000000000000000000000000000000000000234a756963652046696e616e6365205745544820436f6c6c61746572616c205661756c74000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000076a63765745544800000000000000000000000000000000000000000000000000
Deployed Bytecode
0x6080604052600436106103fd5760003560e01c80637ecebe0011610215578063bd1c5d7411610124578063e1d5c064116100b1578063e1d5c06414610ded578063e4af29fc14610e0d578063e59e801814610e23578063ef48644614610e9f578063ef8b30f714610ebf578063f2468d8714610edf578063f69e204614610eff578063f9566d8214610f14578063fbcbc0f114610f34578063fbf4198414610f54578063ffc5ab1614610f8457600080fd5b8063bd1c5d7414610ca6578063c5ebeaec14610cc6578063c613aec014610ce6578063ca8bcd66146109cc578063cb6c0c9a14610d16578063d505accf14610d36578063d8cab31814610d56578063dd62ed3e14610d77578063dd76401714610dad578063ddd5e1b214610dcd57600080fd5b806399f8148e116101a257806399f8148e14610b555780639d919c6314610b8e5780639dca362f14610bd0578063a59a997314610be5578063a612ce2b14610c18578063a9059cbb14610c38578063b17e32f914610c53578063b2b8c93f14610c68578063b3c0a0b314610c7d578063b43e6cb414610c9057600080fd5b80637ecebe00146109ec5780638456cb5914610a1f57806386b9d81f14610a3457806389dbb85714610a5457806390401a7a14610a875780639159b20614610aa757806394408b9a14610ac757806395d89b4114610ae7578063971d6c9514610afc578063985d28aa14610b1c57600080fd5b80633a12c6da116103115780635af451cc1161029e5780635af451cc146108cd5780635c975abb146108e25780636806eaab146108fa5780636856728e1461091a5780636a11d0b21461092f5780636c648fc4146109465780636e553f651461096657806370a08231146109865780637af0bdfd146109b95780637b91c265146109cc57600080fd5b80633a12c6da146107035780633f4ba83a146107195780634031234c1461072e578063410051a514610744578063442b172c1461079757806347a873cb146107d057806347e41a89146107f0578063484d1ad61461086d5780635507f5e91461088d5780635a287cb2146108ad57600080fd5b806312fde4b71161038f57806312fde4b7146105915780631534a277146105a657806318160ddd146105e75780631e8a84b1146106045780631fd9a8c61461062457806322867d781461065457806323b872dd14610674578063313ce567146106945780633574d4c4146106d25780633644e515146106ee57600080fd5b8062f714ce1461040257806301e1d1141461043c578063032e9c761461045f5780630674fa411461047457806306fdde03146104945780630914b18f146104b6578063095ea7b3146104f65780630a28a477146105165780630ba212ee1461053657806311464fbe14610550575b600080fd5b34801561040e57600080fd5b5061042261041d366004614ac3565b610f97565b604080519283526020830191909152015b60405180910390f35b34801561044857600080fd5b50610451611014565b604051908152602001610433565b61047261046d366004614c46565b6110b6565b005b34801561048057600080fd5b5061045161048f366004614c7a565b611199565b3480156104a057600080fd5b506104a96112fe565b6040516104339190614ce7565b3480156104c257600080fd5b506104e66104d1366004614c7a565b60026020526000908152604090205460ff1681565b6040519015158152602001610433565b34801561050257600080fd5b506104e6610511366004614cfa565b611390565b34801561052257600080fd5b50610422610531366004614d26565b6113e4565b34801561054257600080fd5b506008546104e69060ff1681565b34801561055c57600080fd5b506105847f00000000000000000000000063a0a1d02336c0dc96a0b0da37eafb9eb7c0777781565b6040516104339190614d3f565b34801561059d57600080fd5b506105846113f6565b3480156105b257600080fd5b506105846105c1366004614d53565b60056020908152600092835260408084209091529082529020546001600160a01b031681565b3480156105f357600080fd5b506805345cdf77eb68f44c54610451565b34801561061057600080fd5b5061047261061f366004614d8f565b611400565b34801561063057600080fd5b506104e661063f366004614c7a565b60096020526000908152604090205460ff1681565b34801561066057600080fd5b5061045161066f366004614cfa565b6114c0565b34801561068057600080fd5b506104e661068f366004614dbd565b611619565b3480156106a057600080fd5b5060405160ff7f0000000000000000000000000000000000000000000000000000000000000012168152602001610433565b3480156106de57600080fd5b50610451670e92596fd629000081565b3480156106fa57600080fd5b50610451611634565b34801561070f57600080fd5b5061045160105481565b34801561072557600080fd5b506104726116b1565b34801561073a57600080fd5b5061045160125481565b34801561075057600080fd5b5061076461075f366004614c7a565b6116ce565b60405161043391908151815260208083015190820152604080830151908201526060918201519181019190915260800190565b3480156107a357600080fd5b506105846107b2366004614c7a565b6001600160a01b039081166000908152600360205260409020541690565b3480156107dc57600080fd5b506104726107eb366004614cfa565b61175b565b3480156107fc57600080fd5b5061085061080b366004614c7a565b60408051808201825260008082526020918201819052825180840184526001600160a01b03949094168082526004808452938220548015158652915291815282015290565b604080518251151581526020928301519281019290925201610433565b34801561087957600080fd5b50610472610888366004614c7a565b6117f4565b34801561089957600080fd5b506104726108a8366004614dfe565b611868565b3480156108b957600080fd5b506105846108c8366004614d53565b6118fa565b3480156108d957600080fd5b50610472611955565b3480156108ee57600080fd5b5060005460ff166104e6565b34801561090657600080fd5b50610472610915366004614e51565b611a09565b34801561092657600080fd5b50610472611a2f565b34801561093b57600080fd5b50610451620f424081565b34801561095257600080fd5b50610451610961366004614c7a565b611a63565b34801561097257600080fd5b50610422610981366004614ac3565b611b6c565b34801561099257600080fd5b506104516109a1366004614c7a565b6387a211a2600c908152600091909152602090205490565b6104516109c7366004614e6e565b611b9e565b3480156109d857600080fd5b506104726109e7366004614c7a565b611c34565b3480156109f857600080fd5b50610451610a07366004614c7a565b6338377508600c908152600091909152602090205490565b348015610a2b57600080fd5b50610472611c56565b348015610a4057600080fd5b50610584610a4f366004614d53565b611c71565b348015610a6057600080fd5b507f00000000000000000000000021d1887a5dd441dc8c01713713035dd171cd30d2610584565b348015610a9357600080fd5b50610584610aa2366004614cfa565b611c7d565b348015610ab357600080fd5b50610451610ac2366004614c7a565b611c9f565b348015610ad357600080fd5b50610472610ae2366004614c7a565b611cbd565b348015610af357600080fd5b506104a9611d0b565b348015610b0857600080fd5b50610472610b17366004614ed9565b611d1a565b348015610b2857600080fd5b506104e6610b37366004614c7a565b6001600160a01b03166000908152600b602052604090205460ff1690565b348015610b6157600080fd5b506104e6610b70366004614c7a565b6001600160a01b031660009081526006602052604090205460ff1690565b348015610b9a57600080fd5b50610bae610ba9366004614f1f565b611da5565b6040805182518152602080840151908201529181015190820152606001610433565b348015610bdc57600080fd5b50610584611e11565b348015610bf157600080fd5b507f00000000000000000000000044f33bc796f7d3df55040cd3c631628b560715c2610584565b348015610c2457600080fd5b50610451610c33366004614c7a565b611e32565b348015610c4457600080fd5b506104e661068f366004614cfa565b348015610c5f57600080fd5b50610584611ec2565b348015610c7457600080fd5b50610451611f46565b610584610c8b366004614f54565b61215b565b348015610c9c57600080fd5b5061045160115481565b348015610cb257600080fd5b50610472610cc1366004614fb0565b61235a565b348015610cd257600080fd5b50610451610ce1366004614d26565b6123cf565b348015610cf257600080fd5b506104e6610d01366004614c7a565b600b6020526000908152604090205460ff1681565b348015610d2257600080fd5b50610472610d31366004614d8f565b61245f565b348015610d4257600080fd5b50610472610d51366004614fdc565b61249d565b348015610d6257600080fd5b506017546104e690600160a01b900460ff1681565b348015610d8357600080fd5b50610451610d92366004614d53565b602052637f5e9f20600c908152600091909152603490205490565b348015610db957600080fd5b50610472610dc8366004614c7a565b612626565b348015610dd957600080fd5b50610472610de8366004614ac3565b6126c6565b348015610df957600080fd5b50610451610e08366004614c7a565b612882565b348015610e1957600080fd5b5061045160075481565b348015610e2f57600080fd5b50610e43610e3e366004614c7a565b6128a3565b6040516104339190600060e0820190508251825260208301516020830152604083015160408301526060830151606083015260808301511515608083015260a0830151151560a083015260c0830151151560c083015292915050565b348015610eab57600080fd5b50610472610eba366004614cfa565b6129aa565b348015610ecb57600080fd5b50610422610eda366004614d26565b6129cc565b348015610eeb57600080fd5b50610bae610efa366004614cfa565b6129ea565b348015610f0b57600080fd5b50610451612a26565b348015610f2057600080fd5b50610472610f2f366004615053565b612bac565b348015610f4057600080fd5b50610584610f4f366004614c7a565b612def565b348015610f6057600080fd5b50610f69612e41565b60408051825181526020928301519281019290925201610433565b610422610f92366004615095565b612e6f565b600080610fa2612e9c565b601754600160a01b900460ff1615610fbe57610fbc612a26565b505b610fff3384866000604051908082528060200260200182016040528015610ff957816020015b6060815260200190600190039081610fe45790505b50612ec6565b909250905061100d60018055565b9250929050565b60405163e12f3a6160e01b81526000906001600160a01b037f0000000000000000000000004300000000000000000000000000000000000004169063e12f3a6190611063903090600401614d3f565b602060405180830381865afa158015611080573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110a491906150ed565b600d546110b1919061511c565b905090565b8051156111965760145460405163d47eed4560e01b81526000916001600160a01b03169063d47eed45906110ee90859060040161512f565b602060405180830381865afa15801561110b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061112f91906150ed565b601454604051631df3cbc560e31b81529192506001600160a01b03169063ef9e5e2890839061116290869060040161512f565b6000604051808303818588803b15801561117b57600080fd5b505af115801561118f573d6000803e3d6000fd5b5050505050505b50565b6040516370a0823160e01b81526000906001600160a01b037f000000000000000000000000430000000000000000000000000000000000000416906370a08231906111e8908590600401614d3f565b602060405180830381865afa158015611205573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061122991906150ed565b905060005b6001600160a01b0383166000908152600c6020526040902061124f90612eeb565b8110156112f8576001600160a01b0383166000908152600c602052604090206112789082612ef5565b6001600160a01b0316631c083f6a846040518263ffffffff1660e01b81526004016112a39190614d3f565b602060405180830381865afa1580156112c0573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112e491906150ed565b6112ee908361511c565b915060010161122e565b50919050565b6060600e805461130d90615193565b80601f016020809104026020016040519081016040528092919081815260200182805461133990615193565b80156113865780601f1061135b57610100808354040283529160200191611386565b820191906000526020600020905b81548152906001019060200180831161136957829003601f168201915b5050505050905090565b600082602052637f5e9f20600c5233600052816034600c205581600052602c5160601c337f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92560206000a35060015b92915050565b6000806113f083612f01565b93915050565b60006110b1612f45565b61140933612fd6565b61145d57335b60408051637974da6f60e01b81526001600160a01b0390921660048301526024820152600e60448201526d282927aa27a1a7a62fa0a226a4a760911b60648201526084015b60405180910390fd5b6001600160a01b0382166000818152600b6020908152604091829020805460ff19168515159081179091558251938452908301527ffc2e7375e815d084de88de8e8e356e71102275019b06a1b529eee0c8ab57cd34910160405180910390a15050565b60006114ca612e9c565b60405163c883b2e560e01b8152600481018390526001600160a01b0384811660248301523360448301527f00000000000000000000000044f33bc796f7d3df55040cd3c631628b560715c2169063c883b2e5906064016020604051808303816000875af115801561153f573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061156391906150ed565b6001600160a01b0384811660008181526003602090815260409182902054915185815294955091939216917fa42e379bd7db0adade1690b7b2b3b81c2419c87c3c9f0c4f4f5a4da3ce8a8966910160405180910390a36040516347a873cb60e01b815230906347a873cb906115de90869085906004016151c7565b600060405180830381600087803b1580156115f857600080fd5b505af115801561160c573d6000803e3d6000fd5b505050506113de60018055565b600060405163a24e573d60e01b815260040160405180910390fd5b60008061163f6112fe565b8051906020012090506040517f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f81528160208201527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6604082015246606082015230608082015260a081209250505090565b6116ba33612fd6565b6116c4573361140f565b6116cc613082565b565b6116f96040518060800160405280600081526020016000815260200160008152602001600081525090565b600061170483611a63565b9050600061171184611e32565b90506000821561172a5761172783835b906130ce565b90505b604051806080016040528083815260200184815260200182815260200161175060105490565b905295945050505050565b33301461177d5733604051637974da6f60e01b815260040161145491906151e0565b6001600160a01b038216600090815260046020526040902054156117f05760006117a6836128a3565b905080608001516117ee5760405163dd76401760e01b8152309063dd764017906117d4908690600401614d3f565b600060405180830381600087803b15801561117b57600080fd5b505b5050565b6117fd33612fd6565b611807573361140f565b6118128160016130e6565b806001600160a01b0316638456cb596040518163ffffffff1660e01b8152600401600060405180830381600087803b15801561184d57600080fd5b505af1158015611861573d6000803e3d6000fd5b5050505050565b3360009081526002602052604090205460ff16611897576040516282b42960e81b815260040160405180910390fd5b60085460ff1680156118b957503360009081526009602052604090205460ff16155b156118d6576040516282b42960e81b815260040160405180910390fd5b6118de612e9c565b6118eb33858585856131aa565b6118f460018055565b50505050565b600061194e7f000000000000000000000000287f1a4ee258f15e261558b9e50418b86d16b78f8484604051602001611933929190615210565b60405160208183030381529060405280519060200120613364565b9392505050565b3360009081526002602052604090205460ff16611984576040516282b42960e81b815260040160405180910390fd5b60085460ff1680156119a657503360009081526009602052604090205460ff16155b156119c3576040516282b42960e81b815260040160405180910390fd5b60006119ce336128a3565b90508060800151156119f357604051635e3b451760e11b815260040160405180910390fd5b60600151336000908152600a6020526040902055565b611a1233612fd6565b611a1c573361140f565b6008805460ff1916911515919091179055565b611a3833612fd6565b611a42573361140f565b6017805460ff60a01b198116600160a01b9182900460ff1615909102179055565b6001600160a01b0380821660009081526003602052604081205490911681611a8a82611c9f565b90506000611a966133c4565b6001600160a01b031663b3596f077f00000000000000000000000043000000000000000000000000000000000000046040518263ffffffff1660e01b8152600401611ae19190614d3f565b602060405180830381865afa158015611afe573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b2291906150ed565b9050611b4f7f0000000000000000000000000000000000000000000000000000000000000012600a61530e565b611b59828461531d565b611b63919061534a565b95945050505050565b600080611b77612e9c565b601754600160a01b900460ff1615611b9357611b91612a26565b505b610fff843385613427565b3360009081526002602052604081205460ff16611bcd576040516282b42960e81b815260040160405180910390fd5b60085460ff168015611bef57503360009081526009602052604090205460ff16155b15611c0c576040516282b42960e81b815260040160405180910390fd5b611c14612e9c565b611c2133868686866134d0565b9050611c2c60018055565b949350505050565b3330146111965733604051637974da6f60e01b815260040161145491906151e0565b611c5f33612fd6565b611c69573361140f565b6116cc6136ea565b600061194e8383613727565b6001600160a01b0382166000908152600c6020526040812061194e9083612ef5565b6387a211a2600c90815260008281526020909120546113de90612f01565b611cc633612fd6565b611cd0573361140f565b806001600160a01b0316633f4ba83a6040518163ffffffff1660e01b8152600401600060405180830381600087803b15801561184d57600080fd5b6060600f805461130d90615193565b3360009081526006602052604090205460ff16611d49576040516282b42960e81b815260040160405180910390fd5b826001600160a01b0316846001600160a01b03167fb15b5161080eeb6130c6088d7b1e8eceb1092d2a15836c769bd094d9a68c8c6b8484604051611d97929190918252602082015260400190565b60405180910390a350505050565b611dad614a8d565b6000838311611dbc5782611dbe565b835b90506000611dcb86611c9f565b90506000806000611ddc8585613b3b565b92509250925084811015611dee578094505b506040805160608101825294855260208501929092529083015250949350505050565b6000611e1b612e9c565b611e2433613c50565b9050611e2f60018055565b90565b60405163a612ce2b60e01b81526000906001600160a01b037f00000000000000000000000044f33bc796f7d3df55040cd3c631628b560715c2169063a612ce2b90611e81908590600401614d3f565b602060405180830381865afa158015611e9e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113de91906150ed565b60007f00000000000000000000000044f33bc796f7d3df55040cd3c631628b560715c26001600160a01b0316635c222bad6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611f22573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110b1919061536c565b60165460405160009182916001600160a01b039091169063c824e15790611f899060200160208082526005908201526410931054d560da1b604082015260600190565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b8152600401611fbd91815260200190565b602060405180830381865afa158015611fda573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611ffe919061536c565b6016546040519192506000916001600160a01b03909116906321f8a7219061202890602001615389565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b815260040161205c91815260200190565b602060405180830381865afa158015612079573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061209d919061536c565b60405163662aa11d60e01b81529091506001600160a01b0383169063662aa11d906120ce9030908590600401615210565b6020604051808303816000875af11580156120ed573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061211191906150ed565b9250806001600160a01b03167f9c3c39d0eedd3d18612a0e8e76cc7bc873815d3e19206dbbf9825989b1c95e6b8460405161214e91815260200190565b60405180910390a2505090565b60006121678585613727565b90506000806001600160a01b038516156121e057846001600160a01b031663ea2c58046040518163ffffffff1660e01b8152600401602060405180830381865afa1580156121b9573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906121dd91906150ed565b90505b600081156121f5576121f23a8361531d565b90505b604051639035268760e01b81526001600160a01b038916906390352687908390612229908a90899089908c906004016153b0565b6000604051808303818588803b15801561224257600080fd5b505af1158015612256573d6000803e3d6000fd5b50505050506001600160a01b038616158015906122dd5750604051630e041fb560e11b81526001600160a01b03871690631c083f6a9061229a908b90600401614d3f565b602060405180830381865afa1580156122b7573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906122db91906150ed565b155b1561234f576001600160a01b0388166000908152600c602052604090206123049087613ddc565b506001600160a01b03888116600081815260036020526040808220549051848b169491909116917f9910e38adb465481c843222dba5590cfcb99a51e28f2fc633b66289ef06ba4e291a45b505050949350505050565b61236333612fd6565b61236d573361140f565b61237a8383601254613df1565b60108390556011829055601281905560408051848152602081018490529081018290527fafabe1c7d6c2e86cbfc67a8ba53d25a7f8ef59b97d972dd4bf7d7525ba7fdddf9060600160405180910390a1505050565b3360009081526002602052604081205460ff166123fe576040516282b42960e81b815260040160405180910390fd5b60085460ff16801561242057503360009081526009602052604090205460ff16155b1561243d576040516282b42960e81b815260040160405180910390fd5b612445612e9c565b61244f3383613e26565b905061245a60018055565b919050565b61246833612fd6565b612472573361140f565b6001600160a01b03919091166000908152600960205260409020805460ff1916911515919091179055565b60006124a76112fe565b805190602001209050844211156124c657631a15a3cc6000526004601cfd5b6040518860601b60601c98508760601b60601c975065383775081901600e52886000526020600c2080547f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f83528360208401527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6604084015246606084015230608084015260a08320602e527f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c983528a60208401528960408401528860608401528060808401528760a084015260c08320604e526042602c206000528660ff1660205285604052846060526020806080600060015afa8b3d51146125d25763ddafbaef6000526004601cfd5b0190556303faf4f960a51b88176040526034602c2087905587897f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925602060608501a360405250506000606052505050505050565b3330146126485733604051637974da6f60e01b815260040161145491906151e0565b6001600160a01b038116600081815260046020526040808220829055517fccfc0aeacebc685763eb86a3e35dfeac830fd983f2f597b3f142ee667d28acc49190a2604051637b91c26560e01b81523090637b91c265906126ac908490600401614d3f565b600060405180830381600087803b15801561184d57600080fd5b806001600160a01b0381166126ee5760405163d92e233d60e01b815260040160405180910390fd5b3360009081526002602052604090205460ff1661271d576040516282b42960e81b815260040160405180910390fd5b60085460ff16801561273f57503360009081526009602052604090205460ff16155b1561275c576040516282b42960e81b815260040160405180910390fd5b612764612e9c565b600061276f33611e32565b905080156127f357600061278233611199565b905081811182820302808611156127ac5760405163e44069c960e01b815260040160405180910390fd5b6127e16001600160a01b037f000000000000000000000000430000000000000000000000000000000000000416338789613f86565b6127ec3360016130e6565b5050612828565b6128286001600160a01b037f000000000000000000000000430000000000000000000000000000000000000416338587613f86565b336000818152600360209081526040918290205491518781526001600160a01b03909216917f01bfef2bf622406285ca1a4057a39432c0ba15e2069c29ae6098c22affdeaf45910160405180910390a3506117ee60018055565b6001600160a01b0381166000908152600c602052604081206113de90612eeb565b6128e96040518060e00160405280600081526020016000815260200160008152602001600081526020016000151581526020016000151581526020016000151581525090565b60006128f483611199565b9050600061290184611a63565b9050600061290e85611e32565b9050600061291c848461511c565b6040805160e081018252848152602081018690529081018690526000606082018190526080820181905260a0820181905260c08201529550905081158015906129655750600081115b15612993576129748282611721565b60608601819052601154811060a08701526012541160808601526129a1565b81156129a157600160c08601525b50505050919050565b3330146117f05733604051637974da6f60e01b815260040161145491906151e0565b6000806129d883613fe0565b90506129e381612f01565b9150915091565b6129f2614a8d565b6001600160a01b0380841660009081526003602052604081205490911690612a1985611e32565b9050611b63828286611da5565b60405163e12f3a6160e01b81526000907f0000000000000000000000004300000000000000000000000000000000000004906001600160a01b0382169063e12f3a6190612a77903090600401614d3f565b602060405180830381865afa158015612a94573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612ab891906150ed565b9150620f42408210612ba85781600d6000828254612ad6919061511c565b9091555050604051635569f64b60e11b81526001600160a01b037f0000000000000000000000004300000000000000000000000000000000000004169063aad3ec9690612b2990309086906004016151c7565b6020604051808303816000875af1158015612b48573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612b6c91906150ed565b91507f3b6bc0ba304eaa17cdca1b053baac859e721c7a775cddefc825f6286641311fc82604051612b9f91815260200190565b60405180910390a15b5090565b6000612bb7846128a3565b90508060800151612bdb57604051636caa790760e01b815260040160405180910390fd5b6001600160a01b0384166000908152600460205260408120549003612c91576001600160a01b038416600081815260046020526040808220429055517fdcd8b95bdfd2ffcc332acd69f71c9319a5a1006ca18c94d83d854e591cb6e0439190a2604051636545e6b360e11b8152309063ca8bcd6690612c5e908790600401614d3f565b600060405180830381600087803b158015612c7857600080fd5b505af1158015612c8c573d6000803e3d6000fd5b505050505b6001600160a01b0380851660009081526003602052604081205490911690612cb886611e32565b90506000612cc7838388611da5565b9050612ce7833383604001518460200151612ce291906153e3565b614010565b612cf683868360400151614010565b8051612d30906001600160a01b037f0000000000000000000000004300000000000000000000000000000000000004169033908a90613f86565b8051604051631b8fec7360e11b815260048101919091526001600160a01b0388169063371fd8e690602401600060405180830381600087803b158015612d7557600080fd5b505af1158015612d89573d6000803e3d6000fd5b505050602080830151604080850151855182516001600160a01b038e168152948501939093529083015260608201527fe32ec3ea3154879f27d5367898ab3a5ac6b68bf921d7cc610720f417c5cb243c915060800160405180910390a150505050505050565b6001600160a01b03808216600090815260136020526040902054168061245a576113de7f00000000000000000000000063a0a1d02336c0dc96a0b0da37eafb9eb7c07777612e3c8461408e565b613364565b6040805180820190915260008082526020820152612e5d6140d2565b8152612e676141b6565b602082015290565b600080612e7a612e9c565b612e8633858786612ec6565b9092509050612e9460018055565b935093915050565b600260015403612ebf57604051633ee5aeb560e01b815260040160405180910390fd5b6002600155565b600080612ed486868661421b565b9092509050612ee2836110b6565b94509492505050565b60006113de825490565b600061194e838361428b565b6000612f146805345cdf77eb68f44c5490565b15612ba8576805345cdf77eb68f44c54612f2c611014565b612f36908461531d565b612f40919061534a565b6113de565b60007f00000000000000000000000021d1887a5dd441dc8c01713713035dd171cd30d26001600160a01b03166321f8a721604051602001612f8590615389565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b8152600401612fb991815260200190565b602060405180830381865afa158015611f22573d6000803e3d6000fd5b6000816001600160a01b03167f00000000000000000000000021d1887a5dd441dc8c01713713035dd171cd30d26001600160a01b031663893d20e86040518163ffffffff1660e01b8152600401602060405180830381865afa158015613040573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613064919061536c565b6001600160a01b03161461307a57506000919050565b506001919050565b61308a6142b5565b6000805460ff191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa335b6040516130c49190614d3f565b60405180910390a1565b600061194e611e2f84670de0b6b3a7640000856142d8565b6001600160a01b0382166000908152600460205260409020541561311d57604051635e3b451760e11b815260040160405180910390fd5b600061312883611e32565b11156117f0576000613139836128a3565b9050811561318757600061315e611e2f61315260105490565b60208501515b906143ac565b90508082600001511115613185576040516334b3313560e11b815260040160405180910390fd5b505b8060a00151156117ee576040516334b3313560e11b815260040160405180910390fd5b846001600160a01b0316836001600160a01b0316856001600160a01b03167f44afc4b038b803a70a242636bdd48bded871bf13df04e3613998f5ef1915ca8b856040516131f991815260200190565b60405180910390a46001600160a01b038316158015906132835750604051630e041fb560e11b81526001600160a01b03841690631c083f6a90613240908890600401614d3f565b602060405180830381865afa15801561325d573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061328191906150ed565b155b156132f6576001600160a01b0385166000908152600c602052604090206132aa9084613ddc565b50826001600160a01b0316856001600160a01b0316856001600160a01b03167f9910e38adb465481c843222dba5590cfcb99a51e28f2fc633b66289ef06ba4e260405160405180910390a45b801561335b576000613307866143bb565b90506000613314876128a3565b6060015190508181101561333b576040516334b3313560e11b815260040160405180910390fd5b50506001600160a01b0385166000908152600a6020526040812055611861565b611861856143f2565b6040513060388201526f5af43d82803e903d91602b57fd5bf3ff602482015260148101839052733d602d80600a3d3981f3363d3d373d3d3d363d738152605881018290526037600c8201206078820152605560439091012060009061194e565b60007f00000000000000000000000021d1887a5dd441dc8c01713713035dd171cd30d26001600160a01b03166321f8a721604051602001612f85906020808252600e908201526d282924a1a2afa82927ab24a222a960911b604082015260600190565b600080600061343584612def565b6001600160a01b03811660009081526002602052604090205490915060ff1661347157604051635435b28960e11b815260040160405180910390fd5b61347b86856143fd565b60405191945092506001600160a01b038516907fd88c5369d398bea6a7390a17ce98af43f4aacc78fd3587bc368993d98206a304906134bf908490899088906153f6565b60405180910390a250935093915050565b6001600160a01b0383166000908152600b602052604081205460ff1661350957604051631a22ce4f60e11b815260040160405180910390fd5b6001600160a01b0386166000908152600c6020526040902061352b9085614416565b1561357b57836001600160a01b0316866001600160a01b0316866001600160a01b03167ff6fa2840bdce616f9e9bbe7d65ca8bcca0532f1c4aa348c65c79c2cbf6ebf1f960405160405180910390a45b60006001600160a01b038516156135f157846001600160a01b0316638a7c32e16040518163ffffffff1660e01b8152600401602060405180830381865afa1580156135ca573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906135ee91906150ed565b90505b60008115613606576136033a8361531d565b90505b604051634b18bb2360e11b81526001600160a01b03871690639631764690839061363890899089908e9060040161541a565b60206040518083038185885af1158015613656573d6000803e3d6000fd5b50505050506040513d601f19601f8201168201806040525081019061367b91906150ed565b9250876001600160a01b0316866001600160a01b0316886001600160a01b03167fcc3d99ef3608eafdfce86498089694111f40a0dd5b2841cba24bf2dfde1cc16c886040516136cc91815260200190565b60405180910390a46136df8860016130e6565b505095945050505050565b6136f261442b565b6000805460ff191660011790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a2586130b73390565b600080613733846128a3565b9050806080015161375757604051636caa790760e01b815260040160405180910390fd5b6001600160a01b038085166000908152600560209081526040808320878516845290915290205416915081613924576137d87f000000000000000000000000287f1a4ee258f15e261558b9e50418b86d16b78f85856040516020016137bd929190615210565b6040516020818303038152906040528051906020012061444f565b604080516080810182526001600160a01b037f0000000000000000000000004300000000000000000000000000000000000004811682523060208301908152888216838501908152888316606085019081529451630415cc1560e01b81529351831660048501529051821660248401525181166044830152915182166064820152919350831690630415cc1590608401600060405180830381600087803b15801561388257600080fd5b505af1158015613896573d6000803e3d6000fd5b505050506001600160a01b03848116600081815260056020908152604080832088861680855290835281842080546001600160a01b0319169689169687179055948352600690915290819020805460ff19166001179055517f39ee3b3ae7d535f7a027ce37245120586dd668f09e21538a7e0e8d7d5b3f16379061391b908690614d3f565b60405180910390a35b6040516370a0823160e01b81526000906001600160a01b037f000000000000000000000000430000000000000000000000000000000000000416906370a0823190613973908890600401614d3f565b602060405180830381865afa158015613990573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906139b491906150ed565b1115613a7e57613a7e84837f00000000000000000000000043000000000000000000000000000000000000046001600160a01b03166370a08231886040518263ffffffff1660e01b8152600401613a0b9190614d3f565b602060405180830381865afa158015613a28573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613a4c91906150ed565b6001600160a01b037f000000000000000000000000430000000000000000000000000000000000000416929190613f86565b6001600160a01b0384166000908152600460205260408120549003613b34576001600160a01b038416600081815260046020526040808220429055517fdcd8b95bdfd2ffcc332acd69f71c9319a5a1006ca18c94d83d854e591cb6e0439190a2604051636545e6b360e11b8152309063ca8bcd6690613b01908790600401614d3f565b600060405180830381600087803b158015613b1b57600080fd5b505af1158015613b2f573d6000803e3d6000fd5b505050505b5092915050565b600080600080613bd8613b4c6133c4565b6001600160a01b031663b3596f077f00000000000000000000000043000000000000000000000000000000000000046040518263ffffffff1660e01b8152600401613b979190614d3f565b602060405180830381865afa158015613bb4573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611e2f91906150ed565b90506000613bf5611e2f83611721670e92596fd62900008b613158565b905085811115613c2257859450613c1b611e2f670e92596fd629000061172185896143ac565b9250613c29565b8094508692505b6000613c358385611721565b9050613c44611e2f87836144bd565b94505050509250925092565b6001600160a01b03808216600090815260136020526040812054909183911615613c8d57604051635435b28960e11b815260040160405180910390fd5b613cbf7f00000000000000000000000063a0a1d02336c0dc96a0b0da37eafb9eb7c07777613cba8361408e565b61444f565b6001600160a01b038082166000818152600260209081526040808320805460ff191660019081179091559487168084526013835281842080546001600160a01b0319908116871790915594845260039092528220805490931617909155600780549395509192613d3090849061511c565b92505081905550806001600160a01b03167fac631f3001b55ea1509cf3d7e74898f85392a61a76e8149181ae1259622dabc883604051613d709190614d3f565b60405180910390a260405163189acdbd60e31b81526001600160a01b0383169063c4d66de890613da4908490600401614d3f565b600060405180830381600087803b158015613dbe57600080fd5b505af1158015613dd2573d6000803e3d6000fd5b5050505050919050565b600061194e836001600160a01b0384166144cc565b81831080613dfe57508083105b80613e0857508082105b156117ee57604051635435b28960e11b815260040160405180910390fd5b6000613e3061442b565b604051630967fa2960e31b8152600481018390526001600160a01b0384811660248301527f00000000000000000000000044f33bc796f7d3df55040cd3c631628b560715c21690634b3fd148906044016020604051808303816000875af1158015613e9f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613ec391906150ed565b9050613ed08360016130e6565b6001600160a01b0380841660008181526003602052604090819020549051919216907f44dd1331990f12a8382e7da57756538a810f52fa13c1bb0d0ca6b14225be6d3390613f219085815260200190565b60405180910390a36040516377a4322360e11b8152309063ef48644690613f4e90869085906004016151c7565b600060405180830381600087803b158015613f6857600080fd5b505af1158015613f7c573d6000803e3d6000fd5b5050505092915050565b6118f484856001600160a01b03166323b872dd868686604051602401613fae939291906153f6565b604051602081830303815290604052915060e01b6020820180516001600160e01b0383818316178352505050506145bf565b6000613ff36805345cdf77eb68f44c5490565b15612ba857614000611014565b6805345cdf77eb68f44c54612f2c565b60006140366140266805345cdf77eb68f44c5490565b61402e611014565b849190614619565b905081600d600082825461404a91906153e3565b9091555061405a90508482614648565b6118f46001600160a01b037f00000000000000000000000043000000000000000000000000000000000000041684846146d3565b6040516001600160601b0319606083811b8216602084015230901b166034820152600090604801604051602081830303815290604052805190602001209050919050565b60007f00000000000000000000000021d1887a5dd441dc8c01713713035dd171cd30d26001600160a01b031663e5f3d3a5604051602001614141906020808252601a908201527950524f544f434f4c5f4c49515549444154494f4e5f534841524560301b604082015260600190565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b815260040161417591815260200190565b602060405180830381865afa158015614192573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110b191906150ed565b60007f00000000000000000000000021d1887a5dd441dc8c01713713035dd171cd30d26001600160a01b031663e5f3d3a56040516020016141419060208082526010908201526f4c495155494441544f525f534841524560801b604082015260600190565b6000806142298585856146f9565b9092509050600061423986612def565b90506142468160016130e6565b856001600160a01b03167f0b260cc77140cab3405675836fc971314e656137208b77414be51fafd58ae34b61427a88612def565b87866040516134bf939291906153f6565b60008260000182815481106142a2576142a261544b565b9060005260206000200154905092915050565b60005460ff166116cc57604051638dfc202b60e01b815260040160405180910390fd5b60008080600019858709858702925082811083820303915050806000036143125783828161430857614308615334565b049250505061194e565b83811061434357604051630c740aef60e31b8152600481018790526024810186905260448101859052606401611454565b60008486880960026001871981018816978890046003810283188082028403028082028403028082028403028082028403028082028403029081029092039091026000889003889004909101858311909403939093029303949094049190911702949350505050565b600061194e611e2f8484614763565b6001600160a01b0381166000908152600a60205260409020548061245a57604051636571f87b60e11b815260040160405180910390fd5b6111968160006130e6565b60008061440b338486614819565b909590945092505050565b600061194e836001600160a01b038416614884565b60005460ff16156116cc5760405163d93c066560e01b815260040160405180910390fd5b6000763d602d80600a3d3981f3363d3d373d3d3d363d730000008360601b60e81c176000526e5af43d82803e903d91602b57fd5bf38360781b1760205281603760096000f590506001600160a01b0381166113de576040516330be1a3d60e21b815260040160405180910390fd5b600061194e611e2f83856153e3565b600081815260018301602052604081205480156145b55760006144f06001836153e3565b8554909150600090614504906001906153e3565b90508082146145695760008660000182815481106145245761452461544b565b90600052602060002001549050808760000184815481106145475761454761544b565b6000918252602080832090910192909255918252600188019052604090208390555b855486908061457a5761457a615461565b6001900381819060005260206000200160009055905585600101600086815260200190815260200160002060009055600193505050506113de565b60009150506113de565b60006145d46001600160a01b038416836148d3565b905080516000141580156145f95750808060200190518101906145f79190615477565b155b156117ee5782604051635274afe760e01b81526004016114549190614d3f565b60008260001904841183021582026146395763ad251c276000526004601cfd5b50910281810615159190040190565b614654826000836117ee565b6387a211a2600c52816000526020600c2080548083111561467d5763f4d678b86000526004601cfd5b82900390556805345cdf77eb68f44c8054829003905560008181526001600160a01b0383167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef602083a36117f0826000836117ee565b6117ee83846001600160a01b031663a9059cbb8585604051602401613fae9291906151c7565b600080614705836113e4565b809250819350505081600d600082825461471f91906153e3565b9091555061472f90508582614648565b612e946001600160a01b037f00000000000000000000000043000000000000000000000000000000000000041685846146d3565b60008080600019848609848602925082811083820303915050806000036147975750670de0b6b3a7640000900490506113de565b670de0b6b3a764000081106147c957604051635173648d60e01b81526004810186905260248101859052604401611454565b6000670de0b6b3a764000085870962040000818503049310909103600160ee1b02919091177faccb18165bd6fe31ae1cf318dc5b51eee0e1ba569b88cd74c1773b91fac106690291505092915050565b600080614825836129cc565b809250819350505081600d600082825461483f919061511c565b9091555061487a90506001600160a01b037f000000000000000000000000430000000000000000000000000000000000000416863085613f86565b612e9484826148e1565b60008181526001830160205260408120546148cb575081546001818101845560008481526020808220909301849055845484825282860190935260409020919091556113de565b5060006113de565b606061194e83836000614974565b6148ed600083836117ee565b6805345cdf77eb68f44c54818101818110156149115763e5cfe9576000526004601cfd5b806805345cdf77eb68f44c5550506387a211a2600c52816000526020600c208181540181555080602052600c5160601c60007fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef602080a36117f0600083836117ee565b606081471015614999573060405163cd78605960e01b81526004016114549190614d3f565b600080856001600160a01b031684866040516149b59190615494565b60006040518083038185875af1925050503d80600081146149f2576040519150601f19603f3d011682016040523d82523d6000602084013e6149f7565b606091505b5091509150614a07868383614a11565b9695505050505050565b606082614a2657614a2182614a64565b61194e565b8151158015614a3d57506001600160a01b0384163b155b15614a5d5783604051639996b31560e01b81526004016114549190614d3f565b508061194e565b805115614a745780518082602001fd5b604051630a12f52160e11b815260040160405180910390fd5b60405180606001604052806000815260200160008152602001600081525090565b6001600160a01b038116811461119657600080fd5b60008060408385031215614ad657600080fd5b823591506020830135614ae881614aae565b809150509250929050565b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f191681016001600160401b0381118282101715614b3157614b31614af3565b604052919050565b600082601f830112614b4a57600080fd5b81356001600160401b03811115614b6357614b63614af3565b614b76601f8201601f1916602001614b09565b818152846020838601011115614b8b57600080fd5b816020850160208301376000918101602001919091529392505050565b600082601f830112614bb957600080fd5b813560206001600160401b0380831115614bd557614bd5614af3565b8260051b614be4838201614b09565b9384528581018301938381019088861115614bfe57600080fd5b84880192505b85831015614c3a57823584811115614c1c5760008081fd5b614c2a8a87838c0101614b39565b8352509184019190840190614c04565b98975050505050505050565b600060208284031215614c5857600080fd5b81356001600160401b03811115614c6e57600080fd5b611c2c84828501614ba8565b600060208284031215614c8c57600080fd5b813561194e81614aae565b60005b83811015614cb2578181015183820152602001614c9a565b50506000910152565b60008151808452614cd3816020860160208601614c97565b601f01601f19169290920160200192915050565b60208152600061194e6020830184614cbb565b60008060408385031215614d0d57600080fd5b8235614d1881614aae565b946020939093013593505050565b600060208284031215614d3857600080fd5b5035919050565b6001600160a01b0391909116815260200190565b60008060408385031215614d6657600080fd5b8235614d7181614aae565b91506020830135614ae881614aae565b801515811461119657600080fd5b60008060408385031215614da257600080fd5b8235614dad81614aae565b91506020830135614ae881614d81565b600080600060608486031215614dd257600080fd5b8335614ddd81614aae565b92506020840135614ded81614aae565b929592945050506040919091013590565b60008060008060808587031215614e1457600080fd5b8435614e1f81614aae565b93506020850135614e2f81614aae565b9250604085013591506060850135614e4681614d81565b939692955090935050565b600060208284031215614e6357600080fd5b813561194e81614d81565b60008060008060808587031215614e8457600080fd5b8435614e8f81614aae565b93506020850135614e9f81614aae565b92506040850135915060608501356001600160401b03811115614ec157600080fd5b614ecd87828801614b39565b91505092959194509250565b60008060008060808587031215614eef57600080fd5b8435614efa81614aae565b93506020850135614f0a81614aae565b93969395505050506040820135916060013590565b600080600060608486031215614f3457600080fd5b8335614f3f81614aae565b95602085013595506040909401359392505050565b60008060008060808587031215614f6a57600080fd5b8435614f7581614aae565b93506020850135614f8581614aae565b92506040850135614f9581614aae565b915060608501356001600160401b03811115614ec157600080fd5b600080600060608486031215614fc557600080fd5b505081359360208301359350604090920135919050565b600080600080600080600060e0888a031215614ff757600080fd5b873561500281614aae565b9650602088013561501281614aae565b95506040880135945060608801359350608088013560ff8116811461503657600080fd5b9699959850939692959460a0840135945060c09093013592915050565b60008060006060848603121561506857600080fd5b833561507381614aae565b925060208401359150604084013561508a81614aae565b809150509250925092565b6000806000606084860312156150aa57600080fd5b8335925060208401356150bc81614aae565b915060408401356001600160401b038111156150d757600080fd5b6150e386828701614ba8565b9150509250925092565b6000602082840312156150ff57600080fd5b5051919050565b634e487b7160e01b600052601160045260246000fd5b808201808211156113de576113de615106565b600060208083016020845280855180835260408601915060408160051b87010192506020870160005b8281101561518657603f19888603018452615174858351614cbb565b94509285019290850190600101615158565b5092979650505050505050565b600181811c908216806151a757607f821691505b6020821081036112f857634e487b7160e01b600052602260045260246000fd5b6001600160a01b03929092168252602082015260400190565b6001600160a01b039190911681526040602082018190526004908201526329a2a62360e11b606082015260800190565b6001600160a01b0392831681529116602082015260400190565b600181815b8085111561526557816000190482111561524b5761524b615106565b8085161561525857918102915b93841c939080029061522f565b509250929050565b60008261527c575060016113de565b81615289575060006113de565b816001811461529f57600281146152a9576152c5565b60019150506113de565b60ff8411156152ba576152ba615106565b50506001821b6113de565b5060208310610133831016604e8410600b84101617156152e8575081810a6113de565b6152f2838361522a565b806000190482111561530657615306615106565b029392505050565b600061194e60ff84168361526d565b80820281158282048414176113de576113de615106565b634e487b7160e01b600052601260045260246000fd5b60008261536757634e487b7160e01b600052601260045260246000fd5b500490565b60006020828403121561537e57600080fd5b815161194e81614aae565b6020808252600d908201526c2322a2afa1a7a62622a1aa27a960991b604082015260600190565b6001600160a01b0385811682528416602082015260408101839052608060608201819052600090614a0790830184614cbb565b818103818111156113de576113de615106565b6001600160a01b039384168152919092166020820152604081019190915260600190565b8381526060602082015260006154336060830185614cbb565b905060018060a01b0383166040830152949350505050565b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052603160045260246000fd5b60006020828403121561548957600080fd5b815161194e81614d81565b600082516154a6818460208701614c97565b919091019291505056fea264697066735822122053854702facc4cc55a858530a74eee7473b9f534c50f8d3b3fd649a385e8687664736f6c63430008180033
Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)
00000000000000000000000021d1887a5dd441dc8c01713713035dd171cd30d200000000000000000000000002f6eeb4e33bba64bcbea18bd149b9031c2735f70000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000008000000000000000000000000063a0a1d02336c0dc96a0b0da37eafb9eb7c07777000000000000000000000000287f1a4ee258f15e261558b9e50418b86d16b78f000000000000000000000000430000000000000000000000000000000000000400000000000000000000000000000000000000000000000029a2241af62c000000000000000000000000000000000000000000000000000010a741a4627800000000000000000000000000000000000000000000000000000ff59ee833b3000000000000000000000000000000000000000000000000000000000000000001200000000000000000000000000000000000000000000000000000000000000180000000000000000000000000000000000000000000000000000000000000001200000000000000000000000000000000000000000000000000000000000000234a756963652046696e616e6365205745544820436f6c6c61746572616c205661756c74000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000076a63765745544800000000000000000000000000000000000000000000000000
-----Decoded View---------------
Arg [0] : protocolGovernor_ (address): 0x21d1887A5dd441dc8C01713713035dd171CD30D2
Arg [1] : pointsOperator_ (address): 0x02F6EEb4E33bbA64bcBEA18bd149B9031C2735F7
Arg [2] : isAutoCompounding_ (bool): True
Arg [3] : params (tuple):
Arg [1] : account (address): 0x63a0A1d02336c0dc96A0B0DA37Eafb9eb7c07777
Arg [2] : liquidationReceiver (address): 0x287f1a4ee258f15E261558B9E50418b86D16B78f
Arg [3] : collateral (address): 0x4300000000000000000000000000000000000004
Arg [4] : maxLtv (uint256): 3000000000000000000
Arg [5] : riskThreshold (uint256): 1200000000000000000
Arg [6] : liquidationThreshold (uint256): 1150000000000000000
Arg [7] : name (string): Juice Finance WETH Collateral Vault
Arg [8] : symbol (string): jcvWETH
Arg [9] : decimals (uint8): 18
-----Encoded View---------------
18 Constructor Arguments found :
Arg [0] : 00000000000000000000000021d1887a5dd441dc8c01713713035dd171cd30d2
Arg [1] : 00000000000000000000000002f6eeb4e33bba64bcbea18bd149b9031c2735f7
Arg [2] : 0000000000000000000000000000000000000000000000000000000000000001
Arg [3] : 0000000000000000000000000000000000000000000000000000000000000080
Arg [4] : 00000000000000000000000063a0a1d02336c0dc96a0b0da37eafb9eb7c07777
Arg [5] : 000000000000000000000000287f1a4ee258f15e261558b9e50418b86d16b78f
Arg [6] : 0000000000000000000000004300000000000000000000000000000000000004
Arg [7] : 00000000000000000000000000000000000000000000000029a2241af62c0000
Arg [8] : 00000000000000000000000000000000000000000000000010a741a462780000
Arg [9] : 0000000000000000000000000000000000000000000000000ff59ee833b30000
Arg [10] : 0000000000000000000000000000000000000000000000000000000000000120
Arg [11] : 0000000000000000000000000000000000000000000000000000000000000180
Arg [12] : 0000000000000000000000000000000000000000000000000000000000000012
Arg [13] : 0000000000000000000000000000000000000000000000000000000000000023
Arg [14] : 4a756963652046696e616e6365205745544820436f6c6c61746572616c205661
Arg [15] : 756c740000000000000000000000000000000000000000000000000000000000
Arg [16] : 0000000000000000000000000000000000000000000000000000000000000007
Arg [17] : 6a63765745544800000000000000000000000000000000000000000000000000
Loading...
Loading
Loading...
Loading
Loading...
Loading
Net Worth in USD
$216,868.42
Net Worth in ETH
73.361207
Token Allocations
WETH
100.00%
Multichain Portfolio | 35 Chains
| Chain | Token | Portfolio % | Price | Amount | Value |
|---|---|---|---|---|---|
| BLAST | 100.00% | $2,954.86 | 73.3938 | $216,868.42 |
Loading...
Loading
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.