Feature Tip: Add private address tag to any address under My Name Tag !
Overview
ETH Balance
0 ETH
Eth Value
$0.00More Info
Private Name Tags
ContractCreator
Latest 25 internal transactions (View All)
Advanced mode:
Loading...
Loading
Similar Match Source Code This contract matches the deployed Bytecode of the Source Code for Contract 0x03a79E0d...b54996959 The constructor portion of the code might be different and could alter the actual behaviour of the contract
Contract Name:
PendleYieldContractFactory
Compiler Version
v0.8.24+commit.e11b9ed9
Optimization Enabled:
Yes with 1000000 runs
Other Settings:
paris EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: GPL-3.0-or-later /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity ^0.8.17; import "../../interfaces/IPYieldContractFactory.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "../libraries/ExpiryUtilsLib.sol"; import "../libraries/BaseSplitCodeFactory.sol"; import "../libraries/MiniHelpers.sol"; import "../libraries/Errors.sol"; import "../libraries/BoringOwnableUpgradeable.sol"; import "../libraries/StringLib.sol"; import "./PendlePrincipalToken.sol"; import "./PendleYieldToken.sol"; /// @dev If this contract is ever made upgradeable, please pay attention to the numContractDeployed variable contract PendleYieldContractFactory is BoringOwnableUpgradeable, IPYieldContractFactory { using ExpiryUtils for string; using StringLib for string; using StringLib for StringLib.slice; string private constant PT_PREFIX = "PT"; string private constant YT_PREFIX = "YT"; string private constant SY_SYMBOL_PREF = "SY-"; string private constant SY_NAME_PREF = "SY "; address public immutable ytCreationCodeContractA; uint256 public immutable ytCreationCodeSizeA; address public immutable ytCreationCodeContractB; uint256 public immutable ytCreationCodeSizeB; // 1 SLOT uint128 public interestFeeRate; // a fixed point number uint128 public rewardFeeRate; // a fixed point number // 1 SLOT address public treasury; uint96 public expiryDivisor; // SY => expiry => address // returns address(0) if not created mapping(address => mapping(uint256 => address)) public getPT; mapping(address => mapping(uint256 => address)) public getYT; mapping(address => bool) public isPT; mapping(address => bool) public isYT; uint256 public constant maxInterestFeeRate = 2e17; // 20% uint256 public constant maxRewardFeeRate = 2e17; // 20% constructor( address _ytCreationCodeContractA, uint256 _ytCreationCodeSizeA, address _ytCreationCodeContractB, uint256 _ytCreationCodeSizeB ) { ytCreationCodeContractA = _ytCreationCodeContractA; ytCreationCodeSizeA = _ytCreationCodeSizeA; ytCreationCodeContractB = _ytCreationCodeContractB; ytCreationCodeSizeB = _ytCreationCodeSizeB; } function initialize( uint96 _expiryDivisor, uint128 _interestFeeRate, uint128 _rewardFeeRate, address _treasury ) external initializer { __BoringOwnable_init(); setExpiryDivisor(_expiryDivisor); setInterestFeeRate(_interestFeeRate); setRewardFeeRate(_rewardFeeRate); setTreasury(_treasury); } /** * @notice Create a pair of (PT, YT) from any SY and valid expiry. Anyone can create a yield contract * @dev It's intentional to make expiry an uint32 to guard against fat fingers. uint32.max is year 2106 */ function createYieldContract( address SY, uint32 expiry, bool doCacheIndexSameBlock ) external returns (address PT, address YT) { if (MiniHelpers.isTimeInThePast(expiry) || expiry % expiryDivisor != 0) revert Errors.YCFactoryInvalidExpiry(); if (getPT[SY][expiry] != address(0)) revert Errors.YCFactoryYieldContractExisted(); IStandardizedYield _SY = IStandardizedYield(SY); (, , uint8 assetDecimals) = _SY.assetInfo(); string memory syCoreName = _stripSYPrefix(_SY.name()); string memory syCoreSymbol = _stripSYPrefix(_SY.symbol()); PT = Create2.deploy( 0, bytes32(block.chainid), abi.encodePacked( type(PendlePrincipalToken).creationCode, abi.encode( SY, PT_PREFIX.concat(syCoreName, expiry, " "), PT_PREFIX.concat(syCoreSymbol, expiry, "-"), assetDecimals, expiry ) ) ); YT = BaseSplitCodeFactory._create2( 0, bytes32(block.chainid), abi.encode( SY, PT, YT_PREFIX.concat(syCoreName, expiry, " "), YT_PREFIX.concat(syCoreSymbol, expiry, "-"), assetDecimals, expiry, doCacheIndexSameBlock ), ytCreationCodeContractA, ytCreationCodeSizeA, ytCreationCodeContractB, ytCreationCodeSizeB ); IPPrincipalToken(PT).initialize(YT); getPT[SY][expiry] = PT; getYT[SY][expiry] = YT; isPT[PT] = true; isYT[YT] = true; emit CreateYieldContract(SY, expiry, PT, YT); } function setExpiryDivisor(uint96 newExpiryDivisor) public onlyOwner { if (newExpiryDivisor == 0) revert Errors.YCFactoryZeroExpiryDivisor(); expiryDivisor = newExpiryDivisor; emit SetExpiryDivisor(newExpiryDivisor); } function setInterestFeeRate(uint128 newInterestFeeRate) public onlyOwner { if (newInterestFeeRate > maxInterestFeeRate) revert Errors.YCFactoryInterestFeeRateTooHigh(newInterestFeeRate, maxInterestFeeRate); interestFeeRate = newInterestFeeRate; emit SetInterestFeeRate(newInterestFeeRate); } function setRewardFeeRate(uint128 newRewardFeeRate) public onlyOwner { if (newRewardFeeRate > maxRewardFeeRate) revert Errors.YCFactoryRewardFeeRateTooHigh(newRewardFeeRate, maxRewardFeeRate); rewardFeeRate = newRewardFeeRate; emit SetRewardFeeRate(newRewardFeeRate); } function setTreasury(address newTreasury) public onlyOwner { if (newTreasury == address(0)) revert Errors.YCFactoryZeroTreasury(); treasury = newTreasury; emit SetTreasury(newTreasury); } function _stripSYPrefix(string memory _str) internal pure returns (string memory) { StringLib.slice memory str = _str.toSlice(); StringLib.slice memory delim_name = SY_NAME_PREF.toSlice(); StringLib.slice memory delim_symbol = SY_SYMBOL_PREF.toSlice(); return str.beyond(delim_name).beyond(delim_symbol).toString(); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.2; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in * case an upgrade adds a module that needs to be initialized. * * For example: * * [.hljs-theme-light.nopadding] * ```solidity * contract MyToken is ERC20Upgradeable { * function initialize() initializer public { * __ERC20_init("MyToken", "MTK"); * } * } * * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable { * function initializeV2() reinitializer(2) public { * __ERC20Permit_init("MyToken"); * } * } * ``` * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() { * _disableInitializers(); * } * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. * @custom:oz-retyped-from bool */ uint8 private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Triggered when the contract has been initialized or reinitialized. */ event Initialized(uint8 version); /** * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope, * `onlyInitializing` functions can be used to initialize parent contracts. * * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a * constructor. * * Emits an {Initialized} event. */ modifier initializer() { bool isTopLevelCall = !_initializing; require( (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1), "Initializable: contract is already initialized" ); _initialized = 1; if (isTopLevelCall) { _initializing = true; } _; if (isTopLevelCall) { _initializing = false; emit Initialized(1); } } /** * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be * used to initialize parent contracts. * * A reinitializer may be used after the original initialization step. This is essential to configure modules that * are added through upgrades and that require initialization. * * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer` * cannot be nested. If one is invoked in the context of another, execution will revert. * * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in * a contract, executing them in the right order is up to the developer or operator. * * WARNING: setting the version to 255 will prevent any future reinitialization. * * Emits an {Initialized} event. */ modifier reinitializer(uint8 version) { require(!_initializing && _initialized < version, "Initializable: contract is already initialized"); _initialized = version; _initializing = true; _; _initializing = false; emit Initialized(version); } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} and {reinitializer} modifiers, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } /** * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call. * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized * to any version. It is recommended to use this to lock implementation contracts that are designed to be called * through proxies. * * Emits an {Initialized} event the first time it is successfully executed. */ function _disableInitializers() internal virtual { require(!_initializing, "Initializable: contract is initializing"); if (_initialized != type(uint8).max) { _initialized = type(uint8).max; emit Initialized(type(uint8).max); } } /** * @dev Returns the highest version that has been initialized. See {reinitializer}. */ function _getInitializedVersion() internal view returns (uint8) { return _initialized; } /** * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}. */ function _isInitializing() internal view returns (bool) { return _initializing; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * * Furthermore, `isContract` will also return true if the target contract within * the same transaction is already scheduled for destruction by `SELFDESTRUCT`, * which only has an effect at the end of a transaction. * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @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.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @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, it is bubbled up by this * function (like regular Solidity function calls). * * 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. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @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`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract. * * _Available since v4.8._ */ function verifyCallResultFromTarget( address target, bool success, bytes memory returndata, string memory errorMessage ) internal view returns (bytes memory) { if (success) { if (returndata.length == 0) { // only check isContract if the call was successful and the return data is empty // otherwise we already know that it was a contract require(isContract(target), "Address: call to non-contract"); } return returndata; } else { _revert(returndata, errorMessage); } } /** * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason or using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { _revert(returndata, errorMessage); } } function _revert(bytes memory returndata, string memory errorMessage) 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(errorMessage); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.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}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * 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. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => 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 override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override 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 override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override 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 `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `amount` 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 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, spender, amount); 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 `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, allowance(owner, spender) + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { address owner = _msgSender(); uint256 currentAllowance = allowance(owner, spender); require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `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. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer(address from, address to, uint256 amount) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by // decrementing then incrementing. _balances[to] += amount; } emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; unchecked { // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above. _balances[account] += amount; } emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; // Overflow not possible: amount <= accountBalance <= totalSupply. _totalSupply -= amount; } emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` 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. */ function _approve(address owner, address spender, uint256 amount) internal virtual { 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); } /** * @dev Updates `owner` s allowance for `spender` based on spent `amount`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance(address owner, address spender, uint256 amount) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {} }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ 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 v4.9.0) (token/ERC20/extensions/IERC20Permit.sol) pragma solidity ^0.8.0; /** * @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. */ 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]. */ 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 v4.9.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @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 amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` 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 amount) 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 `amount` 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 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` 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 amount) external returns (bool); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../extensions/IERC20Permit.sol"; import "../../../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 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.encodeWithSelector(token.transfer.selector, 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.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 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); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value)); } /** * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value, * non-reverting calls are assumed to be successful. */ function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value)); } } /** * @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.encodeWithSelector(token.approve.selector, spender, value); if (!_callOptionalReturnBool(token, approvalCall)) { _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0)); _callOptionalReturn(token, approvalCall); } } /** * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`. * Revert on invalid signature. */ function safePermit( IERC20Permit token, address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) internal { uint256 nonceBefore = token.nonces(owner); token.permit(owner, spender, value, deadline, v, r, s); uint256 nonceAfter = token.nonces(owner); require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed"); } /** * @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, "SafeERC20: low-level call failed"); require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } /** * @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.isContract(address(token)); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * * Furthermore, `isContract` will also return true if the target contract within * the same transaction is already scheduled for destruction by `SELFDESTRUCT`, * which only has an effect at the end of a transaction. * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @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.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @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, it is bubbled up by this * function (like regular Solidity function calls). * * 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. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @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`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract. * * _Available since v4.8._ */ function verifyCallResultFromTarget( address target, bool success, bytes memory returndata, string memory errorMessage ) internal view returns (bytes memory) { if (success) { if (returndata.length == 0) { // only check isContract if the call was successful and the return data is empty // otherwise we already know that it was a contract require(isContract(target), "Address: call to non-contract"); } return returndata; } else { _revert(returndata, errorMessage); } } /** * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason or using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { _revert(returndata, errorMessage); } } function _revert(bytes memory returndata, string memory errorMessage) 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(errorMessage); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @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; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (utils/Create2.sol) pragma solidity ^0.8.0; /** * @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer. * `CREATE2` can be used to compute in advance the address where a smart * contract will be deployed, which allows for interesting new mechanisms known * as 'counterfactual interactions'. * * See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more * information. */ library Create2 { /** * @dev Deploys a contract using `CREATE2`. The address where the contract * will be deployed can be known in advance via {computeAddress}. * * The bytecode for a contract can be obtained from Solidity with * `type(contractName).creationCode`. * * Requirements: * * - `bytecode` must not be empty. * - `salt` must have not been used for `bytecode` already. * - the factory must have a balance of at least `amount`. * - if `amount` is non-zero, `bytecode` must have a `payable` constructor. */ function deploy(uint256 amount, bytes32 salt, bytes memory bytecode) internal returns (address addr) { require(address(this).balance >= amount, "Create2: insufficient balance"); require(bytecode.length != 0, "Create2: bytecode length is zero"); /// @solidity memory-safe-assembly assembly { addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt) } require(addr != address(0), "Create2: Failed on deploy"); } /** * @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the * `bytecodeHash` or `salt` will result in a new destination address. */ function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address) { return computeAddress(salt, bytecodeHash, address(this)); } /** * @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at * `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}. */ function computeAddress(bytes32 salt, bytes32 bytecodeHash, address deployer) internal pure returns (address addr) { /// @solidity memory-safe-assembly assembly { let ptr := mload(0x40) // Get free memory pointer // | | ↓ ptr ... ↓ ptr + 0x0B (start) ... ↓ ptr + 0x20 ... ↓ ptr + 0x40 ... | // |-------------------|---------------------------------------------------------------------------| // | bytecodeHash | CCCCCCCCCCCCC...CC | // | salt | BBBBBBBBBBBBB...BB | // | deployer | 000000...0000AAAAAAAAAAAAAAAAAAA...AA | // | 0xFF | FF | // |-------------------|---------------------------------------------------------------------------| // | memory | 000000...00FFAAAAAAAAAAAAAAAAAAA...AABBBBBBBBBBBBB...BBCCCCCCCCCCCCC...CC | // | keccak(start, 85) | ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ | mstore(add(ptr, 0x40), bytecodeHash) mstore(add(ptr, 0x20), salt) mstore(ptr, deployer) // Right-aligned with 12 preceding garbage bytes let start := add(ptr, 0x0b) // The hashed data starts at the final garbage byte which we will set to 0xff mstore8(start, 0xff) addr := keccak256(start, 85) } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (utils/structs/EnumerableSet.sol) // This file was procedurally generated from scripts/generate/templates/EnumerableSet.js. pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ```solidity * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. * * [WARNING] * ==== * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure * unusable. * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info. * * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an * array of EnumerableSet. * ==== */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastValue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastValue; // Update the index for the moved value set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { bytes32[] memory store = _values(set._inner); bytes32[] memory result; /// @solidity memory-safe-assembly assembly { result := store } return result; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; /// @solidity memory-safe-assembly assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values in the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; /// @solidity memory-safe-assembly assembly { result := store } return result; } }
// SPDX-License-Identifier: GPL-3.0-or-later // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import "@openzeppelin/contracts/utils/Context.sol"; /** * @dev Pendle's ERC20 implementation, modified from @openzeppelin implementation * Changes are: * - comes with built-in reentrancy protection, storage-packed with totalSupply variable * - delete increaseAllowance / decreaseAllowance * - add nonReentrancy protection to transfer / transferFrom functions * - allow decimals to be passed in * - block self-transfer by default */ // solhint-disable contract PendleERC20 is Context, IERC20, IERC20Metadata { uint8 private constant _NOT_ENTERED = 1; uint8 private constant _ENTERED = 2; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint248 private _totalSupply; uint8 private _status; string private _name; string private _symbol; uint8 public immutable decimals; /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } /** * @dev Sets the values for {name}, {symbol} and {decimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_, uint8 decimals_) { _name = name_; _symbol = symbol_; decimals = decimals_; _status = _NOT_ENTERED; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override 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 `amount`. */ function transfer(address to, uint256 amount) external virtual override nonReentrant returns (bool) { address owner = _msgSender(); _transfer(owner, to, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `amount` 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 amount) external virtual override returns (bool) { address owner = _msgSender(); _approve(owner, spender, amount); 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 `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) external virtual override nonReentrant returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * 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. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer(address from, address to, uint256 amount) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(from != to, "ERC20: transfer to self"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += toUint248(amount); _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= toUint248(amount); emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` 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. */ function _approve(address owner, address spender, uint256 amount) internal virtual { 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); } /** * @dev Updates `owner` s allowance for `spender` based on spent `amount`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance(address owner, address spender, uint256 amount) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {} function toUint248(uint256 x) internal virtual returns (uint248) { require(x <= type(uint248).max); // signed, lim = bit-1 return uint248(x); } }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; library ArrayLib { function sum(uint256[] memory input) internal pure returns (uint256) { uint256 value = 0; for (uint256 i = 0; i < input.length; ) { value += input[i]; unchecked { i++; } } return value; } /// @notice return index of the element if found, else return uint256.max function find(address[] memory array, address element) internal pure returns (uint256 index) { uint256 length = array.length; for (uint256 i = 0; i < length; ) { if (array[i] == element) return i; unchecked { i++; } } return type(uint256).max; } function append(address[] memory inp, address element) internal pure returns (address[] memory out) { uint256 length = inp.length; out = new address[](length + 1); for (uint256 i = 0; i < length; ) { out[i] = inp[i]; unchecked { i++; } } out[length] = element; } function appendHead(address[] memory inp, address element) internal pure returns (address[] memory out) { uint256 length = inp.length; out = new address[](length + 1); out[0] = element; for (uint256 i = 1; i <= length; ) { out[i] = inp[i - 1]; unchecked { i++; } } } /** * @dev This function assumes a and b each contains unidentical elements * @param a array of addresses a * @param b array of addresses b * @return out Concatenation of a and b containing unidentical elements */ function merge(address[] memory a, address[] memory b) internal pure returns (address[] memory out) { unchecked { uint256 countUnidenticalB = 0; bool[] memory isUnidentical = new bool[](b.length); for (uint256 i = 0; i < b.length; ++i) { if (!contains(a, b[i])) { countUnidenticalB++; isUnidentical[i] = true; } } out = new address[](a.length + countUnidenticalB); for (uint256 i = 0; i < a.length; ++i) { out[i] = a[i]; } uint256 id = a.length; for (uint256 i = 0; i < b.length; ++i) { if (isUnidentical[i]) { out[id++] = b[i]; } } } } // various version of contains function contains(address[] memory array, address element) internal pure returns (bool) { uint256 length = array.length; for (uint256 i = 0; i < length; ) { if (array[i] == element) return true; unchecked { i++; } } return false; } function contains(bytes4[] memory array, bytes4 element) internal pure returns (bool) { uint256 length = array.length; for (uint256 i = 0; i < length; ) { if (array[i] == element) return true; unchecked { i++; } } return false; } function create(address a) internal pure returns (address[] memory res) { res = new address[](1); res[0] = a; } function create(address a, address b) internal pure returns (address[] memory res) { res = new address[](2); res[0] = a; res[1] = b; } function create(address a, address b, address c) internal pure returns (address[] memory res) { res = new address[](3); res[0] = a; res[1] = b; res[2] = c; } function create(address a, address b, address c, address d) internal pure returns (address[] memory res) { res = new address[](4); res[0] = a; res[1] = b; res[2] = c; res[3] = d; } function create( address a, address b, address c, address d, address e ) internal pure returns (address[] memory res) { res = new address[](5); res[0] = a; res[1] = b; res[2] = c; res[3] = d; res[4] = e; } function create(uint256 a) internal pure returns (uint256[] memory res) { res = new uint256[](1); res[0] = a; } }
// SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/Create2.sol"; library CodeDeployer { // During contract construction, the full code supplied exists as code, and can be accessed via `codesize` and // `codecopy`. This is not the contract's final code however: whatever the constructor returns is what will be // stored as its code. // // We use this mechanism to have a simple constructor that stores whatever is appended to it. The following opcode // sequence corresponds to the creation code of the following equivalent Solidity contract, plus padding to make the // full code 32 bytes long: // // contract CodeDeployer { // constructor() payable { // uint256 size; // assembly { // size := sub(codesize(), 32) // size of appended data, as constructor is 32 bytes long // codecopy(0, 32, size) // copy all appended data to memory at position 0 // return(0, size) // return appended data for it to be stored as code // } // } // } // // More specifically, it is composed of the following opcodes (plus padding): // // [1] PUSH1 0x20 // [2] CODESIZE // [3] SUB // [4] DUP1 // [6] PUSH1 0x20 // [8] PUSH1 0x00 // [9] CODECOPY // [11] PUSH1 0x00 // [12] RETURN // // The padding is just the 0xfe sequence (invalid opcode). It is important as it lets us work in-place, avoiding // memory allocation and copying. bytes32 private constant _DEPLOYER_CREATION_CODE = 0x602038038060206000396000f3fefefefefefefefefefefefefefefefefefefe; /** * @dev Deploys a contract with `code` as its code, returning the destination address. * * Reverts if deployment fails. */ function deploy(bytes memory code) internal returns (address destination) { bytes32 deployerCreationCode = _DEPLOYER_CREATION_CODE; // We need to concatenate the deployer creation code and `code` in memory, but want to avoid copying all of // `code` (which could be quite long) into a new memory location. Therefore, we operate in-place using // assembly. // solhint-disable-next-line no-inline-assembly assembly { let codeLength := mload(code) // `code` is composed of length and data. We've already stored its length in `codeLength`, so we simply // replace it with the deployer creation code (which is exactly 32 bytes long). mstore(code, deployerCreationCode) // At this point, `code` now points to the deployer creation code immediately followed by `code`'s data // contents. This is exactly what the deployer expects to receive when created. destination := create(0, code, add(codeLength, 32)) // Finally, we restore the original length in order to not mutate `code`. mstore(code, codeLength) } // The create opcode returns the zero address when contract creation fails, so we revert if this happens. require(destination != address(0), "DEPLOYMENT_FAILED_BALANCER"); } } library BaseSplitCodeFactory { function setCreationCode( bytes memory creationCode ) internal returns ( address creationCodeContractA, uint256 creationCodeSizeA, address creationCodeContractB, uint256 creationCodeSizeB ) { unchecked { require(creationCode.length > 0, "zero length"); uint256 creationCodeSize = creationCode.length; // We are going to deploy two contracts: one with approximately the first half of `creationCode`'s contents // (A), and another with the remaining half (B). // We store the lengths in both immutable and stack variables, since immutable variables cannot be read during // construction. creationCodeSizeA = creationCodeSize / 2; creationCodeSizeB = creationCodeSize - creationCodeSizeA; // To deploy the contracts, we're going to use `CodeDeployer.deploy()`, which expects a memory array with // the code to deploy. Note that we cannot simply create arrays for A and B's code by copying or moving // `creationCode`'s contents as they are expected to be very large (> 24kB), so we must operate in-place. // Memory: [ code length ] [ A.data ] [ B.data ] // Creating A's array is simple: we simply replace `creationCode`'s length with A's length. We'll later restore // the original length. bytes memory creationCodeA; assembly { creationCodeA := creationCode mstore(creationCodeA, creationCodeSizeA) } // Memory: [ A.length ] [ A.data ] [ B.data ] // ^ creationCodeA creationCodeContractA = CodeDeployer.deploy(creationCodeA); // Creating B's array is a bit more involved: since we cannot move B's contents, we are going to create a 'new' // memory array starting at A's last 32 bytes, which will be replaced with B's length. We'll back-up this last // byte to later restore it. bytes memory creationCodeB; bytes32 lastByteA; assembly { // `creationCode` points to the array's length, not data, so by adding A's length to it we arrive at A's // last 32 bytes. creationCodeB := add(creationCode, creationCodeSizeA) lastByteA := mload(creationCodeB) mstore(creationCodeB, creationCodeSizeB) } // Memory: [ A.length ] [ A.data[ : -1] ] [ B.length ][ B.data ] // ^ creationCodeA ^ creationCodeB creationCodeContractB = CodeDeployer.deploy(creationCodeB); // We now restore the original contents of `creationCode` by writing back the original length and A's last byte. assembly { mstore(creationCodeA, creationCodeSize) mstore(creationCodeB, lastByteA) } } } /** * @dev Returns the creation code of the contract this factory creates. */ function getCreationCode( address creationCodeContractA, uint256 creationCodeSizeA, address creationCodeContractB, uint256 creationCodeSizeB ) internal view returns (bytes memory) { return _getCreationCodeWithArgs( "", creationCodeContractA, creationCodeSizeA, creationCodeContractB, creationCodeSizeB ); } /** * @dev Returns the creation code that will result in a contract being deployed with `constructorArgs`. */ function _getCreationCodeWithArgs( bytes memory constructorArgs, address creationCodeContractA, uint256 creationCodeSizeA, address creationCodeContractB, uint256 creationCodeSizeB ) private view returns (bytes memory code) { unchecked { // This function exists because `abi.encode()` cannot be instructed to place its result at a specific address. // We need for the ABI-encoded constructor arguments to be located immediately after the creation code, but // cannot rely on `abi.encodePacked()` to perform concatenation as that would involve copying the creation code, // which would be prohibitively expensive. // Instead, we compute the creation code in a pre-allocated array that is large enough to hold *both* the // creation code and the constructor arguments, and then copy the ABI-encoded arguments (which should not be // overly long) right after the end of the creation code. // Immutable variables cannot be used in assembly, so we store them in the stack first. uint256 creationCodeSize = creationCodeSizeA + creationCodeSizeB; uint256 constructorArgsSize = constructorArgs.length; uint256 codeSize = creationCodeSize + constructorArgsSize; assembly { // First, we allocate memory for `code` by retrieving the free memory pointer and then moving it ahead of // `code` by the size of the creation code plus constructor arguments, and 32 bytes for the array length. code := mload(0x40) mstore(0x40, add(code, add(codeSize, 32))) // We now store the length of the code plus constructor arguments. mstore(code, codeSize) // Next, we concatenate the creation code stored in A and B. let dataStart := add(code, 32) extcodecopy(creationCodeContractA, dataStart, 0, creationCodeSizeA) extcodecopy(creationCodeContractB, add(dataStart, creationCodeSizeA), 0, creationCodeSizeB) } // Finally, we copy the constructorArgs to the end of the array. Unfortunately there is no way to avoid this // copy, as it is not possible to tell Solidity where to store the result of `abi.encode()`. uint256 constructorArgsDataPtr; uint256 constructorArgsCodeDataPtr; assembly { constructorArgsDataPtr := add(constructorArgs, 32) constructorArgsCodeDataPtr := add(add(code, 32), creationCodeSize) } _memcpy(constructorArgsCodeDataPtr, constructorArgsDataPtr, constructorArgsSize); } } /** * @dev Deploys a contract with constructor arguments. To create `constructorArgs`, call `abi.encode()` with the * contract's constructor arguments, in order. */ function _create2( uint256 amount, bytes32 salt, bytes memory constructorArgs, address creationCodeContractA, uint256 creationCodeSizeA, address creationCodeContractB, uint256 creationCodeSizeB ) internal returns (address) { unchecked { bytes memory creationCode = _getCreationCodeWithArgs( constructorArgs, creationCodeContractA, creationCodeSizeA, creationCodeContractB, creationCodeSizeB ); return Create2.deploy(amount, salt, creationCode); } } // From // https://github.com/Arachnid/solidity-stringutils/blob/b9a6f6615cf18a87a823cbc461ce9e140a61c305/src/strings.sol function _memcpy(uint256 dest, uint256 src, uint256 len) private pure { unchecked { // Copy word-length chunks while possible for (; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint256 mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } } }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; contract BoringOwnableUpgradeableData { address public owner; address public pendingOwner; } abstract contract BoringOwnableUpgradeable is BoringOwnableUpgradeableData, Initializable { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function __BoringOwnable_init() internal onlyInitializing { owner = msg.sender; } /// @notice Transfers ownership to `newOwner`. Either directly or claimable by the new pending owner. /// Can only be invoked by the current `owner`. /// @param newOwner Address of the new owner. /// @param direct True if `newOwner` should be set immediately. False if `newOwner` needs to use `claimOwnership`. /// @param renounce Allows the `newOwner` to be `address(0)` if `direct` and `renounce` is True. Has no effect otherwise. function transferOwnership(address newOwner, bool direct, bool renounce) public onlyOwner { if (direct) { // Checks require(newOwner != address(0) || renounce, "Ownable: zero address"); // Effects emit OwnershipTransferred(owner, newOwner); owner = newOwner; pendingOwner = address(0); } else { // Effects pendingOwner = newOwner; } } /// @notice Needs to be called by `pendingOwner` to claim ownership. function claimOwnership() public { address _pendingOwner = pendingOwner; // Checks require(msg.sender == _pendingOwner, "Ownable: caller != pending owner"); // Effects emit OwnershipTransferred(owner, _pendingOwner); owner = _pendingOwner; pendingOwner = address(0); } /// @notice Only allows the `owner` to execute the function. modifier onlyOwner() { require(msg.sender == owner, "Ownable: caller is not the owner"); _; } uint256[48] private __gap; }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; library Errors { // BulkSeller error BulkInsufficientSyForTrade(uint256 currentAmount, uint256 requiredAmount); error BulkInsufficientTokenForTrade(uint256 currentAmount, uint256 requiredAmount); error BulkInSufficientSyOut(uint256 actualSyOut, uint256 requiredSyOut); error BulkInSufficientTokenOut(uint256 actualTokenOut, uint256 requiredTokenOut); error BulkInsufficientSyReceived(uint256 actualBalance, uint256 requiredBalance); error BulkNotMaintainer(); error BulkNotAdmin(); error BulkSellerAlreadyExisted(address token, address SY, address bulk); error BulkSellerInvalidToken(address token, address SY); error BulkBadRateTokenToSy(uint256 actualRate, uint256 currentRate, uint256 eps); error BulkBadRateSyToToken(uint256 actualRate, uint256 currentRate, uint256 eps); // APPROX error ApproxFail(); error ApproxParamsInvalid(uint256 guessMin, uint256 guessMax, uint256 eps); error ApproxBinarySearchInputInvalid( uint256 approxGuessMin, uint256 approxGuessMax, uint256 minGuessMin, uint256 maxGuessMax ); // MARKET + MARKET MATH CORE error MarketExpired(); error MarketZeroAmountsInput(); error MarketZeroAmountsOutput(); error MarketZeroLnImpliedRate(); error MarketInsufficientPtForTrade(int256 currentAmount, int256 requiredAmount); error MarketInsufficientPtReceived(uint256 actualBalance, uint256 requiredBalance); error MarketInsufficientSyReceived(uint256 actualBalance, uint256 requiredBalance); error MarketZeroTotalPtOrTotalAsset(int256 totalPt, int256 totalAsset); error MarketExchangeRateBelowOne(int256 exchangeRate); error MarketProportionMustNotEqualOne(); error MarketRateScalarBelowZero(int256 rateScalar); error MarketScalarRootBelowZero(int256 scalarRoot); error MarketProportionTooHigh(int256 proportion, int256 maxProportion); error OracleUninitialized(); error OracleTargetTooOld(uint32 target, uint32 oldest); error OracleZeroCardinality(); error MarketFactoryExpiredPt(); error MarketFactoryInvalidPt(); error MarketFactoryMarketExists(); error MarketFactoryLnFeeRateRootTooHigh(uint80 lnFeeRateRoot, uint256 maxLnFeeRateRoot); error MarketFactoryOverriddenFeeTooHigh(uint80 overriddenFee, uint256 marketLnFeeRateRoot); error MarketFactoryReserveFeePercentTooHigh(uint8 reserveFeePercent, uint8 maxReserveFeePercent); error MarketFactoryZeroTreasury(); error MarketFactoryInitialAnchorTooLow(int256 initialAnchor, int256 minInitialAnchor); error MFNotPendleMarket(address addr); // ROUTER error RouterInsufficientLpOut(uint256 actualLpOut, uint256 requiredLpOut); error RouterInsufficientSyOut(uint256 actualSyOut, uint256 requiredSyOut); error RouterInsufficientPtOut(uint256 actualPtOut, uint256 requiredPtOut); error RouterInsufficientYtOut(uint256 actualYtOut, uint256 requiredYtOut); error RouterInsufficientPYOut(uint256 actualPYOut, uint256 requiredPYOut); error RouterInsufficientTokenOut(uint256 actualTokenOut, uint256 requiredTokenOut); error RouterInsufficientSyRepay(uint256 actualSyRepay, uint256 requiredSyRepay); error RouterInsufficientPtRepay(uint256 actualPtRepay, uint256 requiredPtRepay); error RouterNotAllSyUsed(uint256 netSyDesired, uint256 netSyUsed); error RouterTimeRangeZero(); error RouterCallbackNotPendleMarket(address caller); error RouterInvalidAction(bytes4 selector); error RouterInvalidFacet(address facet); error RouterKyberSwapDataZero(); error SimulationResults(bool success, bytes res); // YIELD CONTRACT error YCExpired(); error YCNotExpired(); error YieldContractInsufficientSy(uint256 actualSy, uint256 requiredSy); error YCNothingToRedeem(); error YCPostExpiryDataNotSet(); error YCNoFloatingSy(); // YieldFactory error YCFactoryInvalidExpiry(); error YCFactoryYieldContractExisted(); error YCFactoryZeroExpiryDivisor(); error YCFactoryZeroTreasury(); error YCFactoryInterestFeeRateTooHigh(uint256 interestFeeRate, uint256 maxInterestFeeRate); error YCFactoryRewardFeeRateTooHigh(uint256 newRewardFeeRate, uint256 maxRewardFeeRate); // SY error SYInvalidTokenIn(address token); error SYInvalidTokenOut(address token); error SYZeroDeposit(); error SYZeroRedeem(); error SYInsufficientSharesOut(uint256 actualSharesOut, uint256 requiredSharesOut); error SYInsufficientTokenOut(uint256 actualTokenOut, uint256 requiredTokenOut); // SY-specific error SYQiTokenMintFailed(uint256 errCode); error SYQiTokenRedeemFailed(uint256 errCode); error SYQiTokenRedeemRewardsFailed(uint256 rewardAccruedType0, uint256 rewardAccruedType1); error SYQiTokenBorrowRateTooHigh(uint256 borrowRate, uint256 borrowRateMax); error SYCurveInvalidPid(); error SYCurve3crvPoolNotFound(); error SYApeDepositAmountTooSmall(uint256 amountDeposited); error SYBalancerInvalidPid(); error SYInvalidRewardToken(address token); error SYStargateRedeemCapExceeded(uint256 amountLpDesired, uint256 amountLpRedeemable); error SYBalancerReentrancy(); error NotFromTrustedRemote(uint16 srcChainId, bytes path); error ApxETHNotEnoughBuffer(); // Liquidity Mining error VCInactivePool(address pool); error VCPoolAlreadyActive(address pool); error VCZeroVePendle(address user); error VCExceededMaxWeight(uint256 totalWeight, uint256 maxWeight); error VCEpochNotFinalized(uint256 wTime); error VCPoolAlreadyAddAndRemoved(address pool); error VEInvalidNewExpiry(uint256 newExpiry); error VEExceededMaxLockTime(); error VEInsufficientLockTime(); error VENotAllowedReduceExpiry(); error VEZeroAmountLocked(); error VEPositionNotExpired(); error VEZeroPosition(); error VEZeroSlope(uint128 bias, uint128 slope); error VEReceiveOldSupply(uint256 msgTime); error GCNotPendleMarket(address caller); error GCNotVotingController(address caller); error InvalidWTime(uint256 wTime); error ExpiryInThePast(uint256 expiry); error ChainNotSupported(uint256 chainId); error FDTotalAmountFundedNotMatch(uint256 actualTotalAmount, uint256 expectedTotalAmount); error FDEpochLengthMismatch(); error FDInvalidPool(address pool); error FDPoolAlreadyExists(address pool); error FDInvalidNewFinishedEpoch(uint256 oldFinishedEpoch, uint256 newFinishedEpoch); error FDInvalidStartEpoch(uint256 startEpoch); error FDInvalidWTimeFund(uint256 lastFunded, uint256 wTime); error FDFutureFunding(uint256 lastFunded, uint256 currentWTime); error BDInvalidEpoch(uint256 epoch, uint256 startTime); // Cross-Chain error MsgNotFromSendEndpoint(uint16 srcChainId, bytes path); error MsgNotFromReceiveEndpoint(address sender); error InsufficientFeeToSendMsg(uint256 currentFee, uint256 requiredFee); error ApproxDstExecutionGasNotSet(); error InvalidRetryData(); // GENERIC MSG error ArrayLengthMismatch(); error ArrayEmpty(); error ArrayOutOfBounds(); error ZeroAddress(); error FailedToSendEther(); error InvalidMerkleProof(); error OnlyLayerZeroEndpoint(); error OnlyYT(); error OnlyYCFactory(); error OnlyWhitelisted(); // Swap Aggregator error SAInsufficientTokenIn(address tokenIn, uint256 amountExpected, uint256 amountActual); error UnsupportedSelector(uint256 aggregatorType, bytes4 selector); }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; library ExpiryUtils { struct Date { uint16 year; uint8 month; uint8 day; } uint256 private constant DAY_IN_SECONDS = 86400; uint256 private constant YEAR_IN_SECONDS = 31536000; uint256 private constant LEAP_YEAR_IN_SECONDS = 31622400; uint16 private constant ORIGIN_YEAR = 1970; /** * @notice Concatenates a Pendle token name/symbol, a yield token name/symbol, * and an expiry, using a delimiter (usually "-" or " "). * @param _bt The Pendle token name/symbol. * @param _yt The yield token name/symbol. * @param _expiry The expiry in epoch time. * @param _delimiter Can be any delimiter, but usually "-" or " ". * @return result Returns the concatenated string. **/ function concat( string memory _bt, string memory _yt, uint256 _expiry, string memory _delimiter ) internal pure returns (string memory result) { result = string(abi.encodePacked(_bt, _delimiter, _yt, _delimiter, toRFC2822String(_expiry))); } function toRFC2822String(uint256 _timestamp) internal pure returns (string memory s) { Date memory d = parseTimestamp(_timestamp); string memory day = uintToString(d.day); string memory month = monthName(d); string memory year = uintToString(d.year); s = string(abi.encodePacked(day, month, year)); } function getDaysInMonth(uint8 _month, uint16 _year) private pure returns (uint8) { if (_month == 1 || _month == 3 || _month == 5 || _month == 7 || _month == 8 || _month == 10 || _month == 12) { return 31; } else if (_month == 4 || _month == 6 || _month == 9 || _month == 11) { return 30; } else if (isLeapYear(_year)) { return 29; } else { return 28; } } function getYear(uint256 _timestamp) private pure returns (uint16) { uint256 secondsAccountedFor = 0; uint16 year; uint256 numLeapYears; // Year year = uint16(ORIGIN_YEAR + _timestamp / YEAR_IN_SECONDS); numLeapYears = leapYearsBefore(year) - leapYearsBefore(ORIGIN_YEAR); secondsAccountedFor += LEAP_YEAR_IN_SECONDS * numLeapYears; secondsAccountedFor += YEAR_IN_SECONDS * (year - ORIGIN_YEAR - numLeapYears); while (secondsAccountedFor > _timestamp) { if (isLeapYear(uint16(year - 1))) { secondsAccountedFor -= LEAP_YEAR_IN_SECONDS; } else { secondsAccountedFor -= YEAR_IN_SECONDS; } year -= 1; } return year; } function isLeapYear(uint16 _year) private pure returns (bool) { return ((_year % 4 == 0) && (_year % 100 != 0)) || (_year % 400 == 0); } function leapYearsBefore(uint256 _year) private pure returns (uint256) { _year -= 1; return _year / 4 - _year / 100 + _year / 400; } function monthName(Date memory d) private pure returns (string memory) { string[12] memory months = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"]; return months[d.month - 1]; } function parseTimestamp(uint256 _timestamp) private pure returns (Date memory d) { uint256 secondsAccountedFor = 0; uint256 buf; uint8 i; // Year d.year = getYear(_timestamp); buf = leapYearsBefore(d.year) - leapYearsBefore(ORIGIN_YEAR); secondsAccountedFor += LEAP_YEAR_IN_SECONDS * buf; secondsAccountedFor += YEAR_IN_SECONDS * (d.year - ORIGIN_YEAR - buf); // Month uint256 secondsInMonth; for (i = 1; i <= 12; i++) { secondsInMonth = DAY_IN_SECONDS * getDaysInMonth(i, d.year); if (secondsInMonth + secondsAccountedFor > _timestamp) { d.month = i; break; } secondsAccountedFor += secondsInMonth; } // Day for (i = 1; i <= getDaysInMonth(d.month, d.year); i++) { if (DAY_IN_SECONDS + secondsAccountedFor > _timestamp) { d.day = i; break; } secondsAccountedFor += DAY_IN_SECONDS; } } function uintToString(uint256 _i) private pure returns (string memory) { if (_i == 0) { return "0"; } uint256 j = _i; uint256 len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len - 1; while (_i != 0) { bstr[k] = bytes1(uint8(48 + (_i % 10))); if (k != 0) k--; _i /= 10; } return string(bstr); } }
// SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.8.0; /* solhint-disable private-vars-leading-underscore, reason-string */ library PMath { uint256 internal constant ONE = 1e18; // 18 decimal places int256 internal constant IONE = 1e18; // 18 decimal places function subMax0(uint256 a, uint256 b) internal pure returns (uint256) { unchecked { return (a >= b ? a - b : 0); } } function subNoNeg(int256 a, int256 b) internal pure returns (int256) { require(a >= b, "negative"); return a - b; // no unchecked since if b is very negative, a - b might overflow } function mulDown(uint256 a, uint256 b) internal pure returns (uint256) { uint256 product = a * b; unchecked { return product / ONE; } } function mulDown(int256 a, int256 b) internal pure returns (int256) { int256 product = a * b; unchecked { return product / IONE; } } function divDown(uint256 a, uint256 b) internal pure returns (uint256) { uint256 aInflated = a * ONE; unchecked { return aInflated / b; } } function divDown(int256 a, int256 b) internal pure returns (int256) { int256 aInflated = a * IONE; unchecked { return aInflated / b; } } function rawDivUp(uint256 a, uint256 b) internal pure returns (uint256) { return (a + b - 1) / b; } function rawDivUp(int256 a, int256 b) internal pure returns (int256) { return (a + b - 1) / b; } // @author Uniswap function sqrt(uint256 y) internal pure returns (uint256 z) { if (y > 3) { z = y; uint256 x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } function square(uint256 x) internal pure returns (uint256) { return x * x; } function squareDown(uint256 x) internal pure returns (uint256) { return mulDown(x, x); } function abs(int256 x) internal pure returns (uint256) { return uint256(x > 0 ? x : -x); } function neg(int256 x) internal pure returns (int256) { return x * (-1); } function neg(uint256 x) internal pure returns (int256) { return Int(x) * (-1); } function max(uint256 x, uint256 y) internal pure returns (uint256) { return (x > y ? x : y); } function max(int256 x, int256 y) internal pure returns (int256) { return (x > y ? x : y); } function min(uint256 x, uint256 y) internal pure returns (uint256) { return (x < y ? x : y); } function min(int256 x, int256 y) internal pure returns (int256) { return (x < y ? x : y); } /*/////////////////////////////////////////////////////////////// SIGNED CASTS //////////////////////////////////////////////////////////////*/ function Int(uint256 x) internal pure returns (int256) { require(x <= uint256(type(int256).max)); return int256(x); } function Int128(int256 x) internal pure returns (int128) { require(type(int128).min <= x && x <= type(int128).max); return int128(x); } function Int128(uint256 x) internal pure returns (int128) { return Int128(Int(x)); } /*/////////////////////////////////////////////////////////////// UNSIGNED CASTS //////////////////////////////////////////////////////////////*/ function Uint(int256 x) internal pure returns (uint256) { require(x >= 0); return uint256(x); } function Uint32(uint256 x) internal pure returns (uint32) { require(x <= type(uint32).max); return uint32(x); } function Uint64(uint256 x) internal pure returns (uint64) { require(x <= type(uint64).max); return uint64(x); } function Uint112(uint256 x) internal pure returns (uint112) { require(x <= type(uint112).max); return uint112(x); } function Uint96(uint256 x) internal pure returns (uint96) { require(x <= type(uint96).max); return uint96(x); } function Uint128(uint256 x) internal pure returns (uint128) { require(x <= type(uint128).max); return uint128(x); } function Uint192(uint256 x) internal pure returns (uint192) { require(x <= type(uint192).max); return uint192(x); } function isAApproxB(uint256 a, uint256 b, uint256 eps) internal pure returns (bool) { return mulDown(b, ONE - eps) <= a && a <= mulDown(b, ONE + eps); } function isAGreaterApproxB(uint256 a, uint256 b, uint256 eps) internal pure returns (bool) { return a >= b && a <= mulDown(b, ONE + eps); } function isASmallerApproxB(uint256 a, uint256 b, uint256 eps) internal pure returns (bool) { return a <= b && a >= mulDown(b, ONE - eps); } }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; library MiniHelpers { function isCurrentlyExpired(uint256 expiry) internal view returns (bool) { return (expiry <= block.timestamp); } function isExpired(uint256 expiry, uint256 blockTime) internal pure returns (bool) { return (expiry <= blockTime); } function isTimeInThePast(uint256 timestamp) internal view returns (bool) { return (timestamp <= block.timestamp); // same definition as isCurrentlyExpired } }
/* * @title String & slice utility library for Solidity contracts. * @author Nick Johnson <[email protected]> * * @dev Functionality in this library is largely implemented using an * abstraction called a 'slice'. A slice represents a part of a string - * anything from the entire string to a single character, or even no * characters at all (a 0-length slice). Since a slice only has to specify * an offset and a length, copying and manipulating slices is a lot less * expensive than copying and manipulating the strings they reference. * * To further reduce gas costs, most functions on slice that need to return * a slice modify the original one instead of allocating a new one; for * instance, `s.split(".")` will return the text up to the first '.', * modifying s to only contain the remainder of the string after the '.'. * In situations where you do not want to modify the original slice, you * can make a copy first with `.copy()`, for example: * `s.copy().split(".")`. Try and avoid using this idiom in loops; since * Solidity has no memory management, it will result in allocating many * short-lived slices that are later discarded. * * Functions that return two slices come in two versions: a non-allocating * version that takes the second slice as an argument, modifying it in * place, and an allocating version that allocates and returns the second * slice; see `nextRune` for example. * * Functions that have to copy string data will return strings rather than * slices; these can be cast back to slices for further processing if * required. * * For convenience, some functions are provided with non-modifying * variants that create a new slice and return both; for instance, * `s.splitNew('.')` leaves s unmodified, and returns two values * corresponding to the left and right parts of the string. */ pragma solidity ^0.8.0; library StringLib { struct slice { uint256 _len; uint256 _ptr; } function memcpy(uint256 dest, uint256 src, uint256 len) private pure { // Copy word-length chunks while possible for (; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint256 mask = type(uint256).max; if (len > 0) { mask = 256 ** (32 - len) - 1; } assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } /* * @dev Returns a slice containing the entire string. * @param self The string to make a slice from. * @return A newly allocated slice containing the entire string. */ function toSlice(string memory self) internal pure returns (slice memory) { uint256 ptr; assembly { ptr := add(self, 0x20) } return slice(bytes(self).length, ptr); } /* * @dev Returns the length of a null-terminated bytes32 string. * @param self The value to find the length of. * @return The length of the string, from 0 to 32. */ function len(bytes32 self) internal pure returns (uint256) { uint256 ret; if (self == 0) return 0; if (uint256(self) & type(uint128).max == 0) { ret += 16; self = bytes32(uint256(self) / 0x100000000000000000000000000000000); } if (uint256(self) & type(uint64).max == 0) { ret += 8; self = bytes32(uint256(self) / 0x10000000000000000); } if (uint256(self) & type(uint32).max == 0) { ret += 4; self = bytes32(uint256(self) / 0x100000000); } if (uint256(self) & type(uint16).max == 0) { ret += 2; self = bytes32(uint256(self) / 0x10000); } if (uint256(self) & type(uint8).max == 0) { ret += 1; } return 32 - ret; } /* * @dev Returns a slice containing the entire bytes32, interpreted as a * null-terminated utf-8 string. * @param self The bytes32 value to convert to a slice. * @return A new slice containing the value of the input argument up to the * first null. */ function toSliceB32(bytes32 self) internal pure returns (slice memory ret) { // Allocate space for `self` in memory, copy it there, and point ret at it assembly { let ptr := mload(0x40) mstore(0x40, add(ptr, 0x20)) mstore(ptr, self) mstore(add(ret, 0x20), ptr) } ret._len = len(self); } /* * @dev Returns a new slice containing the same data as the current slice. * @param self The slice to copy. * @return A new slice containing the same data as `self`. */ function copy(slice memory self) internal pure returns (slice memory) { return slice(self._len, self._ptr); } /* * @dev Copies a slice to a new string. * @param self The slice to copy. * @return A newly allocated string containing the slice's text. */ function toString(slice memory self) internal pure returns (string memory) { string memory ret = new string(self._len); uint256 retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); return ret; } /* * @dev Returns the length in runes of the slice. Note that this operation * takes time proportional to the length of the slice; avoid using it * in loops, and call `slice.empty()` if you only need to know whether * the slice is empty or not. * @param self The slice to operate on. * @return The length of the slice in runes. */ function len(slice memory self) internal pure returns (uint256 l) { // Starting at ptr-31 means the LSB will be the byte we care about uint256 ptr = self._ptr - 31; uint256 end = ptr + self._len; for (l = 0; ptr < end; l++) { uint8 b; assembly { b := and(mload(ptr), 0xFF) } if (b < 0x80) { ptr += 1; } else if (b < 0xE0) { ptr += 2; } else if (b < 0xF0) { ptr += 3; } else if (b < 0xF8) { ptr += 4; } else if (b < 0xFC) { ptr += 5; } else { ptr += 6; } } } /* * @dev Returns true if the slice is empty (has a length of 0). * @param self The slice to operate on. * @return True if the slice is empty, False otherwise. */ function empty(slice memory self) internal pure returns (bool) { return self._len == 0; } /* * @dev Returns a positive number if `other` comes lexicographically after * `self`, a negative number if it comes before, or zero if the * contents of the two slices are equal. Comparison is done per-rune, * on unicode codepoints. * @param self The first slice to compare. * @param other The second slice to compare. * @return The result of the comparison. */ function compare(slice memory self, slice memory other) internal pure returns (int256) { uint256 shortest = self._len; if (other._len < self._len) shortest = other._len; uint256 selfptr = self._ptr; uint256 otherptr = other._ptr; for (uint256 idx = 0; idx < shortest; idx += 32) { uint256 a; uint256 b; assembly { a := mload(selfptr) b := mload(otherptr) } if (a != b) { // Mask out irrelevant bytes and check again uint256 mask = type(uint256).max; // 0xffff... if (shortest < 32) { mask = ~(2 ** (8 * (32 - shortest + idx)) - 1); } unchecked { uint256 diff = (a & mask) - (b & mask); if (diff != 0) return int256(diff); } } selfptr += 32; otherptr += 32; } return int256(self._len) - int256(other._len); } /* * @dev Returns true if the two slices contain the same text. * @param self The first slice to compare. * @param self The second slice to compare. * @return True if the slices are equal, false otherwise. */ function equals(slice memory self, slice memory other) internal pure returns (bool) { return compare(self, other) == 0; } /* * @dev Extracts the first rune in the slice into `rune`, advancing the * slice to point to the next rune and returning `self`. * @param self The slice to operate on. * @param rune The slice that will contain the first rune. * @return `rune`. */ function nextRune(slice memory self, slice memory rune) internal pure returns (slice memory) { rune._ptr = self._ptr; if (self._len == 0) { rune._len = 0; return rune; } uint256 l; uint256 b; // Load the first byte of the rune into the LSBs of b assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) } if (b < 0x80) { l = 1; } else if (b < 0xE0) { l = 2; } else if (b < 0xF0) { l = 3; } else { l = 4; } // Check for truncated codepoints if (l > self._len) { rune._len = self._len; self._ptr += self._len; self._len = 0; return rune; } self._ptr += l; self._len -= l; rune._len = l; return rune; } /* * @dev Returns the first rune in the slice, advancing the slice to point * to the next rune. * @param self The slice to operate on. * @return A slice containing only the first rune from `self`. */ function nextRune(slice memory self) internal pure returns (slice memory ret) { nextRune(self, ret); } /* * @dev Returns the number of the first codepoint in the slice. * @param self The slice to operate on. * @return The number of the first codepoint in the slice. */ function ord(slice memory self) internal pure returns (uint256 ret) { if (self._len == 0) { return 0; } uint256 word; uint256 length; uint256 divisor = 2 ** 248; // Load the rune into the MSBs of b assembly { word := mload(mload(add(self, 32))) } uint256 b = word / divisor; if (b < 0x80) { ret = b; length = 1; } else if (b < 0xE0) { ret = b & 0x1F; length = 2; } else if (b < 0xF0) { ret = b & 0x0F; length = 3; } else { ret = b & 0x07; length = 4; } // Check for truncated codepoints if (length > self._len) { return 0; } for (uint256 i = 1; i < length; i++) { divisor = divisor / 256; b = (word / divisor) & 0xFF; if (b & 0xC0 != 0x80) { // Invalid UTF-8 sequence return 0; } ret = (ret * 64) | (b & 0x3F); } return ret; } /* * @dev Returns the keccak-256 hash of the slice. * @param self The slice to hash. * @return The hash of the slice. */ function keccak(slice memory self) internal pure returns (bytes32 ret) { assembly { ret := keccak256(mload(add(self, 32)), mload(self)) } } /* * @dev Returns true if `self` starts with `needle`. * @param self The slice to operate on. * @param needle The slice to search for. * @return True if the slice starts with the provided text, false otherwise. */ function startsWith(slice memory self, slice memory needle) internal pure returns (bool) { if (self._len < needle._len) { return false; } if (self._ptr == needle._ptr) { return true; } bool equal; assembly { let length := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } return equal; } /* * @dev If `self` starts with `needle`, `needle` is removed from the * beginning of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function beyond(slice memory self, slice memory needle) internal pure returns (slice memory) { if (self._len < needle._len) { return self; } bool equal = true; if (self._ptr != needle._ptr) { assembly { let length := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } } if (equal) { self._len -= needle._len; self._ptr += needle._len; } return self; } /* * @dev Returns true if the slice ends with `needle`. * @param self The slice to operate on. * @param needle The slice to search for. * @return True if the slice starts with the provided text, false otherwise. */ function endsWith(slice memory self, slice memory needle) internal pure returns (bool) { if (self._len < needle._len) { return false; } uint256 selfptr = self._ptr + self._len - needle._len; if (selfptr == needle._ptr) { return true; } bool equal; assembly { let length := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } return equal; } /* * @dev If `self` ends with `needle`, `needle` is removed from the * end of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function until(slice memory self, slice memory needle) internal pure returns (slice memory) { if (self._len < needle._len) { return self; } uint256 selfptr = self._ptr + self._len - needle._len; bool equal = true; if (selfptr != needle._ptr) { assembly { let length := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } } if (equal) { self._len -= needle._len; } return self; } // Returns the memory address of the first byte of the first occurrence of // `needle` in `self`, or the first byte after `self` if not found. function findPtr( uint256 selflen, uint256 selfptr, uint256 needlelen, uint256 needleptr ) private pure returns (uint256) { uint256 ptr = selfptr; uint256 idx; if (needlelen <= selflen) { if (needlelen <= 32) { bytes32 mask; if (needlelen > 0) { mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1)); } bytes32 needledata; assembly { needledata := and(mload(needleptr), mask) } uint256 end = selfptr + selflen - needlelen; bytes32 ptrdata; assembly { ptrdata := and(mload(ptr), mask) } while (ptrdata != needledata) { if (ptr >= end) return selfptr + selflen; ptr++; assembly { ptrdata := and(mload(ptr), mask) } } return ptr; } else { // For long needles, use hashing bytes32 hash; assembly { hash := keccak256(needleptr, needlelen) } for (idx = 0; idx <= selflen - needlelen; idx++) { bytes32 testHash; assembly { testHash := keccak256(ptr, needlelen) } if (hash == testHash) return ptr; ptr += 1; } } } return selfptr + selflen; } // Returns the memory address of the first byte after the last occurrence of // `needle` in `self`, or the address of `self` if not found. function rfindPtr( uint256 selflen, uint256 selfptr, uint256 needlelen, uint256 needleptr ) private pure returns (uint256) { uint256 ptr; if (needlelen <= selflen) { if (needlelen <= 32) { bytes32 mask; if (needlelen > 0) { mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1)); } bytes32 needledata; assembly { needledata := and(mload(needleptr), mask) } ptr = selfptr + selflen - needlelen; bytes32 ptrdata; assembly { ptrdata := and(mload(ptr), mask) } while (ptrdata != needledata) { if (ptr <= selfptr) return selfptr; ptr--; assembly { ptrdata := and(mload(ptr), mask) } } return ptr + needlelen; } else { // For long needles, use hashing bytes32 hash; assembly { hash := keccak256(needleptr, needlelen) } ptr = selfptr + (selflen - needlelen); while (ptr >= selfptr) { bytes32 testHash; assembly { testHash := keccak256(ptr, needlelen) } if (hash == testHash) return ptr + needlelen; ptr -= 1; } } } return selfptr; } /* * @dev Modifies `self` to contain everything from the first occurrence of * `needle` to the end of the slice. `self` is set to the empty slice * if `needle` is not found. * @param self The slice to search and modify. * @param needle The text to search for. * @return `self`. */ function find(slice memory self, slice memory needle) internal pure returns (slice memory) { uint256 ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); self._len -= ptr - self._ptr; self._ptr = ptr; return self; } /* * @dev Modifies `self` to contain the part of the string from the start of * `self` to the end of the first occurrence of `needle`. If `needle` * is not found, `self` is set to the empty slice. * @param self The slice to search and modify. * @param needle The text to search for. * @return `self`. */ function rfind(slice memory self, slice memory needle) internal pure returns (slice memory) { uint256 ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); self._len = ptr - self._ptr; return self; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and `token` to everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function split(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) { uint256 ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = self._ptr; token._len = ptr - self._ptr; if (ptr == self._ptr + self._len) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; self._ptr = ptr + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and returning everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` up to the first occurrence of `delim`. */ function split(slice memory self, slice memory needle) internal pure returns (slice memory token) { split(self, needle, token); } /* * @dev Splits the slice, setting `self` to everything before the last * occurrence of `needle`, and `token` to everything after it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function rsplit(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) { uint256 ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = ptr; token._len = self._len - (ptr - self._ptr); if (ptr == self._ptr) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything before the last * occurrence of `needle`, and returning everything after it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` after the last occurrence of `delim`. */ function rsplit(slice memory self, slice memory needle) internal pure returns (slice memory token) { rsplit(self, needle, token); } /* * @dev Counts the number of nonoverlapping occurrences of `needle` in `self`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return The number of occurrences of `needle` found in `self`. */ function count(slice memory self, slice memory needle) internal pure returns (uint256 cnt) { uint256 ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len; while (ptr <= self._ptr + self._len) { cnt++; ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len; } } /* * @dev Returns True if `self` contains `needle`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return True if `needle` is found in `self`, false otherwise. */ function contains(slice memory self, slice memory needle) internal pure returns (bool) { return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr; } /* * @dev Returns a newly allocated string containing the concatenation of * `self` and `other`. * @param self The first slice to concatenate. * @param other The second slice to concatenate. * @return The concatenation of the two strings. */ function concat(slice memory self, slice memory other) internal pure returns (string memory) { string memory ret = new string(self._len + other._len); uint256 retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); memcpy(retptr + self._len, other._ptr, other._len); return ret; } /* * @dev Joins an array of slices, using `self` as a delimiter, returning a * newly allocated string. * @param self The delimiter to use. * @param parts A list of slices to join. * @return A newly allocated string containing all the slices in `parts`, * joined with `self`. */ function join(slice memory self, slice[] memory parts) internal pure returns (string memory) { if (parts.length == 0) return ""; uint256 length = self._len * (parts.length - 1); for (uint256 i = 0; i < parts.length; i++) length += parts[i]._len; string memory ret = new string(length); uint256 retptr; assembly { retptr := add(ret, 32) } for (uint256 i = 0; i < parts.length; i++) { memcpy(retptr, parts[i]._ptr, parts[i]._len); retptr += parts[i]._len; if (i < parts.length - 1) { memcpy(retptr, self._ptr, self._len); retptr += self._len; } } return ret; } }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "../../interfaces/IWETH.sol"; abstract contract TokenHelper { using SafeERC20 for IERC20; address internal constant NATIVE = address(0); uint256 internal constant LOWER_BOUND_APPROVAL = type(uint96).max / 2; // some tokens use 96 bits for approval function _transferIn(address token, address from, uint256 amount) internal { if (token == NATIVE) require(msg.value == amount, "eth mismatch"); else if (amount != 0) IERC20(token).safeTransferFrom(from, address(this), amount); } function _transferFrom(IERC20 token, address from, address to, uint256 amount) internal { if (amount != 0) token.safeTransferFrom(from, to, amount); } function _transferOut(address token, address to, uint256 amount) internal { if (amount == 0) return; if (token == NATIVE) { (bool success, ) = to.call{value: amount}(""); require(success, "eth send failed"); } else { IERC20(token).safeTransfer(to, amount); } } function _transferOut(address[] memory tokens, address to, uint256[] memory amounts) internal { uint256 numTokens = tokens.length; require(numTokens == amounts.length, "length mismatch"); for (uint256 i = 0; i < numTokens; ) { _transferOut(tokens[i], to, amounts[i]); unchecked { i++; } } } function _selfBalance(address token) internal view returns (uint256) { return (token == NATIVE) ? address(this).balance : IERC20(token).balanceOf(address(this)); } function _selfBalance(IERC20 token) internal view returns (uint256) { return token.balanceOf(address(this)); } /// @notice Approves the stipulated contract to spend the given allowance in the given token /// @dev PLS PAY ATTENTION to tokens that requires the approval to be set to 0 before changing it function _safeApprove(address token, address to, uint256 value) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), "Safe Approve"); } function _safeApproveInf(address token, address to) internal { if (token == NATIVE) return; if (IERC20(token).allowance(address(this), to) < LOWER_BOUND_APPROVAL) { _safeApprove(token, to, 0); _safeApprove(token, to, type(uint256).max); } } function _wrap_unwrap_ETH(address tokenIn, address tokenOut, uint256 netTokenIn) internal { if (tokenIn == NATIVE) IWETH(tokenOut).deposit{value: netTokenIn}(); else IWETH(tokenIn).withdraw(netTokenIn); } }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "../../interfaces/IRewardManager.sol"; import "../libraries/ArrayLib.sol"; import "../libraries/TokenHelper.sol"; import "../libraries/math/PMath.sol"; import "./RewardManagerAbstract.sol"; /// NOTE: RewardManager must not have duplicated rewardTokens abstract contract RewardManagerAbstract is IRewardManager, TokenHelper { using PMath for uint256; uint256 internal constant INITIAL_REWARD_INDEX = 1; struct RewardState { uint128 index; uint128 lastBalance; } struct UserReward { uint128 index; uint128 accrued; } // [token] => [user] => (index,accrued) mapping(address => mapping(address => UserReward)) public userReward; function _updateAndDistributeRewards(address user) internal virtual { _updateAndDistributeRewardsForTwo(user, address(0)); } function _updateAndDistributeRewardsForTwo(address user1, address user2) internal virtual { (address[] memory tokens, uint256[] memory indexes) = _updateRewardIndex(); if (tokens.length == 0) return; if (user1 != address(0) && user1 != address(this)) _distributeRewardsPrivate(user1, tokens, indexes); if (user2 != address(0) && user2 != address(this)) _distributeRewardsPrivate(user2, tokens, indexes); } // should only be callable from `_updateAndDistributeRewardsForTwo` to guarantee user != address(0) && user != address(this) function _distributeRewardsPrivate(address user, address[] memory tokens, uint256[] memory indexes) private { assert(user != address(0) && user != address(this)); uint256 userShares = _rewardSharesUser(user); for (uint256 i = 0; i < tokens.length; ++i) { address token = tokens[i]; uint256 index = indexes[i]; uint256 userIndex = userReward[token][user].index; if (userIndex == 0) { userIndex = INITIAL_REWARD_INDEX.Uint128(); } if (userIndex == index || index == 0) continue; uint256 deltaIndex = index - userIndex; uint256 rewardDelta = userShares.mulDown(deltaIndex); uint256 rewardAccrued = userReward[token][user].accrued + rewardDelta; userReward[token][user] = UserReward({index: index.Uint128(), accrued: rewardAccrued.Uint128()}); } } function _updateRewardIndex() internal virtual returns (address[] memory tokens, uint256[] memory indexes); function _redeemExternalReward() internal virtual; function _doTransferOutRewards( address user, address receiver ) internal virtual returns (uint256[] memory rewardAmounts); function _rewardSharesUser(address user) internal view virtual returns (uint256); }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; library SYUtils { uint256 internal constant ONE = 1e18; function syToAsset(uint256 exchangeRate, uint256 syAmount) internal pure returns (uint256) { return (syAmount * exchangeRate) / ONE; } function syToAssetUp(uint256 exchangeRate, uint256 syAmount) internal pure returns (uint256) { return (syAmount * exchangeRate + ONE - 1) / ONE; } function assetToSy(uint256 exchangeRate, uint256 assetAmount) internal pure returns (uint256) { return (assetAmount * ONE) / exchangeRate; } function assetToSyUp(uint256 exchangeRate, uint256 assetAmount) internal pure returns (uint256) { return (assetAmount * ONE + exchangeRate - 1) / exchangeRate; } }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.17; import "../../interfaces/IPYieldToken.sol"; import "../../interfaces/IPPrincipalToken.sol"; import "../../interfaces/IPInterestManagerYT.sol"; import "../../interfaces/IPYieldContractFactory.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "../libraries/math/PMath.sol"; import "../libraries/TokenHelper.sol"; import "../StandardizedYield/SYUtils.sol"; /* With YT yielding more SYs overtime, which is allowed to be redeemed by users, the reward distribution should be based on the amount of SYs that their YT currently represent, plus with their dueInterest. It has been proven and tested that totalSyRedeemable will not change over time, unless users redeem their interest or redeemPY. Due to this, it is required to update users' accruedReward STRICTLY BEFORE redeeming their interest. */ abstract contract InterestManagerYT is TokenHelper, IPInterestManagerYT { using PMath for uint256; struct UserInterest { uint128 index; uint128 accrued; } mapping(address => UserInterest) public userInterest; function _distributeInterest(address user) internal { _distributeInterestForTwo(user, address(0)); } function _distributeInterestForTwo(address user1, address user2) internal { uint256 index = _getInterestIndex(); if (user1 != address(0) && user1 != address(this)) _distributeInterestPrivate(user1, index); if (user2 != address(0) && user2 != address(this)) _distributeInterestPrivate(user2, index); } function _doTransferOutInterest( address user, address SY, address factory ) internal returns (uint256 interestAmount) { address treasury = IPYieldContractFactory(factory).treasury(); uint256 feeRate = IPYieldContractFactory(factory).interestFeeRate(); uint256 interestPreFee = userInterest[user].accrued; userInterest[user].accrued = 0; uint256 feeAmount = interestPreFee.mulDown(feeRate); interestAmount = interestPreFee - feeAmount; _transferOut(SY, treasury, feeAmount); _transferOut(SY, user, interestAmount); emit CollectInterestFee(feeAmount); } // should only be callable from `_distributeInterestForTwo` & make sure user != address(0) && user != address(this) function _distributeInterestPrivate(address user, uint256 currentIndex) private { assert(user != address(0) && user != address(this)); uint256 prevIndex = userInterest[user].index; if (prevIndex == currentIndex) return; if (prevIndex == 0) { userInterest[user].index = currentIndex.Uint128(); return; } uint256 principal = _YTbalance(user); uint256 interestFromYT = (principal * (currentIndex - prevIndex)).divDown(prevIndex * currentIndex); userInterest[user].accrued += interestFromYT.Uint128(); userInterest[user].index = currentIndex.Uint128(); } function _getInterestIndex() internal virtual returns (uint256 index); function _YTbalance(address user) internal view virtual returns (uint256); }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.17; import "../../interfaces/IPPrincipalToken.sol"; import "../../interfaces/IPYieldToken.sol"; import "../libraries/MiniHelpers.sol"; import "../libraries/Errors.sol"; import "../erc20/PendleERC20.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; contract PendlePrincipalToken is PendleERC20, Initializable, IPPrincipalToken { address public immutable SY; address public immutable factory; uint256 public immutable expiry; address public YT; modifier onlyYT() { if (msg.sender != YT) revert Errors.OnlyYT(); _; } modifier onlyYieldFactory() { if (msg.sender != factory) revert Errors.OnlyYCFactory(); _; } constructor( address _SY, string memory _name, string memory _symbol, uint8 __decimals, uint256 _expiry ) PendleERC20(_name, _symbol, __decimals) { SY = _SY; expiry = _expiry; factory = msg.sender; } function initialize(address _YT) external initializer onlyYieldFactory { YT = _YT; } /** * @dev only callable by the YT correspond to this PT */ function burnByYT(address user, uint256 amount) external onlyYT { _burn(user, amount); } /** * @dev only callable by the YT correspond to this PT */ function mintByYT(address user, uint256 amount) external onlyYT { _mint(user, amount); } function isExpired() public view returns (bool) { return MiniHelpers.isCurrentlyExpired(expiry); } }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.17; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "../../interfaces/IStandardizedYield.sol"; import "../../interfaces/IPYieldToken.sol"; import "../../interfaces/IPPrincipalToken.sol"; import "../libraries/math/PMath.sol"; import "../libraries/ArrayLib.sol"; import "../../interfaces/IPYieldContractFactory.sol"; import "../StandardizedYield/SYUtils.sol"; import "../libraries/Errors.sol"; import "../libraries/MiniHelpers.sol"; import "../RewardManager/RewardManagerAbstract.sol"; import "../erc20/PendleERC20.sol"; import "./InterestManagerYT.sol"; /** Invariance to maintain: - address(0) & address(this) should never have any rewards & activeBalance accounting done. This is guaranteed by address(0) & address(this) check in each updateForTwo function */ contract PendleYieldToken is IPYieldToken, PendleERC20, RewardManagerAbstract, InterestManagerYT { using PMath for uint256; using SafeERC20 for IERC20; using ArrayLib for uint256[]; struct PostExpiryData { uint128 firstPYIndex; uint128 totalSyInterestForTreasury; mapping(address => uint256) firstRewardIndex; mapping(address => uint256) userRewardOwed; } address public immutable SY; address public immutable PT; address public immutable factory; uint256 public immutable expiry; bool public immutable doCacheIndexSameBlock; uint256 public syReserve; uint128 public pyIndexLastUpdatedBlock; uint128 internal _pyIndexStored; PostExpiryData public postExpiry; modifier updateData() { if (isExpired()) _setPostExpiryData(); _; _updateSyReserve(); } modifier notExpired() { if (isExpired()) revert Errors.YCExpired(); _; } /** * @param _doCacheIndexSameBlock if true, the PY index is cached for each block, and thus is * constant for all txs within the same block. Otherwise, the PY index is recalculated for * every tx. */ constructor( address _SY, address _PT, string memory _name, string memory _symbol, uint8 __decimals, uint256 _expiry, bool _doCacheIndexSameBlock ) PendleERC20(_name, _symbol, __decimals) { SY = _SY; PT = _PT; expiry = _expiry; factory = msg.sender; doCacheIndexSameBlock = _doCacheIndexSameBlock; } /** * @notice Tokenize SY into PT + YT of equal qty. Every unit of asset of SY will create 1 PT + 1 YT * @dev SY must be transferred to this contract prior to calling */ function mintPY( address receiverPT, address receiverYT ) external nonReentrant notExpired updateData returns (uint256 amountPYOut) { address[] memory receiverPTs = new address[](1); address[] memory receiverYTs = new address[](1); uint256[] memory amountSyToMints = new uint256[](1); (receiverPTs[0], receiverYTs[0], amountSyToMints[0]) = (receiverPT, receiverYT, _getFloatingSyAmount()); uint256[] memory amountPYOuts = _mintPY(receiverPTs, receiverYTs, amountSyToMints); amountPYOut = amountPYOuts[0]; } /// @notice Tokenize SY into PT + YT for multiple receivers. See `mintPY()` for more details function mintPYMulti( address[] calldata receiverPTs, address[] calldata receiverYTs, uint256[] calldata amountSyToMints ) external nonReentrant notExpired updateData returns (uint256[] memory amountPYOuts) { uint256 length = receiverPTs.length; if (length == 0) revert Errors.ArrayEmpty(); if (receiverYTs.length != length || amountSyToMints.length != length) revert Errors.ArrayLengthMismatch(); uint256 totalSyToMint = amountSyToMints.sum(); if (totalSyToMint > _getFloatingSyAmount()) revert Errors.YieldContractInsufficientSy(totalSyToMint, _getFloatingSyAmount()); amountPYOuts = _mintPY(receiverPTs, receiverYTs, amountSyToMints); } /** * @notice converts PT(+YT) tokens into SY, but interests & rewards are not redeemed at the * same time * @dev PT/YT must be transferred to this contract prior to calling */ function redeemPY(address receiver) external nonReentrant updateData returns (uint256 amountSyOut) { address[] memory receivers = new address[](1); uint256[] memory amounts = new uint256[](1); (receivers[0], amounts[0]) = (receiver, _getAmountPYToRedeem()); uint256[] memory amountSyOuts; amountSyOuts = _redeemPY(receivers, amounts); amountSyOut = amountSyOuts[0]; } /** * @notice redeems PT(+YT) for multiple users. See `redeemPY()` * @dev PT/YT must be transferred to this contract prior to calling * @dev fails if unable to redeem the total PY amount in `amountPYToRedeems` */ function redeemPYMulti( address[] calldata receivers, uint256[] calldata amountPYToRedeems ) external nonReentrant updateData returns (uint256[] memory amountSyOuts) { if (receivers.length != amountPYToRedeems.length) revert Errors.ArrayLengthMismatch(); if (receivers.length == 0) revert Errors.ArrayEmpty(); amountSyOuts = _redeemPY(receivers, amountPYToRedeems); } /** * @notice Redeems interests and rewards for `user` * @param redeemInterest will only transfer out interest for user if true * @param redeemRewards will only transfer out rewards for user if true * @dev With YT yielding interest in the form of SY, which is redeemable by users, the reward * distribution should be based on the amount of SYs that their YT currently represent, plus * their dueInterest. It has been proven and tested that _rewardSharesUser will not change over * time, unless users redeem their dueInterest or redeemPY. Due to this, it is required to * update users' accruedReward STRICTLY BEFORE transferring out their interest. */ function redeemDueInterestAndRewards( address user, bool redeemInterest, bool redeemRewards ) external nonReentrant updateData returns (uint256 interestOut, uint256[] memory rewardsOut) { if (!redeemInterest && !redeemRewards) revert Errors.YCNothingToRedeem(); // if redeemRewards == true, this line must be here for obvious reason // if redeemInterest == true, this line must be here because of the reason above _updateAndDistributeRewards(user); if (redeemRewards) { rewardsOut = _doTransferOutRewards(user, user); emit RedeemRewards(user, rewardsOut); } else { address[] memory tokens = getRewardTokens(); rewardsOut = new uint256[](tokens.length); } if (redeemInterest) { _distributeInterest(user); interestOut = _doTransferOutInterest(user, SY, factory); emit RedeemInterest(user, interestOut); } else { interestOut = 0; } } /** * @dev All rewards and interests accrued post-expiry goes to the treasury. * Reverts if called pre-expiry. */ function redeemInterestAndRewardsPostExpiryForTreasury() external nonReentrant updateData returns (uint256 interestOut, uint256[] memory rewardsOut) { if (!isExpired()) revert Errors.YCNotExpired(); address treasury = IPYieldContractFactory(factory).treasury(); address[] memory tokens = getRewardTokens(); rewardsOut = new uint256[](tokens.length); _redeemExternalReward(); for (uint256 i = 0; i < tokens.length; i++) { rewardsOut[i] = _selfBalance(tokens[i]) - postExpiry.userRewardOwed[tokens[i]]; emit CollectRewardFee(tokens[i], rewardsOut[i]); } _transferOut(tokens, treasury, rewardsOut); interestOut = postExpiry.totalSyInterestForTreasury; postExpiry.totalSyInterestForTreasury = 0; _transferOut(SY, treasury, interestOut); emit CollectInterestFee(interestOut); } /// @notice updates and returns the reward indexes function rewardIndexesCurrent() external override nonReentrant returns (uint256[] memory) { return IStandardizedYield(SY).rewardIndexesCurrent(); } /** * @notice updates and returns the current PY index * @dev this function maximizes the current PY index with the previous index, guaranteeing * non-decreasing PY index * @dev if `doCacheIndexSameBlock` is true, PY index only updates at most once per block, * and has no state changes on the second call onwards (within the same block). * @dev see `pyIndexStored()` for view function for cached value. */ function pyIndexCurrent() public nonReentrant returns (uint256 currentIndex) { currentIndex = _pyIndexCurrent(); } /// @notice returns the last-updated PY index function pyIndexStored() public view returns (uint256) { return _pyIndexStored; } /** * @notice do a final rewards redeeming, and sets post-expiry data * @dev has no effect if called pre-expiry */ function setPostExpiryData() external nonReentrant { if (isExpired()) { _setPostExpiryData(); } } /** * @notice returns the current data post-expiry, if exists * @dev reverts if post-expiry data not set (see `setPostExpiryData()`) * @return firstPYIndex the earliest PY index post-expiry * @return totalSyInterestForTreasury current amount of SY interests post-expiry for treasury * @return firstRewardIndexes the earliest reward indices post-expiry, for each reward token * @return userRewardOwed amount of unclaimed user rewards, for each reward token */ function getPostExpiryData() external view returns ( uint256 firstPYIndex, uint256 totalSyInterestForTreasury, uint256[] memory firstRewardIndexes, uint256[] memory userRewardOwed ) { if (postExpiry.firstPYIndex == 0) revert Errors.YCPostExpiryDataNotSet(); firstPYIndex = postExpiry.firstPYIndex; totalSyInterestForTreasury = postExpiry.totalSyInterestForTreasury; address[] memory tokens = getRewardTokens(); firstRewardIndexes = new uint256[](tokens.length); userRewardOwed = new uint256[](tokens.length); for (uint256 i = 0; i < tokens.length; ++i) { firstRewardIndexes[i] = postExpiry.firstRewardIndex[tokens[i]]; userRewardOwed[i] = postExpiry.userRewardOwed[tokens[i]]; } } function _mintPY( address[] memory receiverPTs, address[] memory receiverYTs, uint256[] memory amountSyToMints ) internal returns (uint256[] memory amountPYOuts) { amountPYOuts = new uint256[](amountSyToMints.length); uint256 index = _pyIndexCurrent(); for (uint256 i = 0; i < amountSyToMints.length; i++) { amountPYOuts[i] = _calcPYToMint(amountSyToMints[i], index); _mint(receiverYTs[i], amountPYOuts[i]); IPPrincipalToken(PT).mintByYT(receiverPTs[i], amountPYOuts[i]); emit Mint(msg.sender, receiverPTs[i], receiverYTs[i], amountSyToMints[i], amountPYOuts[i]); } } function isExpired() public view returns (bool) { return MiniHelpers.isCurrentlyExpired(expiry); } function _redeemPY( address[] memory receivers, uint256[] memory amountPYToRedeems ) internal returns (uint256[] memory amountSyOuts) { uint256 totalAmountPYToRedeem = amountPYToRedeems.sum(); IPPrincipalToken(PT).burnByYT(address(this), totalAmountPYToRedeem); if (!isExpired()) _burn(address(this), totalAmountPYToRedeem); uint256 index = _pyIndexCurrent(); uint256 totalSyInterestPostExpiry; amountSyOuts = new uint256[](receivers.length); for (uint256 i = 0; i < receivers.length; i++) { uint256 syInterestPostExpiry; (amountSyOuts[i], syInterestPostExpiry) = _calcSyRedeemableFromPY(amountPYToRedeems[i], index); _transferOut(SY, receivers[i], amountSyOuts[i]); totalSyInterestPostExpiry += syInterestPostExpiry; emit Burn(msg.sender, receivers[i], amountPYToRedeems[i], amountSyOuts[i]); } if (totalSyInterestPostExpiry != 0) { postExpiry.totalSyInterestForTreasury += totalSyInterestPostExpiry.Uint128(); } } function _calcPYToMint(uint256 amountSy, uint256 indexCurrent) internal pure returns (uint256 amountPY) { // doesn't matter before or after expiry, since mintPY is only allowed before expiry return SYUtils.syToAsset(indexCurrent, amountSy); } function _calcSyRedeemableFromPY( uint256 amountPY, uint256 indexCurrent ) internal view returns (uint256 syToUser, uint256 syInterestPostExpiry) { syToUser = SYUtils.assetToSy(indexCurrent, amountPY); if (isExpired()) { uint256 totalSyRedeemable = SYUtils.assetToSy(postExpiry.firstPYIndex, amountPY); syInterestPostExpiry = totalSyRedeemable - syToUser; } } function _getAmountPYToRedeem() internal view returns (uint256) { if (!isExpired()) return PMath.min(_selfBalance(PT), balanceOf(address(this))); else return _selfBalance(PT); } function _updateSyReserve() internal virtual { syReserve = _selfBalance(SY); } function _getFloatingSyAmount() internal view returns (uint256 amount) { amount = _selfBalance(SY) - syReserve; if (amount == 0) revert Errors.YCNoFloatingSy(); } function _setPostExpiryData() internal { PostExpiryData storage local = postExpiry; if (local.firstPYIndex != 0) return; // already set _redeemExternalReward(); // do a final redeem. All the future reward income will belong to the treasury local.firstPYIndex = _pyIndexCurrent().Uint128(); address[] memory rewardTokens = IStandardizedYield(SY).getRewardTokens(); uint256[] memory rewardIndexes = IStandardizedYield(SY).rewardIndexesCurrent(); for (uint256 i = 0; i < rewardTokens.length; i++) { local.firstRewardIndex[rewardTokens[i]] = rewardIndexes[i]; local.userRewardOwed[rewardTokens[i]] = _selfBalance(rewardTokens[i]); } } /*/////////////////////////////////////////////////////////////// INTEREST-RELATED //////////////////////////////////////////////////////////////*/ function _getInterestIndex() internal virtual override returns (uint256 index) { if (isExpired()) index = postExpiry.firstPYIndex; else index = _pyIndexCurrent(); } function _pyIndexCurrent() internal returns (uint256 currentIndex) { if (doCacheIndexSameBlock && pyIndexLastUpdatedBlock == block.number) return _pyIndexStored; uint128 index128 = PMath.max(IStandardizedYield(SY).exchangeRate(), _pyIndexStored).Uint128(); currentIndex = index128; _pyIndexStored = index128; pyIndexLastUpdatedBlock = uint128(block.number); emit NewInterestIndex(currentIndex); } function _YTbalance(address user) internal view override returns (uint256) { return balanceOf(user); } /*/////////////////////////////////////////////////////////////// REWARDS-RELATED //////////////////////////////////////////////////////////////*/ function getRewardTokens() public view returns (address[] memory) { return IStandardizedYield(SY).getRewardTokens(); } function _doTransferOutRewards( address user, address receiver ) internal virtual override returns (uint256[] memory rewardAmounts) { address[] memory tokens = getRewardTokens(); if (isExpired()) { // post-expiry, all incoming rewards will go to the treasury // hence, we can save users one _redeemExternal here for (uint256 i = 0; i < tokens.length; i++) { uint256 owed = postExpiry.userRewardOwed[tokens[i]]; uint256 accrued = userReward[tokens[i]][user].accrued; postExpiry.userRewardOwed[tokens[i]] = (owed < accrued) ? 0 : owed - accrued; } rewardAmounts = __doTransferOutRewardsLocal(tokens, user, receiver, false); } else { rewardAmounts = __doTransferOutRewardsLocal(tokens, user, receiver, true); } } function __doTransferOutRewardsLocal( address[] memory tokens, address user, address receiver, bool allowedToRedeemExternalReward ) internal returns (uint256[] memory rewardAmounts) { address treasury = IPYieldContractFactory(factory).treasury(); uint256 feeRate = IPYieldContractFactory(factory).rewardFeeRate(); bool redeemExternalThisRound; rewardAmounts = new uint256[](tokens.length); for (uint256 i = 0; i < tokens.length; i++) { uint256 rewardPreFee = userReward[tokens[i]][user].accrued; userReward[tokens[i]][user].accrued = 0; uint256 feeAmount = rewardPreFee.mulDown(feeRate); rewardAmounts[i] = rewardPreFee - feeAmount; if (!redeemExternalThisRound && allowedToRedeemExternalReward) { if (_selfBalance(tokens[i]) < rewardPreFee) { _redeemExternalReward(); redeemExternalThisRound = true; } } _transferOut(tokens[i], treasury, feeAmount); _transferOut(tokens[i], receiver, rewardAmounts[i]); emit CollectRewardFee(tokens[i], feeAmount); } } function _redeemExternalReward() internal virtual override { IStandardizedYield(SY).claimRewards(address(this)); } /// @dev effectively returning the amount of SY generating rewards for this user function _rewardSharesUser(address user) internal view virtual override returns (uint256) { uint256 index = userInterest[user].index; if (index == 0) return 0; return SYUtils.assetToSy(index, balanceOf(user)) + userInterest[user].accrued; } function _updateRewardIndex() internal override returns (address[] memory tokens, uint256[] memory indexes) { tokens = getRewardTokens(); if (isExpired()) { indexes = new uint256[](tokens.length); for (uint256 i = 0; i < tokens.length; i++) indexes[i] = postExpiry.firstRewardIndex[tokens[i]]; } else { indexes = IStandardizedYield(SY).rewardIndexesCurrent(); } } //solhint-disable-next-line ordering function _beforeTokenTransfer(address from, address to, uint256) internal override { if (isExpired()) _setPostExpiryData(); _updateAndDistributeRewardsForTwo(from, to); _distributeInterestForTwo(from, to); } }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; interface IPInterestManagerYT { event CollectInterestFee(uint256 amountInterestFee); function userInterest(address user) external view returns (uint128 lastPYIndex, uint128 accruedInterest); }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; interface IPPrincipalToken is IERC20Metadata { function burnByYT(address user, uint256 amount) external; function mintByYT(address user, uint256 amount) external; function initialize(address _YT) external; function SY() external view returns (address); function YT() external view returns (address); function factory() external view returns (address); function expiry() external view returns (uint256); function isExpired() external view returns (bool); }
// SPDX-License-Identifier: GPL-3.0-or-later /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity ^0.8.0; interface IPYieldContractFactory { event CreateYieldContract(address indexed SY, uint256 indexed expiry, address PT, address YT); event SetExpiryDivisor(uint256 newExpiryDivisor); event SetInterestFeeRate(uint256 newInterestFeeRate); event SetRewardFeeRate(uint256 newRewardFeeRate); event SetTreasury(address indexed treasury); function getPT(address SY, uint256 expiry) external view returns (address); function getYT(address SY, uint256 expiry) external view returns (address); function expiryDivisor() external view returns (uint96); function interestFeeRate() external view returns (uint128); function rewardFeeRate() external view returns (uint128); function treasury() external view returns (address); function isPT(address) external view returns (bool); function isYT(address) external view returns (bool); function createYieldContract( address SY, uint32 expiry, bool doCacheIndexSameBlock ) external returns (address PT, address YT); }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import "./IRewardManager.sol"; import "./IPInterestManagerYT.sol"; interface IPYieldToken is IERC20Metadata, IRewardManager, IPInterestManagerYT { event NewInterestIndex(uint256 indexed newIndex); event Mint( address indexed caller, address indexed receiverPT, address indexed receiverYT, uint256 amountSyToMint, uint256 amountPYOut ); event Burn(address indexed caller, address indexed receiver, uint256 amountPYToRedeem, uint256 amountSyOut); event RedeemRewards(address indexed user, uint256[] amountRewardsOut); event RedeemInterest(address indexed user, uint256 interestOut); event CollectRewardFee(address indexed rewardToken, uint256 amountRewardFee); function mintPY(address receiverPT, address receiverYT) external returns (uint256 amountPYOut); function redeemPY(address receiver) external returns (uint256 amountSyOut); function redeemPYMulti( address[] calldata receivers, uint256[] calldata amountPYToRedeems ) external returns (uint256[] memory amountSyOuts); function redeemDueInterestAndRewards( address user, bool redeemInterest, bool redeemRewards ) external returns (uint256 interestOut, uint256[] memory rewardsOut); function rewardIndexesCurrent() external returns (uint256[] memory); function pyIndexCurrent() external returns (uint256); function pyIndexStored() external view returns (uint256); function getRewardTokens() external view returns (address[] memory); function SY() external view returns (address); function PT() external view returns (address); function factory() external view returns (address); function expiry() external view returns (uint256); function isExpired() external view returns (bool); function doCacheIndexSameBlock() external view returns (bool); function pyIndexLastUpdatedBlock() external view returns (uint128); }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; interface IRewardManager { function userReward(address token, address user) external view returns (uint128 index, uint128 accrued); }
// SPDX-License-Identifier: GPL-3.0-or-later /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; interface IStandardizedYield is IERC20Metadata { /// @dev Emitted when any base tokens is deposited to mint shares event Deposit( address indexed caller, address indexed receiver, address indexed tokenIn, uint256 amountDeposited, uint256 amountSyOut ); /// @dev Emitted when any shares are redeemed for base tokens event Redeem( address indexed caller, address indexed receiver, address indexed tokenOut, uint256 amountSyToRedeem, uint256 amountTokenOut ); /// @dev check `assetInfo()` for more information enum AssetType { TOKEN, LIQUIDITY } /// @dev Emitted when (`user`) claims their rewards event ClaimRewards(address indexed user, address[] rewardTokens, uint256[] rewardAmounts); /** * @notice mints an amount of shares by depositing a base token. * @param receiver shares recipient address * @param tokenIn address of the base tokens to mint shares * @param amountTokenToDeposit amount of base tokens to be transferred from (`msg.sender`) * @param minSharesOut reverts if amount of shares minted is lower than this * @return amountSharesOut amount of shares minted * @dev Emits a {Deposit} event * * Requirements: * - (`tokenIn`) must be a valid base token. */ function deposit( address receiver, address tokenIn, uint256 amountTokenToDeposit, uint256 minSharesOut ) external payable returns (uint256 amountSharesOut); /** * @notice redeems an amount of base tokens by burning some shares * @param receiver recipient address * @param amountSharesToRedeem amount of shares to be burned * @param tokenOut address of the base token to be redeemed * @param minTokenOut reverts if amount of base token redeemed is lower than this * @param burnFromInternalBalance if true, burns from balance of `address(this)`, otherwise burns from `msg.sender` * @return amountTokenOut amount of base tokens redeemed * @dev Emits a {Redeem} event * * Requirements: * - (`tokenOut`) must be a valid base token. */ function redeem( address receiver, uint256 amountSharesToRedeem, address tokenOut, uint256 minTokenOut, bool burnFromInternalBalance ) external returns (uint256 amountTokenOut); /** * @notice exchangeRate * syBalance / 1e18 must return the asset balance of the account * @notice vice-versa, if a user uses some amount of tokens equivalent to X asset, the amount of sy he can mint must be X * exchangeRate / 1e18 * @dev SYUtils's assetToSy & syToAsset should be used instead of raw multiplication & division */ function exchangeRate() external view returns (uint256 res); /** * @notice claims reward for (`user`) * @param user the user receiving their rewards * @return rewardAmounts an array of reward amounts in the same order as `getRewardTokens` * @dev * Emits a `ClaimRewards` event * See {getRewardTokens} for list of reward tokens */ function claimRewards(address user) external returns (uint256[] memory rewardAmounts); /** * @notice get the amount of unclaimed rewards for (`user`) * @param user the user to check for * @return rewardAmounts an array of reward amounts in the same order as `getRewardTokens` */ function accruedRewards(address user) external view returns (uint256[] memory rewardAmounts); function rewardIndexesCurrent() external returns (uint256[] memory indexes); function rewardIndexesStored() external view returns (uint256[] memory indexes); /** * @notice returns the list of reward token addresses */ function getRewardTokens() external view returns (address[] memory); /** * @notice returns the address of the underlying yield token */ function yieldToken() external view returns (address); /** * @notice returns all tokens that can mint this SY */ function getTokensIn() external view returns (address[] memory res); /** * @notice returns all tokens that can be redeemed by this SY */ function getTokensOut() external view returns (address[] memory res); function isValidTokenIn(address token) external view returns (bool); function isValidTokenOut(address token) external view returns (bool); function previewDeposit( address tokenIn, uint256 amountTokenToDeposit ) external view returns (uint256 amountSharesOut); function previewRedeem( address tokenOut, uint256 amountSharesToRedeem ) external view returns (uint256 amountTokenOut); /** * @notice This function contains information to interpret what the asset is * @return assetType the type of the asset (0 for ERC20 tokens, 1 for AMM liquidity tokens, 2 for bridged yield bearing tokens like wstETH, rETH on Arbi whose the underlying asset doesn't exist on the chain) * @return assetAddress the address of the asset * @return assetDecimals the decimals of the asset */ function assetInfo() external view returns (AssetType assetType, address assetAddress, uint8 assetDecimals); }
// SPDX-License-Identifier: GPL-3.0-or-later /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IWETH is IERC20 { event Deposit(address indexed dst, uint256 wad); event Withdrawal(address indexed src, uint256 wad); function deposit() external payable; function withdraw(uint256 wad) external; }
{ "optimizer": { "enabled": true, "runs": 1000000 }, "viaIR": true, "evmVersion": "paris", "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "libraries": {} }
Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
[{"inputs":[{"internalType":"address","name":"_ytCreationCodeContractA","type":"address"},{"internalType":"uint256","name":"_ytCreationCodeSizeA","type":"uint256"},{"internalType":"address","name":"_ytCreationCodeContractB","type":"address"},{"internalType":"uint256","name":"_ytCreationCodeSizeB","type":"uint256"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"uint256","name":"interestFeeRate","type":"uint256"},{"internalType":"uint256","name":"maxInterestFeeRate","type":"uint256"}],"name":"YCFactoryInterestFeeRateTooHigh","type":"error"},{"inputs":[],"name":"YCFactoryInvalidExpiry","type":"error"},{"inputs":[{"internalType":"uint256","name":"newRewardFeeRate","type":"uint256"},{"internalType":"uint256","name":"maxRewardFeeRate","type":"uint256"}],"name":"YCFactoryRewardFeeRateTooHigh","type":"error"},{"inputs":[],"name":"YCFactoryYieldContractExisted","type":"error"},{"inputs":[],"name":"YCFactoryZeroExpiryDivisor","type":"error"},{"inputs":[],"name":"YCFactoryZeroTreasury","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"SY","type":"address"},{"indexed":true,"internalType":"uint256","name":"expiry","type":"uint256"},{"indexed":false,"internalType":"address","name":"PT","type":"address"},{"indexed":false,"internalType":"address","name":"YT","type":"address"}],"name":"CreateYieldContract","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint8","name":"version","type":"uint8"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"newExpiryDivisor","type":"uint256"}],"name":"SetExpiryDivisor","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"newInterestFeeRate","type":"uint256"}],"name":"SetInterestFeeRate","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"newRewardFeeRate","type":"uint256"}],"name":"SetRewardFeeRate","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"treasury","type":"address"}],"name":"SetTreasury","type":"event"},{"inputs":[],"name":"claimOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"SY","type":"address"},{"internalType":"uint32","name":"expiry","type":"uint32"},{"internalType":"bool","name":"doCacheIndexSameBlock","type":"bool"}],"name":"createYieldContract","outputs":[{"internalType":"address","name":"PT","type":"address"},{"internalType":"address","name":"YT","type":"address"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"expiryDivisor","outputs":[{"internalType":"uint96","name":"","type":"uint96"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"}],"name":"getPT","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"}],"name":"getYT","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint96","name":"_expiryDivisor","type":"uint96"},{"internalType":"uint128","name":"_interestFeeRate","type":"uint128"},{"internalType":"uint128","name":"_rewardFeeRate","type":"uint128"},{"internalType":"address","name":"_treasury","type":"address"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"interestFeeRate","outputs":[{"internalType":"uint128","name":"","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"isPT","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"isYT","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxInterestFeeRate","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxRewardFeeRate","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pendingOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"rewardFeeRate","outputs":[{"internalType":"uint128","name":"","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint96","name":"newExpiryDivisor","type":"uint96"}],"name":"setExpiryDivisor","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint128","name":"newInterestFeeRate","type":"uint128"}],"name":"setInterestFeeRate","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint128","name":"newRewardFeeRate","type":"uint128"}],"name":"setRewardFeeRate","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newTreasury","type":"address"}],"name":"setTreasury","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"},{"internalType":"bool","name":"direct","type":"bool"},{"internalType":"bool","name":"renounce","type":"bool"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"treasury","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ytCreationCodeContractA","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ytCreationCodeContractB","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ytCreationCodeSizeA","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ytCreationCodeSizeB","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"}]
Deployed Bytecode
0x608060405260043610156200001357600080fd5b60003560e01c806307274b1914620001c1578063078dfbe714620001bb57806318b7373d14620001b55780632cb5b6c114620001af57806344601d6914620001a95780634e71e0c814620001a3578063586007bc146200019d57806361d027b314620001975780636348cb21146200019157806371846aa8146200018b5780637d39cabf146200018557806387efe5a7146200017f5780638c9f796214620001795780638da5cb5b146200017357806395ce8917146200014f578063a14135f5146200016d578063dd86fea11462000167578063e28a68b61462000161578063e30c3978146200015b578063e9e5f3cf1462000155578063ea938547146200014f578063ebd7cb8a1462000149578063f0f4426014620001435763f5de2d1f146200013d57600080fd5b620017d1565b620016e8565b62001677565b62000e06565b62001636565b620015e2565b62000ef4565b62000ea4565b62000e49565b62000db2565b62000d66565b62000d1a565b62000bc9565b62000b57565b62000992565b6200093e565b62000840565b620006d6565b620005bb565b620004ea565b62000478565b62000272565b620001d8565b6000910312620001d357565b600080fd5b34620001d35760007ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112620001d35760206040517f00000000000000000000000000000000000000000000000000000000000028c68152f35b73ffffffffffffffffffffffffffffffffffffffff811603620001d357565b602435908115158203620001d357565b604435908115158203620001d357565b34620001d35760607ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112620001d357600435620002b18162000233565b620002bb62000252565b90620002c662000262565b9073ffffffffffffffffffffffffffffffffffffffff600093620002ef82865416331462001812565b15620004495781169182159081159162000440575b5015620003e257620003b1916200034c62000333855473ffffffffffffffffffffffffffffffffffffffff1690565b73ffffffffffffffffffffffffffffffffffffffff1690565b7f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08580a373ffffffffffffffffffffffffffffffffffffffff167fffffffffffffffffffffffff00000000000000000000000000000000000000006000541617600055565b620003df7fffffffffffffffffffffffff000000000000000000000000000000000000000060015416600155565b80f35b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601560248201527f4f776e61626c653a207a65726f206164647265737300000000000000000000006044820152fd5b90503862000304565b9150167fffffffffffffffffffffffff0000000000000000000000000000000000000000600154161760015580f35b34620001d35760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112620001d35773ffffffffffffffffffffffffffffffffffffffff600435620004cc8162000233565b166000526036602052602060ff604060002054166040519015158152f35b34620001d35760007ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112620001d357602060405173ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000001785cd0f9d840b3f77533b844aed92fd45d29fda168152f35b600435906fffffffffffffffffffffffffffffffff82168203620001d357565b602435906fffffffffffffffffffffffffffffffff82168203620001d357565b604435906fffffffffffffffffffffffffffffffff82168203620001d357565b34620001d35760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112620001d357620005f66200055b565b6200061b73ffffffffffffffffffffffffffffffffffffffff60005416331462001812565b6fffffffffffffffffffffffffffffffff808216906702c68af0bb1400008083116200069f577f8dfda2f0f14feea9a776359ded0d062934c38098a21d140fcdd9a3dbfb6294c160208486857fffffffffffffffffffffffffffffffff000000000000000000000000000000006032549260801b16911617603255604051908152a1005b82604491604051917f5dbf545100000000000000000000000000000000000000000000000000000000835260048301526024820152fd5b34620001d3576000807ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112620008215773ffffffffffffffffffffffffffffffffffffffff8060015416803303620007c3578062000798928454167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08580a373ffffffffffffffffffffffffffffffffffffffff167fffffffffffffffffffffffff00000000000000000000000000000000000000006000541617600055565b7fffffffffffffffffffffffff00000000000000000000000000000000000000006001541660015580f35b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602060248201527f4f776e61626c653a2063616c6c657220213d2070656e64696e67206f776e65726044820152fd5b80fd5b600435906bffffffffffffffffffffffff82168203620001d357565b34620001d35760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112620001d3576200087b62000824565b73ffffffffffffffffffffffffffffffffffffffff620008a18160005416331462001812565b6bffffffffffffffffffffffff8216801562000914577fdaf60f79a59eb1d8c1748ab26dc83c44f364ce8c1fc497ec2df45d9538a1aa11926020927fffffffffffffffffffffffff00000000000000000000000000000000000000006033549260a01b16911617603355604051908152a1005b60046040517ff2baeb49000000000000000000000000000000000000000000000000000000008152fd5b34620001d35760007ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112620001d357602073ffffffffffffffffffffffffffffffffffffffff60335416604051908152f35b34620001d35760807ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112620001d357620009cd62000824565b62000a6e620009db6200057b565b620009e56200059b565b60643591620009f48362000233565b6001549462000a1d60ff8760a81c16158097819862000b44575b811562000b1e575b506200195a565b8562000a63740100000000000000000000000000000000000000007fffffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffff6001541617600155565b62000ad257620019e6565b62000a7557005b62000aa37fffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffff60015416600155565b604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb384740249890602090a1005b62000b1875010000000000000000000000000000000000000000007fffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffff6001541617600155565b620019e6565b303b1591508162000b32575b503862000a16565b60a01c60ff1660011490503862000b2a565b9050600160ff8260a01c16109062000a0e565b34620001d35760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112620001d35773ffffffffffffffffffffffffffffffffffffffff60043562000bab8162000233565b166000526037602052602060ff604060002054166040519015158152f35b34620001d35760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112620001d3576fffffffffffffffffffffffffffffffff62000c156200055b565b62000c3a73ffffffffffffffffffffffffffffffffffffffff60005416331462001812565b166702c68af0bb14000080821162000ca3577fa9d618683ded3ac7317e1717ad10e9e3b92041092a8e97ceb038c699cc54d640602083807fffffffffffffffffffffffffffffffff000000000000000000000000000000006032541617603255604051908152a1005b90604491604051917f7cc0c73800000000000000000000000000000000000000000000000000000000835260048301526024820152fd5b7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc6040910112620001d35760043562000d138162000233565b9060243590565b34620001d357602062000d2d3662000cda565b73ffffffffffffffffffffffffffffffffffffffff80921660005260348352604060002090600052825260406000205416604051908152f35b34620001d357602062000d793662000cda565b73ffffffffffffffffffffffffffffffffffffffff80921660005260358352604060002090600052825260406000205416604051908152f35b34620001d35760007ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112620001d357602073ffffffffffffffffffffffffffffffffffffffff60005416604051908152f35b34620001d35760007ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112620001d35760206040516702c68af0bb1400008152f35b34620001d35760007ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112620001d35760206040517f00000000000000000000000000000000000000000000000000000000000028c68152f35b34620001d35760007ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112620001d35760206fffffffffffffffffffffffffffffffff60325416604051908152f35b34620001d35760607ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112620001d3576004803562000f348162000233565b60243563ffffffff811691828203620001d35762000f5162000262565b92428111801590620015b3575b6200158a5773ffffffffffffffffffffffffffffffffffffffff948562000fdd62000fc38662000fae8773ffffffffffffffffffffffffffffffffffffffff166000526034602052604060002090565b9063ffffffff16600052602052604060002090565b5473ffffffffffffffffffffffffffffffffffffffff1690565b166200156257858316906040938451967fa40bee500000000000000000000000000000000000000000000000000000000088526060888481875afa978815620014f95760009862001527575b5085517f06fdde030000000000000000000000000000000000000000000000000000000081526000818581885afa8015620014f9576200107391600091620014ff575b50620020d9565b8651907f95d89b410000000000000000000000000000000000000000000000000000000082526000828681895afa8015620014f957620010bf85918c94600091620014ff5750620020d9565b938a8a8a8483611aec9860208a01620010d89062001d66565b99808b526200320660208c0139620010ef62001e42565b8985620010fb62001e7d565b91620011079362002286565b938b6200111362001e42565b916200111e62001eb8565b916200112a9362002286565b94519485946200113e946020870162001f38565b03957fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe096878101835262001173908362001cba565b8c5191829160208301620011879162001f96565b620011929162001f96565b038681018252620011a4908262001cba565b620011b090466200252d565b9c8d94620011bd62001faf565b908c620011c962001e7d565b91620011d59362002286565b96620011e062001faf565b908c620011ec62001eb8565b91620011f89362002286565b8c519788966200120c966020890162001fea565b0390810182526200121e908262001cba565b7f00000000000000000000000000000000000000000000000000000000000028c67f0000000000000000000000001785cd0f9d840b3f77533b844aed92fd45d29fda7f00000000000000000000000000000000000000000000000000000000000028c67f000000000000000000000000ad19ddc04c00c850d502a27d506e9b3986e743c6620012ad9462002815565b620012b990466200252d565b978716803b15620001d35785517fc4d66de800000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff8a1693810193845292600091849182908490829060200103925af1918215620014f957620014d79662000fae8a936200137293620013d896620014db575b50620013b28b620013728562000fae8573ffffffffffffffffffffffffffffffffffffffff166000526034602052604060002090565b9073ffffffffffffffffffffffffffffffffffffffff167fffffffffffffffffffffffff0000000000000000000000000000000000000000825416179055565b73ffffffffffffffffffffffffffffffffffffffff166000526035602052604060002090565b62001432620014078673ffffffffffffffffffffffffffffffffffffffff166000526036602052604060002090565b60017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00825416179055565b62001461620014078773ffffffffffffffffffffffffffffffffffffffff166000526037602052604060002090565b825173ffffffffffffffffffffffffffffffffffffffff8681168252871660208201527faa79d8f17776adeaa316c5411b72e8b0057d064974fa8748f32492ecaa22ecd190604090a35173ffffffffffffffffffffffffffffffffffffffff928316815292909116602083015281906040820190565b0390f35b80620014eb620014f29262001c82565b80620001c7565b386200133c565b62001d38565b6200152091503d806000833e62001517818362001cba565b81019062001dd6565b386200106c565b6200154f91985060603d6060116200155a575b62001546818362001cba565b81019062001cfc565b915050963862001029565b503d6200153a565b6040517fa50d9502000000000000000000000000000000000000000000000000000000008152fd5b846040517f1f687fd0000000000000000000000000000000000000000000000000000000008152fd5b506bffffffffffffffffffffffff620015d9620015d260335460a01c90565b8362001c06565b16151562000f5e565b34620001d35760007ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112620001d357602073ffffffffffffffffffffffffffffffffffffffff60015416604051908152f35b34620001d35760007ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112620001d357602060335460a01c604051908152f35b34620001d35760007ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112620001d357602060405173ffffffffffffffffffffffffffffffffffffffff7f000000000000000000000000ad19ddc04c00c850d502a27d506e9b3986e743c6168152f35b34620001d35760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112620001d357600435620017278162000233565b73ffffffffffffffffffffffffffffffffffffffff906200174e8260005416331462001812565b168015620017a757807fffffffffffffffffffffffff000000000000000000000000000000000000000060335416176033557fcb7ef3e545f5cdb893f5c568ba710fe08f336375a2d9fd66e161033f8fc09ef3600080a2005b60046040517fb8c96731000000000000000000000000000000000000000000000000000000008152fd5b34620001d35760007ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112620001d357602060325460801c604051908152f35b156200181a57565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602060248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e65726044820152fd5b6200189d73ffffffffffffffffffffffffffffffffffffffff60005416331462001812565b6fffffffffffffffffffffffffffffffff90818116916702c68af0bb140000808411620019235750916020917f8dfda2f0f14feea9a776359ded0d062934c38098a21d140fcdd9a3dbfb6294c1937fffffffffffffffffffffffffffffffff000000000000000000000000000000006032549260801b16911617603255604051908152a1565b83604491604051917f5dbf545100000000000000000000000000000000000000000000000000000000835260048301526024820152fd5b156200196257565b60846040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201527f647920696e697469616c697a65640000000000000000000000000000000000006064820152fd5b929160ff60015460a81c161562001aaa577fffffffffffffffffffffffff000000000000000000000000000000000000000091338360005416176000556bffffffffffffffffffffffff851690811562000914577fdaf60f79a59eb1d8c1748ab26dc83c44f364ce8c1fc497ec2df45d9538a1aa11602062001a9c9362001aa89873ffffffffffffffffffffffffffffffffffffffff62001aa2986033549260a01b16911617603355604051908152a162001b2e565b62001878565b62002059565b565b60846040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602b60248201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960448201527f6e697469616c697a696e670000000000000000000000000000000000000000006064820152fd5b6fffffffffffffffffffffffffffffffff9062001b6573ffffffffffffffffffffffffffffffffffffffff60005416331462001812565b166702c68af0bb14000080821162001bcf57506020817fa9d618683ded3ac7317e1717ad10e9e3b92041092a8e97ceb038c699cc54d640927fffffffffffffffffffffffffffffffff000000000000000000000000000000006032541617603255604051908152a1565b60449250604051917f7cc0c73800000000000000000000000000000000000000000000000000000000835260048301526024820152fd5b906bffffffffffffffffffffffff80911691821562001c2457160690565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601260045260246000fd5b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b67ffffffffffffffff811162001c9757604052565b62001c53565b6040810190811067ffffffffffffffff82111762001c9757604052565b90601f7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0910116810190811067ffffffffffffffff82111762001c9757604052565b90816060910312620001d35780516002811015620001d357916040602083015162001d278162000233565b92015160ff81168103620001d35790565b6040513d6000823e3d90fd5b60405190610180820182811067ffffffffffffffff82111762001c9757604052565b9062001aa8604051928362001cba565b67ffffffffffffffff811162001c9757601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe01660200190565b60005b83811062001dc55750506000910152565b818101518382015260200162001db4565b602081830312620001d35780519067ffffffffffffffff8211620001d3570181601f82011215620001d357805162001e0e8162001d76565b9262001e1e604051948562001cba565b81845260208284010111620001d35762001e3f916020808501910162001db1565b90565b6040519062001e518262001c9d565b600282527f50540000000000000000000000000000000000000000000000000000000000006020830152565b6040519062001e8c8262001c9d565b600182527f20000000000000000000000000000000000000000000000000000000000000006020830152565b6040519062001ec78262001c9d565b600182527f2d000000000000000000000000000000000000000000000000000000000000006020830152565b907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0601f60209362001f318151809281875287808801910162001db1565b0116010190565b9395949062001f8960809462001f7a63ffffffff9573ffffffffffffffffffffffffffffffffffffffff60ff9516895260a060208a015260a089019062001ef3565b90878203604089015262001ef3565b9616606085015216910152565b9062001fab6020928281519485920162001db1565b0190565b6040519062001fbe8262001c9d565b600282527f59540000000000000000000000000000000000000000000000000000000000006020830152565b959160c0959897946200203663ffffffff9560ff94620020459473ffffffffffffffffffffffffffffffffffffffff8092168c521660208b015260e060408b015260e08a019062001ef3565b9088820360608a015262001ef3565b971660808601521660a08401521515910152565b73ffffffffffffffffffffffffffffffffffffffff90620020808260005416331462001812565b168015620017a757807fffffffffffffffffffffffff000000000000000000000000000000000000000060335416176033557fcb7ef3e545f5cdb893f5c568ba710fe08f336375a2d9fd66e161033f8fc09ef3600080a2565b620020e49062002636565b6200217f60405191620020f78362001c9d565b6003835262002179620021316020947f53592000000000000000000000000000000000000000000000000000000000008682015262002636565b62002172604051620021438162001c9d565b600381527f53592d00000000000000000000000000000000000000000000000000000000008782015262002636565b9262002795565b62002795565b90815191620021ab620021928462001d76565b93620021a2604051958662001cba565b80855262001d76565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0928481019184013683378083015192519291935b818410156200225557507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff928062002223575b5050518251821691191617905290565b9080929350039081116200224f57620022406200224691620028cc565b6200268f565b90388062002213565b62002660565b929193845181528181018091116200224f57938181018091116200224f57918381019081116200224f5792620021e0565b93919362002293620028dc565b93620022ab620022a38762002faa565b61ffff168652565b6200231d620022db620022d5620022cf620022c8895161ffff1690565b61ffff1690565b62003088565b62002719565b6200231662002310620022ee836200290d565b926200230a620022c8620023048c5161ffff1690565b6200294b565b62002747565b62002922565b9062002787565b9460015b600c60ff82161115620024bc575b5060019660208201965b620023606200235a6200234d8a5160ff1690565b855161ffff1690620030d8565b60ff1690565b60ff8a1611620024955781620023768262002755565b11620023a9576200235a6200234d6200239e62002397620023609462002767565b9b620029b1565b9a9250505062002339565b50506200248195506200243162002488926200243183620023d962001e3f999b60406200243197019060ff169052565b62002438620023fa620023f46200235a604085015160ff1690565b62002ab9565b91620024316200241f620023f4620022c8620024168562002ebf565b945161ffff1690565b91604051988995602087019062001f96565b9062001f96565b03966200246c7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe09889810187528662001cba565b620024316040519a8b9860208a019062001f96565b8462001f96565b0390810183528262001cba565b505062001e3f949650620024819550620024316200248892620024316200243193620023d9565b9695620024e4620024de6200235a620024d7855161ffff1690565b8b620030d8565b62002937565b9087620024f2828462002787565b1162002518576200250f91620025089162002787565b97620029b1565b96959662002321565b60ff909816602083015250389695966200232f565b90805115620025bd576020815191016000f59073ffffffffffffffffffffffffffffffffffffffff8216156200255f57565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601960248201527f437265617465323a204661696c6564206f6e206465706c6f79000000000000006044820152fd5b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602060248201527f437265617465323a2062797465636f6465206c656e677468206973207a65726f6044820152fd5b604051906200262a8262001c9d565b60006020838281520152565b620026406200261b565b50602081519160405192620026558462001c9d565b835201602082015290565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff82019182116200224f57565b907ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe1ecc8082019182116200224f57565b907ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe1d7b0082019182116200224f57565b907ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe2382019182116200224f57565b919082039182116200224f57565b90620151809182018092116200224f57565b906201518082018092116200224f57565b60300190816030116200224f57565b919082018092116200224f57565b90620027a06200261b565b508151908051918281106200280f5760019260208501938451826020860151808303620027fe575b505050620027d8575b5050505090565b81039081116200224f578352519080519182018092116200224f575238808080620027d1565b8192935020912014388281620027c8565b50505090565b906000939594928381019383519086828701996040519a858c9660209b8c998a8a8682809d9881990101604052815201903c8c0101903c920192860101925b808210156200289557907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff91036101000a0190811990511690825116179052565b90919281807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0928651815201940192019062002854565b601f81116200224f576101000a90565b604051906060820182811067ffffffffffffffff82111762001c975760405260006040838281528260208201520152565b906301e2850091808302928304036200224f57565b906301e1338091808302928304036200224f57565b906201518091808302928304036200224f57565b907ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff84e61ffff809316019182116200224f57565b907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff61ffff809316019182116200224f57565b60ff1660ff81146200224f5760010190565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff81146200224f5760010190565b90620029fd8262001d76565b62002a0c604051918262001cba565b8281527fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe062002a3c829462001d76565b0190602036910137565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b90815181101562002a87570160200190565b62002a46565b80156200224f577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0190565b801562002b7b5780600090826000935b62002b6457508062002ae662002adf85620029f1565b946200268f565b915b62002af35750505090565b600a9062002b3362002b0b6200235a84840662002778565b60f81b7fff000000000000000000000000000000000000000000000000000000000000001690565b841a62002b41848762002a75565b538262002b51575b048062002ae8565b9162002b5d9062002a8d565b9162002b49565b9262002b72600a91620029c3565b93048062002ac9565b5060405162002b8a8162001c9d565b600181527f3000000000000000000000000000000000000000000000000000000000000000602082015290565b6040519062002bc68262001c9d565b600382527f4a414e00000000000000000000000000000000000000000000000000000000006020830152565b6040519062002c018262001c9d565b600382527f46454200000000000000000000000000000000000000000000000000000000006020830152565b6040519062002c3c8262001c9d565b600382527f4d415200000000000000000000000000000000000000000000000000000000006020830152565b6040519062002c778262001c9d565b600382527f41505200000000000000000000000000000000000000000000000000000000006020830152565b6040519062002cb28262001c9d565b600382527f4d415900000000000000000000000000000000000000000000000000000000006020830152565b6040519062002ced8262001c9d565b600382527f4a554e00000000000000000000000000000000000000000000000000000000006020830152565b6040519062002d288262001c9d565b600382527f4a554c00000000000000000000000000000000000000000000000000000000006020830152565b6040519062002d638262001c9d565b600382527f41554700000000000000000000000000000000000000000000000000000000006020830152565b6040519062002d9e8262001c9d565b600382527f53455000000000000000000000000000000000000000000000000000000000006020830152565b6040519062002dd98262001c9d565b600382527f4f435400000000000000000000000000000000000000000000000000000000006020830152565b6040519062002e148262001c9d565b600382527f4e4f5600000000000000000000000000000000000000000000000000000000006020830152565b6040519062002e4f8262001c9d565b600382527f44454300000000000000000000000000000000000000000000000000000000006020830152565b60ff7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff9116019060ff82116200224f57565b90600c81101562002a875760051b0190565b62002fa69062002f9f6200235a62002f99602062002edc62001d44565b9462002ee762002bb7565b865262002ef362002bf2565b8287015262002f0162002c2d565b604087015262002f1062002c68565b606087015262002f1f62002ca3565b608087015262002f2e62002cde565b60a087015262002f3d62002d19565b60c087015262002f4c62002d54565b60e087015262002f5b62002d8f565b61010087015262002f6b62002dca565b61012087015262002f7b62002e05565b61014087015262002f8b62002e40565b610160870152015160ff1690565b62002e7b565b9062002ead565b5190565b6107b2906301e13380810482018092116200224f5761ffff8092169162002fd18362003088565b907ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe2382018281116200224f576200300b6101dd916200290d565b9162003017866200294b565b16928303019182116200224f5762002316620030369294939462002922565b828111620030445750905090565b62003076906200305e62003058846200297e565b620031c7565b156200307d576200306f90620026eb565b916200297e565b9062003036565b6200306f90620026bd565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff81019081116200224f578060021c906064810482039182116200224f57610190900481018091116200224f5790565b60ff16600181148015620031bc575b8015620031b1575b8015620031a6575b80156200319b575b801562003190575b801562003185575b156200311c575050601f90565b6004811490811562003179575b81156200316d575b811562003161575b5015620031465750601e90565b6200315190620031c7565b156200315c57601d90565b601c90565b600b9150143862003139565b60098114915062003131565b60068114915062003129565b50600c81146200310f565b50600a811462003107565b5060088114620030ff565b5060078114620030f7565b5060058114620030ef565b5060038114620030e7565b60038116159081620031f0575b8115620031df575090565b905061019061ffff80921606161590565b905061ffff60648183160616151590620031d456fe61010060405234620003a25762001aec803803806200001e81620003a7565b92833981019060a081830312620003a2578051906001600160a01b0382168203620003a2576020818101516001600160401b039490858111620003a2578162000069918501620003cd565b90604084015190868211620003a25762000085918501620003cd565b9460608401519360ff85168503620003a25760800151958251828111620002a2576003918254916001958684811c9416801562000397575b8885101462000381578190601f948581116200032b575b508890858311600114620002c457600092620002b8575b505060001982861b1c191690861b1783555b8051938411620002a25760049586548681811c9116801562000297575b82821014620002825783811162000237575b5080928511600114620001c95750938394918492600095620001bd575b50501b92600019911b1c19161790555b608052600280546001600160f81b0316600160f81b17905560a05260e0523360c0526040516116ac908162000440823960805181610b2f015260a05181610750015260c0518181816102510152610469015260e0518181816101140152610b8a0152f35b01519350388062000149565b92919084601f1981168860005285600020956000905b898383106200021c575050501062000201575b50505050811b01905562000159565b01519060f884600019921b161c1916905538808080620001f2565b858701518955909701969485019488935090810190620001df565b87600052816000208480880160051c82019284891062000278575b0160051c019087905b8281106200026b5750506200012c565b600081550187906200025b565b9250819262000252565b602288634e487b7160e01b6000525260246000fd5b90607f16906200011a565b634e487b7160e01b600052604160045260246000fd5b015190503880620000eb565b90889350601f19831691876000528a6000209260005b8c828210620003145750508411620002fb575b505050811b018355620000fd565b015160001983881b60f8161c19169055388080620002ed565b8385015186558c97909501949384019301620002da565b90915085600052886000208580850160051c8201928b861062000377575b918a91869594930160051c01915b82811062000367575050620000d4565b600081558594508a910162000357565b9250819262000349565b634e487b7160e01b600052602260045260246000fd5b93607f1693620000bd565b600080fd5b6040519190601f01601f191682016001600160401b03811183821017620002a257604052565b919080601f84011215620003a25782516001600160401b038111620002a25760209062000403601f8201601f19168301620003a7565b92818452828287010111620003a25760005b8181106200042b57508260009394955001015290565b85810183015184820184015282016200041556fe608060408181526004918236101561001657600080fd5b600092833560e01c91826306fdde0314610ff457508163095ea7b314610fa557816312a31dcc14610ddd57816318160ddd14610d7f57816323b872dd14610baf5781632f13b60c14610b53578163313ce56714610af757816370a0823114610a96578163781c18db14610a4057816395d89b4114610848578163a9059cbb14610774578163afd27bf514610705578163b64761f91461048d578163c45a01551461041e578163c4d66de8146101ae57508063dd62ed3e1461013b5763e184c9be146100e057600080fd5b3461013757817ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261013757602090517f00000000000000000000000000000000000000000000000000000000000000008152f35b5080fd5b503461013757807ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610137578060209261017661119a565b61017e6111c2565b73ffffffffffffffffffffffffffffffffffffffff91821683526001865283832091168252845220549051908152f35b9190503461041a5760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261041a576101e861119a565b90600580549360ff8560081c16159485809661040d575b80156103f6575b15610373578560017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff008316178455610345575b5073ffffffffffffffffffffffffffffffffffffffff7f000000000000000000000000000000000000000000000000000000000000000016330361031e575075ffffffffffffffffffffffffffffffffffffffff000081549360101b1693847fffffffffffffffffffff0000000000000000000000000000000000000000ffff85161782556102c6578480f35b7f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb3847402498937fffffffffffffffffffff000000000000000000000000000000000000000000ff602094161790555160018152a1388080808480f35b82517ffe108173000000000000000000000000000000000000000000000000000000008152fd5b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00001661010117825538610239565b60848260208651917f08c379a0000000000000000000000000000000000000000000000000000000008352820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201527f647920696e697469616c697a65640000000000000000000000000000000000006064820152fd5b50303b1580156102065750600160ff821614610206565b50600160ff8216106101ff565b8280fd5b50503461013757817ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610137576020905173ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000168152f35b83833461013757807ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610137576104c561119a565b6024359073ffffffffffffffffffffffffffffffffffffffff908160055460101c1633036106dd571691821561065b5782845283602052808420548281106105d85782908486528560205203818520557effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8083116105d45760025490808416818316038181116105a857926020927fff00000000000000000000000000000000000000000000000000000000000000889796937fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef961691161760025551908152a380f35b60248760118a7f4e487b7100000000000000000000000000000000000000000000000000000000835252fd5b8480fd5b60848660208451917f08c379a0000000000000000000000000000000000000000000000000000000008352820152602260248201527f45524332303a206275726e20616d6f756e7420657863656564732062616c616e60448201527f63650000000000000000000000000000000000000000000000000000000000006064820152fd5b517f08c379a0000000000000000000000000000000000000000000000000000000008152602081860152602160248201527f45524332303a206275726e2066726f6d20746865207a65726f2061646472657360448201527f73000000000000000000000000000000000000000000000000000000000000006064820152608490fd5b8584517fb114ba98000000000000000000000000000000000000000000000000000000008152fd5b50503461013757817ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610137576020905173ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000168152f35b50503461013757807ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610137576020907f01000000000000000000000000000000000000000000000000000000000000006107d061119a565b610839600254916107e760028460f81c14156111e5565b7f02000000000000000000000000000000000000000000000000000000000000007effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8094161760025560243590336113fb565b60025416176002555160018152f35b83833461013757817ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101375780519082845460018160011c9060018316928315610a36575b6020938484108114610a0a5783885287959493929181156109af5750600114610933575b50505003601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe01682019267ffffffffffffffff8411838510176109075750829182610903925282611134565b0390f35b806041867f4e487b71000000000000000000000000000000000000000000000000000000006024945252fd5b8888529193925086917f8a35acfbc15ff81a39ae7d344fd709f28e8600b4aa8c65c6b64bfe7fe36bd19b5b82841061099957505050907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe092601f928201019181936108b5565b805488850187015287945092850192810161095e565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0016848701525050151560051b830101905081601f7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe06108b5565b60248960228c7f4e487b7100000000000000000000000000000000000000000000000000000000835252fd5b91607f1691610891565b50503461013757817ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101375760209073ffffffffffffffffffffffffffffffffffffffff60055460101c169051908152f35b5050346101375760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610137578060209273ffffffffffffffffffffffffffffffffffffffff610ae861119a565b16815280845220549051908152f35b50503461013757817ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610137576020905160ff7f0000000000000000000000000000000000000000000000000000000000000000168152f35b50503461013757817ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101375760209051427f000000000000000000000000000000000000000000000000000000000000000011158152f35b839150346101375760607ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261013757610be961119a565b610bf16111c2565b90604435928560025495610c0b60028860f81c14156111e5565b7f02000000000000000000000000000000000000000000000000000000000000007effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8098161760025573ffffffffffffffffffffffffffffffffffffffff8416815260016020528181203382526020522054907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8203610cd5575b6020877f0100000000000000000000000000000000000000000000000000000000000000886108398989896113fb565b848210610d22575092602095949261083992610d15837f01000000000000000000000000000000000000000000000000000000000000009703338361124a565b9250929495819450610ca5565b60649060208851917f08c379a0000000000000000000000000000000000000000000000000000000008352820152601d60248201527f45524332303a20696e73756666696369656e7420616c6c6f77616e63650000006044820152fd5b50503461013757817ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610137576020907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff600254169051908152f35b9190503461041a57807ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261041a57610e1661119a565b906024359173ffffffffffffffffffffffffffffffffffffffff908160055460101c163303610f7d5716928315610f21577effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff808411610f1d57600254918185168284160190828211610ef15750926020927fff000000000000000000000000000000000000000000000000000000000000008896937fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9616911617600255858552848352808520610ee78382546113bf565b905551908152a380f35b8760116024927f4e487b7100000000000000000000000000000000000000000000000000000000835252fd5b8580fd5b602060649251917f08c379a0000000000000000000000000000000000000000000000000000000008352820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f2061646472657373006044820152fd5b8483517fb114ba98000000000000000000000000000000000000000000000000000000008152fd5b50503461013757807ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261013757602090610fed610fe361119a565b602435903361124a565b5160018152f35b8490843461041a57827ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261041a578260035460018160011c906001831692831561112a575b6020938484108114610a0a5783885287959493929181156109af57506001146110ad5750505003601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe01682019267ffffffffffffffff8411838510176109075750829182610903925282611134565b600388529193925086917fc2575a0e9e593c00f959f8c92f12db2869c3395a3b0502d05e2516446f71f85b5b82841061111457505050907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe092601f928201019181936108b5565b80548885018701528794509285019281016110d9565b91607f169161103c565b60208082528251818301819052939260005b858110611186575050507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0601f8460006040809697860101520116010190565b818101830151848201604001528201611146565b6004359073ffffffffffffffffffffffffffffffffffffffff821682036111bd57565b600080fd5b6024359073ffffffffffffffffffffffffffffffffffffffff821682036111bd57565b156111ec57565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c006044820152fd5b73ffffffffffffffffffffffffffffffffffffffff80911691821561133c57169182156112b85760207f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925918360005260018252604060002085600052825280604060002055604051908152a3565b60846040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602260248201527f45524332303a20617070726f766520746f20746865207a65726f20616464726560448201527f73730000000000000000000000000000000000000000000000000000000000006064820152fd5b60846040517f08c379a0000000000000000000000000000000000000000000000000000000008152602060048201526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f2061646460448201527f72657373000000000000000000000000000000000000000000000000000000006064820152fd5b919082018092116113cc57565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b73ffffffffffffffffffffffffffffffffffffffff8091169182156115f2571691821561156e578282146115105760008281528060205260408120549180831061148c57604082827fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9587602096528286520382822055868152206114818282546113bf565b9055604051908152a3565b60846040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602660248201527f45524332303a207472616e7366657220616d6f756e742065786365656473206260448201527f616c616e636500000000000000000000000000000000000000000000000000006064820152fd5b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601760248201527f45524332303a207472616e7366657220746f2073656c660000000000000000006044820152fd5b60846040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602360248201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260448201527f65737300000000000000000000000000000000000000000000000000000000006064820152fd5b60846040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602560248201527f45524332303a207472616e736665722066726f6d20746865207a65726f20616460448201527f64726573730000000000000000000000000000000000000000000000000000006064820152fdfea2646970667358221220bf2c0f35808c300608026574f80fd478d545892daccfdf669960428c1e28adc264736f6c63430008180033a26469706673582212203439b503cc8b860a5deae505d77cde44f5c9e125c2e198b4a76cd48c3b21fd7d64736f6c63430008180033
Loading...
Loading
Loading...
Loading
Multichain Portfolio | 30 Chains
Chain | Token | Portfolio % | Price | Amount | Value |
---|
Loading...
Loading
[ Download: CSV Export ]
[ Download: CSV Export ]
A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.