Overview
S Balance
S Value
$0.00More Info
Private Name Tags
ContractCreator
Latest 25 from a total of 45 transactions
Transaction Hash |
Method
|
Block
|
From
|
To
|
|||||
---|---|---|---|---|---|---|---|---|---|
Collect Fees For... | 17158073 | 9 days ago | IN | 0 S | 0.00771317 | ||||
Collect Fees For... | 17157414 | 9 days ago | IN | 0 S | 0.00771317 | ||||
Reduce Reserves ... | 17011140 | 10 days ago | IN | 0 S | 0.00849145 | ||||
Collect Fees For... | 17010792 | 10 days ago | IN | 0 S | 0.006923 | ||||
Set Reserves Red... | 15686684 | 16 days ago | IN | 0 S | 0.00264572 | ||||
Set Fee Collecto... | 15686679 | 16 days ago | IN | 0 S | 0.00536475 | ||||
Set Reserves Red... | 15686672 | 16 days ago | IN | 0 S | 0.00264572 | ||||
Set Fee Collecto... | 15686667 | 16 days ago | IN | 0 S | 0.00536409 | ||||
Set Reserves Red... | 15686662 | 16 days ago | IN | 0 S | 0.00264572 | ||||
Set Fee Collecto... | 15686656 | 16 days ago | IN | 0 S | 0.00536475 | ||||
Set Reserves Red... | 15686652 | 16 days ago | IN | 0 S | 0.00264572 | ||||
Set Fee Collecto... | 15686647 | 16 days ago | IN | 0 S | 0.00536475 | ||||
Set Reserves Red... | 15686642 | 16 days ago | IN | 0 S | 0.00264572 | ||||
Set Fee Collecto... | 15686636 | 16 days ago | IN | 0 S | 0.00536475 | ||||
Collect Fees For... | 15558389 | 16 days ago | IN | 0 S | 0.006923 | ||||
Set Reserves Red... | 15433271 | 17 days ago | IN | 0 S | 0.00264572 | ||||
Set Fee Collecto... | 15433267 | 17 days ago | IN | 0 S | 0.00536475 | ||||
Collect Fees For... | 14765737 | 20 days ago | IN | 0 S | 0.006923 | ||||
Collect Fees For... | 14765643 | 20 days ago | IN | 0 S | 0.0014181 | ||||
Collect Fees For... | 14765500 | 20 days ago | IN | 0 S | 0.0014181 | ||||
Collect Fees For... | 14765398 | 20 days ago | IN | 0 S | 0.0014181 | ||||
Collect Fees For... | 14764761 | 20 days ago | IN | 0 S | 0.00771317 | ||||
Reduce Reserves ... | 14764510 | 20 days ago | IN | 0 S | 0.00139576 | ||||
Collect Fees For... | 9499040 | 45 days ago | IN | 0 S | 0.006923 | ||||
Collect Fees For... | 5791311 | 70 days ago | IN | 0 S | 0.006923 |
Loading...
Loading
Contract Source Code Verified (Exact Match)
Contract Name:
FeesManager
Compiler Version
v0.8.24+commit.e11b9ed9
Optimization Enabled:
Yes with 200 runs
Other Settings:
paris EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.24; import "../../Lynx/interfaces/ITradingFloorV1.sol"; import "../../Lynx/interfaces/TradingEnumsV1.sol"; import "../../Lynx/interfaces/ILynxVersionedContract.sol"; import "../../AdministrationContracts/ClaimableAdmin.sol"; import "../../Utils/TokenHandlingContractUtils.sol"; import {LexPoolV1} from "../../Lynx/Lex/LexPool/LexPoolV1.sol"; contract FeesManager is ClaimableAdmin, TokenHandlingContractUtils, ILynxVersionedContract, TradingEnumsV1 { // ***** Constants ***** string public constant CONTRACT_NAME = "FeesManager"; string public constant CONTRACT_VERSION = "100"; // 0.1 // ***** Storage ***** ITradingFloorV1 public immutable tradingFloor; // Token => Fee Type => Collector mapping(address => mapping(FeeType => address)) public feesCollectorByType; // Lex Pool => Collector mapping(address => address) public reservesReducerByPool; // ***** Events ***** event CollectorUpdated( address indexed token, FeeType indexed feeType, address indexed collector ); event ReservesReducerUpdated(address indexed pool, address indexed reducer); event FeeCollected( address indexed token, FeeType indexed feeType, address indexed to, uint256 amount ); event ReservesReduced( address indexed pool, address indexed to, uint256 interestShareReduced, uint256 fundingShareReduced ); // ***** Views ***** /** * @notice Returns the name of the contract */ function getContractName() external pure returns (string memory) { return CONTRACT_NAME; } /** * @notice Returns the version of the contract * @dev units are scaled by 1000 (1,000 = 1.00, 1,120 = 1.12) */ function getContractVersion() external pure returns (string memory) { return CONTRACT_VERSION; } /** * @notice Get the fee collector address for all fee types if one exists * @param _token The token for which the fee collector is being checked * @return soleCollector The address of the fee collector if it is the same for all fee types, otherwise address(0) */ function getCollectorForAllTypesIfExists( address _token ) public view returns (address soleCollector) { address collectorForOpenFee = feesCollectorByType[_token][FeeType.OPEN_FEE]; address collectorForCloseFee = feesCollectorByType[_token][ FeeType.CLOSE_FEE ]; address collectorForTriggerFee = feesCollectorByType[_token][ FeeType.TRIGGER_FEE ]; if ( collectorForOpenFee == collectorForCloseFee && collectorForCloseFee == collectorForTriggerFee ) { return collectorForOpenFee; } else { return address(0); } } /** * @notice Check if the address is the fee collector for all fee types * @param _token The token for which the fee collector is being checked * @param _collector The address of the fee collector * @return isCollectorForAllTypes True if the address is the fee collector for all fee types */ function isFeeCollectorForAllTypes( address _token, address _collector ) external view returns (bool) { return getCollectorForAllTypesIfExists(_token) == _collector; } /** * @notice calculate the total of all pending fees * @param _token The token for which the fee collector is being checked * @return totalFees The total amount of all pending fees */ function getSumOfAllPendingFees( address _token ) external view returns (uint256 totalFees) { ( uint256 openFees, uint256 closeFees, uint256 triggerFees ) = getAllPendingFees(_token); totalFees = openFees + closeFees + triggerFees; } /** * @notice Get the fee collector address for a specific fee type * @param _token The token for which the fee collector is being checked * @return openFees The amount of pending open fees * @return closeFees The amount of pending close fees * @return triggerFees The amount of pending trigger fees */ function getAllPendingFees( address _token ) public view returns (uint256 openFees, uint256 closeFees, uint256 triggerFees) { openFees = tradingFloor.feesMap(_token, FeeType.OPEN_FEE); closeFees = tradingFloor.feesMap(_token, FeeType.CLOSE_FEE); triggerFees = tradingFloor.feesMap(_token, FeeType.TRIGGER_FEE); } /** * @notice Get the fee collector address for a specific fee type * @param _token The token for which the fee collector is being checked * @param _feeType The fee type for which the fee collector is being checked * @return collector The address of the fee collector */ function getPendingFeesByType( address _token, FeeType _feeType ) external view returns (uint256) { return tradingFloor.feesMap(_token, _feeType); } // ***** Constructor ***** constructor(address _tradingFloor) ClaimableAdmin() { tradingFloor = ITradingFloorV1(_tradingFloor); } // ***** Admin Functions ***** /** * @notice Sweep any tokens from the contract * @dev Owner can sweep any token * @param _token The token to sweep * @param _amount The amount to sweep */ function sweepTokens(address _token, uint256 _amount) external onlyAdmin { sweepTokensInternal(_token, admin, _amount); } /** * @notice Set the fee collector for all fee types * @param _token The token for which the fee collector is being set * @param _collector The address of the fee collector */ function setFeeCollector( address _token, address _collector ) external onlyAdmin { setFeeCollectorInternal(_token, FeeType.OPEN_FEE, _collector); setFeeCollectorInternal(_token, FeeType.CLOSE_FEE, _collector); setFeeCollectorInternal(_token, FeeType.TRIGGER_FEE, _collector); } /** * @notice Set the fee collector for a specific fee type * @param _token The token for which the fee collector is being set * @param _feeType The fee type for which the fee collector is being set * @param _collector The address of the fee collector */ function setFeeCollectorByType( address _token, address _collector, FeeType _feeType ) external onlyAdmin { setFeeCollectorInternal(_token, _feeType, _collector); } function setReservesReducer( address _pool, address _reducer ) external onlyAdmin { reservesReducerByPool[_pool] = _reducer; emit ReservesReducerUpdated(_pool, _reducer); } // ***** Fees Collection Functions ***** /** * @notice Collect fees for all fee types * @param _asset The asset for which the fees are being collected * @param includeTriggerFees True if trigger fees should be included * @return collectedAmount The amount of fees collected */ function collectFeesForAsset( address _asset, bool includeTriggerFees ) external returns (uint collectedAmount) { address collector = msg.sender; collectedAmount += collectFeeInternal( _asset, FeeType.OPEN_FEE, collector, collector ); collectedAmount += collectFeeInternal( _asset, FeeType.CLOSE_FEE, collector, collector ); if (includeTriggerFees) { collectedAmount += collectFeeInternal( _asset, FeeType.TRIGGER_FEE, collector, collector ); } } /** * @notice Collect fees for a specific fee type * @param _asset The asset for which the fees are being collected * @param _feeType The fee type for which the fees are being collected * @return collectedAmount The amount of fees collected */ function collectFeesForAssetByType( address _asset, FeeType _feeType ) external returns (uint collectedAmount) { address collector = msg.sender; return collectFeeInternal(_asset, _feeType, collector, collector); } // ***** Reserves Collection Functions ***** function reduceReservesForLex(address _pool) external { address collector = msg.sender; reduceReservesInternal(_pool, collector, collector); } function reduceReservesForLexes(address[] calldata _pools) external { address collector = msg.sender; for (uint i = 0; i < _pools.length; i++) { reduceReservesInternal(_pools[i], collector, collector); } } // ***** Internal Functions ***** /** * @notice Set the fee collector for a specific fee type * @param _token The token for which the fee collector is being set * @param _feeType The fee type for which the fee collector is being set * @param _collector The address of the fee collector */ function setFeeCollectorInternal( address _token, FeeType _feeType, address _collector ) internal { feesCollectorByType[_token][_feeType] = _collector; emit CollectorUpdated(_token, _feeType, _collector); } /** * @notice Collect fees for a specific fee type * @param _asset The asset for which the fees are being collected * @param _feeType The fee type for which the fees are being collected * @param _to The address to which the fees are being sent @ @return collectedAmount The amount of fees collected */ function collectFeeInternal( address _asset, FeeType _feeType, address _collector, address _to ) internal returns (uint256 collectedAmount) { require( _collector == feesCollectorByType[_asset][_feeType], "NOT_FEE_COLLECTOR" ); uint balanceBefore = getSelfBalanceInTokenInternal(_asset); tradingFloor.collectFee(_asset, _feeType, address(this)); uint balanceAfter = getSelfBalanceInTokenInternal(_asset); collectedAmount = balanceAfter - balanceBefore; sendTokens(_asset, _to, collectedAmount); emit FeeCollected(_asset, _feeType, _to, collectedAmount); } /** * @notice Collect fees for a specific fee type * @param _pool The pool for which the reserves are being reduced * @param _to The address to which the reserves are being sent @ @return collectedAmount The amount of reserves collected */ function reduceReservesInternal( address _pool, address _collector, address _to ) internal returns (uint256 collectedAmount) { require(_collector == reservesReducerByPool[_pool], "NOT_RESERVES_REDUCER"); address _asset = address(ILexPoolV1(_pool).underlying()); uint balanceBefore = getSelfBalanceInTokenInternal(_asset); (uint256 interestShare, uint256 totalFundingShare) = LexPoolV1(_pool) .reduceReserves(address(this)); uint balanceAfter = getSelfBalanceInTokenInternal(_asset); collectedAmount = balanceAfter - balanceBefore; // Sanity require( collectedAmount == interestShare + totalFundingShare, "INVALID_RESERVES_REDUCTION" ); sendTokens(_asset, _to, collectedAmount); emit ReservesReduced(_pool, _to, interestShare, totalFundingShare); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol) pragma solidity ^0.8.20; /** * @dev Standard ERC20 Errors * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens. */ interface IERC20Errors { /** * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers. * @param sender Address whose tokens are being transferred. * @param balance Current balance for the interacting account. * @param needed Minimum amount required to perform a transfer. */ error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed); /** * @dev Indicates a failure with the token `sender`. Used in transfers. * @param sender Address whose tokens are being transferred. */ error ERC20InvalidSender(address sender); /** * @dev Indicates a failure with the token `receiver`. Used in transfers. * @param receiver Address to which tokens are being transferred. */ error ERC20InvalidReceiver(address receiver); /** * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers. * @param spender Address that may be allowed to operate on tokens without being their owner. * @param allowance Amount of tokens a `spender` is allowed to operate with. * @param needed Minimum amount required to perform a transfer. */ error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed); /** * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals. * @param approver Address initiating an approval operation. */ error ERC20InvalidApprover(address approver); /** * @dev Indicates a failure with the `spender` to be approved. Used in approvals. * @param spender Address that may be allowed to operate on tokens without being their owner. */ error ERC20InvalidSpender(address spender); } /** * @dev Standard ERC721 Errors * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens. */ interface IERC721Errors { /** * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-20. * Used in balance queries. * @param owner Address of the current owner of a token. */ error ERC721InvalidOwner(address owner); /** * @dev Indicates a `tokenId` whose `owner` is the zero address. * @param tokenId Identifier number of a token. */ error ERC721NonexistentToken(uint256 tokenId); /** * @dev Indicates an error related to the ownership over a particular token. Used in transfers. * @param sender Address whose tokens are being transferred. * @param tokenId Identifier number of a token. * @param owner Address of the current owner of a token. */ error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner); /** * @dev Indicates a failure with the token `sender`. Used in transfers. * @param sender Address whose tokens are being transferred. */ error ERC721InvalidSender(address sender); /** * @dev Indicates a failure with the token `receiver`. Used in transfers. * @param receiver Address to which tokens are being transferred. */ error ERC721InvalidReceiver(address receiver); /** * @dev Indicates a failure with the `operator`’s approval. Used in transfers. * @param operator Address that may be allowed to operate on tokens without being their owner. * @param tokenId Identifier number of a token. */ error ERC721InsufficientApproval(address operator, uint256 tokenId); /** * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals. * @param approver Address initiating an approval operation. */ error ERC721InvalidApprover(address approver); /** * @dev Indicates a failure with the `operator` to be approved. Used in approvals. * @param operator Address that may be allowed to operate on tokens without being their owner. */ error ERC721InvalidOperator(address operator); } /** * @dev Standard ERC1155 Errors * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 tokens. */ interface IERC1155Errors { /** * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers. * @param sender Address whose tokens are being transferred. * @param balance Current balance for the interacting account. * @param needed Minimum amount required to perform a transfer. * @param tokenId Identifier number of a token. */ error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId); /** * @dev Indicates a failure with the token `sender`. Used in transfers. * @param sender Address whose tokens are being transferred. */ error ERC1155InvalidSender(address sender); /** * @dev Indicates a failure with the token `receiver`. Used in transfers. * @param receiver Address to which tokens are being transferred. */ error ERC1155InvalidReceiver(address receiver); /** * @dev Indicates a failure with the `operator`’s approval. Used in transfers. * @param operator Address that may be allowed to operate on tokens without being their owner. * @param owner Address of the current owner of a token. */ error ERC1155MissingApprovalForAll(address operator, address owner); /** * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals. * @param approver Address initiating an approval operation. */ error ERC1155InvalidApprover(address approver); /** * @dev Indicates a failure with the `operator` to be approved. Used in approvals. * @param operator Address that may be allowed to operate on tokens without being their owner. */ error ERC1155InvalidOperator(address operator); /** * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation. * Used in batch transfers. * @param idsLength Length of the array of token identifiers * @param valuesLength Length of the array of token amounts */ error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.20; import {IERC20} from "./IERC20.sol"; import {IERC20Metadata} from "./extensions/IERC20Metadata.sol"; import {Context} from "../../utils/Context.sol"; import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * * TIP: For a detailed writeup see our guide * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * The default value of {decimals} is 18. To change this, you should override * this function so it returns a different value. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. */ abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors { mapping(address account => uint256) private _balances; mapping(address account => mapping(address spender => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the default value returned by this function, unless * it's overridden. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `value`. */ function transfer(address to, uint256 value) public virtual returns (bool) { address owner = _msgSender(); _transfer(owner, to, value); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, value); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `value`. * - the caller must have allowance for ``from``'s tokens of at least * `value`. */ function transferFrom(address from, address to, uint256 value) public virtual returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, value); _transfer(from, to, value); return true; } /** * @dev Moves a `value` amount of tokens from `from` to `to`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * NOTE: This function is not virtual, {_update} should be overridden instead. */ function _transfer(address from, address to, uint256 value) internal { if (from == address(0)) { revert ERC20InvalidSender(address(0)); } if (to == address(0)) { revert ERC20InvalidReceiver(address(0)); } _update(from, to, value); } /** * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from` * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding * this function. * * Emits a {Transfer} event. */ function _update(address from, address to, uint256 value) internal virtual { if (from == address(0)) { // Overflow check required: The rest of the code assumes that totalSupply never overflows _totalSupply += value; } else { uint256 fromBalance = _balances[from]; if (fromBalance < value) { revert ERC20InsufficientBalance(from, fromBalance, value); } unchecked { // Overflow not possible: value <= fromBalance <= totalSupply. _balances[from] = fromBalance - value; } } if (to == address(0)) { unchecked { // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply. _totalSupply -= value; } } else { unchecked { // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256. _balances[to] += value; } } emit Transfer(from, to, value); } /** * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0). * Relies on the `_update` mechanism * * Emits a {Transfer} event with `from` set to the zero address. * * NOTE: This function is not virtual, {_update} should be overridden instead. */ function _mint(address account, uint256 value) internal { if (account == address(0)) { revert ERC20InvalidReceiver(address(0)); } _update(address(0), account, value); } /** * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply. * Relies on the `_update` mechanism. * * Emits a {Transfer} event with `to` set to the zero address. * * NOTE: This function is not virtual, {_update} should be overridden instead */ function _burn(address account, uint256 value) internal { if (account == address(0)) { revert ERC20InvalidSender(address(0)); } _update(account, address(0), value); } /** * @dev Sets `value` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. * * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument. */ function _approve(address owner, address spender, uint256 value) internal { _approve(owner, spender, value, true); } /** * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event. * * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any * `Approval` event during `transferFrom` operations. * * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to * true using the following override: * ``` * function _approve(address owner, address spender, uint256 value, bool) internal virtual override { * super._approve(owner, spender, value, true); * } * ``` * * Requirements are the same as {_approve}. */ function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual { if (owner == address(0)) { revert ERC20InvalidApprover(address(0)); } if (spender == address(0)) { revert ERC20InvalidSpender(address(0)); } _allowances[owner][spender] = value; if (emitEvent) { emit Approval(owner, spender, value); } } /** * @dev Updates `owner` s allowance for `spender` based on spent `value`. * * Does not update the allowance value in case of infinite allowance. * Revert if not enough allowance is available. * * Does not emit an {Approval} event. */ function _spendAllowance(address owner, address spender, uint256 value) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { if (currentAllowance < value) { revert ERC20InsufficientAllowance(spender, currentAllowance, value); } unchecked { _approve(owner, spender, currentAllowance - value, false); } } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.20; import {IERC20} from "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.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/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/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/math/SafeCast.sol) // This file was procedurally generated from scripts/generate/templates/SafeCast.js. pragma solidity ^0.8.20; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeCast { /** * @dev Value doesn't fit in an uint of `bits` size. */ error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value); /** * @dev An int value doesn't fit in an uint of `bits` size. */ error SafeCastOverflowedIntToUint(int256 value); /** * @dev Value doesn't fit in an int of `bits` size. */ error SafeCastOverflowedIntDowncast(uint8 bits, int256 value); /** * @dev An uint value doesn't fit in an int of `bits` size. */ error SafeCastOverflowedUintToInt(uint256 value); /** * @dev Returns the downcasted uint248 from uint256, reverting on * overflow (when the input is greater than largest uint248). * * Counterpart to Solidity's `uint248` operator. * * Requirements: * * - input must fit into 248 bits */ function toUint248(uint256 value) internal pure returns (uint248) { if (value > type(uint248).max) { revert SafeCastOverflowedUintDowncast(248, value); } return uint248(value); } /** * @dev Returns the downcasted uint240 from uint256, reverting on * overflow (when the input is greater than largest uint240). * * Counterpart to Solidity's `uint240` operator. * * Requirements: * * - input must fit into 240 bits */ function toUint240(uint256 value) internal pure returns (uint240) { if (value > type(uint240).max) { revert SafeCastOverflowedUintDowncast(240, value); } return uint240(value); } /** * @dev Returns the downcasted uint232 from uint256, reverting on * overflow (when the input is greater than largest uint232). * * Counterpart to Solidity's `uint232` operator. * * Requirements: * * - input must fit into 232 bits */ function toUint232(uint256 value) internal pure returns (uint232) { if (value > type(uint232).max) { revert SafeCastOverflowedUintDowncast(232, value); } return uint232(value); } /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { if (value > type(uint224).max) { revert SafeCastOverflowedUintDowncast(224, value); } return uint224(value); } /** * @dev Returns the downcasted uint216 from uint256, reverting on * overflow (when the input is greater than largest uint216). * * Counterpart to Solidity's `uint216` operator. * * Requirements: * * - input must fit into 216 bits */ function toUint216(uint256 value) internal pure returns (uint216) { if (value > type(uint216).max) { revert SafeCastOverflowedUintDowncast(216, value); } return uint216(value); } /** * @dev Returns the downcasted uint208 from uint256, reverting on * overflow (when the input is greater than largest uint208). * * Counterpart to Solidity's `uint208` operator. * * Requirements: * * - input must fit into 208 bits */ function toUint208(uint256 value) internal pure returns (uint208) { if (value > type(uint208).max) { revert SafeCastOverflowedUintDowncast(208, value); } return uint208(value); } /** * @dev Returns the downcasted uint200 from uint256, reverting on * overflow (when the input is greater than largest uint200). * * Counterpart to Solidity's `uint200` operator. * * Requirements: * * - input must fit into 200 bits */ function toUint200(uint256 value) internal pure returns (uint200) { if (value > type(uint200).max) { revert SafeCastOverflowedUintDowncast(200, value); } return uint200(value); } /** * @dev Returns the downcasted uint192 from uint256, reverting on * overflow (when the input is greater than largest uint192). * * Counterpart to Solidity's `uint192` operator. * * Requirements: * * - input must fit into 192 bits */ function toUint192(uint256 value) internal pure returns (uint192) { if (value > type(uint192).max) { revert SafeCastOverflowedUintDowncast(192, value); } return uint192(value); } /** * @dev Returns the downcasted uint184 from uint256, reverting on * overflow (when the input is greater than largest uint184). * * Counterpart to Solidity's `uint184` operator. * * Requirements: * * - input must fit into 184 bits */ function toUint184(uint256 value) internal pure returns (uint184) { if (value > type(uint184).max) { revert SafeCastOverflowedUintDowncast(184, value); } return uint184(value); } /** * @dev Returns the downcasted uint176 from uint256, reverting on * overflow (when the input is greater than largest uint176). * * Counterpart to Solidity's `uint176` operator. * * Requirements: * * - input must fit into 176 bits */ function toUint176(uint256 value) internal pure returns (uint176) { if (value > type(uint176).max) { revert SafeCastOverflowedUintDowncast(176, value); } return uint176(value); } /** * @dev Returns the downcasted uint168 from uint256, reverting on * overflow (when the input is greater than largest uint168). * * Counterpart to Solidity's `uint168` operator. * * Requirements: * * - input must fit into 168 bits */ function toUint168(uint256 value) internal pure returns (uint168) { if (value > type(uint168).max) { revert SafeCastOverflowedUintDowncast(168, value); } return uint168(value); } /** * @dev Returns the downcasted uint160 from uint256, reverting on * overflow (when the input is greater than largest uint160). * * Counterpart to Solidity's `uint160` operator. * * Requirements: * * - input must fit into 160 bits */ function toUint160(uint256 value) internal pure returns (uint160) { if (value > type(uint160).max) { revert SafeCastOverflowedUintDowncast(160, value); } return uint160(value); } /** * @dev Returns the downcasted uint152 from uint256, reverting on * overflow (when the input is greater than largest uint152). * * Counterpart to Solidity's `uint152` operator. * * Requirements: * * - input must fit into 152 bits */ function toUint152(uint256 value) internal pure returns (uint152) { if (value > type(uint152).max) { revert SafeCastOverflowedUintDowncast(152, value); } return uint152(value); } /** * @dev Returns the downcasted uint144 from uint256, reverting on * overflow (when the input is greater than largest uint144). * * Counterpart to Solidity's `uint144` operator. * * Requirements: * * - input must fit into 144 bits */ function toUint144(uint256 value) internal pure returns (uint144) { if (value > type(uint144).max) { revert SafeCastOverflowedUintDowncast(144, value); } return uint144(value); } /** * @dev Returns the downcasted uint136 from uint256, reverting on * overflow (when the input is greater than largest uint136). * * Counterpart to Solidity's `uint136` operator. * * Requirements: * * - input must fit into 136 bits */ function toUint136(uint256 value) internal pure returns (uint136) { if (value > type(uint136).max) { revert SafeCastOverflowedUintDowncast(136, value); } return uint136(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { if (value > type(uint128).max) { revert SafeCastOverflowedUintDowncast(128, value); } return uint128(value); } /** * @dev Returns the downcasted uint120 from uint256, reverting on * overflow (when the input is greater than largest uint120). * * Counterpart to Solidity's `uint120` operator. * * Requirements: * * - input must fit into 120 bits */ function toUint120(uint256 value) internal pure returns (uint120) { if (value > type(uint120).max) { revert SafeCastOverflowedUintDowncast(120, value); } return uint120(value); } /** * @dev Returns the downcasted uint112 from uint256, reverting on * overflow (when the input is greater than largest uint112). * * Counterpart to Solidity's `uint112` operator. * * Requirements: * * - input must fit into 112 bits */ function toUint112(uint256 value) internal pure returns (uint112) { if (value > type(uint112).max) { revert SafeCastOverflowedUintDowncast(112, value); } return uint112(value); } /** * @dev Returns the downcasted uint104 from uint256, reverting on * overflow (when the input is greater than largest uint104). * * Counterpart to Solidity's `uint104` operator. * * Requirements: * * - input must fit into 104 bits */ function toUint104(uint256 value) internal pure returns (uint104) { if (value > type(uint104).max) { revert SafeCastOverflowedUintDowncast(104, value); } return uint104(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits */ function toUint96(uint256 value) internal pure returns (uint96) { if (value > type(uint96).max) { revert SafeCastOverflowedUintDowncast(96, value); } return uint96(value); } /** * @dev Returns the downcasted uint88 from uint256, reverting on * overflow (when the input is greater than largest uint88). * * Counterpart to Solidity's `uint88` operator. * * Requirements: * * - input must fit into 88 bits */ function toUint88(uint256 value) internal pure returns (uint88) { if (value > type(uint88).max) { revert SafeCastOverflowedUintDowncast(88, value); } return uint88(value); } /** * @dev Returns the downcasted uint80 from uint256, reverting on * overflow (when the input is greater than largest uint80). * * Counterpart to Solidity's `uint80` operator. * * Requirements: * * - input must fit into 80 bits */ function toUint80(uint256 value) internal pure returns (uint80) { if (value > type(uint80).max) { revert SafeCastOverflowedUintDowncast(80, value); } return uint80(value); } /** * @dev Returns the downcasted uint72 from uint256, reverting on * overflow (when the input is greater than largest uint72). * * Counterpart to Solidity's `uint72` operator. * * Requirements: * * - input must fit into 72 bits */ function toUint72(uint256 value) internal pure returns (uint72) { if (value > type(uint72).max) { revert SafeCastOverflowedUintDowncast(72, value); } return uint72(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { if (value > type(uint64).max) { revert SafeCastOverflowedUintDowncast(64, value); } return uint64(value); } /** * @dev Returns the downcasted uint56 from uint256, reverting on * overflow (when the input is greater than largest uint56). * * Counterpart to Solidity's `uint56` operator. * * Requirements: * * - input must fit into 56 bits */ function toUint56(uint256 value) internal pure returns (uint56) { if (value > type(uint56).max) { revert SafeCastOverflowedUintDowncast(56, value); } return uint56(value); } /** * @dev Returns the downcasted uint48 from uint256, reverting on * overflow (when the input is greater than largest uint48). * * Counterpart to Solidity's `uint48` operator. * * Requirements: * * - input must fit into 48 bits */ function toUint48(uint256 value) internal pure returns (uint48) { if (value > type(uint48).max) { revert SafeCastOverflowedUintDowncast(48, value); } return uint48(value); } /** * @dev Returns the downcasted uint40 from uint256, reverting on * overflow (when the input is greater than largest uint40). * * Counterpart to Solidity's `uint40` operator. * * Requirements: * * - input must fit into 40 bits */ function toUint40(uint256 value) internal pure returns (uint40) { if (value > type(uint40).max) { revert SafeCastOverflowedUintDowncast(40, value); } return uint40(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { if (value > type(uint32).max) { revert SafeCastOverflowedUintDowncast(32, value); } return uint32(value); } /** * @dev Returns the downcasted uint24 from uint256, reverting on * overflow (when the input is greater than largest uint24). * * Counterpart to Solidity's `uint24` operator. * * Requirements: * * - input must fit into 24 bits */ function toUint24(uint256 value) internal pure returns (uint24) { if (value > type(uint24).max) { revert SafeCastOverflowedUintDowncast(24, value); } return uint24(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { if (value > type(uint16).max) { revert SafeCastOverflowedUintDowncast(16, value); } return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits */ function toUint8(uint256 value) internal pure returns (uint8) { if (value > type(uint8).max) { revert SafeCastOverflowedUintDowncast(8, value); } return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { if (value < 0) { revert SafeCastOverflowedIntToUint(value); } return uint256(value); } /** * @dev Returns the downcasted int248 from int256, reverting on * overflow (when the input is less than smallest int248 or * greater than largest int248). * * Counterpart to Solidity's `int248` operator. * * Requirements: * * - input must fit into 248 bits */ function toInt248(int256 value) internal pure returns (int248 downcasted) { downcasted = int248(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(248, value); } } /** * @dev Returns the downcasted int240 from int256, reverting on * overflow (when the input is less than smallest int240 or * greater than largest int240). * * Counterpart to Solidity's `int240` operator. * * Requirements: * * - input must fit into 240 bits */ function toInt240(int256 value) internal pure returns (int240 downcasted) { downcasted = int240(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(240, value); } } /** * @dev Returns the downcasted int232 from int256, reverting on * overflow (when the input is less than smallest int232 or * greater than largest int232). * * Counterpart to Solidity's `int232` operator. * * Requirements: * * - input must fit into 232 bits */ function toInt232(int256 value) internal pure returns (int232 downcasted) { downcasted = int232(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(232, value); } } /** * @dev Returns the downcasted int224 from int256, reverting on * overflow (when the input is less than smallest int224 or * greater than largest int224). * * Counterpart to Solidity's `int224` operator. * * Requirements: * * - input must fit into 224 bits */ function toInt224(int256 value) internal pure returns (int224 downcasted) { downcasted = int224(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(224, value); } } /** * @dev Returns the downcasted int216 from int256, reverting on * overflow (when the input is less than smallest int216 or * greater than largest int216). * * Counterpart to Solidity's `int216` operator. * * Requirements: * * - input must fit into 216 bits */ function toInt216(int256 value) internal pure returns (int216 downcasted) { downcasted = int216(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(216, value); } } /** * @dev Returns the downcasted int208 from int256, reverting on * overflow (when the input is less than smallest int208 or * greater than largest int208). * * Counterpart to Solidity's `int208` operator. * * Requirements: * * - input must fit into 208 bits */ function toInt208(int256 value) internal pure returns (int208 downcasted) { downcasted = int208(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(208, value); } } /** * @dev Returns the downcasted int200 from int256, reverting on * overflow (when the input is less than smallest int200 or * greater than largest int200). * * Counterpart to Solidity's `int200` operator. * * Requirements: * * - input must fit into 200 bits */ function toInt200(int256 value) internal pure returns (int200 downcasted) { downcasted = int200(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(200, value); } } /** * @dev Returns the downcasted int192 from int256, reverting on * overflow (when the input is less than smallest int192 or * greater than largest int192). * * Counterpart to Solidity's `int192` operator. * * Requirements: * * - input must fit into 192 bits */ function toInt192(int256 value) internal pure returns (int192 downcasted) { downcasted = int192(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(192, value); } } /** * @dev Returns the downcasted int184 from int256, reverting on * overflow (when the input is less than smallest int184 or * greater than largest int184). * * Counterpart to Solidity's `int184` operator. * * Requirements: * * - input must fit into 184 bits */ function toInt184(int256 value) internal pure returns (int184 downcasted) { downcasted = int184(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(184, value); } } /** * @dev Returns the downcasted int176 from int256, reverting on * overflow (when the input is less than smallest int176 or * greater than largest int176). * * Counterpart to Solidity's `int176` operator. * * Requirements: * * - input must fit into 176 bits */ function toInt176(int256 value) internal pure returns (int176 downcasted) { downcasted = int176(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(176, value); } } /** * @dev Returns the downcasted int168 from int256, reverting on * overflow (when the input is less than smallest int168 or * greater than largest int168). * * Counterpart to Solidity's `int168` operator. * * Requirements: * * - input must fit into 168 bits */ function toInt168(int256 value) internal pure returns (int168 downcasted) { downcasted = int168(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(168, value); } } /** * @dev Returns the downcasted int160 from int256, reverting on * overflow (when the input is less than smallest int160 or * greater than largest int160). * * Counterpart to Solidity's `int160` operator. * * Requirements: * * - input must fit into 160 bits */ function toInt160(int256 value) internal pure returns (int160 downcasted) { downcasted = int160(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(160, value); } } /** * @dev Returns the downcasted int152 from int256, reverting on * overflow (when the input is less than smallest int152 or * greater than largest int152). * * Counterpart to Solidity's `int152` operator. * * Requirements: * * - input must fit into 152 bits */ function toInt152(int256 value) internal pure returns (int152 downcasted) { downcasted = int152(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(152, value); } } /** * @dev Returns the downcasted int144 from int256, reverting on * overflow (when the input is less than smallest int144 or * greater than largest int144). * * Counterpart to Solidity's `int144` operator. * * Requirements: * * - input must fit into 144 bits */ function toInt144(int256 value) internal pure returns (int144 downcasted) { downcasted = int144(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(144, value); } } /** * @dev Returns the downcasted int136 from int256, reverting on * overflow (when the input is less than smallest int136 or * greater than largest int136). * * Counterpart to Solidity's `int136` operator. * * Requirements: * * - input must fit into 136 bits */ function toInt136(int256 value) internal pure returns (int136 downcasted) { downcasted = int136(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(136, value); } } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits */ function toInt128(int256 value) internal pure returns (int128 downcasted) { downcasted = int128(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(128, value); } } /** * @dev Returns the downcasted int120 from int256, reverting on * overflow (when the input is less than smallest int120 or * greater than largest int120). * * Counterpart to Solidity's `int120` operator. * * Requirements: * * - input must fit into 120 bits */ function toInt120(int256 value) internal pure returns (int120 downcasted) { downcasted = int120(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(120, value); } } /** * @dev Returns the downcasted int112 from int256, reverting on * overflow (when the input is less than smallest int112 or * greater than largest int112). * * Counterpart to Solidity's `int112` operator. * * Requirements: * * - input must fit into 112 bits */ function toInt112(int256 value) internal pure returns (int112 downcasted) { downcasted = int112(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(112, value); } } /** * @dev Returns the downcasted int104 from int256, reverting on * overflow (when the input is less than smallest int104 or * greater than largest int104). * * Counterpart to Solidity's `int104` operator. * * Requirements: * * - input must fit into 104 bits */ function toInt104(int256 value) internal pure returns (int104 downcasted) { downcasted = int104(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(104, value); } } /** * @dev Returns the downcasted int96 from int256, reverting on * overflow (when the input is less than smallest int96 or * greater than largest int96). * * Counterpart to Solidity's `int96` operator. * * Requirements: * * - input must fit into 96 bits */ function toInt96(int256 value) internal pure returns (int96 downcasted) { downcasted = int96(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(96, value); } } /** * @dev Returns the downcasted int88 from int256, reverting on * overflow (when the input is less than smallest int88 or * greater than largest int88). * * Counterpart to Solidity's `int88` operator. * * Requirements: * * - input must fit into 88 bits */ function toInt88(int256 value) internal pure returns (int88 downcasted) { downcasted = int88(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(88, value); } } /** * @dev Returns the downcasted int80 from int256, reverting on * overflow (when the input is less than smallest int80 or * greater than largest int80). * * Counterpart to Solidity's `int80` operator. * * Requirements: * * - input must fit into 80 bits */ function toInt80(int256 value) internal pure returns (int80 downcasted) { downcasted = int80(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(80, value); } } /** * @dev Returns the downcasted int72 from int256, reverting on * overflow (when the input is less than smallest int72 or * greater than largest int72). * * Counterpart to Solidity's `int72` operator. * * Requirements: * * - input must fit into 72 bits */ function toInt72(int256 value) internal pure returns (int72 downcasted) { downcasted = int72(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(72, value); } } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits */ function toInt64(int256 value) internal pure returns (int64 downcasted) { downcasted = int64(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(64, value); } } /** * @dev Returns the downcasted int56 from int256, reverting on * overflow (when the input is less than smallest int56 or * greater than largest int56). * * Counterpart to Solidity's `int56` operator. * * Requirements: * * - input must fit into 56 bits */ function toInt56(int256 value) internal pure returns (int56 downcasted) { downcasted = int56(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(56, value); } } /** * @dev Returns the downcasted int48 from int256, reverting on * overflow (when the input is less than smallest int48 or * greater than largest int48). * * Counterpart to Solidity's `int48` operator. * * Requirements: * * - input must fit into 48 bits */ function toInt48(int256 value) internal pure returns (int48 downcasted) { downcasted = int48(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(48, value); } } /** * @dev Returns the downcasted int40 from int256, reverting on * overflow (when the input is less than smallest int40 or * greater than largest int40). * * Counterpart to Solidity's `int40` operator. * * Requirements: * * - input must fit into 40 bits */ function toInt40(int256 value) internal pure returns (int40 downcasted) { downcasted = int40(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(40, value); } } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits */ function toInt32(int256 value) internal pure returns (int32 downcasted) { downcasted = int32(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(32, value); } } /** * @dev Returns the downcasted int24 from int256, reverting on * overflow (when the input is less than smallest int24 or * greater than largest int24). * * Counterpart to Solidity's `int24` operator. * * Requirements: * * - input must fit into 24 bits */ function toInt24(int256 value) internal pure returns (int24 downcasted) { downcasted = int24(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(24, value); } } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits */ function toInt16(int256 value) internal pure returns (int16 downcasted) { downcasted = int16(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(16, value); } } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits */ function toInt8(int256 value) internal pure returns (int8 downcasted) { downcasted = int8(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(8, value); } } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive if (value > uint256(type(int256).max)) { revert SafeCastOverflowedUintToInt(value); } return int256(value); } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.24; import "./AcceptableImplementationClaimableAdminStorage.sol"; /** * @title SafeUpgradeableClaimableAdmin * @dev based on Compound's Unitroller * https://github.com/compound-finance/compound-protocol/blob/a3214f67b73310d547e00fc578e8355911c9d376/contracts/Unitroller.sol */ contract AcceptableImplementationClaimableAdmin is AcceptableImplementationClaimableAdminStorage { /** * @notice Emitted when pendingImplementation is changed */ event NewPendingImplementation( address oldPendingImplementation, address newPendingImplementation ); /** * @notice Emitted when pendingImplementation is accepted, which means delegation implementation is updated */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /*** Admin Functions ***/ function _setPendingImplementation(address newPendingImplementation) public { require(msg.sender == admin, "not admin"); require( approvePendingImplementationInternal(newPendingImplementation), "INVALID_IMPLEMENTATION" ); address oldPendingImplementation = pendingImplementation; pendingImplementation = newPendingImplementation; emit NewPendingImplementation( oldPendingImplementation, pendingImplementation ); } /** * @notice Accepts new implementation. msg.sender must be pendingImplementation * @dev Admin function for new implementation to accept it's role as implementation */ function _acceptImplementation() public returns (uint) { // Check caller is pendingImplementation and pendingImplementation ≠ address(0) require( msg.sender == pendingImplementation && pendingImplementation != address(0), "Not the EXISTING pending implementation" ); // Save current values for inclusion in log address oldImplementation = implementation; address oldPendingImplementation = pendingImplementation; implementation = pendingImplementation; pendingImplementation = address(0); emit NewImplementation(oldImplementation, implementation); emit NewPendingImplementation( oldPendingImplementation, pendingImplementation ); return 0; } /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. */ function _setPendingAdmin(address newPendingAdmin) public { // Check caller = admin require(msg.sender == admin, "Not Admin"); // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin */ function _acceptAdmin() public { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) require( msg.sender == pendingAdmin && pendingAdmin != address(0), "Not the EXISTING pending admin" ); // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); } constructor(address _initialAdmin) { admin = _initialAdmin; emit NewAdmin(address(0), _initialAdmin); } /** * @dev Delegates execution to an implementation contract. * It returns to the external caller whatever the implementation returns * or forwards reverts. */ fallback() external payable { // delegate all other functions to current implementation (bool success, ) = implementation.delegatecall(msg.data); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize()) switch success case 0 { revert(free_mem_ptr, returndatasize()) } default { return(free_mem_ptr, returndatasize()) } } } receive() external payable {} function approvePendingImplementationInternal( address // _implementation ) internal virtual returns (bool) { return true; } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.24; contract ClaimableAdminStorage { /** * @notice Administrator for this contract */ address public admin; /** * @notice Pending administrator for this contract */ address public pendingAdmin; /*** Modifiers ***/ modifier onlyAdmin() { require(msg.sender == admin, "ONLY_ADMIN"); _; } /*** Constructor ***/ constructor() { // Set admin to caller admin = msg.sender; } } contract AcceptableImplementationClaimableAdminStorage is ClaimableAdminStorage { /** * @notice Active logic */ address public implementation; /** * @notice Pending logic */ address public pendingImplementation; } contract AcceptableRegistryImplementationClaimableAdminStorage is AcceptableImplementationClaimableAdminStorage { /** * @notice System Registry */ address public registry; }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.24; import "./AcceptableImplementationClaimableAdmin.sol"; import "./IContractRegistryBase.sol"; /** * @title AcceptableRegistryImplementationClaimableAdmin */ contract AcceptableRegistryImplementationClaimableAdmin is AcceptableImplementationClaimableAdmin, AcceptableRegistryImplementationClaimableAdminStorage { bytes32 public immutable CONTRACT_NAME_HASH; constructor( address _registry, string memory proxyName, address _initialAdmin ) AcceptableImplementationClaimableAdmin(_initialAdmin) { registry = _registry; CONTRACT_NAME_HASH = keccak256(abi.encodePacked(proxyName)); } function approvePendingImplementationInternal( address _implementation ) internal view override returns (bool) { return IContractRegistryBase(registry).isImplementationValidForProxy( CONTRACT_NAME_HASH, _implementation ); } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.24; import "./AcceptableImplementationClaimableAdminStorage.sol"; /** * @title Claimable Admin */ contract ClaimableAdmin is ClaimableAdminStorage { /** * @notice Emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /*** Admin Functions ***/ /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. */ function _setPendingAdmin(address newPendingAdmin) public { // Check caller = admin require(msg.sender == admin, "Not Admin"); // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin */ function _acceptAdmin() public { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) require( msg.sender == pendingAdmin && pendingAdmin != address(0), "Not the EXISTING pending admin" ); // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.24; interface IContractRegistryBase { function isImplementationValidForProxy( bytes32 proxyNameHash, address _implementation ) external view returns (bool); }
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.24; /** * @dev only use immutables and constants in this contract */ contract CommonScales { uint256 public constant PRECISION = 1e18; // 18 decimals uint256 public constant LEVERAGE_SCALE = 100; // 2 decimal points uint256 public constant FRACTION_SCALE = 100000; // 5 decimal points uint256 public constant ACCURACY_IMPROVEMENT_SCALE = 1e9; function calculateLeveragedPosition( uint256 collateral, uint256 leverage ) internal pure returns (uint256) { return (collateral * leverage) / LEVERAGE_SCALE; } }
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.24; interface IAffiliationV1 { event PositionRequested( bytes32 indexed domain, bytes32 indexed referralCode, bytes32 indexed positionId ); event LiquidityProvided( bytes32 indexed domain, bytes32 indexed referralCode, address indexed user, uint amountUnderlying, uint processingEpoch ); }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.24; interface IFundingRateModel { // return value is the "funding paid by heavier side" in PRECISION per OI (heavier side) per second // e.g : (0.01 * PRECISION) = Paying (heavier) side (as a whole) pays 1% of funding per second for each OI unit function getFundingRate( uint256 pairId, uint256 openInterestLong, uint256 openInterestShort, uint256 pairMaxOpenInterest ) external view returns (uint256); }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.24; interface IGlobalLock { function lock() external; function freeLock() external; }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.24; interface IInterestRateModel { // Returns asset/second of interest per borrowed unit // e.g : (0.01 * PRECISION) = 1% of interest per second function getBorrowRate(uint256 utilization) external view returns (uint256); }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.24; import "./LexErrors.sol"; import "./LexPoolAdminEnums.sol"; import "./IPoolAccountantV1.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface LexPoolStructs { struct PendingDeposit { uint256 amount; uint256 minAmountOut; } struct PendingRedeem { uint256 amount; uint256 minAmountOut; uint256 maxAmountOut; } } interface LexPoolEvents is LexPoolAdminEnums { event NewEpoch( uint256 epochId, int256 reportedUnrealizedPricePnL, uint256 exchangeRate, uint256 virtualUnderlyingBalance, uint256 totalSupply ); event AddressUpdated(LexPoolAddressesEnum indexed enumCode, address a); event NumberUpdated(LexPoolNumbersEnum indexed enumCode, uint value); event DepositRequest( address indexed user, uint256 amount, uint256 minAmountOut, uint256 processingEpoch ); event RedeemRequest( address indexed user, uint256 amount, uint256 minAmountOut, uint256 processingEpoch ); event ProcessedDeposit( address indexed user, bool deposited, uint256 depositedAmount ); event ProcessedRedeem( address indexed user, bool redeemed, uint256 withdrawnAmount // Underlying amount ); event CanceledDeposit( address indexed user, uint256 epoch, uint256 cancelledAmount ); event CanceledRedeem( address indexed user, uint256 epoch, uint256 cancelledAmount ); event ImmediateDepositAllowedToggled(bool indexed value); event ImmediateDeposit( address indexed depositor, uint256 depositAmount, uint256 mintAmount ); event ReservesWithdrawn( address _to, uint256 interestShare, uint256 totalFundingShare ); } interface ILexPoolFunctionality is IERC20, LexPoolStructs, LexPoolEvents, LexErrors { function setPoolAccountant( IPoolAccountantFunctionality _poolAccountant ) external; function setPnlRole(address pnl) external; function setMaxExtraWithdrawalAmountF(uint256 maxExtra) external; function setEpochsDelayDeposit(uint256 delay) external; function setEpochsDelayRedeem(uint256 delay) external; function setEpochDuration(uint256 duration) external; function setMinDepositAmount(uint256 amount) external; function toggleImmediateDepositAllowed() external; function reduceReserves( address _to ) external returns (uint256 interestShare, uint256 totalFundingShare); function requestDeposit( uint256 amount, uint256 minAmountOut, bytes32 domain, bytes32 referralCode ) external; function requestDepositViaIntent( address user, uint256 amount, uint256 minAmountOut, bytes32 domain, bytes32 referralCode ) external; function requestRedeem(uint256 amount, uint256 minAmountOut) external; function requestRedeemViaIntent( address user, uint256 amount, uint256 minAmountOut ) external; function processDeposit( address[] memory users ) external returns ( uint256 amountDeposited, uint256 amountCancelled, uint256 counterDeposited, uint256 counterCancelled ); function cancelDeposits( address[] memory users, uint256[] memory epochs ) external; function processRedeems( address[] memory users ) external returns ( uint256 amountRedeemed, uint256 amountCancelled, uint256 counterDeposited, uint256 counterCancelled ); function cancelRedeems( address[] memory users, uint256[] memory epochs ) external; function nextEpoch( int256 totalUnrealizedPricePnL ) external returns (uint256 newExchangeRate); function currentVirtualUtilization() external view returns (uint256); function currentVirtualUtilization( uint256 totalBorrows, uint256 totalReserves, int256 unrealizedFunding ) external view returns (uint256); function virtualBalanceForUtilization() external view returns (uint256); function virtualBalanceForUtilization( uint256 extraAmount, int256 unrealizedFunding ) external view returns (uint256); function underlyingBalanceForExchangeRate() external view returns (uint256); function sendAssetToTrader(address to, uint256 amount) external; function isUtilizationForLPsValid() external view returns (bool); } interface ILexPoolV1 is ILexPoolFunctionality { function name() external view returns (string memory); function symbol() external view returns (string memory); function SELF_UNIT_SCALE() external view returns (uint); function underlyingDecimals() external view returns (uint256); function poolAccountant() external view returns (address); function underlying() external view returns (IERC20); function tradingFloor() external view returns (address); function currentEpoch() external view returns (uint256); function currentExchangeRate() external view returns (uint256); function nextEpochStartMin() external view returns (uint256); function epochDuration() external view returns (uint256); function minDepositAmount() external view returns (uint256); function epochsDelayDeposit() external view returns (uint256); function epochsDelayRedeem() external view returns (uint256); function immediateDepositAllowed() external view returns (bool); function pendingDeposits( uint epoch, address account ) external view returns (PendingDeposit memory); function pendingRedeems( uint epoch, address account ) external view returns (PendingRedeem memory); function pendingDepositAmount() external view returns (uint256); function pendingWithdrawalAmount() external view returns (uint256); }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.24; interface ILynxVersionedContract { /** * @notice Returns the name of the contract */ function getContractName() external view returns (string memory); /** * @notice Returns the version of the contract * @dev units are scaled by 1000 (1,000 = 1.00, 1,120 = 1.12) */ function getContractVersion() external view returns (string memory); }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.24; import "./LexErrors.sol"; import "./ILexPoolV1.sol"; import "./IInterestRateModel.sol"; import "./IFundingRateModel.sol"; import "./TradingEnumsV1.sol"; interface PoolAccountantStructs { // @note To be used for passing information in function calls struct PositionRegistrationParams { uint256 collateral; uint32 leverage; bool long; uint64 openPrice; uint64 tp; } struct PairFunding { // Slot 0 int256 accPerOiLong; // 32 bytes -- Underlying Decimals // Slot 1 int256 accPerOiShort; // 32 bytes -- Underlying Decimals // Slot 2 uint256 lastUpdateTimestamp; // 32 bytes } struct TradeInitialAccFees { // Slot 0 uint256 borrowIndex; // 32 bytes // Slot 1 int256 funding; // 32 bytes -- underlying units -- Underlying Decimals } struct PairOpenInterest { // Slot 0 uint256 long; // 32 bytes -- underlying units -- Dynamic open interest for long positions // Slot 1 uint256 short; // 32 bytes -- underlying units -- Dynamic open interest for short positions } // This struct is not kept in storage struct PairFromTo { string from; string to; } struct Pair { // Slot 0 uint16 id; // 02 bytes uint16 groupId; // 02 bytes uint16 feeId; // 02 bytes uint32 minLeverage; // 04 bytes uint32 maxLeverage; // 04 bytes uint32 maxBorrowF; // 04 bytes -- FRACTION_SCALE (5) // Slot 1 uint256 maxPositionSize; // 32 bytes -- underlying units // Slot 2 uint256 maxGain; // 32 bytes -- underlying units // Slot 3 uint256 maxOpenInterest; // 32 bytes -- Underlying units // Slot 4 uint256 maxSkew; // 32 bytes -- underlying units // Slot 5 uint256 minOpenFee; // 32 bytes -- underlying units. MAX_UINT means use the default group level value // Slot 6 uint256 minPerformanceFee; // 32 bytes -- underlying units } struct Group { // Slot 0 uint16 id; // 02 bytes uint32 minLeverage; // 04 bytes uint32 maxLeverage; // 04 bytes uint32 maxBorrowF; // 04 bytes -- FRACTION_SCALE (5) // Slot 1 uint256 maxPositionSize; // 32 bytes (Underlying units) // Slot 2 uint256 minOpenFee; // 32 bytes (Underlying uints). MAX_UINT means use the default global level value } struct Fee { // Slot 0 uint16 id; // 02 bytes uint32 openFeeF; // 04 bytes -- FRACTION_SCALE (5) (Fraction of leveraged pos) uint32 closeFeeF; // 04 bytes -- FRACTION_SCALE (5) (Fraction of leveraged pos) uint32 performanceFeeF; // 04 bytes -- FRACTION_SCALE (5) (Fraction of performance) } } interface PoolAccountantEvents is PoolAccountantStructs { event PairAdded( uint256 indexed id, string indexed from, string indexed to, Pair pair ); event PairUpdated(uint256 indexed id, Pair pair); event GroupAdded(uint256 indexed id, string indexed groupName, Group group); event GroupUpdated(uint256 indexed id, Group group); event FeeAdded(uint256 indexed id, string indexed name, Fee fee); event FeeUpdated(uint256 indexed id, Fee fee); event TradeInitialAccFeesStored( bytes32 indexed positionId, uint256 borrowIndex, // uint256 rollover, int256 funding ); event AccrueFunding( uint256 indexed pairId, int256 valueLong, int256 valueShort ); event ProtocolFundingShareAccrued( uint16 indexed pairId, uint256 protocolFundingShare ); // event AccRolloverFeesStored(uint256 pairIndex, uint256 value); event FeesCharged( bytes32 indexed positionId, address indexed trader, uint16 indexed pairId, PositionRegistrationParams positionRegistrationParams, // bool long, // uint256 collateral, // Underlying Decimals // uint256 leverage, int256 profitPrecision, // PRECISION uint256 interest, int256 funding, // Underlying Decimals uint256 closingFee, uint256 tradeValue ); event PerformanceFeeCharging( bytes32 indexed positionId, uint256 performanceFee ); event MaxOpenInterestUpdated(uint256 pairIndex, uint256 maxOpenInterest); event AccrueInterest( uint256 cash, uint256 totalInterestNew, uint256 borrowIndexNew, uint256 interestShareNew ); event Borrow( uint256 indexed pairId, uint256 borrowAmount, uint256 newTotalBorrows ); event Repay( uint256 indexed pairId, uint256 repayAmount, uint256 newTotalBorrows ); } interface IPoolAccountantFunctionality is PoolAccountantStructs, PoolAccountantEvents, LexErrors, TradingEnumsV1 { function setTradeIncentivizer(address _tradeIncentivizer) external; function setMaxGainF(uint256 _maxGainF) external; function setFrm(IFundingRateModel _frm) external; function setMinOpenFee(uint256 min) external; function setLexPartF(uint256 partF) external; function setFundingRateMax(uint256 maxValue) external; function setLiquidationThresholdF(uint256 threshold) external; function setLiquidationFeeF(uint256 fee) external; function setIrm(IInterestRateModel _irm) external; function setIrmHard(IInterestRateModel _irm) external; function setInterestShareFactor(uint256 factor) external; function setFundingShareFactor(uint256 factor) external; function setBorrowRateMax(uint256 rate) external; function setMaxTotalBorrows(uint256 maxBorrows) external; function setMaxVirtualUtilization(uint256 _maxVirtualUtilization) external; function resetTradersPairGains(uint256 pairId) external; function addGroup(Group calldata _group) external; function updateGroup(Group calldata _group) external; function addFee(Fee calldata _fee) external; function updateFee(Fee calldata _fee) external; function addPair(Pair calldata _pair) external; function addPairs(Pair[] calldata _pairs) external; function updatePair(Pair calldata _pair) external; function readAndZeroReserves() external returns (uint256 accumulatedInterestShare, uint256 accFundingShare); function registerOpenTrade( bytes32 positionId, address trader, uint16 pairId, uint256 collateral, uint32 leverage, bool long, uint256 tp, uint256 openPrice ) external returns (uint256 fee, uint256 lexPartFee); function registerCloseTrade( bytes32 positionId, address trader, uint16 pairId, PositionRegistrationParams calldata positionRegistrationParams, uint256 closePrice, PositionCloseType positionCloseType ) external returns ( uint256 closingFee, uint256 tradeValue, int256 profitPrecision, uint finalClosePrice ); function registerUpdateTp( bytes32 positionId, address trader, uint16 pairId, uint256 collateral, uint32 leverage, bool long, uint256 openPrice, uint256 oldTriggerPrice, uint256 triggerPrice ) external; // function registerUpdateSl( // address trader, // uint256 pairIndex, // uint256 index, // uint256 collateral, // uint256 leverage, // bool long, // uint256 openPrice, // uint256 triggerPrice // ) external returns (uint256 fee); function accrueInterest() external returns ( uint256 totalInterestNew, uint256 interestShareNew, uint256 borrowIndexNew ); // Limited only for the LexPool function accrueInterest( uint256 availableCash ) external returns ( uint256 totalInterestNew, uint256 interestShareNew, uint256 borrowIndexNew ); function getTradeClosingValues( bytes32 positionId, uint16 pairId, PositionRegistrationParams calldata positionRegistrationParams, uint256 closePrice, bool isLiquidation ) external returns ( uint256 tradeValue, // Underlying Decimals uint256 safeClosingFee, int256 profitPrecision, uint256 interest, int256 funding ); function getTradeLiquidationPrice( bytes32 positionId, uint16 pairId, uint256 openPrice, // PRICE_SCALE (8) uint256 tp, bool long, uint256 collateral, // Underlying Decimals uint32 leverage ) external returns ( uint256 // PRICE_SCALE (8) ); function calcTradeDynamicFees( bytes32 positionId, uint16 pairId, bool long, uint256 collateral, uint32 leverage, uint256 openPrice, uint256 tp ) external returns (uint256 interest, int256 funding); function unrealizedFunding() external view returns (int256); function totalBorrows() external view returns (uint256); function interestShare() external view returns (uint256); function fundingShare() external view returns (uint256); function totalReservesView() external view returns (uint256); function borrowsAndInterestShare() external view returns (uint256 totalBorrows, uint256 totalInterestShare); function pairTotalOpenInterest( uint256 pairIndex ) external view returns (int256); function pricePnL( uint256 pairId, uint256 price ) external view returns (int256); function getAllSupportedPairIds() external view returns (uint16[] memory); function getAllSupportedGroupsIds() external view returns (uint16[] memory); function getAllSupportedFeeIds() external view returns (uint16[] memory); } interface IPoolAccountantV1 is IPoolAccountantFunctionality { function totalBorrows() external view returns (uint256); function maxTotalBorrows() external view returns (uint256); function pairBorrows(uint256 pairId) external view returns (uint256); function groupBorrows(uint256 groupId) external view returns (uint256); function pairMaxBorrow(uint16 pairId) external view returns (uint256); function groupMaxBorrow(uint16 groupId) external view returns (uint256); function lexPool() external view returns (ILexPoolV1); function maxGainF() external view returns (uint256); function interestShareFactor() external view returns (uint256); function fundingShareFactor() external view returns (uint256); function frm() external view returns (IFundingRateModel); function irm() external view returns (IInterestRateModel); function pairs(uint16 pairId) external view returns (Pair memory); function groups(uint16 groupId) external view returns (Group memory); function fees(uint16 feeId) external view returns (Fee memory); function openInterestInPair( uint pairId ) external view returns (PairOpenInterest memory); function minOpenFee() external view returns (uint256); function liquidationThresholdF() external view returns (uint256); function liquidationFeeF() external view returns (uint256); function lexPartF() external view returns (uint256); function tradersPairGains(uint256 pairId) external view returns (int256); function calcBorrowAmount( uint256 collateral, uint256 leverage, bool long, uint256 openPrice, uint256 tp ) external pure returns (uint256); }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.24; import "../../AdministrationContracts/IContractRegistryBase.sol"; import "./IGlobalLock.sol"; interface IRegistryV1Functionality is IContractRegistryBase, IGlobalLock { // **** Locking mechanism **** function isTradersPortalAndLocker( address _address ) external view returns (bool); function isTriggersAndLocker(address _address) external view returns (bool); function isTradersPortalOrTriggersAndLocker( address _address ) external view returns (bool); } interface IRegistryV1 is IRegistryV1Functionality { // **** Public Storage params **** function feesManagers(address asset) external view returns (address); function orderBook() external view returns (address); function tradersPortal() external view returns (address); function triggers() external view returns (address); function tradeIntentsVerifier() external view returns (address); function liquidityIntentsVerifier() external view returns (address); function chipsIntentsVerifier() external view returns (address); function lexProxiesFactory() external view returns (address); function chipsFactory() external view returns (address); /** * @return An array of all supported trading floors */ function getAllSupportedTradingFloors() external view returns (address[] memory); /** * @return An array of all supported settlement assets */ function getSettlementAssetsForTradingFloor( address _tradingFloor ) external view returns (address[] memory); /** * @return The spender role address that is set for this chip */ function getValidSpenderTargetForChipByRole( address chip, string calldata role ) external view returns (address); /** * @return the address of the valid 'burnHandler' for the chip */ function validBurnHandlerForChip( address chip ) external view returns (address); /** * @return The address matching for the given role */ function getDynamicRoleAddress( string calldata _role ) external view returns (address); }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.24; import "./TradingFloorStructsV1.sol"; import "./IPoolAccountantV1.sol"; import "./ILexPoolV1.sol"; interface ITradingFloorV1Functionality is TradingFloorStructsV1 { function supportNewSettlementAsset( address _asset, address _lexPool, address _poolAccountant ) external; function getPositionTriggerInfo( bytes32 _positionId ) external view returns ( PositionPhase positionPhase, uint64 timestamp, uint16 pairId, bool long, uint32 spreadReductionF ); function getPositionPortalInfo( bytes32 _positionId ) external view returns ( PositionPhase positionPhase, uint64 inPhaseSince, address positionTrader ); function storePendingPosition( OpenOrderType _orderType, PositionRequestIdentifiers memory _requestIdentifiers, PositionRequestParams memory _requestParams, uint32 _spreadReductionF ) external returns (bytes32 positionId); function setOpenedPositionToMarketClose( bytes32 _positionId, uint64 _minPrice, uint64 _maxPrice ) external; function cancelPendingPosition( bytes32 _positionId, OpenOrderType _orderType, uint feeFraction ) external; function cancelMarketCloseForPosition( bytes32 _positionId, CloseOrderType _orderType, uint feeFraction ) external; function updatePendingPosition_openLimit( bytes32 _positionId, uint64 _minPrice, uint64 _maxPrice, uint64 _tp, uint64 _sl ) external; function openNewPosition_market( bytes32 _positionId, uint64 assetEffectivePrice, uint256 feeForCancellation ) external; function openNewPosition_limit( bytes32 _positionId, uint64 assetEffectivePrice, uint256 feeForCancellation ) external; function closeExistingPosition_Market( bytes32 _positionId, uint64 assetPrice, uint64 effectivePrice ) external; function closeExistingPosition_Limit( bytes32 _positionId, LimitTrigger limitTrigger, uint64 assetPrice, uint64 effectivePrice ) external; // Manage open trade function updateOpenedPosition( bytes32 _positionId, PositionField updateField, uint64 fieldValue, uint64 effectivePrice ) external; // Fees function collectFee(address _asset, FeeType _feeType, address _to) external; } interface ITradingFloorV1 is ITradingFloorV1Functionality { function PRECISION() external pure returns (uint); // *** Views *** function pairTradersArray( address _asset, uint _pairIndex ) external view returns (address[] memory); function generatePositionHashId( address settlementAsset, address trader, uint16 pairId, uint32 index ) external pure returns (bytes32 hashId); // *** Public Storage addresses *** function lexPoolForAsset(address asset) external view returns (ILexPoolV1); function poolAccountantForAsset( address asset ) external view returns (IPoolAccountantV1); function registry() external view returns (address); // *** Public Storage params *** function positionsById(bytes32 id) external view returns (Position memory); function positionIdentifiersById( bytes32 id ) external view returns (PositionIdentifiers memory); function positionLimitsInfoById( bytes32 id ) external view returns (PositionLimitsInfo memory); function triggerPricesById( bytes32 id ) external view returns (PositionTriggerPrices memory); function pairTradersInfo( address settlementAsset, address trader, uint pairId ) external view returns (PairTraderInfo memory); function spreadReductionsP(uint) external view returns (uint); function maxSlF() external view returns (uint); function maxTradesPerPair() external view returns (uint); function maxSanityProfitF() external view returns (uint); function feesMap( address settlementAsset, FeeType feeType ) external view returns (uint256); }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.24; interface LexErrors { enum CapType { NONE, // 0 MIN_OPEN_FEE, // 1 MAX_POS_SIZE_PAIR, // 2 MAX_POS_SIZE_GROUP, // 3 MAX_LEVERAGE, // 4 MIN_LEVERAGE, // 5 MAX_VIRTUAL_UTILIZATION, // 6 MAX_OPEN_INTEREST, // 7 MAX_ABS_SKEW, // 8 MAX_BORROW_PAIR, // 9 MAX_BORROW_GROUP, // 10 MIN_DEPOSIT_AMOUNT, // 11 MAX_ACCUMULATED_GAINS, // 12 BORROW_RATE_MAX, // 13 FUNDING_RATE_MAX, // 14 MAX_POTENTIAL_GAIN, // 15 MAX_TOTAL_BORROW, // 16 MIN_PERFORMANCE_FEE // 17 //... } error CapError(CapType, uint256 value); }
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.24; interface LexPoolAdminEnums { enum LexPoolAddressesEnum { none, poolAccountant, pnlRole } enum LexPoolNumbersEnum { none, maxExtraWithdrawalAmountF, epochsDelayDeposit, epochsDelayRedeem, epochDuration, minDepositAmount } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.24; interface TradingEnumsV1 { enum PositionPhase { NONE, OPEN_MARKET, OPEN_LIMIT, OPENED, CLOSE_MARKET, CLOSED } enum OpenOrderType { NONE, MARKET, LIMIT } enum CloseOrderType { NONE, MARKET } enum FeeType { NONE, OPEN_FEE, CLOSE_FEE, TRIGGER_FEE } enum LimitTrigger { NONE, TP, SL, LIQ } enum PositionField { NONE, TP, SL } enum PositionCloseType { NONE, TP, SL, LIQ, MARKET } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.24; import "./TradingEnumsV1.sol"; interface TradingFloorStructsV1 is TradingEnumsV1 { enum AdminNumericParam { NONE, MAX_TRADES_PER_PAIR, MAX_SL_F, MAX_SANITY_PROFIT_F } /** * @dev Memory struct for identifiers */ struct PositionRequestIdentifiers { address trader; uint16 pairId; address settlementAsset; uint32 positionIndex; } struct PositionRequestParams { bool long; uint256 collateral; // Settlement Asset Decimals uint32 leverage; uint64 minPrice; // PRICE_SCALE uint64 maxPrice; // PRICE_SCALE uint64 tp; // PRICE_SCALE uint64 sl; // PRICE_SCALE uint64 tpByFraction; // FRACTION_SCALE uint64 slByFraction; // FRACTION_SCALE } /** * @dev Storage struct for identifiers */ struct PositionIdentifiers { // Slot 0 address settlementAsset; // 20 bytes uint16 pairId; // 02 bytes uint32 index; // 04 bytes // Slot 1 address trader; // 20 bytes } struct Position { // Slot 0 uint collateral; // 32 bytes -- Settlement Asset Decimals // Slot 1 PositionPhase phase; // 01 bytes uint64 inPhaseSince; // 08 bytes uint32 leverage; // 04 bytes bool long; // 01 bytes uint64 openPrice; // 08 bytes -- PRICE_SCALE (8) uint32 spreadReductionF; // 04 bytes -- FRACTION_SCALE (5) } /** * Holds the non liquidation limits for the position */ struct PositionLimitsInfo { uint64 tpLastUpdated; // 08 bytes -- timestamp uint64 slLastUpdated; // 08 bytes -- timestamp uint64 tp; // 08 bytes -- PRICE_SCALE (8) uint64 sl; // 08 bytes -- PRICE_SCALE (8) } /** * Holds the prices for opening (and market closing) of a position */ struct PositionTriggerPrices { uint64 minPrice; // 08 bytes -- PRICE_SCALE uint64 maxPrice; // 08 bytes -- PRICE_SCALE uint64 tpByFraction; // 04 bytes -- FRACTION_SCALE uint64 slByFraction; // 04 bytes -- FRACTION_SCALE } /** * @dev administration struct, used to keep tracks on the 'PairTraders' list and * to limit the amount of positions a trader can have */ struct PairTraderInfo { uint32 positionsCounter; // 04 bytes uint32 positionInArray; // 04 bytes (the index + 1) // Note : Can add more fields here } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.24; import "../../AdministrationContracts/AcceptableImplementationClaimableAdminStorage.sol"; import "../interfaces/ITradingFloorV1.sol"; import "../Common/CommonScales.sol"; /** * @title LexCommon * @dev For Lex contracts to inherit from, holding common variables and modifiers */ contract LexCommon is CommonScales, AcceptableRegistryImplementationClaimableAdminStorage { IERC20 public underlying; ITradingFloorV1 public tradingFloor; function initializeLexCommon( ITradingFloorV1 _tradingFloor, IERC20 _underlying ) public { require( address(tradingFloor) == address(0) && address(underlying) == address(0), "Initialized" ); tradingFloor = _tradingFloor; underlying = _underlying; } modifier onlyTradingFloor() { require(msg.sender == address(tradingFloor), "TRADING_FLOOR_ONLY"); _; } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.24; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title LexERC20 * @dev simple erc20 contract. * @notice This is the token that is issued against the deposited funds. * The value of the token is represented by the exchange rate of the pool. */ contract LexERC20 is IERC20 { mapping(address => uint256) internal _balances; mapping(address => mapping(address => uint256)) internal _allowances; uint256 public totalSupply; string public name; string public symbol; function initializeLexERC20( string memory _name, string memory _symbol ) public { require( bytes(name).length == 0 && bytes(symbol).length == 0, "Initialized" ); name = _name; symbol = _symbol; } function decimals() public pure returns (uint8) { return 18; } function balanceOf(address account) public view returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance( address owner, address spender ) public view returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public returns (bool) { _approve(msg.sender, spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][msg.sender]; require( currentAllowance >= amount, "ERC20: transfer amount exceeds allowance" ); unchecked { _approve(sender, msg.sender, currentAllowance - amount); } return true; } function _transfer( address sender, address recipient, uint256 amount ) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } totalSupply -= amount; emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.24; import "../../../AdministrationContracts/AcceptableRegistryImplementationClaimableAdmin.sol"; /** * @title LexPoolProxy * @dev Used as the upgradable lex pool of the Lynx platform */ contract LexPoolProxy is AcceptableRegistryImplementationClaimableAdmin { constructor( address _registry, address _initialAdmin ) AcceptableRegistryImplementationClaimableAdmin( _registry, "LexPool", _initialAdmin ) {} }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.24; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../LexCommon.sol"; import "./LexERC20.sol"; /** * @title LexPoolStorage * @dev Storage contract for LexPool */ abstract contract LexPoolStorage is LexCommon, LexERC20, LexPoolStructs { uint256 public underlyingDecimals; // ***** Roles ***** IPoolAccountantFunctionality public poolAccountant; address public pnlRole; // ***** Depositing and Withdrawing ***** // epoch => user => PendingDeposit mapping(uint256 => mapping(address => PendingDeposit)) public pendingDeposits; // epoch => user => PendingRedeem mapping(uint256 => mapping(address => PendingRedeem)) public pendingRedeems; // epoch => users who deposits on this epoch mapping(uint256 => address[]) public pendingDepositorsArr; // epoch => users who redeems on this epoch mapping(uint256 => address[]) public pendingRedeemersArr; uint256 public pendingDepositAmount; uint256 public pendingWithdrawalAmount; // Extra fraction allowed to be withdrawn when redeem processes uint256 public maxExtraWithdrawalAmountF; uint256 public minDepositAmount; // ***** Epochs ***** uint256 public currentEpoch; uint256 public nextEpochStartMin; // Minimum timestamp that calling nextEpoch will be possible uint256 public currentExchangeRate; uint256 public epochsDelayDeposit; uint256 public epochsDelayRedeem; uint256 public epochDuration; // ***** Flags ***** bool public immediateDepositAllowed; function initializeLexPoolStorage( ITradingFloorV1 _tradingFloor, ERC20 _underlying, uint _epochDuration ) internal { initializeLexERC20( string.concat("Lynx LP ", _underlying.symbol()), string.concat("lx", _underlying.symbol()) ); initializeLexCommon(_tradingFloor, IERC20(_underlying)); underlyingDecimals = _underlying.decimals(); epochDuration = _epochDuration; } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.24; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeCast.sol"; import "../../interfaces/ILexPoolV1.sol"; import "../../interfaces/IPoolAccountantV1.sol"; import "../../interfaces/IRegistryV1.sol"; import "../LexCommon.sol"; import "./LexPoolStorage.sol"; import "./LexPoolProxy.sol"; import "../../interfaces/IAffiliationV1.sol"; /** * @title LexPoolV1 * @dev The main contract for the Lex Pool, holds the liquidity and the logic for depositing and redeeming * and for the epoch system. */ contract LexPoolV1 is LexPoolStorage, ILexPoolFunctionality, IAffiliationV1 { using SafeERC20 for IERC20; using SafeCast for uint256; using SafeCast for int256; // ***** Constants ***** uint public constant SELF_UNIT_SCALE = 1e18; // ***** Modifiers ***** modifier onlyLiquidityIntentsVerifier() { require( msg.sender == IRegistryV1(registry).liquidityIntentsVerifier(), "!LiquidityIntentsVerifier" ); _; } // ***** Views ***** /** * Calculates the beginning timestamp of the next epoch by rounding down to a round "duration" unit multiplication. * @return The timestamp in which the next epoch can start (seconds) */ function calcNextEpochStartMin() public view returns (uint256) { uint256 duration = epochDuration; uint256 virtualEpochIndex = block.timestamp / duration; return (virtualEpochIndex + 1) * duration; } /** * @return The current underlying balance of this contract (underlying scale) */ function currentBalanceInternal() public view returns (uint256) { return underlying.balanceOf(address(this)); } /** * @return The current underlying balance of this contract to be used for exchange rate purposes (underlying scale) */ function underlyingBalanceForExchangeRate() public view returns (uint256) { uint256 balance = currentBalanceInternal(); uint256 pendingAmount = pendingDepositAmount; require(balance > pendingAmount, "Fatal error"); return balance - pendingAmount; } /** * Calculates the amount that is available to be borrowed by reducing the GIVEN amounts and pending * amounts from the current ERC20 balance * @return The amount of underlying (in underlying scale) that is available to be borrowed */ function virtualBalanceForUtilization( uint256 extraAmount, // sum of the amounts that are held by the contract but are not part of the available balance for utilization (such as interestShare and ) int256 unrealizedFunding ) public view returns (uint256) { uint256 balance = currentBalanceInternal(); uint subtractionFromUnrealizedFunding = unrealizedFunding < 0 ? (-unrealizedFunding).toUint256() : 0; uint256 pendingAmount = pendingDepositAmount + pendingWithdrawalAmount; if ( balance < pendingAmount + extraAmount + subtractionFromUnrealizedFunding ) return 0; return balance - pendingAmount - extraAmount - subtractionFromUnrealizedFunding; } /** * Calculates the amount that is available to be borrowed by reducing the CURRENT amounts and pending * amounts from the current ERC20 balance * @return The amount of underlying (in underlying scale) that is available to be borrowed */ function virtualBalanceForUtilization() public view returns (uint256) { return virtualBalanceForUtilization( poolAccountant.totalReservesView(), poolAccountant.unrealizedFunding() ); } /** * Calculates the utilization as a percentage of virtual borrows out the of the total available balance * by the GIVEN values. * @return The 'virtual' utilization, scaled by PRECISION */ function currentVirtualUtilization( uint256 totalBorrows, uint256 interestShare, int256 unrealizedFunding ) public view returns (uint256) { if (totalBorrows == 0) { return 0; } uint256 virtualBalance = virtualBalanceForUtilization( interestShare, unrealizedFunding ); if (virtualBalance == 0) return type(uint256).max; return (totalBorrows * PRECISION) / virtualBalance; } /** * Calculates the utilization as a percentage of virtual borrows out the of the total available balance * by the CURRENT values. * @return The 'virtual' utilization, scaled by PRECISION */ function currentVirtualUtilization() public view returns (uint256) { (uint256 borrows, uint256 interestShare) = poolAccountant .borrowsAndInterestShare(); int256 unrealizedFunding = poolAccountant.unrealizedFunding(); return currentVirtualUtilization(borrows, interestShare, unrealizedFunding); } /** * @return true if the current utilization is less than a hundred */ function isUtilizationForLPsValid() public view returns (bool) { uint256 utilization = currentVirtualUtilization(); uint256 hundredPercent = 1 * PRECISION; return utilization <= hundredPercent; } /** * Utility function to underlying amount to its matching amount in Lex tokens by the current exchange rate */ function underlyingAmountToOwnAmount( uint256 underlyingAmount ) public view returns (uint256 ownAmount) { ownAmount = underlyingAmountToOwnAmountInternal( currentExchangeRate, underlyingAmount ); } /** * Utility function to retrieve the amount of depositors of a given epoch or a subsection of */ function getDepositorsCount(uint256 epoch) external view returns (uint256) { return pendingDepositorsArr[epoch].length; } /** * Utility function to retrieve the amount of redeemers of a given epoch or a subsection of */ function getRedeemersCount(uint256 epoch) external view returns (uint256) { return pendingRedeemersArr[epoch].length; } /** * Utility function to retrieve the array of depositors of a given epoch or a subsection of */ function getDepositors( uint256 epoch, uint256 indexFrom, uint256 count ) external view returns (address[] memory depositors) { return getArrItems(pendingDepositorsArr[epoch], indexFrom, count); } /** * Utility function to retrieve the array of redeemers of a given epoch or a subsection of */ function getRedeemers( uint256 epoch, uint256 indexFrom, uint256 count ) external view returns (address[] memory redeemers) { return getArrItems(pendingRedeemersArr[epoch], indexFrom, count); } // ***** Initialization functions ***** /** * @notice Part of the Proxy mechanism */ function _become(LexPoolProxy proxy) public { require(msg.sender == proxy.admin(), "!proxy.admin"); require(proxy._acceptImplementation() == 0, "fail"); } /** * @notice Used to initialize this contract, can only be called once * @dev This is needed because of the Proxy-Upgrade paradigm. */ function initialize( ERC20 _underlying, ITradingFloorV1 _tradingFloor, uint _epochDuration ) external { initializeLexPoolStorage(_tradingFloor, _underlying, _epochDuration); currentExchangeRate = 10 ** underlyingDecimals; epochsDelayDeposit = 2; epochsDelayRedeem = 2; nextEpochStartMin = calcNextEpochStartMin(); } // ***** Admin functions ***** function setPoolAccountant( IPoolAccountantFunctionality _poolAccountant ) external onlyAdmin { require(address(_poolAccountant) != address(0), "InvalidAddress"); poolAccountant = _poolAccountant; emit AddressUpdated( LexPoolAddressesEnum.poolAccountant, address(_poolAccountant) ); } function setPnlRole(address pnl) external onlyAdmin { require(address(pnl) != address(0), "InvalidAddress"); pnlRole = pnl; emit AddressUpdated(LexPoolAddressesEnum.pnlRole, address(pnl)); } function setMaxExtraWithdrawalAmountF(uint256 maxExtra) external onlyAdmin { maxExtraWithdrawalAmountF = maxExtra; emit NumberUpdated(LexPoolNumbersEnum.maxExtraWithdrawalAmountF, maxExtra); } function setEpochsDelayDeposit(uint256 delay) external onlyAdmin { epochsDelayDeposit = delay; emit NumberUpdated(LexPoolNumbersEnum.epochsDelayDeposit, delay); } function setEpochsDelayRedeem(uint256 delay) external onlyAdmin { epochsDelayRedeem = delay; emit NumberUpdated(LexPoolNumbersEnum.epochsDelayRedeem, delay); } function setEpochDuration(uint256 duration) external onlyAdmin { epochDuration = duration; emit NumberUpdated(LexPoolNumbersEnum.epochDuration, duration); } function setMinDepositAmount(uint256 amount) external onlyAdmin { minDepositAmount = amount; emit NumberUpdated(LexPoolNumbersEnum.minDepositAmount, amount); } /** * Toggle the immediate deposit functionality - this way, no trigger is needed after requesting deposit */ function toggleImmediateDepositAllowed() external onlyAdmin { immediateDepositAllowed = !immediateDepositAllowed; emit ImmediateDepositAllowedToggled(immediateDepositAllowed); } /** * Withdraw the reserves from the system * We accrue interest to maximize the amount of reserves that can be withdrawn */ function reduceReserves( address _to ) external returns (uint256 interestShare, uint256 totalFundingShare) { require( msg.sender == IRegistryV1(registry).feesManagers(address(underlying)), "!feesManager" ); poolAccountant.accrueInterest(virtualBalanceForUtilization()); // Read interest and funding reserves and send them. (interestShare, totalFundingShare) = poolAccountant.readAndZeroReserves(); uint reservesToSend = interestShare + totalFundingShare; if (reservesToSend > 0) { underlying.safeTransfer(_to, reservesToSend); } // Emit event to notify how much was withdrawn // from accumulated interest and funding reserves. emit ReservesWithdrawn(_to, interestShare, totalFundingShare); } // ***** User interaction functions ***** /** * User interaction to deposit to the pool in a single tx using the current exchange rate. * The 'immediateDepositAllowed' must be 'true' to allow this function to pass * We accrue interest before the deposit because the virtualBalanceForUtilization changes (the underlying balance changes) */ function immediateDeposit( uint256 depositAmount, bytes32 domain, bytes32 referralCode ) external nonReentrant { require(immediateDepositAllowed, "!Allowed"); if (depositAmount < minDepositAmount) revert CapError(CapType.MIN_DEPOSIT_AMOUNT, depositAmount); poolAccountant.accrueInterest(virtualBalanceForUtilization()); address user = msg.sender; takeUnderlying(user, depositAmount); uint256 amountToMint = underlyingAmountToOwnAmount(depositAmount); _mint(user, amountToMint); emit ImmediateDeposit(user, depositAmount, amountToMint); emit LiquidityProvided( domain, referralCode, user, depositAmount, currentEpoch ); } /** * Direct EOA interaction for requesting deposit */ function requestDeposit( uint256 amount, uint256 minAmountOut, bytes32 domain, bytes32 referralCode ) external nonReentrant { require(!immediateDepositAllowed, "!Allowed"); address user = msg.sender; requestDepositInternal(user, amount, minAmountOut, domain, referralCode); } /** * Intent based interaction for requesting deposit */ function requestDepositViaIntent( address user, uint256 amount, uint256 minAmountOut, bytes32 domain, bytes32 referralCode ) external nonReentrant onlyLiquidityIntentsVerifier { require(!immediateDepositAllowed, "!Allowed"); requestDepositInternal(user, amount, minAmountOut, domain, referralCode); } /** * User interaction to request to deposit to the pool in a two phases. * The request can be triggered after 'epochsDelayDeposit' epochs have passed * We don't accrue interest here becuase the virtualBalanceForUtilization doesn't change * as the underlying balance and the pendingDepositAmount changes cancel each other out. */ function requestDepositInternal( address user, uint256 amount, uint256 minAmountOut, bytes32 domain, bytes32 referralCode ) internal { if (amount < minDepositAmount) revert CapError(CapType.MIN_DEPOSIT_AMOUNT, amount); uint256 epoch = currentEpoch + epochsDelayDeposit; require(pendingRedeems[epoch][user].amount == 0, "Redeem exists"); takeUnderlying(user, amount); pendingDepositAmount += amount; PendingDeposit storage pendingDeposit = pendingDeposits[epoch][user]; if (pendingDeposit.amount == 0) { // The first time for this user on this epoch // So this user is not yet in the array pendingDepositorsArr[epoch].push(user); } pendingDeposit.amount = pendingDeposit.amount + amount; pendingDeposit.minAmountOut = pendingDeposit.minAmountOut + minAmountOut; emit DepositRequest(user, amount, minAmountOut, epoch); emit LiquidityProvided(domain, referralCode, user, amount, epoch); } /** * Direct EOA interaction for requesting redeeming */ function requestRedeem( uint256 amount, uint256 minAmountOut ) external nonReentrant { address user = msg.sender; requestRedeemInternal(user, amount, minAmountOut); } /** * Intent based interaction for requesting redeeming */ function requestRedeemViaIntent( address user, uint256 amount, uint256 minAmountOut ) external nonReentrant onlyLiquidityIntentsVerifier { requestRedeemInternal(user, amount, minAmountOut); } /** * User interaction to request to redeem from the pool in a two phases. * The request can be triggered after 'epochsDelayRedeem' epochs have passed * Not like requestDeposit, here we have to accrue interest before the request because we do change the state: * the pendingWithdrawalAmount increases by the max amount that can be withdrawn (even though most of the time * the actual withdrawal will be less than the max amount that can be withdrawn). */ function requestRedeemInternal( address user, uint256 amount, uint256 minAmountOut ) internal { uint256 epoch = currentEpoch + epochsDelayRedeem; require(pendingDeposits[epoch][user].amount == 0, "Exists deposit"); poolAccountant.accrueInterest(virtualBalanceForUtilization()); _transfer(user, address(this), amount); uint256 rate = currentExchangeRate; uint256 currentUnderlyingAmountOut = ownAmountToUnderlyingAmountInternal( rate, amount ); require( minAmountOut <= currentUnderlyingAmountOut, "MinAmountOut too high" ); uint256 maxUnderlyingAmountOut = (currentUnderlyingAmountOut * (FRACTION_SCALE + maxExtraWithdrawalAmountF)) / FRACTION_SCALE; pendingWithdrawalAmount += maxUnderlyingAmountOut; verifyUtilizationForLPs(); PendingRedeem storage pendingRedeem = pendingRedeems[epoch][user]; if (pendingRedeem.amount == 0) { // The first time for this user on this epoch // So this user is not yet in the array pendingRedeemersArr[epoch].push(user); } pendingRedeem.amount = pendingRedeem.amount + amount; pendingRedeem.minAmountOut = pendingRedeem.minAmountOut + minAmountOut; pendingRedeem.maxAmountOut = pendingRedeem.maxAmountOut + maxUnderlyingAmountOut; emit RedeemRequest(user, amount, minAmountOut, epoch); } /** * Allows "processing" of pending deposit requests that are due for the current epoch. * Each user's request can be accepted, in which case the user receives the proper amount of Lex tokens, * or cancelled, in which case the user gets their underlying back. * @dev This function is opened to be called by any EOA or contract. * We accrue interest before processing as the pendingDepositAmount changes (causes the virtualBalanceForUtilization to change) */ function processDeposit( address[] calldata users ) external nonReentrant returns ( uint256 amountDeposited, uint256 amountCanceled, uint256 counterDeposited, uint256 counterCanceled ) { poolAccountant.accrueInterest(virtualBalanceForUtilization()); uint256 epochToProcess = currentEpoch; uint256 rate = currentExchangeRate; for (uint8 index = 0; index < users.length; index++) { (bool existed, bool deposited, uint256 amount) = processDepositSingle( epochToProcess, users[index], rate ); if (!existed) { continue; } if (deposited) { amountDeposited += amount; counterDeposited += 1; } else { amountCanceled += amount; counterCanceled += 1; } } pendingDepositAmount -= amountDeposited + amountCanceled; } /** * Handles the logic for a single deposit request */ function processDepositSingle( uint256 epoch, address user, uint256 exchangeRate ) internal returns (bool existed, bool deposited, uint256 amount) { PendingDeposit memory pendingDeposit = pendingDeposits[epoch][user]; if (0 == pendingDeposit.amount) { return (false, false, 0); } existed = true; delete pendingDeposits[epoch][user]; uint256 actualAmountOut = underlyingAmountToOwnAmountInternal( exchangeRate, pendingDeposit.amount ); if (actualAmountOut >= pendingDeposit.minAmountOut) { _mint(user, actualAmountOut); deposited = true; } else { // Cancelling underlying.safeTransfer(user, pendingDeposit.amount); deposited = false; } amount = pendingDeposit.amount; emit ProcessedDeposit(user, deposited, amount); } /** * Allows the cancellation of deposit requests whose matching epoch has passed. * @dev This function is opened to be called by any EOA or contract. * We don't accrue interest here becuase the virtualBalanceForUtilization doesn't change * as the underlying balance and the pendingDepositAmount changes cancel each other out. */ function cancelDeposits( address[] calldata users, uint256[] calldata epochs ) external nonReentrant { require(users.length == epochs.length, "!ArrayLengths"); uint256 maxEpochToCancel = currentEpoch - 1; for (uint8 index = 0; index < users.length; index++) { address user = users[index]; uint256 epoch = epochs[index]; require(epoch <= maxEpochToCancel, "Epoch too soon"); PendingDeposit memory pendingDeposit = pendingDeposits[epoch][user]; delete pendingDeposits[epoch][user]; pendingDepositAmount -= pendingDeposit.amount; underlying.safeTransfer(user, pendingDeposit.amount); emit CanceledDeposit(user, epoch, pendingDeposit.amount); } } /** * Allows "processing" of pending redeem requests that are due for the current epoch. * @dev This function is opened to be called by any EOA or contract. * Accrues interest before processing is required because: * 1. We might have cancelled redeems which changes the pendingWithdrawalAmount but not the underlying balance * 2. The amountRedeemed and the underlyingAllocated for a specific redeem request might not be the same. Which means * that we change the underlying balance and the pendigWithdrawalAmount by different amounts - they don't cancel each other. */ function processRedeems( address[] calldata users ) external nonReentrant returns ( uint256 amountRedeemed, uint256 amountCanceled, uint256 counterRedeemed, uint256 counterCanceled ) { poolAccountant.accrueInterest(virtualBalanceForUtilization()); uint256 epochToProcess = currentEpoch; uint256 rate = currentExchangeRate; uint256 underlyingFreeAllocatedAmount = 0; for (uint8 index = 0; index < users.length; index++) { ( bool existed, bool redeemed, uint256 amount, uint256 underlyingAllocated ) = processRedeemSingle(epochToProcess, users[index], rate); if (!existed) { continue; } if (redeemed) { amountRedeemed += amount; counterRedeemed += 1; } else { amountCanceled += amount; counterCanceled += 1; } underlyingFreeAllocatedAmount += underlyingAllocated; } pendingWithdrawalAmount -= underlyingFreeAllocatedAmount; } /** * Handles the logic for a single redeem request */ function processRedeemSingle( uint256 epoch, address user, uint256 exchangeRate ) internal returns ( bool existed, bool redeemed, uint256 amount, uint256 underlyingAllocated ) { PendingRedeem memory pendingRedeem = pendingRedeems[epoch][user]; if (0 == pendingRedeem.amount) { return (false, false, 0, 0); } existed = true; delete pendingRedeems[epoch][user]; uint256 currentUnderlyingAmountOut = ownAmountToUnderlyingAmountInternal( exchangeRate, pendingRedeem.amount ); uint256 finalUnderlyingAmountOut = (pendingRedeem.maxAmountOut < currentUnderlyingAmountOut) ? pendingRedeem.maxAmountOut : currentUnderlyingAmountOut; if (finalUnderlyingAmountOut >= pendingRedeem.minAmountOut) { _burn(address(this), pendingRedeem.amount); underlying.safeTransfer(user, finalUnderlyingAmountOut); redeemed = true; } else { _transfer(address(this), user, pendingRedeem.amount); redeemed = false; } amount = pendingRedeem.amount; underlyingAllocated = pendingRedeem.maxAmountOut; emit ProcessedRedeem(user, redeemed, amount); } /** * Allows the cancellation of redeem requests whose matching epoch has passed. * @dev This function is opened to be called by any EOA or contract. * We need to accure interest as we change the pendingWithdrawalAmount. */ function cancelRedeems( address[] calldata users, uint256[] calldata epochs ) external nonReentrant { require(users.length == epochs.length, "!ArrayLengths"); poolAccountant.accrueInterest(virtualBalanceForUtilization()); uint256 maxEpochToCancel = currentEpoch - 1; for (uint8 index = 0; index < users.length; index++) { address user = users[index]; uint256 epoch = epochs[index]; require(epoch <= maxEpochToCancel, "Epoch too soon"); PendingRedeem memory pendingRedeem = pendingRedeems[epoch][user]; delete pendingRedeems[epoch][user]; pendingWithdrawalAmount -= pendingRedeem.maxAmountOut; _transfer(address(this), user, pendingRedeem.amount); emit CanceledRedeem(user, epoch, pendingRedeem.amount); } } // ***** PnL Role interaction functions ***** /** * Advances the Pool's epoch while taking into account the unrealized PnL of the opened positions * @dev Can be called only by the "PnlRole" */ function nextEpoch( int256 totalUnrealizedPricePnL // Underlying scale ) external nonReentrant returns (uint256 newExchangeRate) { require(msg.sender == pnlRole, "!Auth"); require(block.timestamp >= nextEpochStartMin, "!Time pass new epoch"); (uint256 totalInterest, uint256 interestShare, ) = poolAccountant .accrueInterest(virtualBalanceForUtilization()); int256 unrealizedFunding = poolAccountant.unrealizedFunding(); uint256 newEpochId = currentEpoch + 1; uint256 supply = totalSupply; uint256 virtualUnderlyingBalance = 0; if (0 == supply) { // newExchangeRate = 1e18; newExchangeRate = (10 ** underlyingDecimals); // 1.00 } else { // Note : Subtracting all values that does not belong to the LPs // and adding values that do virtualUnderlyingBalance = (underlyingBalanceForExchangeRate() .toInt256() + unrealizedFunding + totalInterest.toInt256() - interestShare.toInt256() + totalUnrealizedPricePnL).toUint256(); newExchangeRate = (virtualUnderlyingBalance * (SELF_UNIT_SCALE)) / supply; } currentEpoch = newEpochId; currentExchangeRate = newExchangeRate; nextEpochStartMin = calcNextEpochStartMin(); emit NewEpoch( newEpochId, totalUnrealizedPricePnL, newExchangeRate, virtualUnderlyingBalance, supply ); } // ***** TradingFloor interaction functions ***** /** * Sends assets to a winning trader. */ function sendAssetToTrader( address to, uint256 amount ) external onlyTradingFloor { underlying.safeTransfer(to, amount); } // ***** Internal Views ***** /** * Sanity function to ensure that the utilization is valid */ function verifyUtilizationForLPs() internal view { require(isUtilizationForLPsValid(), "LP utilization"); } /** * Utility function to get a sub array from a given array */ function getArrItems( address[] storage arr, uint256 indexFrom, uint256 count ) internal view returns (address[] memory subArr) { uint256 itemsLeft = arr.length - indexFrom; count = count < itemsLeft ? count : itemsLeft; subArr = new address[](count); for (uint256 index = 0; index < count; index++) { subArr[index] = arr[indexFrom + index]; } } /** * Converts the underlying amount to the amount of self tokens by the current exchange rate */ function underlyingAmountToOwnAmountInternal( uint256 exchangeRate, uint256 underlyingAmount ) internal pure returns (uint256 ownAmount) { ownAmount = (underlyingAmount * SELF_UNIT_SCALE) / exchangeRate; } /** * Converts the (self) LP amount to the equal underlying amount by the current exchange rate */ function ownAmountToUnderlyingAmountInternal( uint256 exchangeRate, uint256 ownAmount ) internal pure returns (uint256 underlyingAmount) { underlyingAmount = (ownAmount * exchangeRate) / SELF_UNIT_SCALE; } // ***** Underlying utils ***** /** * Utility function to safely take underlying tokens (ERC20) from a pre-approved account * @dev Will revert if the contract will not get the exact 'amount' value */ function takeUnderlying(address from, uint amount) internal { uint balanceBefore = underlying.balanceOf(address(this)); underlying.safeTransferFrom(from, address(this), amount); uint balanceAfter = underlying.balanceOf(address(this)); require(balanceAfter - balanceBefore == amount, "DID_NOT_RECEIVE_EXACT"); } // ***** Reentrancy Guard ***** /** * @dev Prevents a contract from calling itself, directly or indirectly. */ modifier nonReentrant() { _beforeNonReentrant(); _; _afterNonReentrant(); } /** * @dev Tries to get the system lock */ function _beforeNonReentrant() private { IRegistryV1(registry).lock(); } /** * @dev Releases the system lock */ function _afterNonReentrant() private { IRegistryV1(registry).freeLock(); } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.24; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; /** * @title TokenHandlingContractUtils * @notice Used to handle token related operations. * @dev DO NOT ADD STORAGE TO THIS CONTRACT */ contract TokenHandlingContractUtils { using SafeERC20 for IERC20; // ***** Events ***** event TokensSwept( address indexed token, address indexed receiver, uint256 amount ); // ***** Internal Util Functions ***** /** * @notice Sweep any tokens from the contract * @param _token The token to sweep * @param _amount The amount to sweep */ function sweepTokensInternal( address _token, address _receiver, uint256 _amount ) internal { uint256 amount = _amount > 0 ? _amount : getSelfBalanceInTokenInternal(_token); sendTokens(_token, _receiver, amount); emit TokensSwept(address(_token), _receiver, amount); } /** * Utility function to safely take tokens (ERC20) from a pre-approved account * @dev Will revert if the contract will not get the exact 'amount' value */ function takeTokens(address _token, address _from, uint256 _amount) internal { uint256 balanceBefore = getSelfBalanceInTokenInternal(_token); IERC20(_token).safeTransferFrom(_from, address(this), _amount); uint256 balanceAfter = getSelfBalanceInTokenInternal(_token); require(balanceAfter - balanceBefore == _amount, "DID_NOT_RECEIVE_EXACT"); } /** * Utility function to safely send tokens (ERC20) */ function sendTokens(address _token, address _to, uint256 _amount) internal { IERC20(_token).safeTransfer(_to, _amount); } function getSelfBalanceInTokenInternal( address _token ) internal view returns (uint256) { return IERC20(_token).balanceOf(address(this)); } }
{ "optimizer": { "enabled": true, "runs": 200 }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "evmVersion": "paris", "metadata": { "useLiteralContent": true }, "libraries": {} }
Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
Contract ABI
API[{"inputs":[{"internalType":"address","name":"_tradingFloor","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"AddressEmptyCode","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"AddressInsufficientBalance","type":"error"},{"inputs":[],"name":"FailedInnerCall","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":true,"internalType":"enum TradingEnumsV1.FeeType","name":"feeType","type":"uint8"},{"indexed":true,"internalType":"address","name":"collector","type":"address"}],"name":"CollectorUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":true,"internalType":"enum TradingEnumsV1.FeeType","name":"feeType","type":"uint8"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"FeeCollected","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"oldAdmin","type":"address"},{"indexed":false,"internalType":"address","name":"newAdmin","type":"address"}],"name":"NewAdmin","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"oldPendingAdmin","type":"address"},{"indexed":false,"internalType":"address","name":"newPendingAdmin","type":"address"}],"name":"NewPendingAdmin","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"pool","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"interestShareReduced","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"fundingShareReduced","type":"uint256"}],"name":"ReservesReduced","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"pool","type":"address"},{"indexed":true,"internalType":"address","name":"reducer","type":"address"}],"name":"ReservesReducerUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":true,"internalType":"address","name":"receiver","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"TokensSwept","type":"event"},{"inputs":[],"name":"CONTRACT_NAME","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"CONTRACT_VERSION","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"_acceptAdmin","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newPendingAdmin","type":"address"}],"name":"_setPendingAdmin","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"admin","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_asset","type":"address"},{"internalType":"bool","name":"includeTriggerFees","type":"bool"}],"name":"collectFeesForAsset","outputs":[{"internalType":"uint256","name":"collectedAmount","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_asset","type":"address"},{"internalType":"enum TradingEnumsV1.FeeType","name":"_feeType","type":"uint8"}],"name":"collectFeesForAssetByType","outputs":[{"internalType":"uint256","name":"collectedAmount","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"enum TradingEnumsV1.FeeType","name":"","type":"uint8"}],"name":"feesCollectorByType","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"}],"name":"getAllPendingFees","outputs":[{"internalType":"uint256","name":"openFees","type":"uint256"},{"internalType":"uint256","name":"closeFees","type":"uint256"},{"internalType":"uint256","name":"triggerFees","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"}],"name":"getCollectorForAllTypesIfExists","outputs":[{"internalType":"address","name":"soleCollector","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getContractName","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"getContractVersion","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"},{"internalType":"enum TradingEnumsV1.FeeType","name":"_feeType","type":"uint8"}],"name":"getPendingFeesByType","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"}],"name":"getSumOfAllPendingFees","outputs":[{"internalType":"uint256","name":"totalFees","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"},{"internalType":"address","name":"_collector","type":"address"}],"name":"isFeeCollectorForAllTypes","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pendingAdmin","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_pool","type":"address"}],"name":"reduceReservesForLex","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address[]","name":"_pools","type":"address[]"}],"name":"reduceReservesForLexes","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"reservesReducerByPool","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"},{"internalType":"address","name":"_collector","type":"address"}],"name":"setFeeCollector","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"},{"internalType":"address","name":"_collector","type":"address"},{"internalType":"enum TradingEnumsV1.FeeType","name":"_feeType","type":"uint8"}],"name":"setFeeCollectorByType","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_pool","type":"address"},{"internalType":"address","name":"_reducer","type":"address"}],"name":"setReservesReducer","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"sweepTokens","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"tradingFloor","outputs":[{"internalType":"contract ITradingFloorV1","name":"","type":"address"}],"stateMutability":"view","type":"function"}]
Contract Creation Code
60a060405234801561001057600080fd5b5060405161170a38038061170a83398101604081905261002f91610052565b600080546001600160a01b031916331790556001600160a01b0316608052610082565b60006020828403121561006457600080fd5b81516001600160a01b038116811461007b57600080fd5b9392505050565b60805161164a6100c0600039600081816101620152818161056c015281816107770152818161081f015281816108b20152610ec0015261164a6000f3fe608060405234801561001057600080fd5b50600436106101585760003560e01c80638aa10435116100c3578063dc42a8d01161007c578063dc42a8d014610395578063dec66036146103a8578063df1e740c146103bb578063e9c714f2146103ce578063f5f5ba72146103d6578063f851a440146103fd57600080fd5b80638aa10435146102fc5780638eefae931461031b578063ae081dd81461032e578063b023d2a214610341578063b71d1a0c14610354578063cf8f5d9b1461036757600080fd5b80635fc032ce116101155780635fc032ce1461023c578063614d08f814610270578063624cc8491461029a57806367d961ab146102ad578063684c306f146102c05780638a20121b146102e957600080fd5b80630d3b0b761461015d578063161c213c146101a157806326782247146101c257806329149799146101d557806338b90333146101ea5780635693f7c314610219575b600080fd5b6101847f000000000000000000000000000000000000000000000000000000000000000081565b6040516001600160a01b0390911681526020015b60405180910390f35b6101b46101af36600461126c565b610410565b604051908152602001610198565b600154610184906001600160a01b031681565b6101e86101e3366004611289565b610444565b005b61020c6040518060400160405280600381526020016203130360ec1b81525081565b60405161019891906112e6565b61022c610227366004611289565b61049f565b6040519015158152602001610198565b61018461024a36600461132d565b60026020908152600092835260408084209091529082529020546001600160a01b031681565b61020c6040518060400160405280600b81526020016a2332b2b9a6b0b730b3b2b960a91b81525081565b6101e86102a836600461126c565b6104c7565b6101846102bb36600461126c565b6104d8565b6101846102ce36600461126c565b6003602052600090815260409020546001600160a01b031681565b6101b46102f736600461132d565b610552565b60408051808201909152600381526203130360ec1b602082015261020c565b6101e8610329366004611362565b6105eb565b6101e861033c3660046113a9565b610620565b6101b461034f36600461142c565b61066c565b6101e861036236600461126c565b6106c8565b61037a61037536600461126c565b610770565b60408051938452602084019290925290820152606001610198565b6101e86103a3366004611289565b610933565b6101e86103b636600461145a565b6109b4565b6101b46103c936600461132d565b6109f6565b6101e8610a05565b60408051808201909152600b81526a2332b2b9a6b0b730b3b2b960a91b602082015261020c565b600054610184906001600160a01b031681565b60008060008061041f85610770565b9194509250905080610431838561149c565b61043b919061149c565b95945050505050565b6000546001600160a01b031633146104775760405162461bcd60e51b815260040161046e906114af565b60405180910390fd5b61048382600183610b23565b61048f82600283610b23565b61049b82600383610b23565b5050565b6000816001600160a01b03166104b4846104d8565b6001600160a01b03161490505b92915050565b336104d3828280610bd7565b505050565b6001600160a01b0381811660009081526002602081815260408084206001855290915280832054918352808320546003845290832054929391821692908216911681831480156105395750806001600160a01b0316826001600160a01b0316145b156105475750909392505050565b506000949350505050565b60405163030d073d60e41b81526000906001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906330d073d0906105a3908690869060040161150b565b602060405180830381865afa1580156105c0573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906105e49190611528565b9392505050565b6000546001600160a01b031633146106155760405162461bcd60e51b815260040161046e906114af565b6104d3838284610b23565b3360005b828110156106665761065d84848381811061064157610641611541565b9050602002016020810190610656919061126c565b8384610bd7565b50600101610624565b50505050565b60003361067c8460018380610e00565b610686908361149c565b91506106958460028384610e00565b61069f908361149c565b915082156106c1576106b48460038384610e00565b6106be908361149c565b91505b5092915050565b6000546001600160a01b0316331461070e5760405162461bcd60e51b81526020600482015260096024820152682737ba1020b236b4b760b91b604482015260640161046e565b600180546001600160a01b038381166001600160a01b031983168117909355604080519190921680825260208201939093527fca4f2f25d0898edd99413412fb94012f9e54ec8142f9b093e7720646a95b16a991015b60405180910390a15050565b60008060007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166330d073d08560016040518363ffffffff1660e01b81526004016107c492919061150b565b602060405180830381865afa1580156107e1573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108059190611528565b60405163030d073d60e41b81529093506001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906330d073d09061085790879060029060040161150b565b602060405180830381865afa158015610874573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108989190611528565b60405163030d073d60e41b81529092506001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906330d073d0906108ea90879060039060040161150b565b602060405180830381865afa158015610907573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061092b9190611528565b929491935050565b6000546001600160a01b0316331461095d5760405162461bcd60e51b815260040161046e906114af565b6001600160a01b0382811660008181526003602052604080822080546001600160a01b0319169486169485179055517f4a9b5fddf7f97b7462cd5ba2f03beeffadce2a3639eab05c74273b01057144d09190a35050565b6000546001600160a01b031633146109de5760405162461bcd60e51b815260040161046e906114af565b60005461049b9083906001600160a01b031683610fb8565b6000336106be84848380610e00565b6001546001600160a01b031633148015610a2957506001546001600160a01b031615155b610a755760405162461bcd60e51b815260206004820152601e60248201527f4e6f7420746865204558495354494e472070656e64696e672061646d696e0000604482015260640161046e565b60008054600180546001600160a01b038082166001600160a01b031980861682179096559490911690915560408051919092168082526020820184905292917ff9ffabca9c8276e99321725bcb43fb076a6c66a54b7f21c4e8146d8519b417dc910160405180910390a1600154604080516001600160a01b03808516825290921660208301527fca4f2f25d0898edd99413412fb94012f9e54ec8142f9b093e7720646a95b16a99101610764565b6001600160a01b03831660009081526002602052604081208291846003811115610b4f57610b4f6114d3565b6003811115610b6057610b606114d3565b8152602081019190915260400160002080546001600160a01b0319166001600160a01b039283161790558116826003811115610b9e57610b9e6114d3565b6040516001600160a01b038616907fc61bbd07293f7265c9f98ba23692a98744e87dce9b9b5a2c126ceff7a14a141390600090a4505050565b6001600160a01b038084166000908152600360205260408120549091848116911614610c3c5760405162461bcd60e51b81526020600482015260146024820152732727aa2fa922a9a2a92b22a9afa922a22aa1a2a960611b604482015260640161046e565b6000846001600160a01b0316636f307dc36040518163ffffffff1660e01b8152600401602060405180830381865afa158015610c7c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ca09190611557565b90506000610cad82611031565b60405163eb449c2f60e01b815230600482015290915060009081906001600160a01b0389169063eb449c2f9060240160408051808303816000875af1158015610cfa573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d1e9190611574565b915091506000610d2d85611031565b9050610d398482611598565b9550610d45828461149c565b8614610d935760405162461bcd60e51b815260206004820152601a60248201527f494e56414c49445f52455345525645535f524544554354494f4e000000000000604482015260640161046e565b610d9e85888861109c565b866001600160a01b0316896001600160a01b03167f98ed365174abfd626e125788d276a0cc7876f564724e52755d04afc16c5141ac8585604051610dec929190918252602082015260400190565b60405180910390a350505050509392505050565b6001600160a01b038416600090815260026020526040812081856003811115610e2b57610e2b6114d3565b6003811115610e3c57610e3c6114d3565b81526020810191909152604001600020546001600160a01b03848116911614610e9b5760405162461bcd60e51b81526020600482015260116024820152702727aa2fa322a2afa1a7a62622a1aa27a960791b604482015260640161046e565b6000610ea686611031565b60405163063e91c560e21b81529091506001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906318fa471490610ef9908990899030906004016115ab565b600060405180830381600087803b158015610f1357600080fd5b505af1158015610f27573d6000803e3d6000fd5b505050506000610f3687611031565b9050610f428282611598565b9250610f4f87858561109c565b836001600160a01b0316866003811115610f6b57610f6b6114d3565b886001600160a01b03167f0e80b333c403be7cb491b3ba7f29fe30014c594adbcbec04272291b2f72f6e6a86604051610fa691815260200190565b60405180910390a45050949350505050565b6000808211610fcf57610fca84611031565b610fd1565b815b9050610fde84848361109c565b826001600160a01b0316846001600160a01b03167fd092d7fceb5ea5a962639fcc27a7bb315e7637e699e3b108cd570c38c75843008360405161102391815260200190565b60405180910390a350505050565b6040516370a0823160e01b81523060048201526000906001600160a01b038316906370a0823190602401602060405180830381865afa158015611078573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906104c19190611528565b604080516001600160a01b03848116602483015260448083018590528351808403909101815260649092019092526020810180516001600160e01b031663a9059cbb60e01b1790526104d391851690849084908490849060006110ff838361114d565b9050805160001415801561112457508080602001905181019061112291906115db565b155b156104d357604051635274afe760e01b81526001600160a01b038416600482015260240161046e565b60606105e48383600084600080856001600160a01b0316848660405161117391906115f8565b60006040518083038185875af1925050503d80600081146111b0576040519150601f19603f3d011682016040523d82523d6000602084013e6111b5565b606091505b50915091506111c58683836111cf565b9695505050505050565b6060826111e4576111df8261122b565b6105e4565b81511580156111fb57506001600160a01b0384163b155b1561122457604051639996b31560e01b81526001600160a01b038516600482015260240161046e565b50806105e4565b80511561123b5780518082602001fd5b604051630a12f52160e11b815260040160405180910390fd5b50565b6001600160a01b038116811461125457600080fd5b60006020828403121561127e57600080fd5b81356105e481611257565b6000806040838503121561129c57600080fd5b82356112a781611257565b915060208301356112b781611257565b809150509250929050565b60005b838110156112dd5781810151838201526020016112c5565b50506000910152565b60208152600082518060208401526113058160408501602087016112c2565b601f01601f19169190910160400192915050565b80356004811061132857600080fd5b919050565b6000806040838503121561134057600080fd5b823561134b81611257565b915061135960208401611319565b90509250929050565b60008060006060848603121561137757600080fd5b833561138281611257565b9250602084013561139281611257565b91506113a060408501611319565b90509250925092565b600080602083850312156113bc57600080fd5b823567ffffffffffffffff808211156113d457600080fd5b818501915085601f8301126113e857600080fd5b8135818111156113f757600080fd5b8660208260051b850101111561140c57600080fd5b60209290920196919550909350505050565b801515811461125457600080fd5b6000806040838503121561143f57600080fd5b823561144a81611257565b915060208301356112b78161141e565b6000806040838503121561146d57600080fd5b823561147881611257565b946020939093013593505050565b634e487b7160e01b600052601160045260246000fd5b808201808211156104c1576104c1611486565b6020808252600a908201526927a7262cafa0a226a4a760b11b604082015260600190565b634e487b7160e01b600052602160045260246000fd5b6004811061150757634e487b7160e01b600052602160045260246000fd5b9052565b6001600160a01b0383168152604081016105e460208301846114e9565b60006020828403121561153a57600080fd5b5051919050565b634e487b7160e01b600052603260045260246000fd5b60006020828403121561156957600080fd5b81516105e481611257565b6000806040838503121561158757600080fd5b505080516020909101519092909150565b818103818111156104c1576104c1611486565b6001600160a01b03848116825260608201906115ca60208401866114e9565b808416604084015250949350505050565b6000602082840312156115ed57600080fd5b81516105e48161141e565b6000825161160a8184602087016112c2565b919091019291505056fea2646970667358221220119f60706adaae6e250a646cb6a9321088acdf6198a95a90bad809afa664ae1d64736f6c6343000818003300000000000000000000000037792eecfa985d0b00a51864c970e7df406aa868
Deployed Bytecode
0x608060405234801561001057600080fd5b50600436106101585760003560e01c80638aa10435116100c3578063dc42a8d01161007c578063dc42a8d014610395578063dec66036146103a8578063df1e740c146103bb578063e9c714f2146103ce578063f5f5ba72146103d6578063f851a440146103fd57600080fd5b80638aa10435146102fc5780638eefae931461031b578063ae081dd81461032e578063b023d2a214610341578063b71d1a0c14610354578063cf8f5d9b1461036757600080fd5b80635fc032ce116101155780635fc032ce1461023c578063614d08f814610270578063624cc8491461029a57806367d961ab146102ad578063684c306f146102c05780638a20121b146102e957600080fd5b80630d3b0b761461015d578063161c213c146101a157806326782247146101c257806329149799146101d557806338b90333146101ea5780635693f7c314610219575b600080fd5b6101847f00000000000000000000000037792eecfa985d0b00a51864c970e7df406aa86881565b6040516001600160a01b0390911681526020015b60405180910390f35b6101b46101af36600461126c565b610410565b604051908152602001610198565b600154610184906001600160a01b031681565b6101e86101e3366004611289565b610444565b005b61020c6040518060400160405280600381526020016203130360ec1b81525081565b60405161019891906112e6565b61022c610227366004611289565b61049f565b6040519015158152602001610198565b61018461024a36600461132d565b60026020908152600092835260408084209091529082529020546001600160a01b031681565b61020c6040518060400160405280600b81526020016a2332b2b9a6b0b730b3b2b960a91b81525081565b6101e86102a836600461126c565b6104c7565b6101846102bb36600461126c565b6104d8565b6101846102ce36600461126c565b6003602052600090815260409020546001600160a01b031681565b6101b46102f736600461132d565b610552565b60408051808201909152600381526203130360ec1b602082015261020c565b6101e8610329366004611362565b6105eb565b6101e861033c3660046113a9565b610620565b6101b461034f36600461142c565b61066c565b6101e861036236600461126c565b6106c8565b61037a61037536600461126c565b610770565b60408051938452602084019290925290820152606001610198565b6101e86103a3366004611289565b610933565b6101e86103b636600461145a565b6109b4565b6101b46103c936600461132d565b6109f6565b6101e8610a05565b60408051808201909152600b81526a2332b2b9a6b0b730b3b2b960a91b602082015261020c565b600054610184906001600160a01b031681565b60008060008061041f85610770565b9194509250905080610431838561149c565b61043b919061149c565b95945050505050565b6000546001600160a01b031633146104775760405162461bcd60e51b815260040161046e906114af565b60405180910390fd5b61048382600183610b23565b61048f82600283610b23565b61049b82600383610b23565b5050565b6000816001600160a01b03166104b4846104d8565b6001600160a01b03161490505b92915050565b336104d3828280610bd7565b505050565b6001600160a01b0381811660009081526002602081815260408084206001855290915280832054918352808320546003845290832054929391821692908216911681831480156105395750806001600160a01b0316826001600160a01b0316145b156105475750909392505050565b506000949350505050565b60405163030d073d60e41b81526000906001600160a01b037f00000000000000000000000037792eecfa985d0b00a51864c970e7df406aa86816906330d073d0906105a3908690869060040161150b565b602060405180830381865afa1580156105c0573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906105e49190611528565b9392505050565b6000546001600160a01b031633146106155760405162461bcd60e51b815260040161046e906114af565b6104d3838284610b23565b3360005b828110156106665761065d84848381811061064157610641611541565b9050602002016020810190610656919061126c565b8384610bd7565b50600101610624565b50505050565b60003361067c8460018380610e00565b610686908361149c565b91506106958460028384610e00565b61069f908361149c565b915082156106c1576106b48460038384610e00565b6106be908361149c565b91505b5092915050565b6000546001600160a01b0316331461070e5760405162461bcd60e51b81526020600482015260096024820152682737ba1020b236b4b760b91b604482015260640161046e565b600180546001600160a01b038381166001600160a01b031983168117909355604080519190921680825260208201939093527fca4f2f25d0898edd99413412fb94012f9e54ec8142f9b093e7720646a95b16a991015b60405180910390a15050565b60008060007f00000000000000000000000037792eecfa985d0b00a51864c970e7df406aa8686001600160a01b03166330d073d08560016040518363ffffffff1660e01b81526004016107c492919061150b565b602060405180830381865afa1580156107e1573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108059190611528565b60405163030d073d60e41b81529093506001600160a01b037f00000000000000000000000037792eecfa985d0b00a51864c970e7df406aa86816906330d073d09061085790879060029060040161150b565b602060405180830381865afa158015610874573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108989190611528565b60405163030d073d60e41b81529092506001600160a01b037f00000000000000000000000037792eecfa985d0b00a51864c970e7df406aa86816906330d073d0906108ea90879060039060040161150b565b602060405180830381865afa158015610907573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061092b9190611528565b929491935050565b6000546001600160a01b0316331461095d5760405162461bcd60e51b815260040161046e906114af565b6001600160a01b0382811660008181526003602052604080822080546001600160a01b0319169486169485179055517f4a9b5fddf7f97b7462cd5ba2f03beeffadce2a3639eab05c74273b01057144d09190a35050565b6000546001600160a01b031633146109de5760405162461bcd60e51b815260040161046e906114af565b60005461049b9083906001600160a01b031683610fb8565b6000336106be84848380610e00565b6001546001600160a01b031633148015610a2957506001546001600160a01b031615155b610a755760405162461bcd60e51b815260206004820152601e60248201527f4e6f7420746865204558495354494e472070656e64696e672061646d696e0000604482015260640161046e565b60008054600180546001600160a01b038082166001600160a01b031980861682179096559490911690915560408051919092168082526020820184905292917ff9ffabca9c8276e99321725bcb43fb076a6c66a54b7f21c4e8146d8519b417dc910160405180910390a1600154604080516001600160a01b03808516825290921660208301527fca4f2f25d0898edd99413412fb94012f9e54ec8142f9b093e7720646a95b16a99101610764565b6001600160a01b03831660009081526002602052604081208291846003811115610b4f57610b4f6114d3565b6003811115610b6057610b606114d3565b8152602081019190915260400160002080546001600160a01b0319166001600160a01b039283161790558116826003811115610b9e57610b9e6114d3565b6040516001600160a01b038616907fc61bbd07293f7265c9f98ba23692a98744e87dce9b9b5a2c126ceff7a14a141390600090a4505050565b6001600160a01b038084166000908152600360205260408120549091848116911614610c3c5760405162461bcd60e51b81526020600482015260146024820152732727aa2fa922a9a2a92b22a9afa922a22aa1a2a960611b604482015260640161046e565b6000846001600160a01b0316636f307dc36040518163ffffffff1660e01b8152600401602060405180830381865afa158015610c7c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ca09190611557565b90506000610cad82611031565b60405163eb449c2f60e01b815230600482015290915060009081906001600160a01b0389169063eb449c2f9060240160408051808303816000875af1158015610cfa573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d1e9190611574565b915091506000610d2d85611031565b9050610d398482611598565b9550610d45828461149c565b8614610d935760405162461bcd60e51b815260206004820152601a60248201527f494e56414c49445f52455345525645535f524544554354494f4e000000000000604482015260640161046e565b610d9e85888861109c565b866001600160a01b0316896001600160a01b03167f98ed365174abfd626e125788d276a0cc7876f564724e52755d04afc16c5141ac8585604051610dec929190918252602082015260400190565b60405180910390a350505050509392505050565b6001600160a01b038416600090815260026020526040812081856003811115610e2b57610e2b6114d3565b6003811115610e3c57610e3c6114d3565b81526020810191909152604001600020546001600160a01b03848116911614610e9b5760405162461bcd60e51b81526020600482015260116024820152702727aa2fa322a2afa1a7a62622a1aa27a960791b604482015260640161046e565b6000610ea686611031565b60405163063e91c560e21b81529091506001600160a01b037f00000000000000000000000037792eecfa985d0b00a51864c970e7df406aa86816906318fa471490610ef9908990899030906004016115ab565b600060405180830381600087803b158015610f1357600080fd5b505af1158015610f27573d6000803e3d6000fd5b505050506000610f3687611031565b9050610f428282611598565b9250610f4f87858561109c565b836001600160a01b0316866003811115610f6b57610f6b6114d3565b886001600160a01b03167f0e80b333c403be7cb491b3ba7f29fe30014c594adbcbec04272291b2f72f6e6a86604051610fa691815260200190565b60405180910390a45050949350505050565b6000808211610fcf57610fca84611031565b610fd1565b815b9050610fde84848361109c565b826001600160a01b0316846001600160a01b03167fd092d7fceb5ea5a962639fcc27a7bb315e7637e699e3b108cd570c38c75843008360405161102391815260200190565b60405180910390a350505050565b6040516370a0823160e01b81523060048201526000906001600160a01b038316906370a0823190602401602060405180830381865afa158015611078573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906104c19190611528565b604080516001600160a01b03848116602483015260448083018590528351808403909101815260649092019092526020810180516001600160e01b031663a9059cbb60e01b1790526104d391851690849084908490849060006110ff838361114d565b9050805160001415801561112457508080602001905181019061112291906115db565b155b156104d357604051635274afe760e01b81526001600160a01b038416600482015260240161046e565b60606105e48383600084600080856001600160a01b0316848660405161117391906115f8565b60006040518083038185875af1925050503d80600081146111b0576040519150601f19603f3d011682016040523d82523d6000602084013e6111b5565b606091505b50915091506111c58683836111cf565b9695505050505050565b6060826111e4576111df8261122b565b6105e4565b81511580156111fb57506001600160a01b0384163b155b1561122457604051639996b31560e01b81526001600160a01b038516600482015260240161046e565b50806105e4565b80511561123b5780518082602001fd5b604051630a12f52160e11b815260040160405180910390fd5b50565b6001600160a01b038116811461125457600080fd5b60006020828403121561127e57600080fd5b81356105e481611257565b6000806040838503121561129c57600080fd5b82356112a781611257565b915060208301356112b781611257565b809150509250929050565b60005b838110156112dd5781810151838201526020016112c5565b50506000910152565b60208152600082518060208401526113058160408501602087016112c2565b601f01601f19169190910160400192915050565b80356004811061132857600080fd5b919050565b6000806040838503121561134057600080fd5b823561134b81611257565b915061135960208401611319565b90509250929050565b60008060006060848603121561137757600080fd5b833561138281611257565b9250602084013561139281611257565b91506113a060408501611319565b90509250925092565b600080602083850312156113bc57600080fd5b823567ffffffffffffffff808211156113d457600080fd5b818501915085601f8301126113e857600080fd5b8135818111156113f757600080fd5b8660208260051b850101111561140c57600080fd5b60209290920196919550909350505050565b801515811461125457600080fd5b6000806040838503121561143f57600080fd5b823561144a81611257565b915060208301356112b78161141e565b6000806040838503121561146d57600080fd5b823561147881611257565b946020939093013593505050565b634e487b7160e01b600052601160045260246000fd5b808201808211156104c1576104c1611486565b6020808252600a908201526927a7262cafa0a226a4a760b11b604082015260600190565b634e487b7160e01b600052602160045260246000fd5b6004811061150757634e487b7160e01b600052602160045260246000fd5b9052565b6001600160a01b0383168152604081016105e460208301846114e9565b60006020828403121561153a57600080fd5b5051919050565b634e487b7160e01b600052603260045260246000fd5b60006020828403121561156957600080fd5b81516105e481611257565b6000806040838503121561158757600080fd5b505080516020909101519092909150565b818103818111156104c1576104c1611486565b6001600160a01b03848116825260608201906115ca60208401866114e9565b808416604084015250949350505050565b6000602082840312156115ed57600080fd5b81516105e48161141e565b6000825161160a8184602087016112c2565b919091019291505056fea2646970667358221220119f60706adaae6e250a646cb6a9321088acdf6198a95a90bad809afa664ae1d64736f6c63430008180033
Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)
00000000000000000000000037792eecfa985d0b00a51864c970e7df406aa868
-----Decoded View---------------
Arg [0] : _tradingFloor (address): 0x37792EecFA985D0b00a51864c970e7df406AA868
-----Encoded View---------------
1 Constructor Arguments found :
Arg [0] : 00000000000000000000000037792eecfa985d0b00a51864c970e7df406aa868
Loading...
Loading
Loading...
Loading
Multichain Portfolio | 34 Chains
Chain | Token | Portfolio % | Price | Amount | Value |
---|
Loading...
Loading
Loading...
Loading
[ 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.