Source Code
| Transaction Hash |
|
Block
|
From
|
To
|
|||||
|---|---|---|---|---|---|---|---|---|---|
Advanced mode: Intended for advanced users or developers and will display all Internal Transactions including zero value transfers.
Latest 5 internal transactions
Advanced mode:
Cross-Chain Transactions
Loading...
Loading
Contract Name:
TwoCryptoDeployer
Compiler Version
v0.8.24+commit.e11b9ed9
Optimization Enabled:
Yes with 1 runs
Other Settings:
cancun EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.19;
import {EIP5095} from "../../interfaces/EIP5095.sol";
import {IPoolDeployer} from "../../interfaces/IPoolDeployer.sol";
import {TwoCryptoNGParams} from "../../Types.sol";
import {TokenNameLib} from "../../utils/TokenNameLib.sol";
import {Errors} from "../../Errors.sol";
type TwoCryptoFactory is address;
/// @notice Wrapper for TwoCryptoFactory
/// @dev Separate external library to downsize Factory contract.
contract TwoCryptoDeployer is IPoolDeployer {
/// @notice https://etherscan.io/address/0x98EE851a00abeE0d95D08cF4CA2BdCE32aeaAF7F
TwoCryptoFactory public immutable factory;
uint256 constant IMPLEMENTATION_IDX = 0;
bytes4 constant DEPLOY_SELECTOR = 0xc955fa04;
constructor(address _factory) {
factory = TwoCryptoFactory.wrap(_factory);
}
function deploy(address underlying, address principalToken, bytes calldata params)
external
payable
returns (address)
{
bytes memory data = _encodeDeployData(underlying, principalToken, params);
(bool success, bytes memory ret) = TwoCryptoFactory.unwrap(factory).call(data);
if (!success) revert Errors.PoolDeployer_FailedToDeployPool();
return abi.decode(ret, (address));
}
function _encodeDeployData(address underlying, address principalToken, bytes calldata params)
internal
view
returns (bytes memory)
{
uint256 maturity = EIP5095(principalToken).maturity();
/// Note: There is a limit on the length of the name and symbol of TwoCrypto LP token.
/// Too long name and symbol cause deployment to fail.
string memory name = TokenNameLib.lpTokenName(underlying, maturity);
string memory symbol = TokenNameLib.lpTokenSymbol(underlying, maturity);
return abi.encodeWithSelector(
DEPLOY_SELECTOR,
name,
symbol,
[underlying, principalToken],
IMPLEMENTATION_IDX,
// Avoid stack too deep error by passing params as a struct instead of individual parameters
// Note: the order of members in the struct must match the order of the parameters in the function
abi.decode(params, (TwoCryptoNGParams))
);
}
}// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
/// @notice Principal tokens (zero-coupon tokens) are redeemable for a single underlying EIP-20 token at a future timestamp.
/// https://eips.ethereum.org/EIPS/eip-5095
interface EIP5095 {
/// @dev We think EIP-5095 `Redeem` event lacks `by` and `principal` fields.
/// So we emit our own `Redeem` event instead of EIP-5095 `Redeem` event.
event Redeem(address indexed owner, address indexed receiver, uint256 underlyings);
/// @notice The address of the underlying token used by the Principal Token for accounting, and redeeming.
function underlying() external view returns (address);
/// @notice The unix timestamp (uint256) at or after which Principal Tokens can be redeemed for their underlying deposit.
function maturity() external view returns (uint256 timestamp);
/// @notice The amount of underlying that would be exchanged for the amount of PTs provided, in an ideal scenario where all the conditions are met.
/// @notice Before maturity, the amount of underlying returned is as if the PTs would be at maturity.
/// @notice MUST NOT be inclusive of any fees that are charged against redemptions.
/// @notice MUST NOT show any variations depending on the caller.
/// @notice MUST NOT reflect slippage or other on-chain conditions, when performing the actual redemption.
/// @notice MUST NOT revert unless due to integer overflow caused by an unreasonably large input.
/// @notice MUST round down towards 0.
/// @notice This calculation MAY NOT reflect the “per-user” price-per-principal-token, and instead should reflect the “average-user’s” price-per-principal-token, meaning what the average user should expect to see when exchanging to and from.
function convertToUnderlying(uint256 principal) external view returns (uint256 underlyings);
/// @notice The amount of principal tokens that the principal token contract would request for redemption in order to provide the amount of underlying specified, in an ideal scenario where all the conditions are met.
/// @notice MUST NOT be inclusive of any fees.
/// @notice MUST NOT show any variations depending on the caller.
/// @notice MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
/// @notice MUST NOT revert unless due to integer overflow caused by an unreasonably large input.
/// @notice MUST round down towards 0.
/// @notice This calculation MAY NOT reflect the “per-user” price-per-principal-token, and instead should reflect the “average-user’s” price-per-principal-token, meaning what the average user should expect to see when redeeming.
function convertToPrincipal(uint256 underlyings) external view returns (uint256 principal);
/// @notice Maximum amount of principal tokens that can be redeemed from the holder balance, through a redeem call.
/// @notice MUST return the maximum amount of principal tokens that could be transferred from holder through redeem and not cause a revert, which MUST NOT be higher than the actual maximum that would be accepted (it should underestimate if necessary).
/// @notice MUST factor in both global and user-specific limits, like if redemption is entirely disabled (even temporarily) it MUST return 0.
/// @notice MUST NOT revert.
function maxRedeem(address owner) external view returns (uint256);
/// @notice Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block, given current on-chain conditions.
/// @notice MUST return as close to and no more than the exact amount of underliyng that would be obtained in a redeem call in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the same transaction.
/// @notice MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the redemption would be accepted, regardless if the user has enough principal tokens, etc.
/// @notice MUST be inclusive of redemption fees. Integrators should be aware of the existence of redemption fees.
/// @notice MUST NOT revert due to principal token contract specific user/global limits. MAY revert due to other conditions that would also cause redeem to revert.
/// Note that any unfavorable discrepancy between convertToUnderlying and previewRedeem SHOULD be considered slippage in price-per-principal-token or some other type of condition.
function previewRedeem(uint256 principal) external view returns (uint256 underlyings);
/// @notice At or after maturity, burns exactly principal of Principal Tokens from from and sends assets of underlying tokens to to.
/// @notice Interfaces and other contracts MUST NOT expect fund custody to be present. While custodial redemption of Principal Tokens through the Principal Token contract is extremely useful for integrators, some protocols may find giving the Principal Token itself custody breaks their backwards compatibility.
/// @notice MUST emit the Redeem event.
/// @notice MUST support a redeem flow where the Principal Tokens are burned from holder directly where holder is msg.sender or msg.sender has EIP-20 approval over the principal tokens of holder. MAY support an additional flow in which the principal tokens are transferred to the Principal Token contract before the redeem execution, and are accounted for during redeem.
/// @notice MUST revert if all of principal cannot be redeemed (due to withdrawal limit being reached, slippage, the holder not having enough Principal Tokens, etc).
/// @notice Note that some implementations will require pre-requesting to the Principal Token before a withdrawal may be performed. Those methods should be performed separately.
function redeem(uint256 principal, address receiver, address owner) external returns (uint256 underlyings);
/// @notice Maximum amount of the underlying asset that can be redeemed from the holder principal token balance, through a withdraw call.
function maxWithdraw(address owner) external view returns (uint256 underlyings);
/// @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block, given current on-chain conditions.
function previewWithdraw(uint256 underlyings) external view returns (uint256 principal);
/// @notice Burns principal from holder and sends exactly assets of underlying tokens to receiver.
/// @notice MUST emit the Redeem event.
/// @notice MUST support a withdraw flow where the principal tokens are burned from holder directly where holder is msg.sender or msg.sender has EIP-20 approval over the principal tokens of holder. MAY support an additional flow in which the principal tokens are transferred to the principal token contract before the withdraw execution, and are accounted for during withdraw.
/// @notice MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the holder not having enough principal tokens, etc).
/// @notice Note that some implementations will require pre-requesting to the principal token contract before a withdrawal may be performed. Those methods should be performed separately.
function withdraw(uint256 underlyings, address receiver, address owner) external returns (uint256 principal);
}// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.10;
/// @notice Standard interface for deploying pools
interface IPoolDeployer {
function deploy(address target, address principalToken, bytes calldata initArgs)
external
payable
returns (address);
}// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.24;
import "./types/Token.sol" as TokenType;
import "./types/FeePcts.sol" as FeePctsType;
import "./types/ApproxValue.sol" as ApproxValueType;
import "./types/TwoCrypto.sol" as TwoCryptoType;
import "./types/ModuleIndex.sol" as ModuleIndexType;
/// The `FeePcts` type is 256 bits long, and packs the following:
///
/// ```
/// | [uint176]: reserved for future use
/// | | [uint16]: postSettlementFeePct
/// | ↓ | [uint16]: redemptionFeePct
/// | ↓ ↓ | [uint16]: performanceFeePct
/// | ↓ ↓ ↓ | [uint16]: issuanceFeePct
/// | ↓ ↓ ↓ ↓ ↓ [uint16]: splitPctBps
/// 0x00000000000000000000000000000000000000000000AAAABBBBCCCCDDDDEEEE
/// ```
type FeePcts is uint256;
using {FeePctsType.unwrap} for FeePcts global;
/// The `ApproxValue` type represents an approximate value from off-chain sources or `Quoter` contract.
type ApproxValue is uint256;
using {ApproxValueType.unwrap} for ApproxValue global;
/// The `Token` type represents an ERC20 token address or the native token address (0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE).
/// Zap contracts use this type to represent tokens in the system.
/// It's main purpose is to provide a type-safe way to represent tokens in the system.
/// ```
/// function supply(address token, address receiver) public payable {
/// SafeTransferLib.safeTransferFromAll(token, receiver); // ❌ Compiler can't find bug.
/// }
///
/// function supply(Token token, address receiver) public payable {
/// SafeTransferLib.safeTransferFromAll(token, receiver); // 👌 Compiler can notice something wrong.
/// }
/// ```
type Token is address;
using {TokenType.unwrap} for Token global;
using {TokenType.erc20} for Token global;
using {TokenType.isNative} for Token global;
using {TokenType.isNotNative} for Token global;
using {TokenType.eq} for Token global;
/// The `TwoCrypto` type represents a Curve finance twocrypto-ng pool (LP token) address not old twocrypto implementation.
type TwoCrypto is address;
using {TwoCryptoType.unwrap} for TwoCrypto global;
struct TwoCryptoNGParams {
uint256 A;
uint256 gamma;
uint256 mid_fee;
uint256 out_fee;
uint256 fee_gamma;
uint256 allowed_extra_profit;
uint256 adjustment_step;
uint256 ma_time;
uint256 initial_price;
}
/// @dev Do not change the order of the enum
// Do not prepend new fee parameters to the enum, as it will break the compatibility with the existing deployments
enum FeeParameters {
FEE_SPLIT_RATIO, // The fee % going to curator. The rest goes to Napier treasury
ISSUANCE_FEE, // The fee % charged on issuance of PT/YT
PERFORMANCE_FEE, // The fee % charged on the interest made by YT
REDEMPTION_FEE, // The fee % charged on redemption of PT/YT
POST_SETTLEMENT_FEE // The fee % charged on performance fee after settlement
}
/// @notice The `TokenReward` struct represents a additional reward token like COMP, AAVE, etc and the amount of reward.
struct TokenReward {
address token;
uint256 amount;
}
using {ModuleIndexType.unwrap} for ModuleIndex global;
using {ModuleIndexType.isSupportedByFactory} for ModuleIndex global;
using {ModuleIndexType.eq as ==} for ModuleIndex global;
/// The `ModuleIndex` type represents a unique index for each module in the system.
type ModuleIndex is uint256;
ModuleIndex constant FEE_MODULE_INDEX = ModuleIndex.wrap(0);
ModuleIndex constant REWARD_PROXY_MODULE_INDEX = ModuleIndex.wrap(1);
ModuleIndex constant VERIFIER_MODULE_INDEX = ModuleIndex.wrap(2);
uint256 constant MAX_MODULES = 3;
/// @dev Do not change the order of the enum
/// @dev Verification status codes in the system for the `VerifierModule`.
enum VerificationStatus {
InvalidArguments, // Unexpected error
Success,
SupplyMoreThanMax,
Restricted,
InvalidSelector
}// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.10;
import {MetadataReaderLib} from "solady/src/utils/MetadataReaderLib.sol";
import {DateTimeLib} from "solady/src/utils/DateTimeLib.sol";
import {LibString} from "solady/src/utils/LibString.sol";
/// @dev Inputs `expiry` that exceed maximum timestamp results in undefined behavior.
library TokenNameLib {
using LibString for uint256;
string constant PY_NAME_PREFIX = "NapierV2-";
function principalTokenName(address target, uint256 expiry) internal view returns (string memory) {
string memory underlyingName = MetadataReaderLib.readName(target);
return string.concat(PY_NAME_PREFIX, "PT-", underlyingName, "@", expiryToDate(expiry));
}
function principalTokenSymbol(address target, uint256 expiry) internal view returns (string memory) {
string memory underlyingSymbol = MetadataReaderLib.readSymbol(target);
return string.concat("PT-", underlyingSymbol, "@", expiryToDate(expiry));
}
function yieldTokenName(address target, uint256 expiry) internal view returns (string memory) {
string memory underlyingName = MetadataReaderLib.readName(target);
return string.concat(PY_NAME_PREFIX, "YT-", underlyingName, "@", expiryToDate(expiry));
}
function yieldTokenSymbol(address target, uint256 expiry) internal view returns (string memory) {
string memory underlyingSymbol = MetadataReaderLib.readSymbol(target);
return string.concat("YT-", underlyingSymbol, "@", expiryToDate(expiry));
}
function lpTokenName(address target, uint256 expiry) internal view returns (string memory) {
string memory underlyingName = MetadataReaderLib.readName(target);
return string.concat("NapierV2-PT/", underlyingName, "@", expiryToDate(expiry));
}
function lpTokenSymbol(address target, uint256 expiry) internal view returns (string memory) {
string memory underlyingSymbol = MetadataReaderLib.readSymbol(target);
return string.concat("NPR-PT/", underlyingSymbol, "@", expiryToDate(expiry));
}
function expiryToDate(uint256 expiry) internal pure returns (string memory) {
(uint256 year, uint256 month, uint256 day) = DateTimeLib.timestampToDate(expiry);
return string.concat(day.toString(), "/", month.toString(), "/", year.toString());
}
}// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.10;
library Errors {
error AccessManaged_Restricted();
error Expired();
error NotExpired();
error PrincipalToken_NotFactory();
error PrincipalToken_VerificationFailed(uint256 code);
error PrincipalToken_CollectRewardFailed();
error PrincipalToken_NotApprovedCollector();
error PrincipalToken_OnlyYieldToken();
error PrincipalToken_InsufficientSharesReceived();
error PrincipalToken_UnderlyingTokenBalanceChanged();
error PrincipalToken_Unstoppable();
error PrincipalToken_ProtectedToken();
error YieldToken_OnlyPrincipalToken();
// Module
error Module_CallFailed();
// FeeModule
error FeeModule_InvalidFeeParam();
error FeeModule_SplitFeeExceedsMaximum();
error FeeModule_SplitFeeMismatchDefault();
error FeeModule_SplitFeeTooLow();
error FeeModule_IssuanceFeeExceedsMaximum();
error FeeModule_PerformanceFeeExceedsMaximum();
error FeeModule_RedemptionFeeExceedsMaximum();
error FeeModule_PostSettlementFeeExceedsMaximum();
// RewardProxy
error RewardProxy_InconsistentRewardTokens();
error Factory_ModuleNotFound();
error Factory_InvalidExpiry();
error Factory_InvalidPoolDeployer();
error Factory_InvalidModule();
error Factory_FeeModuleRequired();
error Factory_PrincipalTokenNotFound();
error Factory_InvalidModuleType();
error Factory_InvalidAddress();
error Factory_InvalidSuite();
error Factory_CannotUpdateFeeModule();
error Factory_InvalidDecimals();
error PoolDeployer_FailedToDeployPool();
error Zap_LengthMismatch();
error Zap_TransactionTooOld();
error Zap_BadTwoCrypto();
error Zap_BadPrincipalToken();
error Zap_BadCallback();
error Zap_InconsistentETHReceived();
error Zap_InsufficientETH();
error Zap_InsufficientPrincipalOutput();
error Zap_InsufficientTokenOutput();
error Zap_InsufficientUnderlyingOutput();
error Zap_InsufficientYieldTokenOutput();
error Zap_InsufficientPrincipalTokenOutput();
error Zap_DebtExceedsUnderlyingReceived();
error Zap_PullYieldTokenGreaterThanInput();
error Zap_BadPoolDeployer();
// Resolver errors
error Resolver_ConversionFailed();
error Resolver_InvalidDecimals();
error Resolver_ZeroAddress();
// VaultConnectorRegistry errors
error VCRegistry_ConnectorNotFound();
// ERC4626Connector errors
error ERC4626Connector_InvalidToken();
error ERC4626Connector_InvalidETHAmount();
error ERC4626Connector_UnexpectedETH();
// WrapperConnector errors
error WrapperConnector_InvalidETHAmount();
error WrapperConnector_UnexpectedETH();
// WrapperFactory errors
error WrapperFactory_ImplementationNotSet();
// Quoter errors
error Quoter_ERC4626FallbackCallFailed();
error Quoter_ConnectorInvalidToken();
error Quoter_InsufficientUnderlyingOutput();
error Quoter_MaximumYtOutputReached();
// ConversionLib errors
error ConversionLib_NegativeYtPrice();
// AggregationRouter errors
error AggregationRouter_UnsupportedRouter();
error AggregationRouter_SwapFailed();
error AggregationRouter_ZeroReturn();
error AggregationRouter_InvalidMsgValue();
// DefaultConnectorFactory errors
error DefaultConnectorFactory_TargetNotERC4626();
error DefaultConnectorFactory_InvalidToken();
// Lens errors
error Lens_LengthMismatch();
// ERC4626Wrapper errors
error ERC4626Wrapper_TokenNotListed();
}// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.24;
import {ERC20} from "solady/src/tokens/ERC20.sol";
import {Token} from "../Types.sol";
import {NATIVE_ETH} from "../Constants.sol";
function unwrap(Token x) pure returns (address result) {
result = Token.unwrap(x);
}
function erc20(Token token) pure returns (ERC20 result) {
result = ERC20(Token.unwrap(token));
}
function isNative(Token x) pure returns (bool result) {
result = Token.unwrap(x) == NATIVE_ETH;
}
function isNotNative(Token x) pure returns (bool result) {
result = Token.unwrap(x) != NATIVE_ETH;
}
function eq(Token token0, address token1) pure returns (bool result) {
result = Token.unwrap(token0) == token1;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* Utils For Test */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
function intoToken(address token) pure returns (Token result) {
result = Token.wrap(token);
}// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.24;
import {FeePcts} from "../Types.sol";
function unwrap(FeePcts x) pure returns (uint256 result) {
result = FeePcts.unwrap(x);
}// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.24;
import {ApproxValue} from "../Types.sol";
function unwrap(ApproxValue x) pure returns (uint256 result) {
result = ApproxValue.unwrap(x);
}// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.24;
import {TwoCrypto} from "../Types.sol";
function unwrap(TwoCrypto x) pure returns (address result) {
result = TwoCrypto.unwrap(x);
}// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.24;
import {ModuleIndex, MAX_MODULES} from "../Types.sol";
function unwrap(ModuleIndex x) pure returns (uint256 result) {
result = ModuleIndex.unwrap(x);
}
/// @dev Checks if the given module index is supported by Factory.
/// @dev Even if Factory supports the module, Principal Token instance may not support it due to the length of the array mismatch.
function isSupportedByFactory(ModuleIndex x) pure returns (bool result) {
result = ModuleIndex.unwrap(x) < MAX_MODULES;
}
function eq(ModuleIndex x, ModuleIndex y) pure returns (bool result) {
result = ModuleIndex.unwrap(x) == ModuleIndex.unwrap(y);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Library for reading contract metadata robustly.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/MetadataReaderLib.sol)
library MetadataReaderLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Default gas stipend for contract reads. High enough for most practical use cases
/// (able to SLOAD about 1000 bytes of data), but low enough to prevent griefing.
uint256 internal constant GAS_STIPEND_NO_GRIEF = 100000;
/// @dev Default string byte length limit.
uint256 internal constant STRING_LIMIT_DEFAULT = 1000;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* METADATA READING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// Best-effort string reading operations.
// Should NOT revert as long as sufficient gas is provided.
//
// Performs the following in order:
// 1. Returns the empty string for the following cases:
// - Reverts.
// - No returndata (e.g. function returns nothing, EOA).
// - Returns empty string.
// 2. Attempts to `abi.decode` the returndata into a string.
// 3. With any remaining gas, scans the returndata from start to end for the
// null byte '\0', to interpret the returndata as a null-terminated string.
/// @dev Equivalent to `readString(abi.encodeWithSignature("name()"))`.
function readName(address target) internal view returns (string memory) {
return _string(target, _ptr(0x06fdde03), STRING_LIMIT_DEFAULT, GAS_STIPEND_NO_GRIEF);
}
/// @dev Equivalent to `readString(abi.encodeWithSignature("name()"), limit)`.
function readName(address target, uint256 limit) internal view returns (string memory) {
return _string(target, _ptr(0x06fdde03), limit, GAS_STIPEND_NO_GRIEF);
}
/// @dev Equivalent to `readString(abi.encodeWithSignature("name()"), limit, gasStipend)`.
function readName(address target, uint256 limit, uint256 gasStipend)
internal
view
returns (string memory)
{
return _string(target, _ptr(0x06fdde03), limit, gasStipend);
}
/// @dev Equivalent to `readString(abi.encodeWithSignature("symbol()"))`.
function readSymbol(address target) internal view returns (string memory) {
return _string(target, _ptr(0x95d89b41), STRING_LIMIT_DEFAULT, GAS_STIPEND_NO_GRIEF);
}
/// @dev Equivalent to `readString(abi.encodeWithSignature("symbol()"), limit)`.
function readSymbol(address target, uint256 limit) internal view returns (string memory) {
return _string(target, _ptr(0x95d89b41), limit, GAS_STIPEND_NO_GRIEF);
}
/// @dev Equivalent to `readString(abi.encodeWithSignature("symbol()"), limit, gasStipend)`.
function readSymbol(address target, uint256 limit, uint256 gasStipend)
internal
view
returns (string memory)
{
return _string(target, _ptr(0x95d89b41), limit, gasStipend);
}
/// @dev Performs a best-effort string query on `target` with `data` as the calldata.
/// The string will be truncated to `STRING_LIMIT_DEFAULT` (1000) bytes.
function readString(address target, bytes memory data) internal view returns (string memory) {
return _string(target, _ptr(data), STRING_LIMIT_DEFAULT, GAS_STIPEND_NO_GRIEF);
}
/// @dev Performs a best-effort string query on `target` with `data` as the calldata.
/// The string will be truncated to `limit` bytes.
function readString(address target, bytes memory data, uint256 limit)
internal
view
returns (string memory)
{
return _string(target, _ptr(data), limit, GAS_STIPEND_NO_GRIEF);
}
/// @dev Performs a best-effort string query on `target` with `data` as the calldata.
/// The string will be truncated to `limit` bytes.
function readString(address target, bytes memory data, uint256 limit, uint256 gasStipend)
internal
view
returns (string memory)
{
return _string(target, _ptr(data), limit, gasStipend);
}
// Best-effort unsigned integer reading operations.
// Should NOT revert as long as sufficient gas is provided.
//
// Performs the following in order:
// 1. Attempts to `abi.decode` the result into a uint256
// (equivalent across all Solidity uint types, downcast as needed).
// 2. Returns zero for the following cases:
// - Reverts.
// - No returndata (e.g. function returns nothing, EOA).
// - Returns zero.
// - `abi.decode` failure.
/// @dev Equivalent to `uint8(readUint(abi.encodeWithSignature("decimals()")))`.
function readDecimals(address target) internal view returns (uint8) {
return uint8(_uint(target, _ptr(0x313ce567), GAS_STIPEND_NO_GRIEF));
}
/// @dev Equivalent to `uint8(readUint(abi.encodeWithSignature("decimals()"), gasStipend))`.
function readDecimals(address target, uint256 gasStipend) internal view returns (uint8) {
return uint8(_uint(target, _ptr(0x313ce567), gasStipend));
}
/// @dev Performs a best-effort uint query on `target` with `data` as the calldata.
function readUint(address target, bytes memory data) internal view returns (uint256) {
return _uint(target, _ptr(data), GAS_STIPEND_NO_GRIEF);
}
/// @dev Performs a best-effort uint query on `target` with `data` as the calldata.
function readUint(address target, bytes memory data, uint256 gasStipend)
internal
view
returns (uint256)
{
return _uint(target, _ptr(data), gasStipend);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PRIVATE HELPERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Attempts to read and return a string at `target`.
function _string(address target, bytes32 ptr, uint256 limit, uint256 gasStipend)
private
view
returns (string memory result)
{
/// @solidity memory-safe-assembly
assembly {
function min(x_, y_) -> _z {
_z := xor(x_, mul(xor(x_, y_), lt(y_, x_)))
}
for {} staticcall(gasStipend, target, add(ptr, 0x20), mload(ptr), 0x00, 0x20) {} {
let m := mload(0x40) // Grab the free memory pointer.
let s := add(0x20, m) // Start of the string's bytes in memory.
// Attempt to `abi.decode` if the returndatasize is greater or equal to 64.
if iszero(lt(returndatasize(), 0x40)) {
let o := mload(0x00) // Load the string's offset in the returndata.
// If the string's offset is within bounds.
if iszero(gt(o, sub(returndatasize(), 0x20))) {
returndatacopy(m, o, 0x20) // Copy the string's length.
// If the full string's end is within bounds.
// Note: If the full string doesn't fit, the `abi.decode` must be aborted
// for compliance purposes, regardless if the truncated string can fit.
if iszero(gt(mload(m), sub(returndatasize(), add(o, 0x20)))) {
let n := min(mload(m), limit) // Truncate if needed.
mstore(m, n) // Overwrite the length.
returndatacopy(s, add(o, 0x20), n) // Copy the string's bytes.
mstore(add(s, n), 0) // Zeroize the slot after the string.
mstore(0x40, add(0x20, add(s, n))) // Allocate memory for the string.
result := m
break
}
}
}
// Try interpreting as a null-terminated string.
let n := min(returndatasize(), limit) // Truncate if needed.
returndatacopy(s, 0, n) // Copy the string's bytes.
mstore8(add(s, n), 0) // Place a '\0' at the end.
let i := s // Pointer to the next byte to scan.
for {} byte(0, mload(i)) { i := add(i, 1) } {} // Scan for '\0'.
mstore(m, sub(i, s)) // Store the string's length.
mstore(i, 0) // Zeroize the slot after the string.
mstore(0x40, add(0x20, i)) // Allocate memory for the string.
result := m
break
}
}
}
/// @dev Attempts to read and return a uint at `target`.
function _uint(address target, bytes32 ptr, uint256 gasStipend)
private
view
returns (uint256 result)
{
/// @solidity memory-safe-assembly
assembly {
result :=
mul(
mload(0x20),
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gasStipend, target, add(ptr, 0x20), mload(ptr), 0x20, 0x20)
)
)
}
}
/// @dev Casts the function selector `s` into a pointer.
function _ptr(uint256 s) private pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
// Layout the calldata in the scratch space for temporary usage.
mstore(0x04, s) // Store the function selector.
mstore(result, 4) // Store the length.
}
}
/// @dev Casts the `data` into a pointer.
function _ptr(bytes memory data) private pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
result := data
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Library for date time operations.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/DateTimeLib.sol)
/// @author Modified from BokkyPooBahsDateTimeLibrary (https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary)
/// @dev
/// Conventions:
/// --------------------------------------------------------------------+
/// Unit | Range | Notes |
/// --------------------------------------------------------------------|
/// timestamp | 0..0x1e18549868c76ff | Unix timestamp. |
/// epochDay | 0..0x16d3e098039 | Days since 1970-01-01. |
/// year | 1970..0xffffffff | Gregorian calendar year. |
/// month | 1..12 | Gregorian calendar month. |
/// day | 1..31 | Gregorian calendar day of month. |
/// weekday | 1..7 | The day of the week (1-indexed). |
/// --------------------------------------------------------------------+
/// All timestamps of days are rounded down to 00:00:00 UTC.
library DateTimeLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// Weekdays are 1-indexed, adhering to ISO 8601.
uint256 internal constant MON = 1;
uint256 internal constant TUE = 2;
uint256 internal constant WED = 3;
uint256 internal constant THU = 4;
uint256 internal constant FRI = 5;
uint256 internal constant SAT = 6;
uint256 internal constant SUN = 7;
// Months and days of months are 1-indexed, adhering to ISO 8601.
uint256 internal constant JAN = 1;
uint256 internal constant FEB = 2;
uint256 internal constant MAR = 3;
uint256 internal constant APR = 4;
uint256 internal constant MAY = 5;
uint256 internal constant JUN = 6;
uint256 internal constant JUL = 7;
uint256 internal constant AUG = 8;
uint256 internal constant SEP = 9;
uint256 internal constant OCT = 10;
uint256 internal constant NOV = 11;
uint256 internal constant DEC = 12;
// These limits are large enough for most practical purposes.
// Inputs that exceed these limits result in undefined behavior.
uint256 internal constant MAX_SUPPORTED_YEAR = 0xffffffff;
uint256 internal constant MAX_SUPPORTED_EPOCH_DAY = 0x16d3e098039;
uint256 internal constant MAX_SUPPORTED_TIMESTAMP = 0x1e18549868c76ff;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* DATE TIME OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the number of days since 1970-01-01 from (`year`,`month`,`day`).
/// See: https://howardhinnant.github.io/date_algorithms.html
/// Note: Inputs outside the supported ranges result in undefined behavior.
/// Use {isSupportedDate} to check if the inputs are supported.
function dateToEpochDay(uint256 year, uint256 month, uint256 day)
internal
pure
returns (uint256 epochDay)
{
/// @solidity memory-safe-assembly
assembly {
year := sub(year, lt(month, 3))
let doy := add(shr(11, add(mul(62719, mod(add(month, 9), 12)), 769)), day)
let yoe := mod(year, 400)
let doe := sub(add(add(mul(yoe, 365), shr(2, yoe)), doy), div(yoe, 100))
epochDay := sub(add(mul(div(year, 400), 146097), doe), 719469)
}
}
/// @dev Returns (`year`,`month`,`day`) from the number of days since 1970-01-01.
/// Note: Inputs outside the supported ranges result in undefined behavior.
/// Use {isSupportedDays} to check if the inputs is supported.
function epochDayToDate(uint256 epochDay)
internal
pure
returns (uint256 year, uint256 month, uint256 day)
{
/// @solidity memory-safe-assembly
assembly {
epochDay := add(epochDay, 719468)
let doe := mod(epochDay, 146097)
let yoe :=
div(sub(sub(add(doe, div(doe, 36524)), div(doe, 1460)), eq(doe, 146096)), 365)
let doy := sub(doe, sub(add(mul(365, yoe), shr(2, yoe)), div(yoe, 100)))
let mp := div(add(mul(5, doy), 2), 153)
day := add(sub(doy, shr(11, add(mul(mp, 62719), 769))), 1)
month := byte(mp, shl(160, 0x030405060708090a0b0c0102))
year := add(add(yoe, mul(div(epochDay, 146097), 400)), lt(month, 3))
}
}
/// @dev Returns the unix timestamp from (`year`,`month`,`day`).
/// Note: Inputs outside the supported ranges result in undefined behavior.
/// Use {isSupportedDate} to check if the inputs are supported.
function dateToTimestamp(uint256 year, uint256 month, uint256 day)
internal
pure
returns (uint256 result)
{
unchecked {
result = dateToEpochDay(year, month, day) * 86400;
}
}
/// @dev Returns (`year`,`month`,`day`) from the given unix timestamp.
/// Note: Inputs outside the supported ranges result in undefined behavior.
/// Use {isSupportedTimestamp} to check if the inputs are supported.
function timestampToDate(uint256 timestamp)
internal
pure
returns (uint256 year, uint256 month, uint256 day)
{
(year, month, day) = epochDayToDate(timestamp / 86400);
}
/// @dev Returns the unix timestamp from
/// (`year`,`month`,`day`,`hour`,`minute`,`second`).
/// Note: Inputs outside the supported ranges result in undefined behavior.
/// Use {isSupportedDateTime} to check if the inputs are supported.
function dateTimeToTimestamp(
uint256 year,
uint256 month,
uint256 day,
uint256 hour,
uint256 minute,
uint256 second
) internal pure returns (uint256 result) {
unchecked {
result = dateToEpochDay(year, month, day) * 86400 + hour * 3600 + minute * 60 + second;
}
}
/// @dev Returns (`year`,`month`,`day`,`hour`,`minute`,`second`)
/// from the given unix timestamp.
/// Note: Inputs outside the supported ranges result in undefined behavior.
/// Use {isSupportedTimestamp} to check if the inputs are supported.
function timestampToDateTime(uint256 timestamp)
internal
pure
returns (
uint256 year,
uint256 month,
uint256 day,
uint256 hour,
uint256 minute,
uint256 second
)
{
unchecked {
(year, month, day) = epochDayToDate(timestamp / 86400);
uint256 secs = timestamp % 86400;
hour = secs / 3600;
secs = secs % 3600;
minute = secs / 60;
second = secs % 60;
}
}
/// @dev Returns if the `year` is leap.
function isLeapYear(uint256 year) internal pure returns (bool leap) {
/// @solidity memory-safe-assembly
assembly {
leap := iszero(and(add(mul(iszero(mod(year, 25)), 12), 3), year))
}
}
/// @dev Returns number of days in given `month` of `year`.
function daysInMonth(uint256 year, uint256 month) internal pure returns (uint256 result) {
bool flag = isLeapYear(year);
/// @solidity memory-safe-assembly
assembly {
// `daysInMonths = [31,28,31,30,31,30,31,31,30,31,30,31]`.
// `result = daysInMonths[month - 1] + isLeapYear(year)`.
result :=
add(byte(month, shl(152, 0x1f1c1f1e1f1e1f1f1e1f1e1f)), and(eq(month, 2), flag))
}
}
/// @dev Returns the weekday from the unix timestamp.
/// Monday: 1, Tuesday: 2, ....., Sunday: 7.
function weekday(uint256 timestamp) internal pure returns (uint256 result) {
unchecked {
result = ((timestamp / 86400 + 3) % 7) + 1;
}
}
/// @dev Returns if (`year`,`month`,`day`) is a supported date.
/// - `1970 <= year <= MAX_SUPPORTED_YEAR`.
/// - `1 <= month <= 12`.
/// - `1 <= day <= daysInMonth(year, month)`.
function isSupportedDate(uint256 year, uint256 month, uint256 day)
internal
pure
returns (bool result)
{
uint256 md = daysInMonth(year, month);
/// @solidity memory-safe-assembly
assembly {
result :=
and(
lt(sub(year, 1970), sub(MAX_SUPPORTED_YEAR, 1969)),
and(lt(sub(month, 1), 12), lt(sub(day, 1), md))
)
}
}
/// @dev Returns if (`year`,`month`,`day`,`hour`,`minute`,`second`) is a supported date time.
/// - `1970 <= year <= MAX_SUPPORTED_YEAR`.
/// - `1 <= month <= 12`.
/// - `1 <= day <= daysInMonth(year, month)`.
/// - `hour < 24`.
/// - `minute < 60`.
/// - `second < 60`.
function isSupportedDateTime(
uint256 year,
uint256 month,
uint256 day,
uint256 hour,
uint256 minute,
uint256 second
) internal pure returns (bool result) {
if (isSupportedDate(year, month, day)) {
/// @solidity memory-safe-assembly
assembly {
result := and(lt(hour, 24), and(lt(minute, 60), lt(second, 60)))
}
}
}
/// @dev Returns if `epochDay` is a supported unix epoch day.
function isSupportedEpochDay(uint256 epochDay) internal pure returns (bool result) {
unchecked {
result = epochDay < MAX_SUPPORTED_EPOCH_DAY + 1;
}
}
/// @dev Returns if `timestamp` is a supported unix timestamp.
function isSupportedTimestamp(uint256 timestamp) internal pure returns (bool result) {
unchecked {
result = timestamp < MAX_SUPPORTED_TIMESTAMP + 1;
}
}
/// @dev Returns the unix timestamp of the given `n`th weekday `wd`, in `month` of `year`.
/// Example: 3rd Friday of Feb 2022 is `nthWeekdayInMonthOfYearTimestamp(2022, 2, 3, 5)`
/// Note: `n` is 1-indexed for traditional consistency.
/// Invalid weekdays (i.e. `wd == 0 || wd > 7`) result in undefined behavior.
function nthWeekdayInMonthOfYearTimestamp(uint256 year, uint256 month, uint256 n, uint256 wd)
internal
pure
returns (uint256 result)
{
uint256 d = dateToEpochDay(year, month, 1);
uint256 md = daysInMonth(year, month);
/// @solidity memory-safe-assembly
assembly {
let diff := sub(wd, add(mod(add(d, 3), 7), 1))
let date := add(mul(sub(n, 1), 7), add(mul(gt(diff, 6), 7), diff))
result := mul(mul(86400, add(date, d)), and(lt(date, md), iszero(iszero(n))))
}
}
/// @dev Returns the unix timestamp of the most recent Monday.
function mondayTimestamp(uint256 timestamp) internal pure returns (uint256 result) {
uint256 t = timestamp;
/// @solidity memory-safe-assembly
assembly {
let day := div(t, 86400)
result := mul(mul(sub(day, mod(add(day, 3), 7)), 86400), gt(t, 345599))
}
}
/// @dev Returns whether the unix timestamp falls on a Saturday or Sunday.
/// To check whether it is a week day, just take the negation of the result.
function isWeekEnd(uint256 timestamp) internal pure returns (bool result) {
result = weekday(timestamp) > FRI;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* DATE TIME ARITHMETIC OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Adds `numYears` to the unix timestamp, and returns the result.
/// Note: The result will share the same Gregorian calendar month,
/// but different Gregorian calendar years for non-zero `numYears`.
/// If the Gregorian calendar month of the result has less days
/// than the Gregorian calendar month day of the `timestamp`,
/// the result's month day will be the maximum possible value for the month.
/// (e.g. from 29th Feb to 28th Feb)
function addYears(uint256 timestamp, uint256 numYears) internal pure returns (uint256 result) {
(uint256 year, uint256 month, uint256 day) = epochDayToDate(timestamp / 86400);
result = _offsetted(year + numYears, month, day, timestamp);
}
/// @dev Adds `numMonths` to the unix timestamp, and returns the result.
/// Note: If the Gregorian calendar month of the result has less days
/// than the Gregorian calendar month day of the `timestamp`,
/// the result's month day will be the maximum possible value for the month.
/// (e.g. from 29th Feb to 28th Feb)
function addMonths(uint256 timestamp, uint256 numMonths)
internal
pure
returns (uint256 result)
{
(uint256 year, uint256 month, uint256 day) = epochDayToDate(timestamp / 86400);
month = _sub(month + numMonths, 1);
result = _offsetted(year + month / 12, _add(month % 12, 1), day, timestamp);
}
/// @dev Adds `numDays` to the unix timestamp, and returns the result.
function addDays(uint256 timestamp, uint256 numDays) internal pure returns (uint256 result) {
result = timestamp + numDays * 86400;
}
/// @dev Adds `numHours` to the unix timestamp, and returns the result.
function addHours(uint256 timestamp, uint256 numHours) internal pure returns (uint256 result) {
result = timestamp + numHours * 3600;
}
/// @dev Adds `numMinutes` to the unix timestamp, and returns the result.
function addMinutes(uint256 timestamp, uint256 numMinutes)
internal
pure
returns (uint256 result)
{
result = timestamp + numMinutes * 60;
}
/// @dev Adds `numSeconds` to the unix timestamp, and returns the result.
function addSeconds(uint256 timestamp, uint256 numSeconds)
internal
pure
returns (uint256 result)
{
result = timestamp + numSeconds;
}
/// @dev Subtracts `numYears` from the unix timestamp, and returns the result.
/// Note: The result will share the same Gregorian calendar month,
/// but different Gregorian calendar years for non-zero `numYears`.
/// If the Gregorian calendar month of the result has less days
/// than the Gregorian calendar month day of the `timestamp`,
/// the result's month day will be the maximum possible value for the month.
/// (e.g. from 29th Feb to 28th Feb)
function subYears(uint256 timestamp, uint256 numYears) internal pure returns (uint256 result) {
(uint256 year, uint256 month, uint256 day) = epochDayToDate(timestamp / 86400);
result = _offsetted(year - numYears, month, day, timestamp);
}
/// @dev Subtracts `numYears` from the unix timestamp, and returns the result.
/// Note: If the Gregorian calendar month of the result has less days
/// than the Gregorian calendar month day of the `timestamp`,
/// the result's month day will be the maximum possible value for the month.
/// (e.g. from 29th Feb to 28th Feb)
function subMonths(uint256 timestamp, uint256 numMonths)
internal
pure
returns (uint256 result)
{
(uint256 year, uint256 month, uint256 day) = epochDayToDate(timestamp / 86400);
uint256 yearMonth = _totalMonths(year, month) - _add(numMonths, 1);
result = _offsetted(yearMonth / 12, _add(yearMonth % 12, 1), day, timestamp);
}
/// @dev Subtracts `numDays` from the unix timestamp, and returns the result.
function subDays(uint256 timestamp, uint256 numDays) internal pure returns (uint256 result) {
result = timestamp - numDays * 86400;
}
/// @dev Subtracts `numHours` from the unix timestamp, and returns the result.
function subHours(uint256 timestamp, uint256 numHours) internal pure returns (uint256 result) {
result = timestamp - numHours * 3600;
}
/// @dev Subtracts `numMinutes` from the unix timestamp, and returns the result.
function subMinutes(uint256 timestamp, uint256 numMinutes)
internal
pure
returns (uint256 result)
{
result = timestamp - numMinutes * 60;
}
/// @dev Subtracts `numSeconds` from the unix timestamp, and returns the result.
function subSeconds(uint256 timestamp, uint256 numSeconds)
internal
pure
returns (uint256 result)
{
result = timestamp - numSeconds;
}
/// @dev Returns the difference in Gregorian calendar years
/// between `fromTimestamp` and `toTimestamp`.
/// Note: Even if the true time difference is less than a year,
/// the difference can be non-zero is the timestamps are
/// from different Gregorian calendar years
function diffYears(uint256 fromTimestamp, uint256 toTimestamp)
internal
pure
returns (uint256 result)
{
toTimestamp - fromTimestamp;
(uint256 fromYear,,) = epochDayToDate(fromTimestamp / 86400);
(uint256 toYear,,) = epochDayToDate(toTimestamp / 86400);
result = _sub(toYear, fromYear);
}
/// @dev Returns the difference in Gregorian calendar months
/// between `fromTimestamp` and `toTimestamp`.
/// Note: Even if the true time difference is less than a month,
/// the difference can be non-zero is the timestamps are
/// from different Gregorian calendar months.
function diffMonths(uint256 fromTimestamp, uint256 toTimestamp)
internal
pure
returns (uint256 result)
{
toTimestamp - fromTimestamp;
(uint256 fromYear, uint256 fromMonth,) = epochDayToDate(fromTimestamp / 86400);
(uint256 toYear, uint256 toMonth,) = epochDayToDate(toTimestamp / 86400);
result = _sub(_totalMonths(toYear, toMonth), _totalMonths(fromYear, fromMonth));
}
/// @dev Returns the difference in days between `fromTimestamp` and `toTimestamp`.
function diffDays(uint256 fromTimestamp, uint256 toTimestamp)
internal
pure
returns (uint256 result)
{
result = (toTimestamp - fromTimestamp) / 86400;
}
/// @dev Returns the difference in hours between `fromTimestamp` and `toTimestamp`.
function diffHours(uint256 fromTimestamp, uint256 toTimestamp)
internal
pure
returns (uint256 result)
{
result = (toTimestamp - fromTimestamp) / 3600;
}
/// @dev Returns the difference in minutes between `fromTimestamp` and `toTimestamp`.
function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp)
internal
pure
returns (uint256 result)
{
result = (toTimestamp - fromTimestamp) / 60;
}
/// @dev Returns the difference in seconds between `fromTimestamp` and `toTimestamp`.
function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp)
internal
pure
returns (uint256 result)
{
result = toTimestamp - fromTimestamp;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PRIVATE HELPERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Unchecked arithmetic for computing the total number of months.
function _totalMonths(uint256 numYears, uint256 numMonths)
private
pure
returns (uint256 total)
{
unchecked {
total = numYears * 12 + numMonths;
}
}
/// @dev Unchecked arithmetic for adding two numbers.
function _add(uint256 a, uint256 b) private pure returns (uint256 c) {
unchecked {
c = a + b;
}
}
/// @dev Unchecked arithmetic for subtracting two numbers.
function _sub(uint256 a, uint256 b) private pure returns (uint256 c) {
unchecked {
c = a - b;
}
}
/// @dev Returns the offsetted timestamp.
function _offsetted(uint256 year, uint256 month, uint256 day, uint256 timestamp)
private
pure
returns (uint256 result)
{
uint256 dm = daysInMonth(year, month);
if (day >= dm) {
day = dm;
}
result = dateToEpochDay(year, month, day) * 86400 + (timestamp % 86400);
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import {LibBytes} from "./LibBytes.sol";
/// @notice Library for converting numbers into strings and other string operations.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/LibString.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/LibString.sol)
///
/// @dev Note:
/// For performance and bytecode compactness, most of the string operations are restricted to
/// byte strings (7-bit ASCII), except where otherwise specified.
/// Usage of byte string operations on charsets with runes spanning two or more bytes
/// can lead to undefined behavior.
library LibString {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STRUCTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Goated string storage struct that totally MOGs, no cap, fr.
/// Uses less gas and bytecode than Solidity's native string storage. It's meta af.
/// Packs length with the first 31 bytes if <255 bytes, so it’s mad tight.
struct StringStorage {
bytes32 _spacer;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The length of the output is too small to contain all the hex digits.
error HexLengthInsufficient();
/// @dev The length of the string is more than 32 bytes.
error TooBigForSmallString();
/// @dev The input string must be a 7-bit ASCII.
error StringNot7BitASCII();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The constant returned when the `search` is not found in the string.
uint256 internal constant NOT_FOUND = type(uint256).max;
/// @dev Lookup for '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.
uint128 internal constant ALPHANUMERIC_7_BIT_ASCII = 0x7fffffe07fffffe03ff000000000000;
/// @dev Lookup for 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.
uint128 internal constant LETTERS_7_BIT_ASCII = 0x7fffffe07fffffe0000000000000000;
/// @dev Lookup for 'abcdefghijklmnopqrstuvwxyz'.
uint128 internal constant LOWERCASE_7_BIT_ASCII = 0x7fffffe000000000000000000000000;
/// @dev Lookup for 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.
uint128 internal constant UPPERCASE_7_BIT_ASCII = 0x7fffffe0000000000000000;
/// @dev Lookup for '0123456789'.
uint128 internal constant DIGITS_7_BIT_ASCII = 0x3ff000000000000;
/// @dev Lookup for '0123456789abcdefABCDEF'.
uint128 internal constant HEXDIGITS_7_BIT_ASCII = 0x7e0000007e03ff000000000000;
/// @dev Lookup for '01234567'.
uint128 internal constant OCTDIGITS_7_BIT_ASCII = 0xff000000000000;
/// @dev Lookup for '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'.
uint128 internal constant PRINTABLE_7_BIT_ASCII = 0x7fffffffffffffffffffffff00003e00;
/// @dev Lookup for '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'.
uint128 internal constant PUNCTUATION_7_BIT_ASCII = 0x78000001f8000001fc00fffe00000000;
/// @dev Lookup for ' \t\n\r\x0b\x0c'.
uint128 internal constant WHITESPACE_7_BIT_ASCII = 0x100003e00;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STRING STORAGE OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Sets the value of the string storage `$` to `s`.
function set(StringStorage storage $, string memory s) internal {
LibBytes.set(bytesStorage($), bytes(s));
}
/// @dev Sets the value of the string storage `$` to `s`.
function setCalldata(StringStorage storage $, string calldata s) internal {
LibBytes.setCalldata(bytesStorage($), bytes(s));
}
/// @dev Sets the value of the string storage `$` to the empty string.
function clear(StringStorage storage $) internal {
delete $._spacer;
}
/// @dev Returns whether the value stored is `$` is the empty string "".
function isEmpty(StringStorage storage $) internal view returns (bool) {
return uint256($._spacer) & 0xff == uint256(0);
}
/// @dev Returns the length of the value stored in `$`.
function length(StringStorage storage $) internal view returns (uint256) {
return LibBytes.length(bytesStorage($));
}
/// @dev Returns the value stored in `$`.
function get(StringStorage storage $) internal view returns (string memory) {
return string(LibBytes.get(bytesStorage($)));
}
/// @dev Helper to cast `$` to a `BytesStorage`.
function bytesStorage(StringStorage storage $)
internal
pure
returns (LibBytes.BytesStorage storage casted)
{
/// @solidity memory-safe-assembly
assembly {
casted.slot := $.slot
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* DECIMAL OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the base 10 decimal representation of `value`.
function toString(uint256 value) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
// The maximum value of a uint256 contains 78 digits (1 byte per digit), but
// we allocate 0xa0 bytes to keep the free memory pointer 32-byte word aligned.
// We will need 1 word for the trailing zeros padding, 1 word for the length,
// and 3 words for a maximum of 78 digits.
result := add(mload(0x40), 0x80)
mstore(0x40, add(result, 0x20)) // Allocate memory.
mstore(result, 0) // Zeroize the slot after the string.
let end := result // Cache the end of the memory to calculate the length later.
let w := not(0) // Tsk.
// We write the string from rightmost digit to leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
for { let temp := value } 1 {} {
result := add(result, w) // `sub(result, 1)`.
// Store the character to the pointer.
// The ASCII index of the '0' character is 48.
mstore8(result, add(48, mod(temp, 10)))
temp := div(temp, 10) // Keep dividing `temp` until zero.
if iszero(temp) { break }
}
let n := sub(end, result)
result := sub(result, 0x20) // Move the pointer 32 bytes back to make room for the length.
mstore(result, n) // Store the length.
}
}
/// @dev Returns the base 10 decimal representation of `value`.
function toString(int256 value) internal pure returns (string memory result) {
if (value >= 0) return toString(uint256(value));
unchecked {
result = toString(~uint256(value) + 1);
}
/// @solidity memory-safe-assembly
assembly {
// We still have some spare memory space on the left,
// as we have allocated 3 words (96 bytes) for up to 78 digits.
let n := mload(result) // Load the string length.
mstore(result, 0x2d) // Store the '-' character.
result := sub(result, 1) // Move back the string pointer by a byte.
mstore(result, add(n, 1)) // Update the string length.
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* HEXADECIMAL OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the hexadecimal representation of `value`,
/// left-padded to an input length of `byteCount` bytes.
/// The output is prefixed with "0x" encoded using 2 hexadecimal digits per byte,
/// giving a total length of `byteCount * 2 + 2` bytes.
/// Reverts if `byteCount` is too small for the output to contain all the digits.
function toHexString(uint256 value, uint256 byteCount)
internal
pure
returns (string memory result)
{
result = toHexStringNoPrefix(value, byteCount);
/// @solidity memory-safe-assembly
assembly {
let n := add(mload(result), 2) // Compute the length.
mstore(result, 0x3078) // Store the "0x" prefix.
result := sub(result, 2) // Move the pointer.
mstore(result, n) // Store the length.
}
}
/// @dev Returns the hexadecimal representation of `value`,
/// left-padded to an input length of `byteCount` bytes.
/// The output is not prefixed with "0x" and is encoded using 2 hexadecimal digits per byte,
/// giving a total length of `byteCount * 2` bytes.
/// Reverts if `byteCount` is too small for the output to contain all the digits.
function toHexStringNoPrefix(uint256 value, uint256 byteCount)
internal
pure
returns (string memory result)
{
/// @solidity memory-safe-assembly
assembly {
// We need 0x20 bytes for the trailing zeros padding, `byteCount * 2` bytes
// for the digits, 0x02 bytes for the prefix, and 0x20 bytes for the length.
// We add 0x20 to the total and round down to a multiple of 0x20.
// (0x20 + 0x20 + 0x02 + 0x20) = 0x62.
result := add(mload(0x40), and(add(shl(1, byteCount), 0x42), not(0x1f)))
mstore(0x40, add(result, 0x20)) // Allocate memory.
mstore(result, 0) // Zeroize the slot after the string.
let end := result // Cache the end to calculate the length later.
// Store "0123456789abcdef" in scratch space.
mstore(0x0f, 0x30313233343536373839616263646566)
let start := sub(result, add(byteCount, byteCount))
let w := not(1) // Tsk.
let temp := value
// We write the string from rightmost digit to leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
for {} 1 {} {
result := add(result, w) // `sub(result, 2)`.
mstore8(add(result, 1), mload(and(temp, 15)))
mstore8(result, mload(and(shr(4, temp), 15)))
temp := shr(8, temp)
if iszero(xor(result, start)) { break }
}
if temp {
mstore(0x00, 0x2194895a) // `HexLengthInsufficient()`.
revert(0x1c, 0x04)
}
let n := sub(end, result)
result := sub(result, 0x20)
mstore(result, n) // Store the length.
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is prefixed with "0x" and encoded using 2 hexadecimal digits per byte.
/// As address are 20 bytes long, the output will left-padded to have
/// a length of `20 * 2 + 2` bytes.
function toHexString(uint256 value) internal pure returns (string memory result) {
result = toHexStringNoPrefix(value);
/// @solidity memory-safe-assembly
assembly {
let n := add(mload(result), 2) // Compute the length.
mstore(result, 0x3078) // Store the "0x" prefix.
result := sub(result, 2) // Move the pointer.
mstore(result, n) // Store the length.
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is prefixed with "0x".
/// The output excludes leading "0" from the `toHexString` output.
/// `0x00: "0x0", 0x01: "0x1", 0x12: "0x12", 0x123: "0x123"`.
function toMinimalHexString(uint256 value) internal pure returns (string memory result) {
result = toHexStringNoPrefix(value);
/// @solidity memory-safe-assembly
assembly {
let o := eq(byte(0, mload(add(result, 0x20))), 0x30) // Whether leading zero is present.
let n := add(mload(result), 2) // Compute the length.
mstore(add(result, o), 0x3078) // Store the "0x" prefix, accounting for leading zero.
result := sub(add(result, o), 2) // Move the pointer, accounting for leading zero.
mstore(result, sub(n, o)) // Store the length, accounting for leading zero.
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output excludes leading "0" from the `toHexStringNoPrefix` output.
/// `0x00: "0", 0x01: "1", 0x12: "12", 0x123: "123"`.
function toMinimalHexStringNoPrefix(uint256 value)
internal
pure
returns (string memory result)
{
result = toHexStringNoPrefix(value);
/// @solidity memory-safe-assembly
assembly {
let o := eq(byte(0, mload(add(result, 0x20))), 0x30) // Whether leading zero is present.
let n := mload(result) // Get the length.
result := add(result, o) // Move the pointer, accounting for leading zero.
mstore(result, sub(n, o)) // Store the length, accounting for leading zero.
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is encoded using 2 hexadecimal digits per byte.
/// As address are 20 bytes long, the output will left-padded to have
/// a length of `20 * 2` bytes.
function toHexStringNoPrefix(uint256 value) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
// We need 0x20 bytes for the trailing zeros padding, 0x20 bytes for the length,
// 0x02 bytes for the prefix, and 0x40 bytes for the digits.
// The next multiple of 0x20 above (0x20 + 0x20 + 0x02 + 0x40) is 0xa0.
result := add(mload(0x40), 0x80)
mstore(0x40, add(result, 0x20)) // Allocate memory.
mstore(result, 0) // Zeroize the slot after the string.
let end := result // Cache the end to calculate the length later.
mstore(0x0f, 0x30313233343536373839616263646566) // Store the "0123456789abcdef" lookup.
let w := not(1) // Tsk.
// We write the string from rightmost digit to leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
for { let temp := value } 1 {} {
result := add(result, w) // `sub(result, 2)`.
mstore8(add(result, 1), mload(and(temp, 15)))
mstore8(result, mload(and(shr(4, temp), 15)))
temp := shr(8, temp)
if iszero(temp) { break }
}
let n := sub(end, result)
result := sub(result, 0x20)
mstore(result, n) // Store the length.
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is prefixed with "0x", encoded using 2 hexadecimal digits per byte,
/// and the alphabets are capitalized conditionally according to
/// https://eips.ethereum.org/EIPS/eip-55
function toHexStringChecksummed(address value) internal pure returns (string memory result) {
result = toHexString(value);
/// @solidity memory-safe-assembly
assembly {
let mask := shl(6, div(not(0), 255)) // `0b010000000100000000 ...`
let o := add(result, 0x22)
let hashed := and(keccak256(o, 40), mul(34, mask)) // `0b10001000 ... `
let t := shl(240, 136) // `0b10001000 << 240`
for { let i := 0 } 1 {} {
mstore(add(i, i), mul(t, byte(i, hashed)))
i := add(i, 1)
if eq(i, 20) { break }
}
mstore(o, xor(mload(o), shr(1, and(mload(0x00), and(mload(o), mask)))))
o := add(o, 0x20)
mstore(o, xor(mload(o), shr(1, and(mload(0x20), and(mload(o), mask)))))
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is prefixed with "0x" and encoded using 2 hexadecimal digits per byte.
function toHexString(address value) internal pure returns (string memory result) {
result = toHexStringNoPrefix(value);
/// @solidity memory-safe-assembly
assembly {
let n := add(mload(result), 2) // Compute the length.
mstore(result, 0x3078) // Store the "0x" prefix.
result := sub(result, 2) // Move the pointer.
mstore(result, n) // Store the length.
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is encoded using 2 hexadecimal digits per byte.
function toHexStringNoPrefix(address value) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
// Allocate memory.
// We need 0x20 bytes for the trailing zeros padding, 0x20 bytes for the length,
// 0x02 bytes for the prefix, and 0x28 bytes for the digits.
// The next multiple of 0x20 above (0x20 + 0x20 + 0x02 + 0x28) is 0x80.
mstore(0x40, add(result, 0x80))
mstore(0x0f, 0x30313233343536373839616263646566) // Store the "0123456789abcdef" lookup.
result := add(result, 2)
mstore(result, 40) // Store the length.
let o := add(result, 0x20)
mstore(add(o, 40), 0) // Zeroize the slot after the string.
value := shl(96, value)
// We write the string from rightmost digit to leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
for { let i := 0 } 1 {} {
let p := add(o, add(i, i))
let temp := byte(i, value)
mstore8(add(p, 1), mload(and(temp, 15)))
mstore8(p, mload(shr(4, temp)))
i := add(i, 1)
if eq(i, 20) { break }
}
}
}
/// @dev Returns the hex encoded string from the raw bytes.
/// The output is encoded using 2 hexadecimal digits per byte.
function toHexString(bytes memory raw) internal pure returns (string memory result) {
result = toHexStringNoPrefix(raw);
/// @solidity memory-safe-assembly
assembly {
let n := add(mload(result), 2) // Compute the length.
mstore(result, 0x3078) // Store the "0x" prefix.
result := sub(result, 2) // Move the pointer.
mstore(result, n) // Store the length.
}
}
/// @dev Returns the hex encoded string from the raw bytes.
/// The output is encoded using 2 hexadecimal digits per byte.
function toHexStringNoPrefix(bytes memory raw) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
let n := mload(raw)
result := add(mload(0x40), 2) // Skip 2 bytes for the optional prefix.
mstore(result, add(n, n)) // Store the length of the output.
mstore(0x0f, 0x30313233343536373839616263646566) // Store the "0123456789abcdef" lookup.
let o := add(result, 0x20)
let end := add(raw, n)
for {} iszero(eq(raw, end)) {} {
raw := add(raw, 1)
mstore8(add(o, 1), mload(and(mload(raw), 15)))
mstore8(o, mload(and(shr(4, mload(raw)), 15)))
o := add(o, 2)
}
mstore(o, 0) // Zeroize the slot after the string.
mstore(0x40, add(o, 0x20)) // Allocate memory.
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* RUNE STRING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the number of UTF characters in the string.
function runeCount(string memory s) internal pure returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
if mload(s) {
mstore(0x00, div(not(0), 255))
mstore(0x20, 0x0202020202020202020202020202020202020202020202020303030304040506)
let o := add(s, 0x20)
let end := add(o, mload(s))
for { result := 1 } 1 { result := add(result, 1) } {
o := add(o, byte(0, mload(shr(250, mload(o)))))
if iszero(lt(o, end)) { break }
}
}
}
}
/// @dev Returns if this string is a 7-bit ASCII string.
/// (i.e. all characters codes are in [0..127])
function is7BitASCII(string memory s) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
result := 1
let mask := shl(7, div(not(0), 255))
let n := mload(s)
if n {
let o := add(s, 0x20)
let end := add(o, n)
let last := mload(end)
mstore(end, 0)
for {} 1 {} {
if and(mask, mload(o)) {
result := 0
break
}
o := add(o, 0x20)
if iszero(lt(o, end)) { break }
}
mstore(end, last)
}
}
}
/// @dev Returns if this string is a 7-bit ASCII string,
/// AND all characters are in the `allowed` lookup.
/// Note: If `s` is empty, returns true regardless of `allowed`.
function is7BitASCII(string memory s, uint128 allowed) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
result := 1
if mload(s) {
let allowed_ := shr(128, shl(128, allowed))
let o := add(s, 0x20)
for { let end := add(o, mload(s)) } 1 {} {
result := and(result, shr(byte(0, mload(o)), allowed_))
o := add(o, 1)
if iszero(and(result, lt(o, end))) { break }
}
}
}
}
/// @dev Converts the bytes in the 7-bit ASCII string `s` to
/// an allowed lookup for use in `is7BitASCII(s, allowed)`.
/// To save runtime gas, you can cache the result in an immutable variable.
function to7BitASCIIAllowedLookup(string memory s) internal pure returns (uint128 result) {
/// @solidity memory-safe-assembly
assembly {
if mload(s) {
let o := add(s, 0x20)
for { let end := add(o, mload(s)) } 1 {} {
result := or(result, shl(byte(0, mload(o)), 1))
o := add(o, 1)
if iszero(lt(o, end)) { break }
}
if shr(128, result) {
mstore(0x00, 0xc9807e0d) // `StringNot7BitASCII()`.
revert(0x1c, 0x04)
}
}
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* BYTE STRING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// For performance and bytecode compactness, byte string operations are restricted
// to 7-bit ASCII strings. All offsets are byte offsets, not UTF character offsets.
// Usage of byte string operations on charsets with runes spanning two or more bytes
// can lead to undefined behavior.
/// @dev Returns `subject` all occurrences of `needle` replaced with `replacement`.
function replace(string memory subject, string memory needle, string memory replacement)
internal
pure
returns (string memory)
{
return string(LibBytes.replace(bytes(subject), bytes(needle), bytes(replacement)));
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from left to right, starting from `from`.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function indexOf(string memory subject, string memory needle, uint256 from)
internal
pure
returns (uint256)
{
return LibBytes.indexOf(bytes(subject), bytes(needle), from);
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from left to right.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function indexOf(string memory subject, string memory needle) internal pure returns (uint256) {
return LibBytes.indexOf(bytes(subject), bytes(needle), 0);
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from right to left, starting from `from`.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function lastIndexOf(string memory subject, string memory needle, uint256 from)
internal
pure
returns (uint256)
{
return LibBytes.lastIndexOf(bytes(subject), bytes(needle), from);
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from right to left.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function lastIndexOf(string memory subject, string memory needle)
internal
pure
returns (uint256)
{
return LibBytes.lastIndexOf(bytes(subject), bytes(needle), type(uint256).max);
}
/// @dev Returns true if `needle` is found in `subject`, false otherwise.
function contains(string memory subject, string memory needle) internal pure returns (bool) {
return LibBytes.contains(bytes(subject), bytes(needle));
}
/// @dev Returns whether `subject` starts with `needle`.
function startsWith(string memory subject, string memory needle) internal pure returns (bool) {
return LibBytes.startsWith(bytes(subject), bytes(needle));
}
/// @dev Returns whether `subject` ends with `needle`.
function endsWith(string memory subject, string memory needle) internal pure returns (bool) {
return LibBytes.endsWith(bytes(subject), bytes(needle));
}
/// @dev Returns `subject` repeated `times`.
function repeat(string memory subject, uint256 times) internal pure returns (string memory) {
return string(LibBytes.repeat(bytes(subject), times));
}
/// @dev Returns a copy of `subject` sliced from `start` to `end` (exclusive).
/// `start` and `end` are byte offsets.
function slice(string memory subject, uint256 start, uint256 end)
internal
pure
returns (string memory)
{
return string(LibBytes.slice(bytes(subject), start, end));
}
/// @dev Returns a copy of `subject` sliced from `start` to the end of the string.
/// `start` is a byte offset.
function slice(string memory subject, uint256 start) internal pure returns (string memory) {
return string(LibBytes.slice(bytes(subject), start, type(uint256).max));
}
/// @dev Returns all the indices of `needle` in `subject`.
/// The indices are byte offsets.
function indicesOf(string memory subject, string memory needle)
internal
pure
returns (uint256[] memory)
{
return LibBytes.indicesOf(bytes(subject), bytes(needle));
}
/// @dev Returns a arrays of strings based on the `delimiter` inside of the `subject` string.
function split(string memory subject, string memory delimiter)
internal
pure
returns (string[] memory result)
{
bytes[] memory a = LibBytes.split(bytes(subject), bytes(delimiter));
/// @solidity memory-safe-assembly
assembly {
result := a
}
}
/// @dev Returns a concatenated string of `a` and `b`.
/// Cheaper than `string.concat()` and does not de-align the free memory pointer.
function concat(string memory a, string memory b) internal pure returns (string memory) {
return string(LibBytes.concat(bytes(a), bytes(b)));
}
/// @dev Returns a copy of the string in either lowercase or UPPERCASE.
/// WARNING! This function is only compatible with 7-bit ASCII strings.
function toCase(string memory subject, bool toUpper)
internal
pure
returns (string memory result)
{
/// @solidity memory-safe-assembly
assembly {
let n := mload(subject)
if n {
result := mload(0x40)
let o := add(result, 0x20)
let d := sub(subject, result)
let flags := shl(add(70, shl(5, toUpper)), 0x3ffffff)
for { let end := add(o, n) } 1 {} {
let b := byte(0, mload(add(d, o)))
mstore8(o, xor(and(shr(b, flags), 0x20), b))
o := add(o, 1)
if eq(o, end) { break }
}
mstore(result, n) // Store the length.
mstore(o, 0) // Zeroize the slot after the string.
mstore(0x40, add(o, 0x20)) // Allocate memory.
}
}
}
/// @dev Returns a string from a small bytes32 string.
/// `s` must be null-terminated, or behavior will be undefined.
function fromSmallString(bytes32 s) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
let n := 0
for {} byte(n, s) { n := add(n, 1) } {} // Scan for '\0'.
mstore(result, n) // Store the length.
let o := add(result, 0x20)
mstore(o, s) // Store the bytes of the string.
mstore(add(o, n), 0) // Zeroize the slot after the string.
mstore(0x40, add(result, 0x40)) // Allocate memory.
}
}
/// @dev Returns the small string, with all bytes after the first null byte zeroized.
function normalizeSmallString(bytes32 s) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
for {} byte(result, s) { result := add(result, 1) } {} // Scan for '\0'.
mstore(0x00, s)
mstore(result, 0x00)
result := mload(0x00)
}
}
/// @dev Returns the string as a normalized null-terminated small string.
function toSmallString(string memory s) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(s)
if iszero(lt(result, 33)) {
mstore(0x00, 0xec92f9a3) // `TooBigForSmallString()`.
revert(0x1c, 0x04)
}
result := shl(shl(3, sub(32, result)), mload(add(s, result)))
}
}
/// @dev Returns a lowercased copy of the string.
/// WARNING! This function is only compatible with 7-bit ASCII strings.
function lower(string memory subject) internal pure returns (string memory result) {
result = toCase(subject, false);
}
/// @dev Returns an UPPERCASED copy of the string.
/// WARNING! This function is only compatible with 7-bit ASCII strings.
function upper(string memory subject) internal pure returns (string memory result) {
result = toCase(subject, true);
}
/// @dev Escapes the string to be used within HTML tags.
function escapeHTML(string memory s) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
let end := add(s, mload(s))
let o := add(result, 0x20)
// Store the bytes of the packed offsets and strides into the scratch space.
// `packed = (stride << 5) | offset`. Max offset is 20. Max stride is 6.
mstore(0x1f, 0x900094)
mstore(0x08, 0xc0000000a6ab)
// Store ""&'<>" into the scratch space.
mstore(0x00, shl(64, 0x2671756f743b26616d703b262333393b266c743b2667743b))
for {} iszero(eq(s, end)) {} {
s := add(s, 1)
let c := and(mload(s), 0xff)
// Not in `["\"","'","&","<",">"]`.
if iszero(and(shl(c, 1), 0x500000c400000000)) {
mstore8(o, c)
o := add(o, 1)
continue
}
let t := shr(248, mload(c))
mstore(o, mload(and(t, 0x1f)))
o := add(o, shr(5, t))
}
mstore(o, 0) // Zeroize the slot after the string.
mstore(result, sub(o, add(result, 0x20))) // Store the length.
mstore(0x40, add(o, 0x20)) // Allocate memory.
}
}
/// @dev Escapes the string to be used within double-quotes in a JSON.
/// If `addDoubleQuotes` is true, the result will be enclosed in double-quotes.
function escapeJSON(string memory s, bool addDoubleQuotes)
internal
pure
returns (string memory result)
{
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
let o := add(result, 0x20)
if addDoubleQuotes {
mstore8(o, 34)
o := add(1, o)
}
// Store "\\u0000" in scratch space.
// Store "0123456789abcdef" in scratch space.
// Also, store `{0x08:"b", 0x09:"t", 0x0a:"n", 0x0c:"f", 0x0d:"r"}`.
// into the scratch space.
mstore(0x15, 0x5c75303030303031323334353637383961626364656662746e006672)
// Bitmask for detecting `["\"","\\"]`.
let e := or(shl(0x22, 1), shl(0x5c, 1))
for { let end := add(s, mload(s)) } iszero(eq(s, end)) {} {
s := add(s, 1)
let c := and(mload(s), 0xff)
if iszero(lt(c, 0x20)) {
if iszero(and(shl(c, 1), e)) {
// Not in `["\"","\\"]`.
mstore8(o, c)
o := add(o, 1)
continue
}
mstore8(o, 0x5c) // "\\".
mstore8(add(o, 1), c)
o := add(o, 2)
continue
}
if iszero(and(shl(c, 1), 0x3700)) {
// Not in `["\b","\t","\n","\f","\d"]`.
mstore8(0x1d, mload(shr(4, c))) // Hex value.
mstore8(0x1e, mload(and(c, 15))) // Hex value.
mstore(o, mload(0x19)) // "\\u00XX".
o := add(o, 6)
continue
}
mstore8(o, 0x5c) // "\\".
mstore8(add(o, 1), mload(add(c, 8)))
o := add(o, 2)
}
if addDoubleQuotes {
mstore8(o, 34)
o := add(1, o)
}
mstore(o, 0) // Zeroize the slot after the string.
mstore(result, sub(o, add(result, 0x20))) // Store the length.
mstore(0x40, add(o, 0x20)) // Allocate memory.
}
}
/// @dev Escapes the string to be used within double-quotes in a JSON.
function escapeJSON(string memory s) internal pure returns (string memory result) {
result = escapeJSON(s, false);
}
/// @dev Encodes `s` so that it can be safely used in a URI,
/// just like `encodeURIComponent` in JavaScript.
/// See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
/// See: https://datatracker.ietf.org/doc/html/rfc2396
/// See: https://datatracker.ietf.org/doc/html/rfc3986
function encodeURIComponent(string memory s) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
// Store "0123456789ABCDEF" in scratch space.
// Uppercased to be consistent with JavaScript's implementation.
mstore(0x0f, 0x30313233343536373839414243444546)
let o := add(result, 0x20)
for { let end := add(s, mload(s)) } iszero(eq(s, end)) {} {
s := add(s, 1)
let c := and(mload(s), 0xff)
// If not in `[0-9A-Z-a-z-_.!~*'()]`.
if iszero(and(1, shr(c, 0x47fffffe87fffffe03ff678200000000))) {
mstore8(o, 0x25) // '%'.
mstore8(add(o, 1), mload(and(shr(4, c), 15)))
mstore8(add(o, 2), mload(and(c, 15)))
o := add(o, 3)
continue
}
mstore8(o, c)
o := add(o, 1)
}
mstore(result, sub(o, add(result, 0x20))) // Store the length.
mstore(o, 0) // Zeroize the slot after the string.
mstore(0x40, add(o, 0x20)) // Allocate memory.
}
}
/// @dev Returns whether `a` equals `b`.
function eq(string memory a, string memory b) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
result := eq(keccak256(add(a, 0x20), mload(a)), keccak256(add(b, 0x20), mload(b)))
}
}
/// @dev Returns whether `a` equals `b`, where `b` is a null-terminated small string.
function eqs(string memory a, bytes32 b) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
// These should be evaluated on compile time, as far as possible.
let m := not(shl(7, div(not(iszero(b)), 255))) // `0x7f7f ...`.
let x := not(or(m, or(b, add(m, and(b, m)))))
let r := shl(7, iszero(iszero(shr(128, x))))
r := or(r, shl(6, iszero(iszero(shr(64, shr(r, x))))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// forgefmt: disable-next-item
result := gt(eq(mload(a), add(iszero(x), xor(31, shr(3, r)))),
xor(shr(add(8, r), b), shr(add(8, r), mload(add(a, 0x20)))))
}
}
/// @dev Returns 0 if `a == b`, -1 if `a < b`, +1 if `a > b`.
/// If `a` == b[:a.length]`, and `a.length < b.length`, returns -1.
function cmp(string memory a, string memory b) internal pure returns (int256) {
return LibBytes.cmp(bytes(a), bytes(b));
}
/// @dev Packs a single string with its length into a single word.
/// Returns `bytes32(0)` if the length is zero or greater than 31.
function packOne(string memory a) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
// We don't need to zero right pad the string,
// since this is our own custom non-standard packing scheme.
result :=
mul(
// Load the length and the bytes.
mload(add(a, 0x1f)),
// `length != 0 && length < 32`. Abuses underflow.
// Assumes that the length is valid and within the block gas limit.
lt(sub(mload(a), 1), 0x1f)
)
}
}
/// @dev Unpacks a string packed using {packOne}.
/// Returns the empty string if `packed` is `bytes32(0)`.
/// If `packed` is not an output of {packOne}, the output behavior is undefined.
function unpackOne(bytes32 packed) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40) // Grab the free memory pointer.
mstore(0x40, add(result, 0x40)) // Allocate 2 words (1 for the length, 1 for the bytes).
mstore(result, 0) // Zeroize the length slot.
mstore(add(result, 0x1f), packed) // Store the length and bytes.
mstore(add(add(result, 0x20), mload(result)), 0) // Right pad with zeroes.
}
}
/// @dev Packs two strings with their lengths into a single word.
/// Returns `bytes32(0)` if combined length is zero or greater than 30.
function packTwo(string memory a, string memory b) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
let aLen := mload(a)
// We don't need to zero right pad the strings,
// since this is our own custom non-standard packing scheme.
result :=
mul(
or( // Load the length and the bytes of `a` and `b`.
shl(shl(3, sub(0x1f, aLen)), mload(add(a, aLen))), mload(sub(add(b, 0x1e), aLen))),
// `totalLen != 0 && totalLen < 31`. Abuses underflow.
// Assumes that the lengths are valid and within the block gas limit.
lt(sub(add(aLen, mload(b)), 1), 0x1e)
)
}
}
/// @dev Unpacks strings packed using {packTwo}.
/// Returns the empty strings if `packed` is `bytes32(0)`.
/// If `packed` is not an output of {packTwo}, the output behavior is undefined.
function unpackTwo(bytes32 packed)
internal
pure
returns (string memory resultA, string memory resultB)
{
/// @solidity memory-safe-assembly
assembly {
resultA := mload(0x40) // Grab the free memory pointer.
resultB := add(resultA, 0x40)
// Allocate 2 words for each string (1 for the length, 1 for the byte). Total 4 words.
mstore(0x40, add(resultB, 0x40))
// Zeroize the length slots.
mstore(resultA, 0)
mstore(resultB, 0)
// Store the lengths and bytes.
mstore(add(resultA, 0x1f), packed)
mstore(add(resultB, 0x1f), mload(add(add(resultA, 0x20), mload(resultA))))
// Right pad with zeroes.
mstore(add(add(resultA, 0x20), mload(resultA)), 0)
mstore(add(add(resultB, 0x20), mload(resultB)), 0)
}
}
/// @dev Directly returns `a` without copying.
function directReturn(string memory a) internal pure {
assembly {
// Assumes that the string does not start from the scratch space.
let retStart := sub(a, 0x20)
let retUnpaddedSize := add(mload(a), 0x40)
// Right pad with zeroes. Just in case the string is produced
// by a method that doesn't zero right pad.
mstore(add(retStart, retUnpaddedSize), 0)
mstore(retStart, 0x20) // Store the return offset.
// End the transaction, returning the string.
return(retStart, and(not(0x1f), add(0x1f, retUnpaddedSize)))
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Simple ERC20 + EIP-2612 implementation.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/tokens/ERC20.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol)
///
/// @dev Note:
/// - The ERC20 standard allows minting and transferring to and from the zero address,
/// minting and transferring zero tokens, as well as self-approvals.
/// For performance, this implementation WILL NOT revert for such actions.
/// Please add any checks with overrides if desired.
/// - The `permit` function uses the ecrecover precompile (0x1).
///
/// If you are overriding:
/// - NEVER violate the ERC20 invariant:
/// the total sum of all balances must be equal to `totalSupply()`.
/// - Check that the overridden function is actually used in the function you want to
/// change the behavior of. Much of the code has been manually inlined for performance.
abstract contract ERC20 {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The total supply has overflowed.
error TotalSupplyOverflow();
/// @dev The allowance has overflowed.
error AllowanceOverflow();
/// @dev The allowance has underflowed.
error AllowanceUnderflow();
/// @dev Insufficient balance.
error InsufficientBalance();
/// @dev Insufficient allowance.
error InsufficientAllowance();
/// @dev The permit is invalid.
error InvalidPermit();
/// @dev The permit has expired.
error PermitExpired();
/// @dev The allowance of Permit2 is fixed at infinity.
error Permit2AllowanceIsFixedAtInfinity();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EVENTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Emitted when `amount` tokens is transferred from `from` to `to`.
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @dev Emitted when `amount` tokens is approved by `owner` to be used by `spender`.
event Approval(address indexed owner, address indexed spender, uint256 amount);
/// @dev `keccak256(bytes("Transfer(address,address,uint256)"))`.
uint256 private constant _TRANSFER_EVENT_SIGNATURE =
0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef;
/// @dev `keccak256(bytes("Approval(address,address,uint256)"))`.
uint256 private constant _APPROVAL_EVENT_SIGNATURE =
0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STORAGE */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The storage slot for the total supply.
uint256 private constant _TOTAL_SUPPLY_SLOT = 0x05345cdf77eb68f44c;
/// @dev The balance slot of `owner` is given by:
/// ```
/// mstore(0x0c, _BALANCE_SLOT_SEED)
/// mstore(0x00, owner)
/// let balanceSlot := keccak256(0x0c, 0x20)
/// ```
uint256 private constant _BALANCE_SLOT_SEED = 0x87a211a2;
/// @dev The allowance slot of (`owner`, `spender`) is given by:
/// ```
/// mstore(0x20, spender)
/// mstore(0x0c, _ALLOWANCE_SLOT_SEED)
/// mstore(0x00, owner)
/// let allowanceSlot := keccak256(0x0c, 0x34)
/// ```
uint256 private constant _ALLOWANCE_SLOT_SEED = 0x7f5e9f20;
/// @dev The nonce slot of `owner` is given by:
/// ```
/// mstore(0x0c, _NONCES_SLOT_SEED)
/// mstore(0x00, owner)
/// let nonceSlot := keccak256(0x0c, 0x20)
/// ```
uint256 private constant _NONCES_SLOT_SEED = 0x38377508;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev `(_NONCES_SLOT_SEED << 16) | 0x1901`.
uint256 private constant _NONCES_SLOT_SEED_WITH_SIGNATURE_PREFIX = 0x383775081901;
/// @dev `keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)")`.
bytes32 private constant _DOMAIN_TYPEHASH =
0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f;
/// @dev `keccak256("1")`.
/// If you need to use a different version, override `_versionHash`.
bytes32 private constant _DEFAULT_VERSION_HASH =
0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6;
/// @dev `keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)")`.
bytes32 private constant _PERMIT_TYPEHASH =
0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
/// @dev The canonical Permit2 address.
/// For signature-based allowance granting for single transaction ERC20 `transferFrom`.
/// To enable, override `_givePermit2InfiniteAllowance()`.
/// [Github](https://github.com/Uniswap/permit2)
/// [Etherscan](https://etherscan.io/address/0x000000000022D473030F116dDEE9F6B43aC78BA3)
address internal constant _PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ERC20 METADATA */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the name of the token.
function name() public view virtual returns (string memory);
/// @dev Returns the symbol of the token.
function symbol() public view virtual returns (string memory);
/// @dev Returns the decimals places of the token.
function decimals() public view virtual returns (uint8) {
return 18;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ERC20 */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the amount of tokens in existence.
function totalSupply() public view virtual returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
result := sload(_TOTAL_SUPPLY_SLOT)
}
}
/// @dev Returns the amount of tokens owned by `owner`.
function balanceOf(address owner) public view virtual returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x0c, _BALANCE_SLOT_SEED)
mstore(0x00, owner)
result := sload(keccak256(0x0c, 0x20))
}
}
/// @dev Returns the amount of tokens that `spender` can spend on behalf of `owner`.
function allowance(address owner, address spender)
public
view
virtual
returns (uint256 result)
{
if (_givePermit2InfiniteAllowance()) {
if (spender == _PERMIT2) return type(uint256).max;
}
/// @solidity memory-safe-assembly
assembly {
mstore(0x20, spender)
mstore(0x0c, _ALLOWANCE_SLOT_SEED)
mstore(0x00, owner)
result := sload(keccak256(0x0c, 0x34))
}
}
/// @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
///
/// Emits a {Approval} event.
function approve(address spender, uint256 amount) public virtual returns (bool) {
if (_givePermit2InfiniteAllowance()) {
/// @solidity memory-safe-assembly
assembly {
// If `spender == _PERMIT2 && amount != type(uint256).max`.
if iszero(or(xor(shr(96, shl(96, spender)), _PERMIT2), iszero(not(amount)))) {
mstore(0x00, 0x3f68539a) // `Permit2AllowanceIsFixedAtInfinity()`.
revert(0x1c, 0x04)
}
}
}
/// @solidity memory-safe-assembly
assembly {
// Compute the allowance slot and store the amount.
mstore(0x20, spender)
mstore(0x0c, _ALLOWANCE_SLOT_SEED)
mstore(0x00, caller())
sstore(keccak256(0x0c, 0x34), amount)
// Emit the {Approval} event.
mstore(0x00, amount)
log3(0x00, 0x20, _APPROVAL_EVENT_SIGNATURE, caller(), shr(96, mload(0x2c)))
}
return true;
}
/// @dev Transfer `amount` tokens from the caller to `to`.
///
/// Requirements:
/// - `from` must at least have `amount`.
///
/// Emits a {Transfer} event.
function transfer(address to, uint256 amount) public virtual returns (bool) {
_beforeTokenTransfer(msg.sender, to, amount);
/// @solidity memory-safe-assembly
assembly {
// Compute the balance slot and load its value.
mstore(0x0c, _BALANCE_SLOT_SEED)
mstore(0x00, caller())
let fromBalanceSlot := keccak256(0x0c, 0x20)
let fromBalance := sload(fromBalanceSlot)
// Revert if insufficient balance.
if gt(amount, fromBalance) {
mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
revert(0x1c, 0x04)
}
// Subtract and store the updated balance.
sstore(fromBalanceSlot, sub(fromBalance, amount))
// Compute the balance slot of `to`.
mstore(0x00, to)
let toBalanceSlot := keccak256(0x0c, 0x20)
// Add and store the updated balance of `to`.
// Will not overflow because the sum of all user balances
// cannot exceed the maximum uint256 value.
sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
// Emit the {Transfer} event.
mstore(0x20, amount)
log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, caller(), shr(96, mload(0x0c)))
}
_afterTokenTransfer(msg.sender, to, amount);
return true;
}
/// @dev Transfers `amount` tokens from `from` to `to`.
///
/// Note: Does not update the allowance if it is the maximum uint256 value.
///
/// Requirements:
/// - `from` must at least have `amount`.
/// - The caller must have at least `amount` of allowance to transfer the tokens of `from`.
///
/// Emits a {Transfer} event.
function transferFrom(address from, address to, uint256 amount) public virtual returns (bool) {
_beforeTokenTransfer(from, to, amount);
// Code duplication is for zero-cost abstraction if possible.
if (_givePermit2InfiniteAllowance()) {
/// @solidity memory-safe-assembly
assembly {
let from_ := shl(96, from)
if iszero(eq(caller(), _PERMIT2)) {
// Compute the allowance slot and load its value.
mstore(0x20, caller())
mstore(0x0c, or(from_, _ALLOWANCE_SLOT_SEED))
let allowanceSlot := keccak256(0x0c, 0x34)
let allowance_ := sload(allowanceSlot)
// If the allowance is not the maximum uint256 value.
if not(allowance_) {
// Revert if the amount to be transferred exceeds the allowance.
if gt(amount, allowance_) {
mstore(0x00, 0x13be252b) // `InsufficientAllowance()`.
revert(0x1c, 0x04)
}
// Subtract and store the updated allowance.
sstore(allowanceSlot, sub(allowance_, amount))
}
}
// Compute the balance slot and load its value.
mstore(0x0c, or(from_, _BALANCE_SLOT_SEED))
let fromBalanceSlot := keccak256(0x0c, 0x20)
let fromBalance := sload(fromBalanceSlot)
// Revert if insufficient balance.
if gt(amount, fromBalance) {
mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
revert(0x1c, 0x04)
}
// Subtract and store the updated balance.
sstore(fromBalanceSlot, sub(fromBalance, amount))
// Compute the balance slot of `to`.
mstore(0x00, to)
let toBalanceSlot := keccak256(0x0c, 0x20)
// Add and store the updated balance of `to`.
// Will not overflow because the sum of all user balances
// cannot exceed the maximum uint256 value.
sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
// Emit the {Transfer} event.
mstore(0x20, amount)
log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, from_), shr(96, mload(0x0c)))
}
} else {
/// @solidity memory-safe-assembly
assembly {
let from_ := shl(96, from)
// Compute the allowance slot and load its value.
mstore(0x20, caller())
mstore(0x0c, or(from_, _ALLOWANCE_SLOT_SEED))
let allowanceSlot := keccak256(0x0c, 0x34)
let allowance_ := sload(allowanceSlot)
// If the allowance is not the maximum uint256 value.
if not(allowance_) {
// Revert if the amount to be transferred exceeds the allowance.
if gt(amount, allowance_) {
mstore(0x00, 0x13be252b) // `InsufficientAllowance()`.
revert(0x1c, 0x04)
}
// Subtract and store the updated allowance.
sstore(allowanceSlot, sub(allowance_, amount))
}
// Compute the balance slot and load its value.
mstore(0x0c, or(from_, _BALANCE_SLOT_SEED))
let fromBalanceSlot := keccak256(0x0c, 0x20)
let fromBalance := sload(fromBalanceSlot)
// Revert if insufficient balance.
if gt(amount, fromBalance) {
mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
revert(0x1c, 0x04)
}
// Subtract and store the updated balance.
sstore(fromBalanceSlot, sub(fromBalance, amount))
// Compute the balance slot of `to`.
mstore(0x00, to)
let toBalanceSlot := keccak256(0x0c, 0x20)
// Add and store the updated balance of `to`.
// Will not overflow because the sum of all user balances
// cannot exceed the maximum uint256 value.
sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
// Emit the {Transfer} event.
mstore(0x20, amount)
log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, from_), shr(96, mload(0x0c)))
}
}
_afterTokenTransfer(from, to, amount);
return true;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EIP-2612 */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev For more performance, override to return the constant value
/// of `keccak256(bytes(name()))` if `name()` will never change.
function _constantNameHash() internal view virtual returns (bytes32 result) {}
/// @dev If you need a different value, override this function.
function _versionHash() internal view virtual returns (bytes32 result) {
result = _DEFAULT_VERSION_HASH;
}
/// @dev For inheriting contracts to increment the nonce.
function _incrementNonce(address owner) internal virtual {
/// @solidity memory-safe-assembly
assembly {
mstore(0x0c, _NONCES_SLOT_SEED)
mstore(0x00, owner)
let nonceSlot := keccak256(0x0c, 0x20)
sstore(nonceSlot, add(1, sload(nonceSlot)))
}
}
/// @dev Returns the current nonce for `owner`.
/// This value is used to compute the signature for EIP-2612 permit.
function nonces(address owner) public view virtual returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
// Compute the nonce slot and load its value.
mstore(0x0c, _NONCES_SLOT_SEED)
mstore(0x00, owner)
result := sload(keccak256(0x0c, 0x20))
}
}
/// @dev Sets `value` as the allowance of `spender` over the tokens of `owner`,
/// authorized by a signed approval by `owner`.
///
/// Emits a {Approval} event.
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual {
if (_givePermit2InfiniteAllowance()) {
/// @solidity memory-safe-assembly
assembly {
// If `spender == _PERMIT2 && value != type(uint256).max`.
if iszero(or(xor(shr(96, shl(96, spender)), _PERMIT2), iszero(not(value)))) {
mstore(0x00, 0x3f68539a) // `Permit2AllowanceIsFixedAtInfinity()`.
revert(0x1c, 0x04)
}
}
}
bytes32 nameHash = _constantNameHash();
// We simply calculate it on-the-fly to allow for cases where the `name` may change.
if (nameHash == bytes32(0)) nameHash = keccak256(bytes(name()));
bytes32 versionHash = _versionHash();
/// @solidity memory-safe-assembly
assembly {
// Revert if the block timestamp is greater than `deadline`.
if gt(timestamp(), deadline) {
mstore(0x00, 0x1a15a3cc) // `PermitExpired()`.
revert(0x1c, 0x04)
}
let m := mload(0x40) // Grab the free memory pointer.
// Clean the upper 96 bits.
owner := shr(96, shl(96, owner))
spender := shr(96, shl(96, spender))
// Compute the nonce slot and load its value.
mstore(0x0e, _NONCES_SLOT_SEED_WITH_SIGNATURE_PREFIX)
mstore(0x00, owner)
let nonceSlot := keccak256(0x0c, 0x20)
let nonceValue := sload(nonceSlot)
// Prepare the domain separator.
mstore(m, _DOMAIN_TYPEHASH)
mstore(add(m, 0x20), nameHash)
mstore(add(m, 0x40), versionHash)
mstore(add(m, 0x60), chainid())
mstore(add(m, 0x80), address())
mstore(0x2e, keccak256(m, 0xa0))
// Prepare the struct hash.
mstore(m, _PERMIT_TYPEHASH)
mstore(add(m, 0x20), owner)
mstore(add(m, 0x40), spender)
mstore(add(m, 0x60), value)
mstore(add(m, 0x80), nonceValue)
mstore(add(m, 0xa0), deadline)
mstore(0x4e, keccak256(m, 0xc0))
// Prepare the ecrecover calldata.
mstore(0x00, keccak256(0x2c, 0x42))
mstore(0x20, and(0xff, v))
mstore(0x40, r)
mstore(0x60, s)
let t := staticcall(gas(), 1, 0x00, 0x80, 0x20, 0x20)
// If the ecrecover fails, the returndatasize will be 0x00,
// `owner` will be checked if it equals the hash at 0x00,
// which evaluates to false (i.e. 0), and we will revert.
// If the ecrecover succeeds, the returndatasize will be 0x20,
// `owner` will be compared against the returned address at 0x20.
if iszero(eq(mload(returndatasize()), owner)) {
mstore(0x00, 0xddafbaef) // `InvalidPermit()`.
revert(0x1c, 0x04)
}
// Increment and store the updated nonce.
sstore(nonceSlot, add(nonceValue, t)) // `t` is 1 if ecrecover succeeds.
// Compute the allowance slot and store the value.
// The `owner` is already at slot 0x20.
mstore(0x40, or(shl(160, _ALLOWANCE_SLOT_SEED), spender))
sstore(keccak256(0x2c, 0x34), value)
// Emit the {Approval} event.
log3(add(m, 0x60), 0x20, _APPROVAL_EVENT_SIGNATURE, owner, spender)
mstore(0x40, m) // Restore the free memory pointer.
mstore(0x60, 0) // Restore the zero pointer.
}
}
/// @dev Returns the EIP-712 domain separator for the EIP-2612 permit.
function DOMAIN_SEPARATOR() public view virtual returns (bytes32 result) {
bytes32 nameHash = _constantNameHash();
// We simply calculate it on-the-fly to allow for cases where the `name` may change.
if (nameHash == bytes32(0)) nameHash = keccak256(bytes(name()));
bytes32 versionHash = _versionHash();
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Grab the free memory pointer.
mstore(m, _DOMAIN_TYPEHASH)
mstore(add(m, 0x20), nameHash)
mstore(add(m, 0x40), versionHash)
mstore(add(m, 0x60), chainid())
mstore(add(m, 0x80), address())
result := keccak256(m, 0xa0)
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL MINT FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Mints `amount` tokens to `to`, increasing the total supply.
///
/// Emits a {Transfer} event.
function _mint(address to, uint256 amount) internal virtual {
_beforeTokenTransfer(address(0), to, amount);
/// @solidity memory-safe-assembly
assembly {
let totalSupplyBefore := sload(_TOTAL_SUPPLY_SLOT)
let totalSupplyAfter := add(totalSupplyBefore, amount)
// Revert if the total supply overflows.
if lt(totalSupplyAfter, totalSupplyBefore) {
mstore(0x00, 0xe5cfe957) // `TotalSupplyOverflow()`.
revert(0x1c, 0x04)
}
// Store the updated total supply.
sstore(_TOTAL_SUPPLY_SLOT, totalSupplyAfter)
// Compute the balance slot and load its value.
mstore(0x0c, _BALANCE_SLOT_SEED)
mstore(0x00, to)
let toBalanceSlot := keccak256(0x0c, 0x20)
// Add and store the updated balance.
sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
// Emit the {Transfer} event.
mstore(0x20, amount)
log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, 0, shr(96, mload(0x0c)))
}
_afterTokenTransfer(address(0), to, amount);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL BURN FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Burns `amount` tokens from `from`, reducing the total supply.
///
/// Emits a {Transfer} event.
function _burn(address from, uint256 amount) internal virtual {
_beforeTokenTransfer(from, address(0), amount);
/// @solidity memory-safe-assembly
assembly {
// Compute the balance slot and load its value.
mstore(0x0c, _BALANCE_SLOT_SEED)
mstore(0x00, from)
let fromBalanceSlot := keccak256(0x0c, 0x20)
let fromBalance := sload(fromBalanceSlot)
// Revert if insufficient balance.
if gt(amount, fromBalance) {
mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
revert(0x1c, 0x04)
}
// Subtract and store the updated balance.
sstore(fromBalanceSlot, sub(fromBalance, amount))
// Subtract and store the updated total supply.
sstore(_TOTAL_SUPPLY_SLOT, sub(sload(_TOTAL_SUPPLY_SLOT), amount))
// Emit the {Transfer} event.
mstore(0x00, amount)
log3(0x00, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, shl(96, from)), 0)
}
_afterTokenTransfer(from, address(0), amount);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL TRANSFER FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Moves `amount` of tokens from `from` to `to`.
function _transfer(address from, address to, uint256 amount) internal virtual {
_beforeTokenTransfer(from, to, amount);
/// @solidity memory-safe-assembly
assembly {
let from_ := shl(96, from)
// Compute the balance slot and load its value.
mstore(0x0c, or(from_, _BALANCE_SLOT_SEED))
let fromBalanceSlot := keccak256(0x0c, 0x20)
let fromBalance := sload(fromBalanceSlot)
// Revert if insufficient balance.
if gt(amount, fromBalance) {
mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
revert(0x1c, 0x04)
}
// Subtract and store the updated balance.
sstore(fromBalanceSlot, sub(fromBalance, amount))
// Compute the balance slot of `to`.
mstore(0x00, to)
let toBalanceSlot := keccak256(0x0c, 0x20)
// Add and store the updated balance of `to`.
// Will not overflow because the sum of all user balances
// cannot exceed the maximum uint256 value.
sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
// Emit the {Transfer} event.
mstore(0x20, amount)
log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, from_), shr(96, mload(0x0c)))
}
_afterTokenTransfer(from, to, amount);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL ALLOWANCE FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Updates the allowance of `owner` for `spender` based on spent `amount`.
function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
if (_givePermit2InfiniteAllowance()) {
if (spender == _PERMIT2) return; // Do nothing, as allowance is infinite.
}
/// @solidity memory-safe-assembly
assembly {
// Compute the allowance slot and load its value.
mstore(0x20, spender)
mstore(0x0c, _ALLOWANCE_SLOT_SEED)
mstore(0x00, owner)
let allowanceSlot := keccak256(0x0c, 0x34)
let allowance_ := sload(allowanceSlot)
// If the allowance is not the maximum uint256 value.
if not(allowance_) {
// Revert if the amount to be transferred exceeds the allowance.
if gt(amount, allowance_) {
mstore(0x00, 0x13be252b) // `InsufficientAllowance()`.
revert(0x1c, 0x04)
}
// Subtract and store the updated allowance.
sstore(allowanceSlot, sub(allowance_, amount))
}
}
}
/// @dev Sets `amount` as the allowance of `spender` over the tokens of `owner`.
///
/// Emits a {Approval} event.
function _approve(address owner, address spender, uint256 amount) internal virtual {
if (_givePermit2InfiniteAllowance()) {
/// @solidity memory-safe-assembly
assembly {
// If `spender == _PERMIT2 && amount != type(uint256).max`.
if iszero(or(xor(shr(96, shl(96, spender)), _PERMIT2), iszero(not(amount)))) {
mstore(0x00, 0x3f68539a) // `Permit2AllowanceIsFixedAtInfinity()`.
revert(0x1c, 0x04)
}
}
}
/// @solidity memory-safe-assembly
assembly {
let owner_ := shl(96, owner)
// Compute the allowance slot and store the amount.
mstore(0x20, spender)
mstore(0x0c, or(owner_, _ALLOWANCE_SLOT_SEED))
sstore(keccak256(0x0c, 0x34), amount)
// Emit the {Approval} event.
mstore(0x00, amount)
log3(0x00, 0x20, _APPROVAL_EVENT_SIGNATURE, shr(96, owner_), shr(96, mload(0x2c)))
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* HOOKS TO OVERRIDE */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Hook that is called before any transfer of tokens.
/// This includes minting and burning.
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}
/// @dev Hook that is called after any transfer of tokens.
/// This includes minting and burning.
function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PERMIT2 */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns whether to fix the Permit2 contract's allowance at infinity.
///
/// This value should be kept constant after contract initialization,
/// or else the actual allowance values may not match with the {Approval} events.
/// For best performance, return a compile-time constant for zero-cost abstraction.
function _givePermit2InfiniteAllowance() internal view virtual returns (bool) {
return true;
}
}// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.10; uint256 constant BASIS_POINTS = 10_000; uint256 constant WAD = 1e18; address constant NATIVE_ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // Roles uint256 constant FEE_MANAGER_ROLE = 1 << 0; uint256 constant FEE_COLLECTOR_ROLE = 1 << 1; uint256 constant DEV_ROLE = 1 << 2; uint256 constant PAUSER_ROLE = 1 << 3; uint256 constant GOVERNANCE_ROLE = 1 << 4; uint256 constant CONNECTOR_REGISTRY_ROLE = 1 << 5; // TwoCrypto uint256 constant TARGET_INDEX = 0; uint256 constant PT_INDEX = 1; // Currency address constant WETH_ETHEREUM_MAINNET = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // Default fee split ratio (100% to Curator) uint16 constant DEFAULT_SPLIT_RATIO_BPS = uint16(BASIS_POINTS);
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Library for byte related operations.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/LibBytes.sol)
library LibBytes {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STRUCTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Goated bytes storage struct that totally MOGs, no cap, fr.
/// Uses less gas and bytecode than Solidity's native bytes storage. It's meta af.
/// Packs length with the first 31 bytes if <255 bytes, so it’s mad tight.
struct BytesStorage {
bytes32 _spacer;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The constant returned when the `search` is not found in the bytes.
uint256 internal constant NOT_FOUND = type(uint256).max;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* BYTE STORAGE OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Sets the value of the bytes storage `$` to `s`.
function set(BytesStorage storage $, bytes memory s) internal {
/// @solidity memory-safe-assembly
assembly {
let n := mload(s)
let packed := or(0xff, shl(8, n))
for { let i := 0 } 1 {} {
if iszero(gt(n, 0xfe)) {
i := 0x1f
packed := or(n, shl(8, mload(add(s, i))))
if iszero(gt(n, i)) { break }
}
let o := add(s, 0x20)
mstore(0x00, $.slot)
for { let p := keccak256(0x00, 0x20) } 1 {} {
sstore(add(p, shr(5, i)), mload(add(o, i)))
i := add(i, 0x20)
if iszero(lt(i, n)) { break }
}
break
}
sstore($.slot, packed)
}
}
/// @dev Sets the value of the bytes storage `$` to `s`.
function setCalldata(BytesStorage storage $, bytes calldata s) internal {
/// @solidity memory-safe-assembly
assembly {
let packed := or(0xff, shl(8, s.length))
for { let i := 0 } 1 {} {
if iszero(gt(s.length, 0xfe)) {
i := 0x1f
packed := or(s.length, shl(8, shr(8, calldataload(s.offset))))
if iszero(gt(s.length, i)) { break }
}
mstore(0x00, $.slot)
for { let p := keccak256(0x00, 0x20) } 1 {} {
sstore(add(p, shr(5, i)), calldataload(add(s.offset, i)))
i := add(i, 0x20)
if iszero(lt(i, s.length)) { break }
}
break
}
sstore($.slot, packed)
}
}
/// @dev Sets the value of the bytes storage `$` to the empty bytes.
function clear(BytesStorage storage $) internal {
delete $._spacer;
}
/// @dev Returns whether the value stored is `$` is the empty bytes "".
function isEmpty(BytesStorage storage $) internal view returns (bool) {
return uint256($._spacer) & 0xff == uint256(0);
}
/// @dev Returns the length of the value stored in `$`.
function length(BytesStorage storage $) internal view returns (uint256 result) {
result = uint256($._spacer);
/// @solidity memory-safe-assembly
assembly {
let n := and(0xff, result)
result := or(mul(shr(8, result), eq(0xff, n)), mul(n, iszero(eq(0xff, n))))
}
}
/// @dev Returns the value stored in `$`.
function get(BytesStorage storage $) internal view returns (bytes memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
let o := add(result, 0x20)
let packed := sload($.slot)
let n := shr(8, packed)
for { let i := 0 } 1 {} {
if iszero(eq(or(packed, 0xff), packed)) {
mstore(o, packed)
n := and(0xff, packed)
i := 0x1f
if iszero(gt(n, i)) { break }
}
mstore(0x00, $.slot)
for { let p := keccak256(0x00, 0x20) } 1 {} {
mstore(add(o, i), sload(add(p, shr(5, i))))
i := add(i, 0x20)
if iszero(lt(i, n)) { break }
}
break
}
mstore(result, n) // Store the length of the memory.
mstore(add(o, n), 0) // Zeroize the slot after the bytes.
mstore(0x40, add(add(o, n), 0x20)) // Allocate memory.
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* BYTES OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns `subject` all occurrences of `needle` replaced with `replacement`.
function replace(bytes memory subject, bytes memory needle, bytes memory replacement)
internal
pure
returns (bytes memory result)
{
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
let needleLen := mload(needle)
let replacementLen := mload(replacement)
let d := sub(result, subject) // Memory difference.
let i := add(subject, 0x20) // Subject bytes pointer.
mstore(0x00, add(i, mload(subject))) // End of subject.
if iszero(gt(needleLen, mload(subject))) {
let subjectSearchEnd := add(sub(mload(0x00), needleLen), 1)
let h := 0 // The hash of `needle`.
if iszero(lt(needleLen, 0x20)) { h := keccak256(add(needle, 0x20), needleLen) }
let s := mload(add(needle, 0x20))
for { let m := shl(3, sub(0x20, and(needleLen, 0x1f))) } 1 {} {
let t := mload(i)
// Whether the first `needleLen % 32` bytes of `subject` and `needle` matches.
if iszero(shr(m, xor(t, s))) {
if h {
if iszero(eq(keccak256(i, needleLen), h)) {
mstore(add(i, d), t)
i := add(i, 1)
if iszero(lt(i, subjectSearchEnd)) { break }
continue
}
}
// Copy the `replacement` one word at a time.
for { let j := 0 } 1 {} {
mstore(add(add(i, d), j), mload(add(add(replacement, 0x20), j)))
j := add(j, 0x20)
if iszero(lt(j, replacementLen)) { break }
}
d := sub(add(d, replacementLen), needleLen)
if needleLen {
i := add(i, needleLen)
if iszero(lt(i, subjectSearchEnd)) { break }
continue
}
}
mstore(add(i, d), t)
i := add(i, 1)
if iszero(lt(i, subjectSearchEnd)) { break }
}
}
let end := mload(0x00)
let n := add(sub(d, add(result, 0x20)), end)
// Copy the rest of the bytes one word at a time.
for {} lt(i, end) { i := add(i, 0x20) } { mstore(add(i, d), mload(i)) }
let o := add(i, d)
mstore(o, 0) // Zeroize the slot after the bytes.
mstore(0x40, add(o, 0x20)) // Allocate memory.
mstore(result, n) // Store the length.
}
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from left to right, starting from `from`.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function indexOf(bytes memory subject, bytes memory needle, uint256 from)
internal
pure
returns (uint256 result)
{
/// @solidity memory-safe-assembly
assembly {
result := not(0) // Initialize to `NOT_FOUND`.
for { let subjectLen := mload(subject) } 1 {} {
if iszero(mload(needle)) {
result := from
if iszero(gt(from, subjectLen)) { break }
result := subjectLen
break
}
let needleLen := mload(needle)
let subjectStart := add(subject, 0x20)
subject := add(subjectStart, from)
let end := add(sub(add(subjectStart, subjectLen), needleLen), 1)
let m := shl(3, sub(0x20, and(needleLen, 0x1f)))
let s := mload(add(needle, 0x20))
if iszero(and(lt(subject, end), lt(from, subjectLen))) { break }
if iszero(lt(needleLen, 0x20)) {
for { let h := keccak256(add(needle, 0x20), needleLen) } 1 {} {
if iszero(shr(m, xor(mload(subject), s))) {
if eq(keccak256(subject, needleLen), h) {
result := sub(subject, subjectStart)
break
}
}
subject := add(subject, 1)
if iszero(lt(subject, end)) { break }
}
break
}
for {} 1 {} {
if iszero(shr(m, xor(mload(subject), s))) {
result := sub(subject, subjectStart)
break
}
subject := add(subject, 1)
if iszero(lt(subject, end)) { break }
}
break
}
}
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from left to right.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function indexOf(bytes memory subject, bytes memory needle) internal pure returns (uint256) {
return indexOf(subject, needle, 0);
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from right to left, starting from `from`.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function lastIndexOf(bytes memory subject, bytes memory needle, uint256 from)
internal
pure
returns (uint256 result)
{
/// @solidity memory-safe-assembly
assembly {
for {} 1 {} {
result := not(0) // Initialize to `NOT_FOUND`.
let needleLen := mload(needle)
if gt(needleLen, mload(subject)) { break }
let w := result
let fromMax := sub(mload(subject), needleLen)
if iszero(gt(fromMax, from)) { from := fromMax }
let end := add(add(subject, 0x20), w)
subject := add(add(subject, 0x20), from)
if iszero(gt(subject, end)) { break }
// As this function is not too often used,
// we shall simply use keccak256 for smaller bytecode size.
for { let h := keccak256(add(needle, 0x20), needleLen) } 1 {} {
if eq(keccak256(subject, needleLen), h) {
result := sub(subject, add(end, 1))
break
}
subject := add(subject, w) // `sub(subject, 1)`.
if iszero(gt(subject, end)) { break }
}
break
}
}
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from right to left.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function lastIndexOf(bytes memory subject, bytes memory needle)
internal
pure
returns (uint256)
{
return lastIndexOf(subject, needle, type(uint256).max);
}
/// @dev Returns true if `needle` is found in `subject`, false otherwise.
function contains(bytes memory subject, bytes memory needle) internal pure returns (bool) {
return indexOf(subject, needle) != NOT_FOUND;
}
/// @dev Returns whether `subject` starts with `needle`.
function startsWith(bytes memory subject, bytes memory needle)
internal
pure
returns (bool result)
{
/// @solidity memory-safe-assembly
assembly {
let n := mload(needle)
// Just using keccak256 directly is actually cheaper.
let t := eq(keccak256(add(subject, 0x20), n), keccak256(add(needle, 0x20), n))
result := lt(gt(n, mload(subject)), t)
}
}
/// @dev Returns whether `subject` ends with `needle`.
function endsWith(bytes memory subject, bytes memory needle)
internal
pure
returns (bool result)
{
/// @solidity memory-safe-assembly
assembly {
let n := mload(needle)
let notInRange := gt(n, mload(subject))
// `subject + 0x20 + max(subject.length - needle.length, 0)`.
let t := add(add(subject, 0x20), mul(iszero(notInRange), sub(mload(subject), n)))
// Just using keccak256 directly is actually cheaper.
result := gt(eq(keccak256(t, n), keccak256(add(needle, 0x20), n)), notInRange)
}
}
/// @dev Returns `subject` repeated `times`.
function repeat(bytes memory subject, uint256 times)
internal
pure
returns (bytes memory result)
{
/// @solidity memory-safe-assembly
assembly {
let l := mload(subject) // Subject length.
if iszero(or(iszero(times), iszero(l))) {
result := mload(0x40)
subject := add(subject, 0x20)
let o := add(result, 0x20)
for {} 1 {} {
// Copy the `subject` one word at a time.
for { let j := 0 } 1 {} {
mstore(add(o, j), mload(add(subject, j)))
j := add(j, 0x20)
if iszero(lt(j, l)) { break }
}
o := add(o, l)
times := sub(times, 1)
if iszero(times) { break }
}
mstore(o, 0) // Zeroize the slot after the bytes.
mstore(0x40, add(o, 0x20)) // Allocate memory.
mstore(result, sub(o, add(result, 0x20))) // Store the length.
}
}
}
/// @dev Returns a copy of `subject` sliced from `start` to `end` (exclusive).
/// `start` and `end` are byte offsets.
function slice(bytes memory subject, uint256 start, uint256 end)
internal
pure
returns (bytes memory result)
{
/// @solidity memory-safe-assembly
assembly {
let l := mload(subject) // Subject length.
if iszero(gt(l, end)) { end := l }
if iszero(gt(l, start)) { start := l }
if lt(start, end) {
result := mload(0x40)
let n := sub(end, start)
let i := add(subject, start)
let w := not(0x1f)
// Copy the `subject` one word at a time, backwards.
for { let j := and(add(n, 0x1f), w) } 1 {} {
mstore(add(result, j), mload(add(i, j)))
j := add(j, w) // `sub(j, 0x20)`.
if iszero(j) { break }
}
let o := add(add(result, 0x20), n)
mstore(o, 0) // Zeroize the slot after the bytes.
mstore(0x40, add(o, 0x20)) // Allocate memory.
mstore(result, n) // Store the length.
}
}
}
/// @dev Returns a copy of `subject` sliced from `start` to the end of the bytes.
/// `start` is a byte offset.
function slice(bytes memory subject, uint256 start)
internal
pure
returns (bytes memory result)
{
result = slice(subject, start, type(uint256).max);
}
/// @dev Returns a copy of `subject` sliced from `start` to `end` (exclusive).
/// `start` and `end` are byte offsets. Faster than Solidity's native slicing.
function sliceCalldata(bytes calldata subject, uint256 start, uint256 end)
internal
pure
returns (bytes calldata result)
{
/// @solidity memory-safe-assembly
assembly {
end := xor(end, mul(xor(end, subject.length), lt(subject.length, end)))
start := xor(start, mul(xor(start, subject.length), lt(subject.length, start)))
result.offset := add(subject.offset, start)
result.length := mul(lt(start, end), sub(end, start))
}
}
/// @dev Returns a copy of `subject` sliced from `start` to the end of the bytes.
/// `start` is a byte offset. Faster than Solidity's native slicing.
function sliceCalldata(bytes calldata subject, uint256 start)
internal
pure
returns (bytes calldata result)
{
/// @solidity memory-safe-assembly
assembly {
start := xor(start, mul(xor(start, subject.length), lt(subject.length, start)))
result.offset := add(subject.offset, start)
result.length := mul(lt(start, subject.length), sub(subject.length, start))
}
}
/// @dev Reduces the size of `subject` to `n`.
/// If `n` is greater than the size of `subject`, this will be a no-op.
function truncate(bytes memory subject, uint256 n)
internal
pure
returns (bytes memory result)
{
/// @solidity memory-safe-assembly
assembly {
result := subject
mstore(mul(lt(n, mload(result)), result), n)
}
}
/// @dev Returns a copy of `subject`, with the length reduced to `n`.
/// If `n` is greater than the size of `subject`, this will be a no-op.
function truncatedCalldata(bytes calldata subject, uint256 n)
internal
pure
returns (bytes calldata result)
{
/// @solidity memory-safe-assembly
assembly {
result.offset := subject.offset
result.length := xor(n, mul(xor(n, subject.length), lt(subject.length, n)))
}
}
/// @dev Returns all the indices of `needle` in `subject`.
/// The indices are byte offsets.
function indicesOf(bytes memory subject, bytes memory needle)
internal
pure
returns (uint256[] memory result)
{
/// @solidity memory-safe-assembly
assembly {
let searchLen := mload(needle)
if iszero(gt(searchLen, mload(subject))) {
result := mload(0x40)
let i := add(subject, 0x20)
let o := add(result, 0x20)
let subjectSearchEnd := add(sub(add(i, mload(subject)), searchLen), 1)
let h := 0 // The hash of `needle`.
if iszero(lt(searchLen, 0x20)) { h := keccak256(add(needle, 0x20), searchLen) }
let s := mload(add(needle, 0x20))
for { let m := shl(3, sub(0x20, and(searchLen, 0x1f))) } 1 {} {
let t := mload(i)
// Whether the first `searchLen % 32` bytes of `subject` and `needle` matches.
if iszero(shr(m, xor(t, s))) {
if h {
if iszero(eq(keccak256(i, searchLen), h)) {
i := add(i, 1)
if iszero(lt(i, subjectSearchEnd)) { break }
continue
}
}
mstore(o, sub(i, add(subject, 0x20))) // Append to `result`.
o := add(o, 0x20)
i := add(i, searchLen) // Advance `i` by `searchLen`.
if searchLen {
if iszero(lt(i, subjectSearchEnd)) { break }
continue
}
}
i := add(i, 1)
if iszero(lt(i, subjectSearchEnd)) { break }
}
mstore(result, shr(5, sub(o, add(result, 0x20)))) // Store the length of `result`.
// Allocate memory for result.
// We allocate one more word, so this array can be recycled for {split}.
mstore(0x40, add(o, 0x20))
}
}
}
/// @dev Returns a arrays of bytess based on the `delimiter` inside of the `subject` bytes.
function split(bytes memory subject, bytes memory delimiter)
internal
pure
returns (bytes[] memory result)
{
uint256[] memory indices = indicesOf(subject, delimiter);
/// @solidity memory-safe-assembly
assembly {
let w := not(0x1f)
let indexPtr := add(indices, 0x20)
let indicesEnd := add(indexPtr, shl(5, add(mload(indices), 1)))
mstore(add(indicesEnd, w), mload(subject))
mstore(indices, add(mload(indices), 1))
for { let prevIndex := 0 } 1 {} {
let index := mload(indexPtr)
mstore(indexPtr, 0x60)
if iszero(eq(index, prevIndex)) {
let element := mload(0x40)
let l := sub(index, prevIndex)
mstore(element, l) // Store the length of the element.
// Copy the `subject` one word at a time, backwards.
for { let o := and(add(l, 0x1f), w) } 1 {} {
mstore(add(element, o), mload(add(add(subject, prevIndex), o)))
o := add(o, w) // `sub(o, 0x20)`.
if iszero(o) { break }
}
mstore(add(add(element, 0x20), l), 0) // Zeroize the slot after the bytes.
// Allocate memory for the length and the bytes, rounded up to a multiple of 32.
mstore(0x40, add(element, and(add(l, 0x3f), w)))
mstore(indexPtr, element) // Store the `element` into the array.
}
prevIndex := add(index, mload(delimiter))
indexPtr := add(indexPtr, 0x20)
if iszero(lt(indexPtr, indicesEnd)) { break }
}
result := indices
if iszero(mload(delimiter)) {
result := add(indices, 0x20)
mstore(result, sub(mload(indices), 2))
}
}
}
/// @dev Returns a concatenated bytes of `a` and `b`.
/// Cheaper than `bytes.concat()` and does not de-align the free memory pointer.
function concat(bytes memory a, bytes memory b) internal pure returns (bytes memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
let w := not(0x1f)
let aLen := mload(a)
// Copy `a` one word at a time, backwards.
for { let o := and(add(aLen, 0x20), w) } 1 {} {
mstore(add(result, o), mload(add(a, o)))
o := add(o, w) // `sub(o, 0x20)`.
if iszero(o) { break }
}
let bLen := mload(b)
let output := add(result, aLen)
// Copy `b` one word at a time, backwards.
for { let o := and(add(bLen, 0x20), w) } 1 {} {
mstore(add(output, o), mload(add(b, o)))
o := add(o, w) // `sub(o, 0x20)`.
if iszero(o) { break }
}
let totalLen := add(aLen, bLen)
let last := add(add(result, 0x20), totalLen)
mstore(last, 0) // Zeroize the slot after the bytes.
mstore(result, totalLen) // Store the length.
mstore(0x40, add(last, 0x20)) // Allocate memory.
}
}
/// @dev Returns whether `a` equals `b`.
function eq(bytes memory a, bytes memory b) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
result := eq(keccak256(add(a, 0x20), mload(a)), keccak256(add(b, 0x20), mload(b)))
}
}
/// @dev Returns whether `a` equals `b`, where `b` is a null-terminated small bytes.
function eqs(bytes memory a, bytes32 b) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
// These should be evaluated on compile time, as far as possible.
let m := not(shl(7, div(not(iszero(b)), 255))) // `0x7f7f ...`.
let x := not(or(m, or(b, add(m, and(b, m)))))
let r := shl(7, iszero(iszero(shr(128, x))))
r := or(r, shl(6, iszero(iszero(shr(64, shr(r, x))))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// forgefmt: disable-next-item
result := gt(eq(mload(a), add(iszero(x), xor(31, shr(3, r)))),
xor(shr(add(8, r), b), shr(add(8, r), mload(add(a, 0x20)))))
}
}
/// @dev Returns 0 if `a == b`, -1 if `a < b`, +1 if `a > b`.
/// If `a` == b[:a.length]`, and `a.length < b.length`, returns -1.
function cmp(bytes memory a, bytes memory b) internal pure returns (int256 result) {
/// @solidity memory-safe-assembly
assembly {
let aLen := mload(a)
let bLen := mload(b)
let n := and(xor(aLen, mul(xor(aLen, bLen), lt(bLen, aLen))), not(0x1f))
if n {
for { let i := 0x20 } 1 {} {
let x := mload(add(a, i))
let y := mload(add(b, i))
if iszero(or(xor(x, y), eq(i, n))) {
i := add(i, 0x20)
continue
}
result := sub(gt(x, y), lt(x, y))
break
}
}
// forgefmt: disable-next-item
if iszero(result) {
let l := 0x201f1e1d1c1b1a191817161514131211100f0e0d0c0b0a090807060504030201
let x := and(mload(add(add(a, 0x20), n)), shl(shl(3, byte(sub(aLen, n), l)), not(0)))
let y := and(mload(add(add(b, 0x20), n)), shl(shl(3, byte(sub(bLen, n), l)), not(0)))
result := sub(gt(x, y), lt(x, y))
if iszero(result) { result := sub(gt(aLen, bLen), lt(aLen, bLen)) }
}
}
}
/// @dev Directly returns `a` without copying.
function directReturn(bytes memory a) internal pure {
assembly {
// Assumes that the bytes does not start from the scratch space.
let retStart := sub(a, 0x20)
let retUnpaddedSize := add(mload(a), 0x40)
// Right pad with zeroes. Just in case the bytes is produced
// by a method that doesn't zero right pad.
mstore(add(retStart, retUnpaddedSize), 0)
mstore(retStart, 0x20) // Store the return offset.
// End the transaction, returning the bytes.
return(retStart, and(not(0x1f), add(0x1f, retUnpaddedSize)))
}
}
/// @dev Directly returns `a` with minimal copying.
function directReturn(bytes[] memory a) internal pure {
assembly {
let n := mload(a) // `a.length`.
let o := add(a, 0x20) // Start of elements in `a`.
let u := a // Highest memory slot.
let w := not(0x1f)
for { let i := 0 } iszero(eq(i, n)) { i := add(i, 1) } {
let c := add(o, shl(5, i)) // Location of pointer to `a[i]`.
let s := mload(c) // `a[i]`.
let l := mload(s) // `a[i].length`.
let r := and(l, 0x1f) // `a[i].length % 32`.
let z := add(0x20, and(l, w)) // Offset of last word in `a[i]` from `s`.
// If `s` comes before `o`, or `s` is not zero right padded.
if iszero(lt(lt(s, o), or(iszero(r), iszero(shl(shl(3, r), mload(add(s, z))))))) {
let m := mload(0x40)
mstore(m, l) // Copy `a[i].length`.
for {} 1 {} {
mstore(add(m, z), mload(add(s, z))) // Copy `a[i]`, backwards.
z := add(z, w) // `sub(z, 0x20)`.
if iszero(z) { break }
}
let e := add(add(m, 0x20), l)
mstore(e, 0) // Zeroize the slot after the copied bytes.
mstore(0x40, add(e, 0x20)) // Allocate memory.
s := m
}
mstore(c, sub(s, o)) // Convert to calldata offset.
let t := add(l, add(s, 0x20))
if iszero(lt(t, u)) { u := t }
}
let retStart := add(a, w) // Assumes `a` doesn't start from scratch space.
mstore(retStart, 0x20) // Store the return offset.
return(retStart, add(0x40, sub(u, retStart))) // End the transaction.
}
}
/// @dev Returns the word at `offset`, without any bounds checks.
/// To load an address, you can use `address(bytes20(load(a, offset)))`.
function load(bytes memory a, uint256 offset) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(add(add(a, 0x20), offset))
}
}
/// @dev Returns the word at `offset`, without any bounds checks.
/// To load an address, you can use `address(bytes20(loadCalldata(a, offset)))`.
function loadCalldata(bytes calldata a, uint256 offset)
internal
pure
returns (bytes32 result)
{
/// @solidity memory-safe-assembly
assembly {
result := calldataload(add(a.offset, offset))
}
}
/// @dev Returns empty calldata bytes. For silencing the compiler.
function emptyCalldata() internal pure returns (bytes calldata result) {
/// @solidity memory-safe-assembly
assembly {
result.length := 0
}
}
}{
"remappings": [
"@openzeppelin/=node_modules/@openzeppelin/",
"forge-std/=node_modules/forge-std/",
"halmos-cheatcodes/=node_modules/halmos-cheatcodes/",
"solady/=node_modules/solady/"
],
"optimizer": {
"enabled": true,
"runs": 1
},
"metadata": {
"useLiteralContent": false,
"bytecodeHash": "ipfs",
"appendCBOR": true
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"evmVersion": "cancun",
"viaIR": false,
"libraries": {}
}Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
Contract ABI
API[{"inputs":[{"internalType":"address","name":"_factory","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"PoolDeployer_FailedToDeployPool","type":"error"},{"inputs":[{"internalType":"address","name":"underlying","type":"address"},{"internalType":"address","name":"principalToken","type":"address"},{"internalType":"bytes","name":"params","type":"bytes"}],"name":"deploy","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"factory","outputs":[{"internalType":"TwoCryptoFactory","name":"","type":"address"}],"stateMutability":"view","type":"function"}]Contract Creation Code
60a060405234801561000f575f80fd5b5060405161099938038061099983398101604081905261002e9161003f565b6001600160a01b031660805261006c565b5f6020828403121561004f575f80fd5b81516001600160a01b0381168114610065575f80fd5b9392505050565b6080516109106100895f395f8181606c015260a201526109105ff3fe608060405260043610610028575f3560e01c80632db5b86f1461002c578063c45a01551461005b575b5f80fd5b61003f61003a36600461051a565b61008e565b6040516001600160a01b03909116815260200160405180910390f35b348015610066575f80fd5b5061003f7f000000000000000000000000000000000000000000000000000000000000000081565b5f8061009c8686868661015b565b90505f807f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316836040516100d891906105c6565b5f604051808303815f865af19150503d805f8114610111576040519150601f19603f3d011682016040523d82523d5f602084013e610116565b606091505b509150915081610139576040516307e5a6f760e11b815260040160405180910390fd5b8080602001905181019061014d91906105e1565b93505050505b949350505050565b60605f846001600160a01b031663204f83f96040518163ffffffff1660e01b8152600401602060405180830381865afa15801561019a573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906101be9190610603565b90505f6101cb8783610266565b90505f6101d888846102a7565b604080518082019091526001600160a01b03808b168252891660208201529091506332557e8160e21b90839083905f6102138a8c018c61064f565b6040516024016102279594939291906106f3565b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b0319909316929092179091529350505050949350505050565b60605f610272846102d0565b90508061027e846102fc565b60405160200161028f9291906107c1565b60405160208183030381529060405291505092915050565b60605f6102b384610356565b9050806102bf846102fc565b60405160200161028f929190610814565b60606102f6826102ea6306fdde0360049081525f90815290565b6103e8620186a0610370565b92915050565b60605f805f61030a85610417565b925092509250610319816104c1565b610322836104c1565b61032b856104c1565b60405160200161033d93929190610862565b6040516020818303038152906040529350505050919050565b60606102f6826102ea6395d89b4160049081525f90815290565b606060205f8551602087018886fa15610153576040518060200160403d106103da575f5160203d0381116103d857602081843e602081013d038351116103d857825186811181881802188084528060208301843e5f9201918252506020016040529050610153565b505b3d8581118187180218805f833e5f8183015350805b80515f1a15610400576001016103ef565b90810382525f815260200160405295945050505050565b5f80806104b461042a62015180866108bb565b5f805f620afa6c8401935062023ab1840661016d62023ab082146105b48304618eac84048401030304606481048160021c8261016d0201038203915060996002836005020104600161030161f4ff830201600b1c84030193506b030405060708090a0b0c010260a01b811a9450506003841061019062023ab1880402820101945050509193909250565b9196909550909350915050565b60606080604051019050602081016040525f8152805f19835b928101926030600a8206018453600a9004806104da575050819003601f19909101908152919050565b6001600160a01b0381168114610517575f80fd5b50565b5f805f806060858703121561052d575f80fd5b843561053881610503565b9350602085013561054881610503565b925060408501356001600160401b0380821115610563575f80fd5b818701915087601f830112610576575f80fd5b813581811115610584575f80fd5b886020828501011115610595575f80fd5b95989497505060200194505050565b5f5b838110156105be5781810151838201526020016105a6565b50505f910152565b5f82516105d78184602087016105a4565b9190910192915050565b5f602082840312156105f1575f80fd5b81516105fc81610503565b9392505050565b5f60208284031215610613575f80fd5b5051919050565b60405161012081016001600160401b038111828210171561064957634e487b7160e01b5f52604160045260245ffd5b60405290565b5f6101208284031215610660575f80fd5b61066861061a565b823581526020830135602082015260408301356040820152606083013560608201526080830135608082015260a083013560a082015260c083013560c082015260e083013560e08201526101008084013581830152508091505092915050565b5f81518084526106df8160208601602086016105a4565b601f01601f19169290920160200192915050565b5f6101c0808352610706818401896106c8565b90506020838203602085015261071c82896106c8565b9250604084019150865f5b600281101561074d5781516001600160a01b031684529282019290820190600101610727565b50505050836080830152825160a0830152602083015160c0830152604083015160e083015260608301516101008181850152608085015161012085015260a085015161014085015260c085015161016085015260e0850151610180850152808501516101a085015250509695505050505050565b6b4e617069657256322d50542f60a01b81525f83516107e781600c8501602088016105a4565b600160fe1b600c91840191820152835161080881600d8401602088016105a4565b01600d01949350505050565b664e50522d50542f60c81b81525f83516108358160078501602088016105a4565b600160fe1b60079184019182015283516108568160088401602088016105a4565b01600801949350505050565b5f84516108738184602089016105a4565b8083019050602f60f81b8082528551610893816001850160208a016105a4565b600192019182015283516108ae8160028401602088016105a4565b0160020195945050505050565b5f826108d557634e487b7160e01b5f52601260045260245ffd5b50049056fea2646970667358221220a6387aebc3a87c4f5ccb61702229cf435ea2617b6348bb1b99e2aa237ae5ff9664736f6c6343000818003300000000000000000000000098ee851a00abee0d95d08cf4ca2bdce32aeaaf7f
Deployed Bytecode
0x608060405260043610610028575f3560e01c80632db5b86f1461002c578063c45a01551461005b575b5f80fd5b61003f61003a36600461051a565b61008e565b6040516001600160a01b03909116815260200160405180910390f35b348015610066575f80fd5b5061003f7f00000000000000000000000098ee851a00abee0d95d08cf4ca2bdce32aeaaf7f81565b5f8061009c8686868661015b565b90505f807f00000000000000000000000098ee851a00abee0d95d08cf4ca2bdce32aeaaf7f6001600160a01b0316836040516100d891906105c6565b5f604051808303815f865af19150503d805f8114610111576040519150601f19603f3d011682016040523d82523d5f602084013e610116565b606091505b509150915081610139576040516307e5a6f760e11b815260040160405180910390fd5b8080602001905181019061014d91906105e1565b93505050505b949350505050565b60605f846001600160a01b031663204f83f96040518163ffffffff1660e01b8152600401602060405180830381865afa15801561019a573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906101be9190610603565b90505f6101cb8783610266565b90505f6101d888846102a7565b604080518082019091526001600160a01b03808b168252891660208201529091506332557e8160e21b90839083905f6102138a8c018c61064f565b6040516024016102279594939291906106f3565b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b0319909316929092179091529350505050949350505050565b60605f610272846102d0565b90508061027e846102fc565b60405160200161028f9291906107c1565b60405160208183030381529060405291505092915050565b60605f6102b384610356565b9050806102bf846102fc565b60405160200161028f929190610814565b60606102f6826102ea6306fdde0360049081525f90815290565b6103e8620186a0610370565b92915050565b60605f805f61030a85610417565b925092509250610319816104c1565b610322836104c1565b61032b856104c1565b60405160200161033d93929190610862565b6040516020818303038152906040529350505050919050565b60606102f6826102ea6395d89b4160049081525f90815290565b606060205f8551602087018886fa15610153576040518060200160403d106103da575f5160203d0381116103d857602081843e602081013d038351116103d857825186811181881802188084528060208301843e5f9201918252506020016040529050610153565b505b3d8581118187180218805f833e5f8183015350805b80515f1a15610400576001016103ef565b90810382525f815260200160405295945050505050565b5f80806104b461042a62015180866108bb565b5f805f620afa6c8401935062023ab1840661016d62023ab082146105b48304618eac84048401030304606481048160021c8261016d0201038203915060996002836005020104600161030161f4ff830201600b1c84030193506b030405060708090a0b0c010260a01b811a9450506003841061019062023ab1880402820101945050509193909250565b9196909550909350915050565b60606080604051019050602081016040525f8152805f19835b928101926030600a8206018453600a9004806104da575050819003601f19909101908152919050565b6001600160a01b0381168114610517575f80fd5b50565b5f805f806060858703121561052d575f80fd5b843561053881610503565b9350602085013561054881610503565b925060408501356001600160401b0380821115610563575f80fd5b818701915087601f830112610576575f80fd5b813581811115610584575f80fd5b886020828501011115610595575f80fd5b95989497505060200194505050565b5f5b838110156105be5781810151838201526020016105a6565b50505f910152565b5f82516105d78184602087016105a4565b9190910192915050565b5f602082840312156105f1575f80fd5b81516105fc81610503565b9392505050565b5f60208284031215610613575f80fd5b5051919050565b60405161012081016001600160401b038111828210171561064957634e487b7160e01b5f52604160045260245ffd5b60405290565b5f6101208284031215610660575f80fd5b61066861061a565b823581526020830135602082015260408301356040820152606083013560608201526080830135608082015260a083013560a082015260c083013560c082015260e083013560e08201526101008084013581830152508091505092915050565b5f81518084526106df8160208601602086016105a4565b601f01601f19169290920160200192915050565b5f6101c0808352610706818401896106c8565b90506020838203602085015261071c82896106c8565b9250604084019150865f5b600281101561074d5781516001600160a01b031684529282019290820190600101610727565b50505050836080830152825160a0830152602083015160c0830152604083015160e083015260608301516101008181850152608085015161012085015260a085015161014085015260c085015161016085015260e0850151610180850152808501516101a085015250509695505050505050565b6b4e617069657256322d50542f60a01b81525f83516107e781600c8501602088016105a4565b600160fe1b600c91840191820152835161080881600d8401602088016105a4565b01600d01949350505050565b664e50522d50542f60c81b81525f83516108358160078501602088016105a4565b600160fe1b60079184019182015283516108568160088401602088016105a4565b01600801949350505050565b5f84516108738184602089016105a4565b8083019050602f60f81b8082528551610893816001850160208a016105a4565b600192019182015283516108ae8160028401602088016105a4565b0160020195945050505050565b5f826108d557634e487b7160e01b5f52601260045260245ffd5b50049056fea2646970667358221220a6387aebc3a87c4f5ccb61702229cf435ea2617b6348bb1b99e2aa237ae5ff9664736f6c63430008180033
Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)
00000000000000000000000098ee851a00abee0d95d08cf4ca2bdce32aeaaf7f
-----Decoded View---------------
Arg [0] : _factory (address): 0x98EE851a00abeE0d95D08cF4CA2BdCE32aeaAF7F
-----Encoded View---------------
1 Constructor Arguments found :
Arg [0] : 00000000000000000000000098ee851a00abee0d95d08cf4ca2bdce32aeaaf7f
Loading...
Loading
Loading...
Loading
Loading...
Loading
Net Worth in USD
$0.00
Net Worth in FRAX
0
Multichain Portfolio | 35 Chains
| Chain | Token | Portfolio % | Price | Amount | Value |
|---|
Loading...
Loading
Loading...
Loading
Loading...
Loading
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.