Source Code
Overview
ETH Balance
0 ETH
ETH Value
$0.00View more zero value Internal Transactions in Advanced View mode
Advanced mode:
Cross-Chain Transactions
Loading...
Loading
Contract Source Code Verified (Exact Match)
Contract Name:
BladeVerifiedExchange
Compiler Version
v0.8.28+commit.7893614a
Optimization Enabled:
Yes with 1000 runs
Other Settings:
cancun EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.20;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {SD59x18, sd} from "@prb/math/src/SD59x18.sol";
import "../base/BladeErrors.sol";
import {Constants} from "../base/Constants.sol";
import {Signature, UtilStruct} from "../types/BladeTypes.sol";
import {BladeCommonExchange} from "../base/BladeCommonExchange.sol";
import {OracleManager} from "../variants/OracleManager.sol";
import {SafeAggregatorInterface, AggregatorV3Interface} from "../libraries/SafeAggregatorInterface.sol";
import {WrapperContractInterface} from "../interfaces/WrapperContractInterface.sol";
import {BladeSignatureLib} from "../libraries/BladeSignatureLib.sol";
contract BladeVerifiedExchange is BladeCommonExchange, OracleManager {
using SafeERC20 for IERC20;
using EnumerableSet for EnumerableSet.AddressSet;
using SafeCast for uint256;
using SafeCast for int256;
// For prevention of replay attacks
mapping(bytes32 => bool) invalidatedDigests;
error DigestAlreadyUsed();
constructor(
address theSigner,
address theWrapper,
address[] memory tokens,
address[] memory _oracles,
uint256[] memory minTimeTolerances,
address initialOwner
)
BladeCommonExchange(theSigner, theWrapper, tokens, initialOwner)
OracleManager(tokens, _oracles, minTimeTolerances)
{}
function _isToken(address token) internal view override returns (bool) {
return isToken(token);
}
function _nTokens() internal view override returns (uint) {
return nTokens();
}
function _tokenAt(uint index) internal view override returns (address) {
return tokenAt(index);
}
function _getLastBalance(address token) internal view override returns (uint256) {
return getLastBalance(token);
}
function _getTokenDecimals(address token) internal view override returns (uint8) {
return tokenDecimals[token];
}
// Used to invalidate a signature digest
function _checkAndInvalidateDigest(bytes32 theDigest) private {
if (invalidatedDigests[theDigest]) {
revert DigestAlreadyUsed();
}
invalidatedDigests[theDigest] = true;
}
function _unpackGoodUntil(
uint256 packedGoodUntil
)
private pure
returns (
uint256 pX,
uint256 pY,
uint256 wX,
uint256 wY,
uint256 k
)
{
/*
* Input asset price in 8 decimals - uint64
* Output asset price in 8 decimals - uint64
* k value in 18 decimals - uint64
* Input asset weight - uint16
* Output asset weight - uint16
* Current good until value - uint32 - can be taken as uint256(uint32(packedGoodUntil))
*/
// goodUntil = uint256(uint32(packedGoodUntil));
packedGoodUntil = packedGoodUntil >> 32;
wY = uint256(uint16(packedGoodUntil));
packedGoodUntil = packedGoodUntil >> 16;
wX = uint256(uint16(packedGoodUntil));
packedGoodUntil = packedGoodUntil >> 16;
k = uint256(uint64(packedGoodUntil));
packedGoodUntil = packedGoodUntil >> 64;
pY = uint256(uint64(packedGoodUntil));
packedGoodUntil = packedGoodUntil >> 64;
pX = uint256(uint64(packedGoodUntil));
}
/*
Before calling:
Set qX = lastBalances[inAsset];
Set qY = lastBalances[outAsset];
Multiply all quantities (q and in/out) by 10**(18-asset.decimals()).
This puts all quantities in 18 decimals.
Assumed decimals:
K: 18
Quantities: 18 (ONE_IN_DEFAULT_DECIMALS = 1e18)
Prices: 8 (ONE_IN_PRICE_DECIMALS = 1e8)
Weights: 0 (100 = 100)
*/
function _swapIncreasesInvariant(
uint256 inX,
uint256 pX,
uint256 qX,
uint256 wX,
uint256 outY,
uint256 pY,
uint256 qY,
uint256 wY,
uint256 k
)
private pure
returns (bool)
{
uint256 invariantBefore;
uint256 invariantAfter;
{
uint256 pqX = pX * qX / ONE_IN_PRICE_DECIMALS;
uint256 pqwXk = _fractionalPow(pqX * wX, k);
if (pqwXk > 0) {
invariantBefore += (Constants.ONE_IN_DEFAULT_DECIMALS * pqX) / pqwXk;
}
uint256 pqY = pY * qY / ONE_IN_PRICE_DECIMALS;
uint256 pqwYk = _fractionalPow(pqY * wY, k);
if (pqwYk > 0) {
invariantBefore += (Constants.ONE_IN_DEFAULT_DECIMALS * pqY) / pqwYk;
}
}
{
uint256 pqXinX = (pX * (qX + inX)) / ONE_IN_PRICE_DECIMALS;
uint256 pqwXinXk = _fractionalPow(pqXinX * wX, k);
if (pqwXinXk > 0) {
invariantAfter += (Constants.ONE_IN_DEFAULT_DECIMALS * pqXinX) / pqwXinXk;
}
uint256 pqYoutY = pY * (qY - outY) / ONE_IN_PRICE_DECIMALS;
uint256 pqwYoutYk = _fractionalPow(pqYoutY * wY, k);
if (pqwYoutYk > 0) {
invariantAfter += (Constants.ONE_IN_DEFAULT_DECIMALS * pqYoutY) / pqwYoutYk;
}
}
return invariantAfter > invariantBefore;
}
function _fractionalPow(
uint256 input,
uint256 pow
)
private pure
returns (uint256)
{
if (input == 0) {
return 0;
} else {
// input^(pow/1e18) -> exp2( (pow * log2( input ) / 1e18 ) )
// Convert input to SD59x18 and compute log2(input)
SD59x18 log2Input = sd(input.toInt256()).log2();
// Multiply by pow and divide by 1e18 to scale properly
SD59x18 exponent = sd(pow.toInt256()).mul(log2Input).div(sd(int256(Constants.ONE_IN_DEFAULT_DECIMALS)));
// Compute exp2() and safely convert int256 to uint256
int256 resultInt = exponent.exp2().unwrap();
return resultInt.toUint256();
}
}
function _currentDeltaOverLastBalance(address token) private view returns (uint256) {
return IERC20(token).balanceOf(address(this)) - lastBalances[token];
}
function _sync(address token) internal override {
lastBalances[token] = IERC20(token).balanceOf(address(this));
}
function _syncAll() private {
uint i;
uint n = assetSet.length();
while (i < n) {
_sync(tokenAt(i));
i++;
}
}
// _syncAndTransfer() and _unwrapAndForwardEth() are the two additional ways tokens leave the pool
// Since they transfer assets, they are all marked as nonReentrant
function _syncAndTransfer(
address inputToken,
address outputToken,
address recipient,
uint256 amount
)
private
nonReentrant
{
_sync(inputToken);
IERC20(outputToken).safeTransfer(recipient, amount);
_sync(outputToken);
}
// Essentially transferAsset, but for raw ETH
function _unwrapAndForwardEth(address recipient, uint256 amount) private nonReentrant {
/* EFFECTS */
WrapperContractInterface(WRAPPER_CONTRACT).withdraw(amount);
_sync(WRAPPER_CONTRACT);
/* INTERACTIONS */
safeEthSend(recipient, amount);
}
function _verifyTokensAndGetAmounts(
address inputToken,
address outputToken,
uint256 inputAmount,
uint256 outputAmount
)
private view
returns (
uint256 actualInput,
uint256 fairOutput
)
{
if (!isToken(inputToken)) revert TokenNotInPool();
if (!isToken(outputToken)) revert TokenNotInPool();
actualInput = _currentDeltaOverLastBalance(inputToken);
fairOutput = calculateFairOutput(inputAmount, actualInput, outputAmount);
}
function _swapValidation(
address inputToken,
address outputToken,
uint256 inputAmount,
uint256 outputAmount,
uint256 goodUntil,
address destinationAddress,
Signature memory theSignature
)
private
returns (
uint256 actualInput,
uint256 fairOutput
)
{
bytes32 digest = _verifySwapSignature(
inputToken,
outputToken,
inputAmount,
outputAmount,
goodUntil,
destinationAddress,
theSignature
);
// Validate digest already used
_checkAndInvalidateDigest(digest);
(actualInput, fairOutput) = _verifyTokensAndGetAmounts(
inputToken,
outputToken,
inputAmount,
outputAmount
);
_unpackAndCheckInvariantAndPrice(
inputToken,
actualInput,
outputToken,
fairOutput,
goodUntil
);
}
function sellTokenForEth(
address inputToken,
uint256 inputAmount,
uint256 outputAmount,
uint256 goodUntil,
address destinationAddress,
Signature calldata theSignature,
bytes calldata auxiliaryData
)
external
marketIsRunning
receivedInTime(uint256(uint32(goodUntil)))
{
_sellTokenForEth(
inputToken,
inputAmount,
outputAmount,
goodUntil,
destinationAddress,
theSignature,
auxiliaryData
);
}
function _sellTokenForEth(
address inputToken,
uint256 inputAmount,
uint256 outputAmount,
uint256 goodUntil,
address destinationAddress,
Signature memory theSignature,
bytes memory auxiliaryData
)
private
{
(uint256 actualInput, uint256 fairOutput) = _swapValidation(
inputToken,
WRAPPER_CONTRACT,
inputAmount,
outputAmount,
goodUntil,
destinationAddress,
theSignature
);
// We have to _sync the input token manually here
_sync(inputToken);
_unwrapAndForwardEth(destinationAddress, fairOutput);
emit Swapped(
inputToken,
WRAPPER_CONTRACT,
destinationAddress,
actualInput,
fairOutput,
auxiliaryData
);
}
function swap(
address inputToken,
address outputToken,
uint256 inputAmount,
uint256 outputAmount,
uint256 goodUntil,
address destinationAddress,
Signature calldata theSignature,
bytes calldata auxiliaryData
)
external
marketIsRunning
receivedInTime(uint256(uint32(goodUntil)))
{
_swap(
inputToken,
outputToken,
inputAmount,
outputAmount,
goodUntil,
destinationAddress,
theSignature,
auxiliaryData
);
}
function _swap(
address inputToken,
address outputToken,
uint256 inputAmount,
uint256 outputAmount,
uint256 goodUntil,
address destinationAddress,
Signature memory theSignature,
bytes memory auxiliaryData
)
private
{
(uint256 actualInput, uint256 fairOutput) = _swapValidation(
inputToken,
outputToken,
inputAmount,
outputAmount,
goodUntil,
destinationAddress,
theSignature
);
// OK, now we are safe to transfer
_syncAndTransfer(inputToken, outputToken, destinationAddress, fairOutput);
emit Swapped(
inputToken,
outputToken,
destinationAddress,
actualInput,
fairOutput,
auxiliaryData
);
}
// Oracle verification integration
function deposit(
address depositor,
uint256[] calldata depositAmounts,
uint256 lockTime,
uint256 poolTokens,
uint256 goodUntil,
Signature calldata theSignature,
bytes calldata extraData
)
public payable override
marketIsRunning
receivedInTime(goodUntil)
validLockTime(lockTime)
{
_deposit(
depositor,
depositAmounts,
lockTime,
poolTokens,
goodUntil,
theSignature,
extraData
);
}
function _deposit(
address depositor,
uint256[] memory depositAmounts,
uint256 lockTime,
uint256 poolTokens,
uint256 goodUntil,
Signature memory theSignature,
bytes memory extraData
)
private
{
// wraps msg.value if existent as it will be used in the following checks
_wrapMsgValue();
bytes32 digest = _depositChecks(
depositor,
depositAmounts,
lockTime,
poolTokens,
goodUntil,
theSignature,
extraData
);
// Validate digest already used
_checkAndInvalidateDigest(digest);
// Did we actually deposit what we said we would? Revert otherwise
_verifyDepositAmountsWithOracles(depositAmounts, poolTokens);
// OK now we're good
_syncAll();
_finalizeDeposit(depositor, lockTime, poolTokens);
}
// Oracle verification integration
function depositSingleAsset(
address depositor,
address inputToken,
uint256 inputAmount,
uint256 lockTime,
uint256 poolTokens,
uint256 goodUntil,
Signature calldata theSignature,
bytes calldata extraData
)
external payable
marketIsRunning
receivedInTime(goodUntil)
validLockTime(lockTime)
{
_depositSingleAsset(
depositor,
inputToken,
inputAmount,
lockTime,
poolTokens,
goodUntil,
theSignature,
extraData
);
}
function _depositSingleAsset(
address depositor,
address inputToken,
uint256 inputAmount,
uint256 lockTime,
uint256 poolTokens,
uint256 goodUntil,
Signature memory theSignature,
bytes memory extraData
)
private
{
if (!isToken(inputToken)) revert TokenNotInPool();
// wraps msg.value if existent as it will be used in the following checks
_wrapMsgValue();
bytes32 digest = _singleDepositChecks(
depositor,
inputToken,
inputAmount,
lockTime,
poolTokens,
goodUntil,
theSignature,
extraData
);
// Validate digest already used
_checkAndInvalidateDigest(digest);
// Did we actually deposit what we said we would? Revert otherwise
_verifyDepositSingleAssetAmountWithOracles(inputToken, inputAmount, poolTokens);
// sync the balance
_sync(inputToken);
_finalizeDeposit(depositor, lockTime, poolTokens);
}
function withdrawSingleAsset(
address tokenHolder,
uint256 poolTokenAmountToBurn,
address assetAddress,
uint256 assetAmount,
uint256 goodUntil,
Signature calldata theSignature,
bytes calldata extraData
)
external override
marketIsRunning
onlyTokenHolder(tokenHolder)
receivedInTime(goodUntil)
{
bool sendEthBack;
if (assetAddress == ETH_SIGIL) {
assetAddress = WRAPPER_CONTRACT;
sendEthBack = true;
}
bytes32 digest = _singleWithdrawChecks(
tokenHolder,
poolTokenAmountToBurn,
assetAddress,
assetAmount,
goodUntil,
theSignature,
extraData
);
// Validate digest already used
_checkAndInvalidateDigest(digest);
// Revert if oracle prices don't match amount withdrawn
_verifyWithdrawSingleAssetAmountWithOracles(
assetAddress,
assetAmount,
poolTokenAmountToBurn
);
// Reverts if balance is insufficient
_burn(msg.sender, poolTokenAmountToBurn);
// Reverts if balance is insufficient
// syncs done automatically on transfer
if (sendEthBack) {
_unwrapAndForwardEth(msg.sender, assetAmount);
} else {
transferAsset(assetAddress, msg.sender, assetAmount);
}
emit AssetWithdrawn(
tokenHolder,
poolTokenAmountToBurn,
assetAddress,
assetAmount
);
}
// Don't need a separate "transmit" function here since it's already payable
function sellEthForToken(
address outputToken,
uint256 inputAmount,
uint256 outputAmount,
uint256 goodUntil,
address destinationAddress,
Signature calldata theSignature,
bytes calldata auxiliaryData
)
external payable
marketIsRunning
receivedInTime(uint256(uint32(goodUntil)))
{
_sellEthForToken(
outputToken,
inputAmount,
outputAmount,
goodUntil,
destinationAddress,
theSignature,
auxiliaryData
);
}
function _sellEthForToken(
address outputToken,
uint256 inputAmount,
uint256 outputAmount,
uint256 goodUntil,
address destinationAddress,
Signature memory theSignature,
bytes memory auxiliaryData
)
private
{
// Wrap ETH (as balance or value) as input
safeEthSend(WRAPPER_CONTRACT, inputAmount);
_swap(
WRAPPER_CONTRACT,
outputToken,
inputAmount,
outputAmount,
goodUntil,
destinationAddress,
theSignature,
auxiliaryData
);
}
function transmitAndDepositSingleAsset(
address inputToken,
uint256 inputAmount,
uint256 lockTime,
uint256 poolTokens,
uint256 goodUntil,
Signature calldata theSignature,
bytes calldata extraData
)
external
marketIsRunning
receivedInTime(goodUntil)
validLockTime(lockTime)
{
IERC20(inputToken).safeTransferFrom(msg.sender, address(this), inputAmount);
_depositSingleAsset(
msg.sender,
inputToken,
inputAmount,
lockTime,
poolTokens,
goodUntil,
theSignature,
extraData
);
}
function transmitAndSellTokenForEth(
address inputToken,
uint256 inputAmount,
uint256 outputAmount,
uint256 goodUntil,
address destinationAddress,
Signature calldata theSignature,
bytes calldata auxiliaryData
)
external override
marketIsRunning
receivedInTime(uint256(uint32(goodUntil)))
{
IERC20(inputToken).safeTransferFrom(msg.sender, address(this), inputAmount);
_sellTokenForEth(
inputToken,
inputAmount,
outputAmount,
goodUntil,
destinationAddress,
theSignature,
auxiliaryData
);
}
// all-in-one transfer from msg.sender to destinationAddress.
function transmitAndSwap(
address inputToken,
address outputToken,
uint256 inputAmount,
uint256 outputAmount,
uint256 goodUntil,
address destinationAddress,
Signature calldata theSignature,
bytes calldata auxiliaryData
)
external override
marketIsRunning
receivedInTime(uint256(uint32(goodUntil)))
{
IERC20(inputToken).safeTransferFrom(msg.sender, address(this), inputAmount);
_swap(
inputToken,
outputToken,
inputAmount,
outputAmount,
goodUntil,
destinationAddress,
theSignature,
auxiliaryData
);
}
function _unpackAndCheckInvariantAndPrice(
address inputToken,
uint256 inputAmount,
address outputToken,
uint256 outputAmount,
uint256 goodUntil
)
private view
{
UtilStruct memory s;
(
uint256 pX,
uint256 pY,
uint256 wX,
uint256 wY,
uint256 k
) = _unpackGoodUntil(goodUntil);
s.qX = lastBalances[inputToken];
s.qY = lastBalances[outputToken];
s.decimalMultiplierX = 10 ** (18 - tokenDecimals[inputToken]);
s.decimalMultiplierY = 10 ** (18 - tokenDecimals[outputToken]);
bool ok = _swapIncreasesInvariant(
inputAmount * s.decimalMultiplierX,
pX,
s.qX * s.decimalMultiplierX,
wX,
outputAmount * s.decimalMultiplierY,
pY,
s.qY * s.decimalMultiplierY,
wY,
k
);
if (!ok) revert InvariantCheckFailed();
// Only validate price if both tokens have an oracle set
if (
oracles[inputToken].oracleAddress != address(0) &&
oracles[outputToken].oracleAddress != address(0)
) {
// Revert if oracle price is out of boundaries
validatePrice(inputAmount, outputAmount, inputToken, outputToken);
}
}
/**
* @notice Verifies that a multi-asset deposit matches the expected LP token value.
* @dev Reverts if the USD value of the LP tokens exceeds the value of the deposited tokens plus tolerance.
* @param depositAmounts The array of deposited token amounts, indexed by token order.
* @param poolTokens The amount of LP tokens expected to be minted.
* @custom:requirements prices must be available for all tokens and use 18 decimals.
*/
function _verifyDepositAmountsWithOracles(
uint256[] memory depositAmounts,
uint256 poolTokens
)
private view
{
bool oracleVerification = false;
if (_areAllOraclesSet()) {
oracleVerification = true;
}
uint n = nTokens();
uint256 depositValue = 0;
for (uint i = 0; i < n; ++i) {
if (depositAmounts[i] > 0) {
depositValue += _verifyAssetDeposit(tokenAt(i), depositAmounts[i], oracleVerification);
}
}
if (oracleVerification) {
_verifyPoolTokensFairValue(poolTokens, depositValue);
}
}
/**
* @notice Verifies a single-asset deposit against the expected LP token value.
* @dev Uses current oracle prices to compute and compare values.
* @param assetAddress The token being deposited.
* @param assetAmount The amount of the token to deposit.
* @param poolTokens The amount of LP tokens expected to be minted.
*/
function _verifyDepositSingleAssetAmountWithOracles(
address assetAddress,
uint256 assetAmount,
uint256 poolTokens
)
private view
{
bool oracleVerification = false;
if (_areAllOraclesSet()) {
oracleVerification = true;
}
uint256 depositValue = _verifyAssetDeposit(assetAddress, assetAmount, oracleVerification);
if (oracleVerification) {
_verifyPoolTokensFairValue(poolTokens, depositValue);
}
}
function _verifyPoolTokensFairValue(uint256 poolTokens, uint256 valueToCompare) private view {
uint256 lpTokenPrice = _getLpTokenPrice(totalSupply());
uint256 poolTokensValue = (poolTokens * lpTokenPrice) / Constants.ONE_IN_DEFAULT_DECIMALS;
_revertIfDeviationTooHigh(poolTokensValue, valueToCompare);
}
function _verifyAssetDeposit(
address token,
uint256 expectedAmount,
bool oracleVerification
)
private view
returns (uint256 depositValue)
{
uint256 delta = _currentDeltaOverLastBalance(token);
if (delta < expectedAmount) {
revert InsufficientInput();
}
if (oracleVerification) {
depositValue = _getAssetAmountUsdValue(token, delta);
}
}
/**
* @notice Verifies a single-asset withdrawal against the value of LP tokens burned.
* @dev Reverts if the USD value of the withdrawal exceeds LP token value plus tolerance.
* @param assetAddress The token being withdrawn.
* @param assetAmount The amount of the token to withdraw.
* @param poolTokens The amount of LP tokens being burned.
*/
function _verifyWithdrawSingleAssetAmountWithOracles(
address assetAddress,
uint256 assetAmount,
uint256 poolTokens
)
private view
{
// skip if we don’t yet have a full set of price oracles
if (_areAllOraclesSet()) {
uint256 withdrawValue = _getAssetAmountUsdValue(assetAddress, assetAmount);
_verifyPoolTokensFairValue(withdrawValue, poolTokens);
}
}
/*
unpack: internal function to unpack uint256 representation
Input arguments:
amountAndAddress: uint256 where first 24 hexchars are a uint96 shortened uint256
and last 40 hexchars are an address
Returns: unpacked amount and address
*/
function _unpack(
uint256 amountAndAddress
)
private pure
returns (
uint256 amount,
address contractAddress
)
{
// uint256 -> uint160 automatically takes just last 40 hexchars
contractAddress = address(uint160(amountAndAddress));
// shift over the 40 hexchars to capture the amount
amount = amountAndAddress >> 160;
}
/*
packedTransmitAndDepositSingleAsset: deposit a single asset in an efficient way
Input arguments:
packedInput: Amount and contract address of asset to deposit
packedConfig: First 32 hexchars are poolTokens, next 24 are goodUntil, next 6 is lockTime in minutes, final 2 are v
r, s: Signature values
*/
function packedTransmitAndDepositSingleAsset(
uint256 packedInput,
uint256 packedConfig,
bytes32 r,
bytes32 s,
bytes calldata extraData
)
external payable
marketIsRunning
{
uint256 poolTokens = packedConfig >> 128;
uint256 goodUntil = uint256(uint96(packedConfig >> 32));
uint256 lockTime = uint256(uint24(packedConfig >> 8));
// validates message expiration
if (goodUntil < block.timestamp) {
revert ExpiredMessage();
}
// validates vesting time
if (lockTime < 1) {
revert InvalidLockTime();
}
Signature memory theSignature;
uint256 inputAmount;
address inputToken;
{
// scope to avoid stack too deep errors
(inputAmount, inputToken) = _unpack(packedInput);
uint8 v = uint8(packedConfig);
theSignature = Signature(v, r, s);
delete v;
if (inputToken == ETH_SIGIL) {
// Don't need to wrap the ETH here, do it in the deposit function
inputToken = WRAPPER_CONTRACT;
} else {
IERC20(inputToken).safeTransferFrom(msg.sender, address(this), inputAmount);
}
}
_depositSingleAsset(
msg.sender,
inputToken,
inputAmount,
lockTime,
poolTokens,
goodUntil,
theSignature,
extraData
);
}
/*
unpackAndSwap: internal function that performs unpacks a set of calldata-packed inputs and performs a swap
Input arguments:
packedInput: input amount and contract
packedOutput: output amount and contract
packedGoodUntil: packed good until (for verifier, direct from server)
impliedOutputPrice: implied price for the output token to verify with the oracle
auxData: bytes32, identifier. Final 20 bytes are destination address. First 12 bytes are auxData identifier string.
r, vs: Signature values using EIP 2098 - https://eips.ethereum.org/EIPS/eip-2098
performTransfer: if tokens should be transferred from msg.sender
*/
function _unpackAndSwap(
uint256 packedInput,
uint256 packedOutput,
uint256 packedGoodUntil,
bytes32 auxData,
bytes32 r,
bytes32 vs,
bool performTransfer
)
private
{
(uint256 inputAmount, address inputContractAddress) = _unpack(packedInput);
(uint256 outputAmount, address outputContractAddress) = _unpack(packedOutput);
Signature memory theSignature;
{
// Directly from https://eips.ethereum.org/EIPS/eip-2098
bytes32 s = vs & 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
uint8 v = 27 + uint8(uint256(vs) >> 255);
theSignature = Signature(v, r, s);
}
if (performTransfer && (inputContractAddress != ETH_SIGIL)) {
IERC20(inputContractAddress).safeTransferFrom(msg.sender, address(this), inputAmount);
}
_performUnpackedSwap(
inputContractAddress,
outputContractAddress,
inputAmount,
outputAmount,
packedGoodUntil,
auxData,
theSignature
);
}
function _performUnpackedSwap(
address inputContractAddress,
address outputContractAddress,
uint256 inputAmount,
uint256 outputAmount,
uint256 goodUntil,
bytes32 auxData,
Signature memory theSignature
)
private
{
address destinationAddress = address(uint160(uint256(auxData)));
bytes12 prefix = bytes12(auxData);
bytes memory auxiliaryData = abi.encodePacked(prefix);
if (inputContractAddress == ETH_SIGIL) {
_sellEthForToken(
outputContractAddress,
inputAmount,
outputAmount,
goodUntil,
destinationAddress,
theSignature,
auxiliaryData
);
} else if (outputContractAddress == ETH_SIGIL) {
_sellTokenForEth(
inputContractAddress,
inputAmount,
outputAmount,
goodUntil,
destinationAddress,
theSignature,
auxiliaryData
);
} else {
_swap(
inputContractAddress,
outputContractAddress,
inputAmount,
outputAmount,
goodUntil,
destinationAddress,
theSignature,
auxiliaryData
);
}
}
// external function to transfer tokens and perform swap from packed calldata
function packedTransmitAndSwap(
uint256 packedInput,
uint256 packedOutput,
uint256 packedGoodUntil,
bytes32 auxData,
bytes32 r,
bytes32 vs
)
external payable
marketIsRunning
receivedInTime(uint256(uint32(packedGoodUntil)))
{
_unpackAndSwap(
packedInput,
packedOutput,
packedGoodUntil,
auxData,
r,
vs,
true
);
}
// external function to perform swap from packed calldata
function packedSwap(
uint256 packedInput,
uint256 packedOutput,
uint256 packedGoodUntil,
bytes32 auxData,
bytes32 r,
bytes32 vs
)
external payable
marketIsRunning
receivedInTime(uint256(uint32(packedGoodUntil)))
{
_unpackAndSwap(
packedInput,
packedOutput,
packedGoodUntil,
auxData,
r,
vs,
false
);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard ERC-20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.
*/
interface IERC20Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC20InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC20InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
* @param spender Address that may be allowed to operate on tokens without being their owner.
* @param allowance Amount of tokens a `spender` is allowed to operate with.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC20InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `spender` to be approved. Used in approvals.
* @param spender Address that may be allowed to operate on tokens without being their owner.
*/
error ERC20InvalidSpender(address spender);
}
/**
* @dev Standard ERC-721 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
*/
interface IERC721Errors {
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-20.
* Used in balance queries.
* @param owner Address of the current owner of a token.
*/
error ERC721InvalidOwner(address owner);
/**
* @dev Indicates a `tokenId` whose `owner` is the zero address.
* @param tokenId Identifier number of a token.
*/
error ERC721NonexistentToken(uint256 tokenId);
/**
* @dev Indicates an error related to the ownership over a particular token. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param tokenId Identifier number of a token.
* @param owner Address of the current owner of a token.
*/
error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC721InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC721InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param tokenId Identifier number of a token.
*/
error ERC721InsufficientApproval(address operator, uint256 tokenId);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC721InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC721InvalidOperator(address operator);
}
/**
* @dev Standard ERC-1155 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.
*/
interface IERC1155Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
* @param tokenId Identifier number of a token.
*/
error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC1155InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC1155InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param owner Address of the current owner of a token.
*/
error ERC1155MissingApprovalForAll(address operator, address owner);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC1155InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC1155InvalidOperator(address operator);
/**
* @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
* Used in batch transfers.
* @param idsLength Length of the array of token identifiers
* @param valuesLength Length of the array of token amounts
*/
error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "../utils/introspection/IERC165.sol";// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../token/ERC20/IERC20.sol";// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC-20
* applications.
*/
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
mapping(address account => uint256) private _balances;
mapping(address account => mapping(address spender => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* Both values are immutable: they can only be set once during construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `value`.
*/
function transfer(address to, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_transfer(owner, to, value);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Skips emitting an {Approval} event indicating an allowance update. This is not
* required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `value`.
* - the caller must have allowance for ``from``'s tokens of at least
* `value`.
*/
function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, value);
_transfer(from, to, value);
return true;
}
/**
* @dev Moves a `value` amount of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _transfer(address from, address to, uint256 value) internal {
if (from == address(0)) {
revert ERC20InvalidSender(address(0));
}
if (to == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(from, to, value);
}
/**
* @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
* (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
* this function.
*
* Emits a {Transfer} event.
*/
function _update(address from, address to, uint256 value) internal virtual {
if (from == address(0)) {
// Overflow check required: The rest of the code assumes that totalSupply never overflows
_totalSupply += value;
} else {
uint256 fromBalance = _balances[from];
if (fromBalance < value) {
revert ERC20InsufficientBalance(from, fromBalance, value);
}
unchecked {
// Overflow not possible: value <= fromBalance <= totalSupply.
_balances[from] = fromBalance - value;
}
}
if (to == address(0)) {
unchecked {
// Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
_totalSupply -= value;
}
} else {
unchecked {
// Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
_balances[to] += value;
}
}
emit Transfer(from, to, value);
}
/**
* @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
* Relies on the `_update` mechanism
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _mint(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(address(0), account, value);
}
/**
* @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
* Relies on the `_update` mechanism.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead
*/
function _burn(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidSender(address(0));
}
_update(account, address(0), value);
}
/**
* @dev Sets `value` as the allowance of `spender` over the `owner`'s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
*/
function _approve(address owner, address spender, uint256 value) internal {
_approve(owner, spender, value, true);
}
/**
* @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
*
* By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
* `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
* `Approval` event during `transferFrom` operations.
*
* Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
* true using the following override:
*
* ```solidity
* function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
* super._approve(owner, spender, value, true);
* }
* ```
*
* Requirements are the same as {_approve}.
*/
function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
if (owner == address(0)) {
revert ERC20InvalidApprover(address(0));
}
if (spender == address(0)) {
revert ERC20InvalidSpender(address(0));
}
_allowances[owner][spender] = value;
if (emitEvent) {
emit Approval(owner, spender, value);
}
}
/**
* @dev Updates `owner`'s allowance for `spender` based on spent `value`.
*
* Does not update the allowance value in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Does not emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance < type(uint256).max) {
if (currentAllowance < value) {
revert ERC20InsufficientAllowance(spender, currentAllowance, value);
}
unchecked {
_approve(owner, spender, currentAllowance - value, false);
}
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC-20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
// bubble errors
if iszero(success) {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize())
revert(ptr, returndatasize())
}
returnSize := returndatasize()
returnValue := mload(0)
}
if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
bool success;
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
returnSize := returndatasize()
returnValue := mload(0)
}
return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/Arrays.sol)
// This file was procedurally generated from scripts/generate/templates/Arrays.js.
pragma solidity ^0.8.20;
import {Comparators} from "./Comparators.sol";
import {SlotDerivation} from "./SlotDerivation.sol";
import {StorageSlot} from "./StorageSlot.sol";
import {Math} from "./math/Math.sol";
/**
* @dev Collection of functions related to array types.
*/
library Arrays {
using SlotDerivation for bytes32;
using StorageSlot for bytes32;
/**
* @dev Sort an array of uint256 (in memory) following the provided comparator function.
*
* This function does the sorting "in place", meaning that it overrides the input. The object is returned for
* convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
*
* NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
* array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
* when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
* consume more gas than is available in a block, leading to potential DoS.
*
* IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
*/
function sort(
uint256[] memory array,
function(uint256, uint256) pure returns (bool) comp
) internal pure returns (uint256[] memory) {
_quickSort(_begin(array), _end(array), comp);
return array;
}
/**
* @dev Variant of {sort} that sorts an array of uint256 in increasing order.
*/
function sort(uint256[] memory array) internal pure returns (uint256[] memory) {
sort(array, Comparators.lt);
return array;
}
/**
* @dev Sort an array of address (in memory) following the provided comparator function.
*
* This function does the sorting "in place", meaning that it overrides the input. The object is returned for
* convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
*
* NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
* array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
* when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
* consume more gas than is available in a block, leading to potential DoS.
*
* IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
*/
function sort(
address[] memory array,
function(address, address) pure returns (bool) comp
) internal pure returns (address[] memory) {
sort(_castToUint256Array(array), _castToUint256Comp(comp));
return array;
}
/**
* @dev Variant of {sort} that sorts an array of address in increasing order.
*/
function sort(address[] memory array) internal pure returns (address[] memory) {
sort(_castToUint256Array(array), Comparators.lt);
return array;
}
/**
* @dev Sort an array of bytes32 (in memory) following the provided comparator function.
*
* This function does the sorting "in place", meaning that it overrides the input. The object is returned for
* convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
*
* NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
* array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
* when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
* consume more gas than is available in a block, leading to potential DoS.
*
* IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
*/
function sort(
bytes32[] memory array,
function(bytes32, bytes32) pure returns (bool) comp
) internal pure returns (bytes32[] memory) {
sort(_castToUint256Array(array), _castToUint256Comp(comp));
return array;
}
/**
* @dev Variant of {sort} that sorts an array of bytes32 in increasing order.
*/
function sort(bytes32[] memory array) internal pure returns (bytes32[] memory) {
sort(_castToUint256Array(array), Comparators.lt);
return array;
}
/**
* @dev Performs a quick sort of a segment of memory. The segment sorted starts at `begin` (inclusive), and stops
* at end (exclusive). Sorting follows the `comp` comparator.
*
* Invariant: `begin <= end`. This is the case when initially called by {sort} and is preserved in subcalls.
*
* IMPORTANT: Memory locations between `begin` and `end` are not validated/zeroed. This function should
* be used only if the limits are within a memory array.
*/
function _quickSort(uint256 begin, uint256 end, function(uint256, uint256) pure returns (bool) comp) private pure {
unchecked {
if (end - begin < 0x40) return;
// Use first element as pivot
uint256 pivot = _mload(begin);
// Position where the pivot should be at the end of the loop
uint256 pos = begin;
for (uint256 it = begin + 0x20; it < end; it += 0x20) {
if (comp(_mload(it), pivot)) {
// If the value stored at the iterator's position comes before the pivot, we increment the
// position of the pivot and move the value there.
pos += 0x20;
_swap(pos, it);
}
}
_swap(begin, pos); // Swap pivot into place
_quickSort(begin, pos, comp); // Sort the left side of the pivot
_quickSort(pos + 0x20, end, comp); // Sort the right side of the pivot
}
}
/**
* @dev Pointer to the memory location of the first element of `array`.
*/
function _begin(uint256[] memory array) private pure returns (uint256 ptr) {
assembly ("memory-safe") {
ptr := add(array, 0x20)
}
}
/**
* @dev Pointer to the memory location of the first memory word (32bytes) after `array`. This is the memory word
* that comes just after the last element of the array.
*/
function _end(uint256[] memory array) private pure returns (uint256 ptr) {
unchecked {
return _begin(array) + array.length * 0x20;
}
}
/**
* @dev Load memory word (as a uint256) at location `ptr`.
*/
function _mload(uint256 ptr) private pure returns (uint256 value) {
assembly {
value := mload(ptr)
}
}
/**
* @dev Swaps the elements memory location `ptr1` and `ptr2`.
*/
function _swap(uint256 ptr1, uint256 ptr2) private pure {
assembly {
let value1 := mload(ptr1)
let value2 := mload(ptr2)
mstore(ptr1, value2)
mstore(ptr2, value1)
}
}
/// @dev Helper: low level cast address memory array to uint256 memory array
function _castToUint256Array(address[] memory input) private pure returns (uint256[] memory output) {
assembly {
output := input
}
}
/// @dev Helper: low level cast bytes32 memory array to uint256 memory array
function _castToUint256Array(bytes32[] memory input) private pure returns (uint256[] memory output) {
assembly {
output := input
}
}
/// @dev Helper: low level cast address comp function to uint256 comp function
function _castToUint256Comp(
function(address, address) pure returns (bool) input
) private pure returns (function(uint256, uint256) pure returns (bool) output) {
assembly {
output := input
}
}
/// @dev Helper: low level cast bytes32 comp function to uint256 comp function
function _castToUint256Comp(
function(bytes32, bytes32) pure returns (bool) input
) private pure returns (function(uint256, uint256) pure returns (bool) output) {
assembly {
output := input
}
}
/**
* @dev Searches a sorted `array` and returns the first index that contains
* a value greater or equal to `element`. If no such index exists (i.e. all
* values in the array are strictly less than `element`), the array length is
* returned. Time complexity O(log n).
*
* NOTE: The `array` is expected to be sorted in ascending order, and to
* contain no repeated elements.
*
* IMPORTANT: Deprecated. This implementation behaves as {lowerBound} but lacks
* support for repeated elements in the array. The {lowerBound} function should
* be used instead.
*/
function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
uint256 low = 0;
uint256 high = array.length;
if (high == 0) {
return 0;
}
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds towards zero (it does integer division with truncation).
if (unsafeAccess(array, mid).value > element) {
high = mid;
} else {
low = mid + 1;
}
}
// At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
if (low > 0 && unsafeAccess(array, low - 1).value == element) {
return low - 1;
} else {
return low;
}
}
/**
* @dev Searches an `array` sorted in ascending order and returns the first
* index that contains a value greater or equal than `element`. If no such index
* exists (i.e. all values in the array are strictly less than `element`), the array
* length is returned. Time complexity O(log n).
*
* See C++'s https://en.cppreference.com/w/cpp/algorithm/lower_bound[lower_bound].
*/
function lowerBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
uint256 low = 0;
uint256 high = array.length;
if (high == 0) {
return 0;
}
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds towards zero (it does integer division with truncation).
if (unsafeAccess(array, mid).value < element) {
// this cannot overflow because mid < high
unchecked {
low = mid + 1;
}
} else {
high = mid;
}
}
return low;
}
/**
* @dev Searches an `array` sorted in ascending order and returns the first
* index that contains a value strictly greater than `element`. If no such index
* exists (i.e. all values in the array are strictly less than `element`), the array
* length is returned. Time complexity O(log n).
*
* See C++'s https://en.cppreference.com/w/cpp/algorithm/upper_bound[upper_bound].
*/
function upperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
uint256 low = 0;
uint256 high = array.length;
if (high == 0) {
return 0;
}
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds towards zero (it does integer division with truncation).
if (unsafeAccess(array, mid).value > element) {
high = mid;
} else {
// this cannot overflow because mid < high
unchecked {
low = mid + 1;
}
}
}
return low;
}
/**
* @dev Same as {lowerBound}, but with an array in memory.
*/
function lowerBoundMemory(uint256[] memory array, uint256 element) internal pure returns (uint256) {
uint256 low = 0;
uint256 high = array.length;
if (high == 0) {
return 0;
}
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds towards zero (it does integer division with truncation).
if (unsafeMemoryAccess(array, mid) < element) {
// this cannot overflow because mid < high
unchecked {
low = mid + 1;
}
} else {
high = mid;
}
}
return low;
}
/**
* @dev Same as {upperBound}, but with an array in memory.
*/
function upperBoundMemory(uint256[] memory array, uint256 element) internal pure returns (uint256) {
uint256 low = 0;
uint256 high = array.length;
if (high == 0) {
return 0;
}
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds towards zero (it does integer division with truncation).
if (unsafeMemoryAccess(array, mid) > element) {
high = mid;
} else {
// this cannot overflow because mid < high
unchecked {
low = mid + 1;
}
}
}
return low;
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeAccess(address[] storage arr, uint256 pos) internal pure returns (StorageSlot.AddressSlot storage) {
bytes32 slot;
assembly ("memory-safe") {
slot := arr.slot
}
return slot.deriveArray().offset(pos).getAddressSlot();
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeAccess(bytes32[] storage arr, uint256 pos) internal pure returns (StorageSlot.Bytes32Slot storage) {
bytes32 slot;
assembly ("memory-safe") {
slot := arr.slot
}
return slot.deriveArray().offset(pos).getBytes32Slot();
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeAccess(uint256[] storage arr, uint256 pos) internal pure returns (StorageSlot.Uint256Slot storage) {
bytes32 slot;
assembly ("memory-safe") {
slot := arr.slot
}
return slot.deriveArray().offset(pos).getUint256Slot();
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeMemoryAccess(address[] memory arr, uint256 pos) internal pure returns (address res) {
assembly {
res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
}
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeMemoryAccess(bytes32[] memory arr, uint256 pos) internal pure returns (bytes32 res) {
assembly {
res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
}
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeMemoryAccess(uint256[] memory arr, uint256 pos) internal pure returns (uint256 res) {
assembly {
res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
}
}
/**
* @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
*
* WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
*/
function unsafeSetLength(address[] storage array, uint256 len) internal {
assembly ("memory-safe") {
sstore(array.slot, len)
}
}
/**
* @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
*
* WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
*/
function unsafeSetLength(bytes32[] storage array, uint256 len) internal {
assembly ("memory-safe") {
sstore(array.slot, len)
}
}
/**
* @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
*
* WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
*/
function unsafeSetLength(uint256[] storage array, uint256 len) internal {
assembly ("memory-safe") {
sstore(array.slot, len)
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Comparators.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides a set of functions to compare values.
*
* _Available since v5.1._
*/
library Comparators {
function lt(uint256 a, uint256 b) internal pure returns (bool) {
return a < b;
}
function gt(uint256 a, uint256 b) internal pure returns (bool) {
return a > b;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.20;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS
}
/**
* @dev The signature derives the `address(0)`.
*/
error ECDSAInvalidSignature();
/**
* @dev The signature has an invalid length.
*/
error ECDSAInvalidSignatureLength(uint256 length);
/**
* @dev The signature has an S value that is in the upper half order.
*/
error ECDSAInvalidSignatureS(bytes32 s);
/**
* @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not
* return address(0) without also returning an error description. Errors are documented using an enum (error type)
* and a bytes32 providing additional information about the error.
*
* If no error is returned, then the address can be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*/
function tryRecover(
bytes32 hash,
bytes memory signature
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly ("memory-safe") {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else {
return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[ERC-2098 short signatures]
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
unchecked {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
// We do not check for an overflow here since the shift operation results in 0 or 1.
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*/
function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS, s);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature, bytes32(0));
}
return (signer, RecoverError.NoError, bytes32(0));
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
*/
function _throwError(RecoverError error, bytes32 errorArg) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert ECDSAInvalidSignature();
} else if (error == RecoverError.InvalidSignatureLength) {
revert ECDSAInvalidSignatureLength(uint256(errorArg));
} else if (error == RecoverError.InvalidSignatureS) {
revert ECDSAInvalidSignatureS(errorArg);
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/cryptography/MessageHashUtils.sol)
pragma solidity ^0.8.20;
import {Strings} from "../Strings.sol";
/**
* @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing.
*
* The library provides methods for generating a hash of a message that conforms to the
* https://eips.ethereum.org/EIPS/eip-191[ERC-191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712]
* specifications.
*/
library MessageHashUtils {
/**
* @dev Returns the keccak256 digest of an ERC-191 signed data with version
* `0x45` (`personal_sign` messages).
*
* The digest is calculated by prefixing a bytes32 `messageHash` with
* `"\x19Ethereum Signed Message:\n32"` and hashing the result. It corresponds with the
* hash signed when using the https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sign[`eth_sign`] JSON-RPC method.
*
* NOTE: The `messageHash` parameter is intended to be the result of hashing a raw message with
* keccak256, although any bytes32 value can be safely used because the final digest will
* be re-hashed.
*
* See {ECDSA-recover}.
*/
function toEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32 digest) {
assembly ("memory-safe") {
mstore(0x00, "\x19Ethereum Signed Message:\n32") // 32 is the bytes-length of messageHash
mstore(0x1c, messageHash) // 0x1c (28) is the length of the prefix
digest := keccak256(0x00, 0x3c) // 0x3c is the length of the prefix (0x1c) + messageHash (0x20)
}
}
/**
* @dev Returns the keccak256 digest of an ERC-191 signed data with version
* `0x45` (`personal_sign` messages).
*
* The digest is calculated by prefixing an arbitrary `message` with
* `"\x19Ethereum Signed Message:\n" + len(message)` and hashing the result. It corresponds with the
* hash signed when using the https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sign[`eth_sign`] JSON-RPC method.
*
* See {ECDSA-recover}.
*/
function toEthSignedMessageHash(bytes memory message) internal pure returns (bytes32) {
return
keccak256(bytes.concat("\x19Ethereum Signed Message:\n", bytes(Strings.toString(message.length)), message));
}
/**
* @dev Returns the keccak256 digest of an ERC-191 signed data with version
* `0x00` (data with intended validator).
*
* The digest is calculated by prefixing an arbitrary `data` with `"\x19\x00"` and the intended
* `validator` address. Then hashing the result.
*
* See {ECDSA-recover}.
*/
function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(hex"19_00", validator, data));
}
/**
* @dev Variant of {toDataWithIntendedValidatorHash-address-bytes} optimized for cases where `data` is a bytes32.
*/
function toDataWithIntendedValidatorHash(
address validator,
bytes32 messageHash
) internal pure returns (bytes32 digest) {
assembly ("memory-safe") {
mstore(0x00, hex"19_00")
mstore(0x02, shl(96, validator))
mstore(0x16, messageHash)
digest := keccak256(0x00, 0x36)
}
}
/**
* @dev Returns the keccak256 digest of an EIP-712 typed data (ERC-191 version `0x01`).
*
* The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with
* `\x19\x01` and hashing the result. It corresponds to the hash signed by the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712.
*
* See {ECDSA-recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 digest) {
assembly ("memory-safe") {
let ptr := mload(0x40)
mstore(ptr, hex"19_01")
mstore(add(ptr, 0x02), domainSeparator)
mstore(add(ptr, 0x22), structHash)
digest := keccak256(ptr, 0x42)
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Return the 512-bit addition of two uint256.
*
* The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
*/
function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
assembly ("memory-safe") {
low := add(a, b)
high := lt(low, a)
}
}
/**
* @dev Return the 512-bit multiplication of two uint256.
*
* The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
*/
function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
// 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
// the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = high * 2²⁵⁶ + low.
assembly ("memory-safe") {
let mm := mulmod(a, b, not(0))
low := mul(a, b)
high := sub(sub(mm, low), lt(mm, low))
}
}
/**
* @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a + b;
success = c >= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a - b;
success = c <= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a * b;
assembly ("memory-safe") {
// Only true when the multiplication doesn't overflow
// (c / a == b) || (a == 0)
success := or(eq(div(c, a), b), iszero(a))
}
// equivalent to: success ? c : 0
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `DIV` opcode returns zero when the denominator is 0.
result := div(a, b)
}
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `MOD` opcode returns zero when the denominator is 0.
result := mod(a, b)
}
}
}
/**
* @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryAdd(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
*/
function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
(, uint256 result) = trySub(a, b);
return result;
}
/**
* @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryMul(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * SafeCast.toUint(condition));
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a < b, a, b);
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
Panic.panic(Panic.DIVISION_BY_ZERO);
}
// The following calculation ensures accurate ceiling division without overflow.
// Since a is non-zero, (a - 1) / b will not overflow.
// The largest possible result occurs when (a - 1) / b is type(uint256).max,
// but the largest value we can obtain is type(uint256).max - 1, which happens
// when a = type(uint256).max and b = 1.
unchecked {
return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
}
}
/**
* @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
*
* Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
// Handle non-overflow cases, 256 by 256 division.
if (high == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return low / denominator;
}
// Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
if (denominator <= high) {
Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [high low].
uint256 remainder;
assembly ("memory-safe") {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
high := sub(high, gt(remainder, low))
low := sub(low, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
uint256 twos = denominator & (0 - denominator);
assembly ("memory-safe") {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [high low] by twos.
low := div(low, twos)
// Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from high into low.
low |= high * twos;
// Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
// that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv ≡ 1 mod 2⁴.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
// works in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2⁸
inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
inverse *= 2 - denominator * inverse; // inverse mod 2³²
inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is
// less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
// is no longer required.
result = low * inverse;
return result;
}
}
/**
* @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
}
/**
* @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
*/
function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
if (high >= 1 << n) {
Panic.panic(Panic.UNDER_OVERFLOW);
}
return (high << (256 - n)) | (low >> n);
}
}
/**
* @dev Calculates x * y >> n with full precision, following the selected rounding direction.
*/
function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
}
/**
* @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
*
* If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
* If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
*
* If the input value is not inversible, 0 is returned.
*
* NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
* inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
*/
function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
unchecked {
if (n == 0) return 0;
// The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
// Used to compute integers x and y such that: ax + ny = gcd(a, n).
// When the gcd is 1, then the inverse of a modulo n exists and it's x.
// ax + ny = 1
// ax = 1 + (-y)n
// ax ≡ 1 (mod n) # x is the inverse of a modulo n
// If the remainder is 0 the gcd is n right away.
uint256 remainder = a % n;
uint256 gcd = n;
// Therefore the initial coefficients are:
// ax + ny = gcd(a, n) = n
// 0a + 1n = n
int256 x = 0;
int256 y = 1;
while (remainder != 0) {
uint256 quotient = gcd / remainder;
(gcd, remainder) = (
// The old remainder is the next gcd to try.
remainder,
// Compute the next remainder.
// Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
// where gcd is at most n (capped to type(uint256).max)
gcd - remainder * quotient
);
(x, y) = (
// Increment the coefficient of a.
y,
// Decrement the coefficient of n.
// Can overflow, but the result is casted to uint256 so that the
// next value of y is "wrapped around" to a value between 0 and n - 1.
x - y * int256(quotient)
);
}
if (gcd != 1) return 0; // No inverse exists.
return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
}
}
/**
* @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
*
* From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
* prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
* `a**(p-2)` is the modular multiplicative inverse of a in Fp.
*
* NOTE: this function does NOT check that `p` is a prime greater than `2`.
*/
function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
unchecked {
return Math.modExp(a, p - 2, p);
}
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
*
* Requirements:
* - modulus can't be zero
* - underlying staticcall to precompile must succeed
*
* IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
* sure the chain you're using it on supports the precompiled contract for modular exponentiation
* at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
* the underlying function will succeed given the lack of a revert, but the result may be incorrectly
* interpreted as 0.
*/
function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
(bool success, uint256 result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
* It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
* to operate modulo 0 or if the underlying precompile reverted.
*
* IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
* you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
* https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
* of a revert, but the result may be incorrectly interpreted as 0.
*/
function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
if (m == 0) return (false, 0);
assembly ("memory-safe") {
let ptr := mload(0x40)
// | Offset | Content | Content (Hex) |
// |-----------|------------|--------------------------------------------------------------------|
// | 0x00:0x1f | size of b | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x20:0x3f | size of e | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x40:0x5f | size of m | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x60:0x7f | value of b | 0x<.............................................................b> |
// | 0x80:0x9f | value of e | 0x<.............................................................e> |
// | 0xa0:0xbf | value of m | 0x<.............................................................m> |
mstore(ptr, 0x20)
mstore(add(ptr, 0x20), 0x20)
mstore(add(ptr, 0x40), 0x20)
mstore(add(ptr, 0x60), b)
mstore(add(ptr, 0x80), e)
mstore(add(ptr, 0xa0), m)
// Given the result < m, it's guaranteed to fit in 32 bytes,
// so we can use the memory scratch space located at offset 0.
success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
result := mload(0x00)
}
}
/**
* @dev Variant of {modExp} that supports inputs of arbitrary length.
*/
function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
(bool success, bytes memory result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Variant of {tryModExp} that supports inputs of arbitrary length.
*/
function tryModExp(
bytes memory b,
bytes memory e,
bytes memory m
) internal view returns (bool success, bytes memory result) {
if (_zeroBytes(m)) return (false, new bytes(0));
uint256 mLen = m.length;
// Encode call args in result and move the free memory pointer
result = abi.encodePacked(b.length, e.length, mLen, b, e, m);
assembly ("memory-safe") {
let dataPtr := add(result, 0x20)
// Write result on top of args to avoid allocating extra memory.
success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
// Overwrite the length.
// result.length > returndatasize() is guaranteed because returndatasize() == m.length
mstore(result, mLen)
// Set the memory pointer after the returned data.
mstore(0x40, add(dataPtr, mLen))
}
}
/**
* @dev Returns whether the provided byte array is zero.
*/
function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
for (uint256 i = 0; i < byteArray.length; ++i) {
if (byteArray[i] != 0) {
return false;
}
}
return true;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* This method is based on Newton's method for computing square roots; the algorithm is restricted to only
* using integer operations.
*/
function sqrt(uint256 a) internal pure returns (uint256) {
unchecked {
// Take care of easy edge cases when a == 0 or a == 1
if (a <= 1) {
return a;
}
// In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
// sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
// the current value as `ε_n = | x_n - sqrt(a) |`.
//
// For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
// of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
// bigger than any uint256.
//
// By noticing that
// `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
// we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
// to the msb function.
uint256 aa = a;
uint256 xn = 1;
if (aa >= (1 << 128)) {
aa >>= 128;
xn <<= 64;
}
if (aa >= (1 << 64)) {
aa >>= 64;
xn <<= 32;
}
if (aa >= (1 << 32)) {
aa >>= 32;
xn <<= 16;
}
if (aa >= (1 << 16)) {
aa >>= 16;
xn <<= 8;
}
if (aa >= (1 << 8)) {
aa >>= 8;
xn <<= 4;
}
if (aa >= (1 << 4)) {
aa >>= 4;
xn <<= 2;
}
if (aa >= (1 << 2)) {
xn <<= 1;
}
// We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
//
// We can refine our estimation by noticing that the middle of that interval minimizes the error.
// If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
// This is going to be our x_0 (and ε_0)
xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)
// From here, Newton's method give us:
// x_{n+1} = (x_n + a / x_n) / 2
//
// One should note that:
// x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
// = ((x_n² + a) / (2 * x_n))² - a
// = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
// = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
// = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
// = (x_n² - a)² / (2 * x_n)²
// = ((x_n² - a) / (2 * x_n))²
// ≥ 0
// Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
//
// This gives us the proof of quadratic convergence of the sequence:
// ε_{n+1} = | x_{n+1} - sqrt(a) |
// = | (x_n + a / x_n) / 2 - sqrt(a) |
// = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
// = | (x_n - sqrt(a))² / (2 * x_n) |
// = | ε_n² / (2 * x_n) |
// = ε_n² / | (2 * x_n) |
//
// For the first iteration, we have a special case where x_0 is known:
// ε_1 = ε_0² / | (2 * x_0) |
// ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
// ≤ 2**(2*e-4) / (3 * 2**(e-1))
// ≤ 2**(e-3) / 3
// ≤ 2**(e-3-log2(3))
// ≤ 2**(e-4.5)
//
// For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
// ε_{n+1} = ε_n² / | (2 * x_n) |
// ≤ (2**(e-k))² / (2 * 2**(e-1))
// ≤ 2**(2*e-2*k) / 2**e
// ≤ 2**(e-2*k)
xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5) -- special case, see above
xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9) -- general case with k = 4.5
xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18) -- general case with k = 9
xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36) -- general case with k = 18
xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72) -- general case with k = 36
xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144) -- general case with k = 72
// Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
// ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
// sqrt(a) or sqrt(a) + 1.
return xn - SafeCast.toUint(xn > a / xn);
}
}
/**
* @dev Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// If upper 8 bits of 16-bit half set, add 8 to result
r |= SafeCast.toUint((x >> r) > 0xff) << 3;
// If upper 4 bits of 8-bit half set, add 4 to result
r |= SafeCast.toUint((x >> r) > 0xf) << 2;
// Shifts value right by the current result and use it as an index into this lookup table:
//
// | x (4 bits) | index | table[index] = MSB position |
// |------------|---------|-----------------------------|
// | 0000 | 0 | table[0] = 0 |
// | 0001 | 1 | table[1] = 0 |
// | 0010 | 2 | table[2] = 1 |
// | 0011 | 3 | table[3] = 1 |
// | 0100 | 4 | table[4] = 2 |
// | 0101 | 5 | table[5] = 2 |
// | 0110 | 6 | table[6] = 2 |
// | 0111 | 7 | table[7] = 2 |
// | 1000 | 8 | table[8] = 3 |
// | 1001 | 9 | table[9] = 3 |
// | 1010 | 10 | table[10] = 3 |
// | 1011 | 11 | table[11] = 3 |
// | 1100 | 12 | table[12] = 3 |
// | 1101 | 13 | table[13] = 3 |
// | 1110 | 14 | table[14] = 3 |
// | 1111 | 15 | table[15] = 3 |
//
// The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the last 16 bytes.
assembly ("memory-safe") {
r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
}
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.20;
/**
* @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeCast {
/**
* @dev Value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
/**
* @dev An int value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedIntToUint(int256 value);
/**
* @dev Value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);
/**
* @dev An uint value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedUintToInt(uint256 value);
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toUint248(uint256 value) internal pure returns (uint248) {
if (value > type(uint248).max) {
revert SafeCastOverflowedUintDowncast(248, value);
}
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toUint240(uint256 value) internal pure returns (uint240) {
if (value > type(uint240).max) {
revert SafeCastOverflowedUintDowncast(240, value);
}
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toUint232(uint256 value) internal pure returns (uint232) {
if (value > type(uint232).max) {
revert SafeCastOverflowedUintDowncast(232, value);
}
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
if (value > type(uint224).max) {
revert SafeCastOverflowedUintDowncast(224, value);
}
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toUint216(uint256 value) internal pure returns (uint216) {
if (value > type(uint216).max) {
revert SafeCastOverflowedUintDowncast(216, value);
}
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toUint208(uint256 value) internal pure returns (uint208) {
if (value > type(uint208).max) {
revert SafeCastOverflowedUintDowncast(208, value);
}
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toUint200(uint256 value) internal pure returns (uint200) {
if (value > type(uint200).max) {
revert SafeCastOverflowedUintDowncast(200, value);
}
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toUint192(uint256 value) internal pure returns (uint192) {
if (value > type(uint192).max) {
revert SafeCastOverflowedUintDowncast(192, value);
}
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toUint184(uint256 value) internal pure returns (uint184) {
if (value > type(uint184).max) {
revert SafeCastOverflowedUintDowncast(184, value);
}
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toUint176(uint256 value) internal pure returns (uint176) {
if (value > type(uint176).max) {
revert SafeCastOverflowedUintDowncast(176, value);
}
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toUint168(uint256 value) internal pure returns (uint168) {
if (value > type(uint168).max) {
revert SafeCastOverflowedUintDowncast(168, value);
}
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toUint160(uint256 value) internal pure returns (uint160) {
if (value > type(uint160).max) {
revert SafeCastOverflowedUintDowncast(160, value);
}
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toUint152(uint256 value) internal pure returns (uint152) {
if (value > type(uint152).max) {
revert SafeCastOverflowedUintDowncast(152, value);
}
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toUint144(uint256 value) internal pure returns (uint144) {
if (value > type(uint144).max) {
revert SafeCastOverflowedUintDowncast(144, value);
}
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toUint136(uint256 value) internal pure returns (uint136) {
if (value > type(uint136).max) {
revert SafeCastOverflowedUintDowncast(136, value);
}
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
if (value > type(uint128).max) {
revert SafeCastOverflowedUintDowncast(128, value);
}
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toUint120(uint256 value) internal pure returns (uint120) {
if (value > type(uint120).max) {
revert SafeCastOverflowedUintDowncast(120, value);
}
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toUint112(uint256 value) internal pure returns (uint112) {
if (value > type(uint112).max) {
revert SafeCastOverflowedUintDowncast(112, value);
}
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toUint104(uint256 value) internal pure returns (uint104) {
if (value > type(uint104).max) {
revert SafeCastOverflowedUintDowncast(104, value);
}
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
if (value > type(uint96).max) {
revert SafeCastOverflowedUintDowncast(96, value);
}
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toUint88(uint256 value) internal pure returns (uint88) {
if (value > type(uint88).max) {
revert SafeCastOverflowedUintDowncast(88, value);
}
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toUint80(uint256 value) internal pure returns (uint80) {
if (value > type(uint80).max) {
revert SafeCastOverflowedUintDowncast(80, value);
}
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toUint72(uint256 value) internal pure returns (uint72) {
if (value > type(uint72).max) {
revert SafeCastOverflowedUintDowncast(72, value);
}
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
if (value > type(uint64).max) {
revert SafeCastOverflowedUintDowncast(64, value);
}
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toUint56(uint256 value) internal pure returns (uint56) {
if (value > type(uint56).max) {
revert SafeCastOverflowedUintDowncast(56, value);
}
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toUint48(uint256 value) internal pure returns (uint48) {
if (value > type(uint48).max) {
revert SafeCastOverflowedUintDowncast(48, value);
}
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toUint40(uint256 value) internal pure returns (uint40) {
if (value > type(uint40).max) {
revert SafeCastOverflowedUintDowncast(40, value);
}
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
if (value > type(uint32).max) {
revert SafeCastOverflowedUintDowncast(32, value);
}
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toUint24(uint256 value) internal pure returns (uint24) {
if (value > type(uint24).max) {
revert SafeCastOverflowedUintDowncast(24, value);
}
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
if (value > type(uint16).max) {
revert SafeCastOverflowedUintDowncast(16, value);
}
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toUint8(uint256 value) internal pure returns (uint8) {
if (value > type(uint8).max) {
revert SafeCastOverflowedUintDowncast(8, value);
}
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
if (value < 0) {
revert SafeCastOverflowedIntToUint(value);
}
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(248, value);
}
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(240, value);
}
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(232, value);
}
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(224, value);
}
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(216, value);
}
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(208, value);
}
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(200, value);
}
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(192, value);
}
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(184, value);
}
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(176, value);
}
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(168, value);
}
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(160, value);
}
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(152, value);
}
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(144, value);
}
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(136, value);
}
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(128, value);
}
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(120, value);
}
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(112, value);
}
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(104, value);
}
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(96, value);
}
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(88, value);
}
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(80, value);
}
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(72, value);
}
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(64, value);
}
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(56, value);
}
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(48, value);
}
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(40, value);
}
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(32, value);
}
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(24, value);
}
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(16, value);
}
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(8, value);
}
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
if (value > uint256(type(int256).max)) {
revert SafeCastOverflowedUintToInt(value);
}
return int256(value);
}
/**
* @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
*/
function toUint(bool b) internal pure returns (uint256 u) {
assembly ("memory-safe") {
u := iszero(iszero(b))
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.20;
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, int256 a, int256 b) internal pure returns (int256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * int256(SafeCast.toUint(condition)));
}
}
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return ternary(a < b, a, b);
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// Formula from the "Bit Twiddling Hacks" by Sean Eron Anderson.
// Since `n` is a signed integer, the generated bytecode will use the SAR opcode to perform the right shift,
// taking advantage of the most significant (or "sign" bit) in two's complement representation.
// This opcode adds new most significant bits set to the value of the previous most significant bit. As a result,
// the mask will either be `bytes32(0)` (if n is positive) or `~bytes32(0)` (if n is negative).
int256 mask = n >> 255;
// A `bytes32(0)` mask leaves the input unchanged, while a `~bytes32(0)` mask complements it.
return uint256((n + mask) ^ mask);
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)
pragma solidity ^0.8.20;
/**
* @dev Helper library for emitting standardized panic codes.
*
* ```solidity
* contract Example {
* using Panic for uint256;
*
* // Use any of the declared internal constants
* function foo() { Panic.GENERIC.panic(); }
*
* // Alternatively
* function foo() { Panic.panic(Panic.GENERIC); }
* }
* ```
*
* Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
*
* _Available since v5.1._
*/
// slither-disable-next-line unused-state
library Panic {
/// @dev generic / unspecified error
uint256 internal constant GENERIC = 0x00;
/// @dev used by the assert() builtin
uint256 internal constant ASSERT = 0x01;
/// @dev arithmetic underflow or overflow
uint256 internal constant UNDER_OVERFLOW = 0x11;
/// @dev division or modulo by zero
uint256 internal constant DIVISION_BY_ZERO = 0x12;
/// @dev enum conversion error
uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
/// @dev invalid encoding in storage
uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
/// @dev empty array pop
uint256 internal constant EMPTY_ARRAY_POP = 0x31;
/// @dev array out of bounds access
uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
/// @dev resource error (too large allocation or too large array)
uint256 internal constant RESOURCE_ERROR = 0x41;
/// @dev calling invalid internal function
uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;
/// @dev Reverts with a panic code. Recommended to use with
/// the internal constants with predefined codes.
function panic(uint256 code) internal pure {
assembly ("memory-safe") {
mstore(0x00, 0x4e487b71)
mstore(0x20, code)
revert(0x1c, 0x24)
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
uint256 private _status;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_status = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
if (_status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
_status = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == ENTERED;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/SlotDerivation.sol)
// This file was procedurally generated from scripts/generate/templates/SlotDerivation.js.
pragma solidity ^0.8.20;
/**
* @dev Library for computing storage (and transient storage) locations from namespaces and deriving slots
* corresponding to standard patterns. The derivation method for array and mapping matches the storage layout used by
* the solidity language / compiler.
*
* See https://docs.soliditylang.org/en/v0.8.20/internals/layout_in_storage.html#mappings-and-dynamic-arrays[Solidity docs for mappings and dynamic arrays.].
*
* Example usage:
* ```solidity
* contract Example {
* // Add the library methods
* using StorageSlot for bytes32;
* using SlotDerivation for bytes32;
*
* // Declare a namespace
* string private constant _NAMESPACE = "<namespace>"; // eg. OpenZeppelin.Slot
*
* function setValueInNamespace(uint256 key, address newValue) internal {
* _NAMESPACE.erc7201Slot().deriveMapping(key).getAddressSlot().value = newValue;
* }
*
* function getValueInNamespace(uint256 key) internal view returns (address) {
* return _NAMESPACE.erc7201Slot().deriveMapping(key).getAddressSlot().value;
* }
* }
* ```
*
* TIP: Consider using this library along with {StorageSlot}.
*
* NOTE: This library provides a way to manipulate storage locations in a non-standard way. Tooling for checking
* upgrade safety will ignore the slots accessed through this library.
*
* _Available since v5.1._
*/
library SlotDerivation {
/**
* @dev Derive an ERC-7201 slot from a string (namespace).
*/
function erc7201Slot(string memory namespace) internal pure returns (bytes32 slot) {
assembly ("memory-safe") {
mstore(0x00, sub(keccak256(add(namespace, 0x20), mload(namespace)), 1))
slot := and(keccak256(0x00, 0x20), not(0xff))
}
}
/**
* @dev Add an offset to a slot to get the n-th element of a structure or an array.
*/
function offset(bytes32 slot, uint256 pos) internal pure returns (bytes32 result) {
unchecked {
return bytes32(uint256(slot) + pos);
}
}
/**
* @dev Derive the location of the first element in an array from the slot where the length is stored.
*/
function deriveArray(bytes32 slot) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, slot)
result := keccak256(0x00, 0x20)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, address key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, and(key, shr(96, not(0))))
mstore(0x20, slot)
result := keccak256(0x00, 0x40)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, bool key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, iszero(iszero(key)))
mstore(0x20, slot)
result := keccak256(0x00, 0x40)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, bytes32 key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, key)
mstore(0x20, slot)
result := keccak256(0x00, 0x40)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, uint256 key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, key)
mstore(0x20, slot)
result := keccak256(0x00, 0x40)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, int256 key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, key)
mstore(0x20, slot)
result := keccak256(0x00, 0x40)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, string memory key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
let length := mload(key)
let begin := add(key, 0x20)
let end := add(begin, length)
let cache := mload(end)
mstore(end, slot)
result := keccak256(begin, add(length, 0x20))
mstore(end, cache)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, bytes memory key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
let length := mload(key)
let begin := add(key, 0x20)
let end := add(begin, length)
let cache := mload(end)
mstore(end, slot)
result := keccak256(begin, add(length, 0x20))
mstore(end, cache)
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC-1967 implementation slot:
* ```solidity
* contract ERC1967 {
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct Int256Slot {
int256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Int256Slot` with member `value` located at `slot`.
*/
function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
/**
* @dev Returns a `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/Strings.sol)
pragma solidity ^0.8.20;
import {Math} from "./math/Math.sol";
import {SafeCast} from "./math/SafeCast.sol";
import {SignedMath} from "./math/SignedMath.sol";
/**
* @dev String operations.
*/
library Strings {
using SafeCast for *;
bytes16 private constant HEX_DIGITS = "0123456789abcdef";
uint8 private constant ADDRESS_LENGTH = 20;
uint256 private constant SPECIAL_CHARS_LOOKUP =
(1 << 0x08) | // backspace
(1 << 0x09) | // tab
(1 << 0x0a) | // newline
(1 << 0x0c) | // form feed
(1 << 0x0d) | // carriage return
(1 << 0x22) | // double quote
(1 << 0x5c); // backslash
/**
* @dev The `value` string doesn't fit in the specified `length`.
*/
error StringsInsufficientHexLength(uint256 value, uint256 length);
/**
* @dev The string being parsed contains characters that are not in scope of the given base.
*/
error StringsInvalidChar();
/**
* @dev The string being parsed is not a properly formatted address.
*/
error StringsInvalidAddressFormat();
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
assembly ("memory-safe") {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
assembly ("memory-safe") {
mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toStringSigned(int256 value) internal pure returns (string memory) {
return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
uint256 localValue = value;
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = HEX_DIGITS[localValue & 0xf];
localValue >>= 4;
}
if (localValue != 0) {
revert StringsInsufficientHexLength(value, length);
}
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
* representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its checksummed ASCII `string` hexadecimal
* representation, according to EIP-55.
*/
function toChecksumHexString(address addr) internal pure returns (string memory) {
bytes memory buffer = bytes(toHexString(addr));
// hash the hex part of buffer (skip length + 2 bytes, length 40)
uint256 hashValue;
assembly ("memory-safe") {
hashValue := shr(96, keccak256(add(buffer, 0x22), 40))
}
for (uint256 i = 41; i > 1; --i) {
// possible values for buffer[i] are 48 (0) to 57 (9) and 97 (a) to 102 (f)
if (hashValue & 0xf > 7 && uint8(buffer[i]) > 96) {
// case shift by xoring with 0x20
buffer[i] ^= 0x20;
}
hashValue >>= 4;
}
return string(buffer);
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
}
/**
* @dev Parse a decimal string and returns the value as a `uint256`.
*
* Requirements:
* - The string must be formatted as `[0-9]*`
* - The result must fit into an `uint256` type
*/
function parseUint(string memory input) internal pure returns (uint256) {
return parseUint(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseUint-string} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `[0-9]*`
* - The result must fit into an `uint256` type
*/
function parseUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {
(bool success, uint256 value) = tryParseUint(input, begin, end);
if (!success) revert StringsInvalidChar();
return value;
}
/**
* @dev Variant of {parseUint-string} that returns false if the parsing fails because of an invalid character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseUint(string memory input) internal pure returns (bool success, uint256 value) {
return _tryParseUintUncheckedBounds(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseUint-string-uint256-uint256} that returns false if the parsing fails because of an invalid
* character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseUint(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, uint256 value) {
if (end > bytes(input).length || begin > end) return (false, 0);
return _tryParseUintUncheckedBounds(input, begin, end);
}
/**
* @dev Implementation of {tryParseUint-string-uint256-uint256} that does not check bounds. Caller should make sure that
* `begin <= end <= input.length`. Other inputs would result in undefined behavior.
*/
function _tryParseUintUncheckedBounds(
string memory input,
uint256 begin,
uint256 end
) private pure returns (bool success, uint256 value) {
bytes memory buffer = bytes(input);
uint256 result = 0;
for (uint256 i = begin; i < end; ++i) {
uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
if (chr > 9) return (false, 0);
result *= 10;
result += chr;
}
return (true, result);
}
/**
* @dev Parse a decimal string and returns the value as a `int256`.
*
* Requirements:
* - The string must be formatted as `[-+]?[0-9]*`
* - The result must fit in an `int256` type.
*/
function parseInt(string memory input) internal pure returns (int256) {
return parseInt(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseInt-string} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `[-+]?[0-9]*`
* - The result must fit in an `int256` type.
*/
function parseInt(string memory input, uint256 begin, uint256 end) internal pure returns (int256) {
(bool success, int256 value) = tryParseInt(input, begin, end);
if (!success) revert StringsInvalidChar();
return value;
}
/**
* @dev Variant of {parseInt-string} that returns false if the parsing fails because of an invalid character or if
* the result does not fit in a `int256`.
*
* NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
*/
function tryParseInt(string memory input) internal pure returns (bool success, int256 value) {
return _tryParseIntUncheckedBounds(input, 0, bytes(input).length);
}
uint256 private constant ABS_MIN_INT256 = 2 ** 255;
/**
* @dev Variant of {parseInt-string-uint256-uint256} that returns false if the parsing fails because of an invalid
* character or if the result does not fit in a `int256`.
*
* NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
*/
function tryParseInt(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, int256 value) {
if (end > bytes(input).length || begin > end) return (false, 0);
return _tryParseIntUncheckedBounds(input, begin, end);
}
/**
* @dev Implementation of {tryParseInt-string-uint256-uint256} that does not check bounds. Caller should make sure that
* `begin <= end <= input.length`. Other inputs would result in undefined behavior.
*/
function _tryParseIntUncheckedBounds(
string memory input,
uint256 begin,
uint256 end
) private pure returns (bool success, int256 value) {
bytes memory buffer = bytes(input);
// Check presence of a negative sign.
bytes1 sign = begin == end ? bytes1(0) : bytes1(_unsafeReadBytesOffset(buffer, begin)); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
bool positiveSign = sign == bytes1("+");
bool negativeSign = sign == bytes1("-");
uint256 offset = (positiveSign || negativeSign).toUint();
(bool absSuccess, uint256 absValue) = tryParseUint(input, begin + offset, end);
if (absSuccess && absValue < ABS_MIN_INT256) {
return (true, negativeSign ? -int256(absValue) : int256(absValue));
} else if (absSuccess && negativeSign && absValue == ABS_MIN_INT256) {
return (true, type(int256).min);
} else return (false, 0);
}
/**
* @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as a `uint256`.
*
* Requirements:
* - The string must be formatted as `(0x)?[0-9a-fA-F]*`
* - The result must fit in an `uint256` type.
*/
function parseHexUint(string memory input) internal pure returns (uint256) {
return parseHexUint(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseHexUint-string} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `(0x)?[0-9a-fA-F]*`
* - The result must fit in an `uint256` type.
*/
function parseHexUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {
(bool success, uint256 value) = tryParseHexUint(input, begin, end);
if (!success) revert StringsInvalidChar();
return value;
}
/**
* @dev Variant of {parseHexUint-string} that returns false if the parsing fails because of an invalid character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseHexUint(string memory input) internal pure returns (bool success, uint256 value) {
return _tryParseHexUintUncheckedBounds(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseHexUint-string-uint256-uint256} that returns false if the parsing fails because of an
* invalid character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseHexUint(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, uint256 value) {
if (end > bytes(input).length || begin > end) return (false, 0);
return _tryParseHexUintUncheckedBounds(input, begin, end);
}
/**
* @dev Implementation of {tryParseHexUint-string-uint256-uint256} that does not check bounds. Caller should make sure that
* `begin <= end <= input.length`. Other inputs would result in undefined behavior.
*/
function _tryParseHexUintUncheckedBounds(
string memory input,
uint256 begin,
uint256 end
) private pure returns (bool success, uint256 value) {
bytes memory buffer = bytes(input);
// skip 0x prefix if present
bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(buffer, begin)) == bytes2("0x"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
uint256 offset = hasPrefix.toUint() * 2;
uint256 result = 0;
for (uint256 i = begin + offset; i < end; ++i) {
uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
if (chr > 15) return (false, 0);
result *= 16;
unchecked {
// Multiplying by 16 is equivalent to a shift of 4 bits (with additional overflow check).
// This guarantees that adding a value < 16 will not cause an overflow, hence the unchecked.
result += chr;
}
}
return (true, result);
}
/**
* @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as an `address`.
*
* Requirements:
* - The string must be formatted as `(0x)?[0-9a-fA-F]{40}`
*/
function parseAddress(string memory input) internal pure returns (address) {
return parseAddress(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseAddress-string} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `(0x)?[0-9a-fA-F]{40}`
*/
function parseAddress(string memory input, uint256 begin, uint256 end) internal pure returns (address) {
(bool success, address value) = tryParseAddress(input, begin, end);
if (!success) revert StringsInvalidAddressFormat();
return value;
}
/**
* @dev Variant of {parseAddress-string} that returns false if the parsing fails because the input is not a properly
* formatted address. See {parseAddress-string} requirements.
*/
function tryParseAddress(string memory input) internal pure returns (bool success, address value) {
return tryParseAddress(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseAddress-string-uint256-uint256} that returns false if the parsing fails because input is not a properly
* formatted address. See {parseAddress-string-uint256-uint256} requirements.
*/
function tryParseAddress(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, address value) {
if (end > bytes(input).length || begin > end) return (false, address(0));
bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(bytes(input), begin)) == bytes2("0x"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
uint256 expectedLength = 40 + hasPrefix.toUint() * 2;
// check that input is the correct length
if (end - begin == expectedLength) {
// length guarantees that this does not overflow, and value is at most type(uint160).max
(bool s, uint256 v) = _tryParseHexUintUncheckedBounds(input, begin, end);
return (s, address(uint160(v)));
} else {
return (false, address(0));
}
}
function _tryParseChr(bytes1 chr) private pure returns (uint8) {
uint8 value = uint8(chr);
// Try to parse `chr`:
// - Case 1: [0-9]
// - Case 2: [a-f]
// - Case 3: [A-F]
// - otherwise not supported
unchecked {
if (value > 47 && value < 58) value -= 48;
else if (value > 96 && value < 103) value -= 87;
else if (value > 64 && value < 71) value -= 55;
else return type(uint8).max;
}
return value;
}
/**
* @dev Escape special characters in JSON strings. This can be useful to prevent JSON injection in NFT metadata.
*
* WARNING: This function should only be used in double quoted JSON strings. Single quotes are not escaped.
*
* NOTE: This function escapes all unicode characters, and not just the ones in ranges defined in section 2.5 of
* RFC-4627 (U+0000 to U+001F, U+0022 and U+005C). ECMAScript's `JSON.parse` does recover escaped unicode
* characters that are not in this range, but other tooling may provide different results.
*/
function escapeJSON(string memory input) internal pure returns (string memory) {
bytes memory buffer = bytes(input);
bytes memory output = new bytes(2 * buffer.length); // worst case scenario
uint256 outputLength = 0;
for (uint256 i; i < buffer.length; ++i) {
bytes1 char = bytes1(_unsafeReadBytesOffset(buffer, i));
if (((SPECIAL_CHARS_LOOKUP & (1 << uint8(char))) != 0)) {
output[outputLength++] = "\\";
if (char == 0x08) output[outputLength++] = "b";
else if (char == 0x09) output[outputLength++] = "t";
else if (char == 0x0a) output[outputLength++] = "n";
else if (char == 0x0c) output[outputLength++] = "f";
else if (char == 0x0d) output[outputLength++] = "r";
else if (char == 0x5c) output[outputLength++] = "\\";
else if (char == 0x22) {
// solhint-disable-next-line quotes
output[outputLength++] = '"';
}
} else {
output[outputLength++] = char;
}
}
// write the actual length and deallocate unused memory
assembly ("memory-safe") {
mstore(output, outputLength)
mstore(0x40, add(output, shl(5, shr(5, add(outputLength, 63)))))
}
return string(output);
}
/**
* @dev Reads a bytes32 from a bytes array without bounds checking.
*
* NOTE: making this function internal would mean it could be used with memory unsafe offset, and marking the
* assembly block as such would prevent some optimizations.
*/
function _unsafeReadBytesOffset(bytes memory buffer, uint256 offset) private pure returns (bytes32 value) {
// This is not memory safe in the general case, but all calls to this private function are within bounds.
assembly ("memory-safe") {
value := mload(add(buffer, add(0x20, offset)))
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
pragma solidity ^0.8.20;
import {Arrays} from "../Arrays.sol";
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
* - Set can be cleared (all elements removed) in O(n).
*
* ```solidity
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*
* [WARNING]
* ====
* Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
* unusable.
* See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
*
* In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
* array of EnumerableSet.
* ====
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position is the index of the value in the `values` array plus 1.
// Position 0 is used to mean a value is not in the set.
mapping(bytes32 value => uint256) _positions;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._positions[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We cache the value's position to prevent multiple reads from the same storage slot
uint256 position = set._positions[value];
if (position != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 valueIndex = position - 1;
uint256 lastIndex = set._values.length - 1;
if (valueIndex != lastIndex) {
bytes32 lastValue = set._values[lastIndex];
// Move the lastValue to the index where the value to delete is
set._values[valueIndex] = lastValue;
// Update the tracked position of the lastValue (that was just moved)
set._positions[lastValue] = position;
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the tracked position for the deleted slot
delete set._positions[value];
return true;
} else {
return false;
}
}
/**
* @dev Removes all the values from a set. O(n).
*
* WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
* function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
*/
function _clear(Set storage set) private {
uint256 len = _length(set);
for (uint256 i = 0; i < len; ++i) {
delete set._positions[set._values[i]];
}
Arrays.unsafeSetLength(set._values, 0);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._positions[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Removes all the values from a set. O(n).
*
* WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
* function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
*/
function clear(Bytes32Set storage set) internal {
_clear(set._inner);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
bytes32[] memory store = _values(set._inner);
bytes32[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes all the values from a set. O(n).
*
* WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
* function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
*/
function clear(AddressSet storage set) internal {
_clear(set._inner);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Removes all the values from a set. O(n).
*
* WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
* function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
*/
function clear(UintSet storage set) internal {
_clear(set._inner);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
// Common.sol
//
// Common mathematical functions used in both SD59x18 and UD60x18. Note that these global functions do not
// always operate with SD59x18 and UD60x18 numbers.
/*//////////////////////////////////////////////////////////////////////////
CUSTOM ERRORS
//////////////////////////////////////////////////////////////////////////*/
/// @notice Thrown when the resultant value in {mulDiv} overflows uint256.
error PRBMath_MulDiv_Overflow(uint256 x, uint256 y, uint256 denominator);
/// @notice Thrown when the resultant value in {mulDiv18} overflows uint256.
error PRBMath_MulDiv18_Overflow(uint256 x, uint256 y);
/// @notice Thrown when one of the inputs passed to {mulDivSigned} is `type(int256).min`.
error PRBMath_MulDivSigned_InputTooSmall();
/// @notice Thrown when the resultant value in {mulDivSigned} overflows int256.
error PRBMath_MulDivSigned_Overflow(int256 x, int256 y);
/*//////////////////////////////////////////////////////////////////////////
CONSTANTS
//////////////////////////////////////////////////////////////////////////*/
/// @dev The maximum value a uint128 number can have.
uint128 constant MAX_UINT128 = type(uint128).max;
/// @dev The maximum value a uint40 number can have.
uint40 constant MAX_UINT40 = type(uint40).max;
/// @dev The maximum value a uint64 number can have.
uint64 constant MAX_UINT64 = type(uint64).max;
/// @dev The unit number, which the decimal precision of the fixed-point types.
uint256 constant UNIT = 1e18;
/// @dev The unit number inverted mod 2^256.
uint256 constant UNIT_INVERSE = 78156646155174841979727994598816262306175212592076161876661_508869554232690281;
/// @dev The the largest power of two that divides the decimal value of `UNIT`. The logarithm of this value is the least significant
/// bit in the binary representation of `UNIT`.
uint256 constant UNIT_LPOTD = 262144;
/*//////////////////////////////////////////////////////////////////////////
FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
/// @notice Calculates the binary exponent of x using the binary fraction method.
/// @dev Has to use 192.64-bit fixed-point numbers. See https://ethereum.stackexchange.com/a/96594/24693.
/// @param x The exponent as an unsigned 192.64-bit fixed-point number.
/// @return result The result as an unsigned 60.18-decimal fixed-point number.
/// @custom:smtchecker abstract-function-nondet
function exp2(uint256 x) pure returns (uint256 result) {
unchecked {
// Start from 0.5 in the 192.64-bit fixed-point format.
result = 0x800000000000000000000000000000000000000000000000;
// The following logic multiplies the result by $\sqrt{2^{-i}}$ when the bit at position i is 1. Key points:
//
// 1. Intermediate results will not overflow, as the starting point is 2^191 and all magic factors are under 2^65.
// 2. The rationale for organizing the if statements into groups of 8 is gas savings. If the result of performing
// a bitwise AND operation between x and any value in the array [0x80; 0x40; 0x20; 0x10; 0x08; 0x04; 0x02; 0x01] is 1,
// we know that `x & 0xFF` is also 1.
if (x & 0xFF00000000000000 > 0) {
if (x & 0x8000000000000000 > 0) {
result = (result * 0x16A09E667F3BCC909) >> 64;
}
if (x & 0x4000000000000000 > 0) {
result = (result * 0x1306FE0A31B7152DF) >> 64;
}
if (x & 0x2000000000000000 > 0) {
result = (result * 0x1172B83C7D517ADCE) >> 64;
}
if (x & 0x1000000000000000 > 0) {
result = (result * 0x10B5586CF9890F62A) >> 64;
}
if (x & 0x800000000000000 > 0) {
result = (result * 0x1059B0D31585743AE) >> 64;
}
if (x & 0x400000000000000 > 0) {
result = (result * 0x102C9A3E778060EE7) >> 64;
}
if (x & 0x200000000000000 > 0) {
result = (result * 0x10163DA9FB33356D8) >> 64;
}
if (x & 0x100000000000000 > 0) {
result = (result * 0x100B1AFA5ABCBED61) >> 64;
}
}
if (x & 0xFF000000000000 > 0) {
if (x & 0x80000000000000 > 0) {
result = (result * 0x10058C86DA1C09EA2) >> 64;
}
if (x & 0x40000000000000 > 0) {
result = (result * 0x1002C605E2E8CEC50) >> 64;
}
if (x & 0x20000000000000 > 0) {
result = (result * 0x100162F3904051FA1) >> 64;
}
if (x & 0x10000000000000 > 0) {
result = (result * 0x1000B175EFFDC76BA) >> 64;
}
if (x & 0x8000000000000 > 0) {
result = (result * 0x100058BA01FB9F96D) >> 64;
}
if (x & 0x4000000000000 > 0) {
result = (result * 0x10002C5CC37DA9492) >> 64;
}
if (x & 0x2000000000000 > 0) {
result = (result * 0x1000162E525EE0547) >> 64;
}
if (x & 0x1000000000000 > 0) {
result = (result * 0x10000B17255775C04) >> 64;
}
}
if (x & 0xFF0000000000 > 0) {
if (x & 0x800000000000 > 0) {
result = (result * 0x1000058B91B5BC9AE) >> 64;
}
if (x & 0x400000000000 > 0) {
result = (result * 0x100002C5C89D5EC6D) >> 64;
}
if (x & 0x200000000000 > 0) {
result = (result * 0x10000162E43F4F831) >> 64;
}
if (x & 0x100000000000 > 0) {
result = (result * 0x100000B1721BCFC9A) >> 64;
}
if (x & 0x80000000000 > 0) {
result = (result * 0x10000058B90CF1E6E) >> 64;
}
if (x & 0x40000000000 > 0) {
result = (result * 0x1000002C5C863B73F) >> 64;
}
if (x & 0x20000000000 > 0) {
result = (result * 0x100000162E430E5A2) >> 64;
}
if (x & 0x10000000000 > 0) {
result = (result * 0x1000000B172183551) >> 64;
}
}
if (x & 0xFF00000000 > 0) {
if (x & 0x8000000000 > 0) {
result = (result * 0x100000058B90C0B49) >> 64;
}
if (x & 0x4000000000 > 0) {
result = (result * 0x10000002C5C8601CC) >> 64;
}
if (x & 0x2000000000 > 0) {
result = (result * 0x1000000162E42FFF0) >> 64;
}
if (x & 0x1000000000 > 0) {
result = (result * 0x10000000B17217FBB) >> 64;
}
if (x & 0x800000000 > 0) {
result = (result * 0x1000000058B90BFCE) >> 64;
}
if (x & 0x400000000 > 0) {
result = (result * 0x100000002C5C85FE3) >> 64;
}
if (x & 0x200000000 > 0) {
result = (result * 0x10000000162E42FF1) >> 64;
}
if (x & 0x100000000 > 0) {
result = (result * 0x100000000B17217F8) >> 64;
}
}
if (x & 0xFF000000 > 0) {
if (x & 0x80000000 > 0) {
result = (result * 0x10000000058B90BFC) >> 64;
}
if (x & 0x40000000 > 0) {
result = (result * 0x1000000002C5C85FE) >> 64;
}
if (x & 0x20000000 > 0) {
result = (result * 0x100000000162E42FF) >> 64;
}
if (x & 0x10000000 > 0) {
result = (result * 0x1000000000B17217F) >> 64;
}
if (x & 0x8000000 > 0) {
result = (result * 0x100000000058B90C0) >> 64;
}
if (x & 0x4000000 > 0) {
result = (result * 0x10000000002C5C860) >> 64;
}
if (x & 0x2000000 > 0) {
result = (result * 0x1000000000162E430) >> 64;
}
if (x & 0x1000000 > 0) {
result = (result * 0x10000000000B17218) >> 64;
}
}
if (x & 0xFF0000 > 0) {
if (x & 0x800000 > 0) {
result = (result * 0x1000000000058B90C) >> 64;
}
if (x & 0x400000 > 0) {
result = (result * 0x100000000002C5C86) >> 64;
}
if (x & 0x200000 > 0) {
result = (result * 0x10000000000162E43) >> 64;
}
if (x & 0x100000 > 0) {
result = (result * 0x100000000000B1721) >> 64;
}
if (x & 0x80000 > 0) {
result = (result * 0x10000000000058B91) >> 64;
}
if (x & 0x40000 > 0) {
result = (result * 0x1000000000002C5C8) >> 64;
}
if (x & 0x20000 > 0) {
result = (result * 0x100000000000162E4) >> 64;
}
if (x & 0x10000 > 0) {
result = (result * 0x1000000000000B172) >> 64;
}
}
if (x & 0xFF00 > 0) {
if (x & 0x8000 > 0) {
result = (result * 0x100000000000058B9) >> 64;
}
if (x & 0x4000 > 0) {
result = (result * 0x10000000000002C5D) >> 64;
}
if (x & 0x2000 > 0) {
result = (result * 0x1000000000000162E) >> 64;
}
if (x & 0x1000 > 0) {
result = (result * 0x10000000000000B17) >> 64;
}
if (x & 0x800 > 0) {
result = (result * 0x1000000000000058C) >> 64;
}
if (x & 0x400 > 0) {
result = (result * 0x100000000000002C6) >> 64;
}
if (x & 0x200 > 0) {
result = (result * 0x10000000000000163) >> 64;
}
if (x & 0x100 > 0) {
result = (result * 0x100000000000000B1) >> 64;
}
}
if (x & 0xFF > 0) {
if (x & 0x80 > 0) {
result = (result * 0x10000000000000059) >> 64;
}
if (x & 0x40 > 0) {
result = (result * 0x1000000000000002C) >> 64;
}
if (x & 0x20 > 0) {
result = (result * 0x10000000000000016) >> 64;
}
if (x & 0x10 > 0) {
result = (result * 0x1000000000000000B) >> 64;
}
if (x & 0x8 > 0) {
result = (result * 0x10000000000000006) >> 64;
}
if (x & 0x4 > 0) {
result = (result * 0x10000000000000003) >> 64;
}
if (x & 0x2 > 0) {
result = (result * 0x10000000000000001) >> 64;
}
if (x & 0x1 > 0) {
result = (result * 0x10000000000000001) >> 64;
}
}
// In the code snippet below, two operations are executed simultaneously:
//
// 1. The result is multiplied by $(2^n + 1)$, where $2^n$ represents the integer part, and the additional 1
// accounts for the initial guess of 0.5. This is achieved by subtracting from 191 instead of 192.
// 2. The result is then converted to an unsigned 60.18-decimal fixed-point format.
//
// The underlying logic is based on the relationship $2^{191-ip} = 2^{ip} / 2^{191}$, where $ip$ denotes the,
// integer part, $2^n$.
result *= UNIT;
result >>= (191 - (x >> 64));
}
}
/// @notice Finds the zero-based index of the first 1 in the binary representation of x.
///
/// @dev See the note on "msb" in this Wikipedia article: https://en.wikipedia.org/wiki/Find_first_set
///
/// Each step in this implementation is equivalent to this high-level code:
///
/// ```solidity
/// if (x >= 2 ** 128) {
/// x >>= 128;
/// result += 128;
/// }
/// ```
///
/// Where 128 is replaced with each respective power of two factor. See the full high-level implementation here:
/// https://gist.github.com/PaulRBerg/f932f8693f2733e30c4d479e8e980948
///
/// The Yul instructions used below are:
///
/// - "gt" is "greater than"
/// - "or" is the OR bitwise operator
/// - "shl" is "shift left"
/// - "shr" is "shift right"
///
/// @param x The uint256 number for which to find the index of the most significant bit.
/// @return result The index of the most significant bit as a uint256.
/// @custom:smtchecker abstract-function-nondet
function msb(uint256 x) pure returns (uint256 result) {
// 2^128
assembly ("memory-safe") {
let factor := shl(7, gt(x, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
x := shr(factor, x)
result := or(result, factor)
}
// 2^64
assembly ("memory-safe") {
let factor := shl(6, gt(x, 0xFFFFFFFFFFFFFFFF))
x := shr(factor, x)
result := or(result, factor)
}
// 2^32
assembly ("memory-safe") {
let factor := shl(5, gt(x, 0xFFFFFFFF))
x := shr(factor, x)
result := or(result, factor)
}
// 2^16
assembly ("memory-safe") {
let factor := shl(4, gt(x, 0xFFFF))
x := shr(factor, x)
result := or(result, factor)
}
// 2^8
assembly ("memory-safe") {
let factor := shl(3, gt(x, 0xFF))
x := shr(factor, x)
result := or(result, factor)
}
// 2^4
assembly ("memory-safe") {
let factor := shl(2, gt(x, 0xF))
x := shr(factor, x)
result := or(result, factor)
}
// 2^2
assembly ("memory-safe") {
let factor := shl(1, gt(x, 0x3))
x := shr(factor, x)
result := or(result, factor)
}
// 2^1
// No need to shift x any more.
assembly ("memory-safe") {
let factor := gt(x, 0x1)
result := or(result, factor)
}
}
/// @notice Calculates x*y÷denominator with 512-bit precision.
///
/// @dev Credits to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv.
///
/// Notes:
/// - The result is rounded toward zero.
///
/// Requirements:
/// - The denominator must not be zero.
/// - The result must fit in uint256.
///
/// @param x The multiplicand as a uint256.
/// @param y The multiplier as a uint256.
/// @param denominator The divisor as a uint256.
/// @return result The result as a uint256.
/// @custom:smtchecker abstract-function-nondet
function mulDiv(uint256 x, uint256 y, uint256 denominator) pure returns (uint256 result) {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512-bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly ("memory-safe") {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
unchecked {
return prod0 / denominator;
}
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
if (prod1 >= denominator) {
revert PRBMath_MulDiv_Overflow(x, y, denominator);
}
////////////////////////////////////////////////////////////////////////////
// 512 by 256 division
////////////////////////////////////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly ("memory-safe") {
// Compute remainder using the mulmod Yul instruction.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512-bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
unchecked {
// Calculate the largest power of two divisor of the denominator using the unary operator ~. This operation cannot overflow
// because the denominator cannot be zero at this point in the function execution. The result is always >= 1.
// For more detail, see https://cs.stackexchange.com/q/138556/92363.
uint256 lpotdod = denominator & (~denominator + 1);
uint256 flippedLpotdod;
assembly ("memory-safe") {
// Factor powers of two out of denominator.
denominator := div(denominator, lpotdod)
// Divide [prod1 prod0] by lpotdod.
prod0 := div(prod0, lpotdod)
// Get the flipped value `2^256 / lpotdod`. If the `lpotdod` is zero, the flipped value is one.
// `sub(0, lpotdod)` produces the two's complement version of `lpotdod`, which is equivalent to flipping all the bits.
// However, `div` interprets this value as an unsigned value: https://ethereum.stackexchange.com/q/147168/24693
flippedLpotdod := add(div(sub(0, lpotdod), lpotdod), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * flippedLpotdod;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
}
}
/// @notice Calculates x*y÷1e18 with 512-bit precision.
///
/// @dev A variant of {mulDiv} with constant folding, i.e. in which the denominator is hard coded to 1e18.
///
/// Notes:
/// - The body is purposely left uncommented; to understand how this works, see the documentation in {mulDiv}.
/// - The result is rounded toward zero.
/// - We take as an axiom that the result cannot be `MAX_UINT256` when x and y solve the following system of equations:
///
/// $$
/// \begin{cases}
/// x * y = MAX\_UINT256 * UNIT \\
/// (x * y) \% UNIT \geq \frac{UNIT}{2}
/// \end{cases}
/// $$
///
/// Requirements:
/// - Refer to the requirements in {mulDiv}.
/// - The result must fit in uint256.
///
/// @param x The multiplicand as an unsigned 60.18-decimal fixed-point number.
/// @param y The multiplier as an unsigned 60.18-decimal fixed-point number.
/// @return result The result as an unsigned 60.18-decimal fixed-point number.
/// @custom:smtchecker abstract-function-nondet
function mulDiv18(uint256 x, uint256 y) pure returns (uint256 result) {
uint256 prod0;
uint256 prod1;
assembly ("memory-safe") {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
if (prod1 == 0) {
unchecked {
return prod0 / UNIT;
}
}
if (prod1 >= UNIT) {
revert PRBMath_MulDiv18_Overflow(x, y);
}
uint256 remainder;
assembly ("memory-safe") {
remainder := mulmod(x, y, UNIT)
result :=
mul(
or(
div(sub(prod0, remainder), UNIT_LPOTD),
mul(sub(prod1, gt(remainder, prod0)), add(div(sub(0, UNIT_LPOTD), UNIT_LPOTD), 1))
),
UNIT_INVERSE
)
}
}
/// @notice Calculates x*y÷denominator with 512-bit precision.
///
/// @dev This is an extension of {mulDiv} for signed numbers, which works by computing the signs and the absolute values separately.
///
/// Notes:
/// - The result is rounded toward zero.
///
/// Requirements:
/// - Refer to the requirements in {mulDiv}.
/// - None of the inputs can be `type(int256).min`.
/// - The result must fit in int256.
///
/// @param x The multiplicand as an int256.
/// @param y The multiplier as an int256.
/// @param denominator The divisor as an int256.
/// @return result The result as an int256.
/// @custom:smtchecker abstract-function-nondet
function mulDivSigned(int256 x, int256 y, int256 denominator) pure returns (int256 result) {
if (x == type(int256).min || y == type(int256).min || denominator == type(int256).min) {
revert PRBMath_MulDivSigned_InputTooSmall();
}
// Get hold of the absolute values of x, y and the denominator.
uint256 xAbs;
uint256 yAbs;
uint256 dAbs;
unchecked {
xAbs = x < 0 ? uint256(-x) : uint256(x);
yAbs = y < 0 ? uint256(-y) : uint256(y);
dAbs = denominator < 0 ? uint256(-denominator) : uint256(denominator);
}
// Compute the absolute value of x*y÷denominator. The result must fit in int256.
uint256 resultAbs = mulDiv(xAbs, yAbs, dAbs);
if (resultAbs > uint256(type(int256).max)) {
revert PRBMath_MulDivSigned_Overflow(x, y);
}
// Get the signs of x, y and the denominator.
uint256 sx;
uint256 sy;
uint256 sd;
assembly ("memory-safe") {
// "sgt" is the "signed greater than" assembly instruction and "sub(0,1)" is -1 in two's complement.
sx := sgt(x, sub(0, 1))
sy := sgt(y, sub(0, 1))
sd := sgt(denominator, sub(0, 1))
}
// XOR over sx, sy and sd. What this does is to check whether there are 1 or 3 negative signs in the inputs.
// If there are, the result should be negative. Otherwise, it should be positive.
unchecked {
result = sx ^ sy ^ sd == 0 ? -int256(resultAbs) : int256(resultAbs);
}
}
/// @notice Calculates the square root of x using the Babylonian method.
///
/// @dev See https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.
///
/// Notes:
/// - If x is not a perfect square, the result is rounded down.
/// - Credits to OpenZeppelin for the explanations in comments below.
///
/// @param x The uint256 number for which to calculate the square root.
/// @return result The result as a uint256.
/// @custom:smtchecker abstract-function-nondet
function sqrt(uint256 x) pure returns (uint256 result) {
if (x == 0) {
return 0;
}
// For our first guess, we calculate the biggest power of 2 which is smaller than the square root of x.
//
// We know that the "msb" (most significant bit) of x is a power of 2 such that we have:
//
// $$
// msb(x) <= x <= 2*msb(x)$
// $$
//
// We write $msb(x)$ as $2^k$, and we get:
//
// $$
// k = log_2(x)
// $$
//
// Thus, we can write the initial inequality as:
//
// $$
// 2^{log_2(x)} <= x <= 2*2^{log_2(x)+1} \\
// sqrt(2^k) <= sqrt(x) < sqrt(2^{k+1}) \\
// 2^{k/2} <= sqrt(x) < 2^{(k+1)/2} <= 2^{(k/2)+1}
// $$
//
// Consequently, $2^{log_2(x) /2} is a good first approximation of sqrt(x) with at least one correct bit.
uint256 xAux = uint256(x);
result = 1;
if (xAux >= 2 ** 128) {
xAux >>= 128;
result <<= 64;
}
if (xAux >= 2 ** 64) {
xAux >>= 64;
result <<= 32;
}
if (xAux >= 2 ** 32) {
xAux >>= 32;
result <<= 16;
}
if (xAux >= 2 ** 16) {
xAux >>= 16;
result <<= 8;
}
if (xAux >= 2 ** 8) {
xAux >>= 8;
result <<= 4;
}
if (xAux >= 2 ** 4) {
xAux >>= 4;
result <<= 2;
}
if (xAux >= 2 ** 2) {
result <<= 1;
}
// At this point, `result` is an estimation with at least one bit of precision. We know the true value has at
// most 128 bits, since it is the square root of a uint256. Newton's method converges quadratically (precision
// doubles at every iteration). We thus need at most 7 iteration to turn our partial result with one bit of
// precision into the expected uint128 result.
unchecked {
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
// If x is not a perfect square, round the result toward zero.
uint256 roundedResult = x / result;
if (result >= roundedResult) {
result = roundedResult;
}
}
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "../Common.sol" as Common;
import "./Errors.sol" as CastingErrors;
import { SD59x18 } from "../sd59x18/ValueType.sol";
import { UD60x18 } from "../ud60x18/ValueType.sol";
import { SD1x18 } from "./ValueType.sol";
/// @notice Casts an SD1x18 number into SD59x18.
/// @dev There is no overflow check because SD1x18 ⊆ SD59x18.
function intoSD59x18(SD1x18 x) pure returns (SD59x18 result) {
result = SD59x18.wrap(int256(SD1x18.unwrap(x)));
}
/// @notice Casts an SD1x18 number into UD60x18.
/// @dev Requirements:
/// - x ≥ 0
function intoUD60x18(SD1x18 x) pure returns (UD60x18 result) {
int64 xInt = SD1x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD1x18_ToUD60x18_Underflow(x);
}
result = UD60x18.wrap(uint64(xInt));
}
/// @notice Casts an SD1x18 number into uint128.
/// @dev Requirements:
/// - x ≥ 0
function intoUint128(SD1x18 x) pure returns (uint128 result) {
int64 xInt = SD1x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD1x18_ToUint128_Underflow(x);
}
result = uint128(uint64(xInt));
}
/// @notice Casts an SD1x18 number into uint256.
/// @dev Requirements:
/// - x ≥ 0
function intoUint256(SD1x18 x) pure returns (uint256 result) {
int64 xInt = SD1x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD1x18_ToUint256_Underflow(x);
}
result = uint256(uint64(xInt));
}
/// @notice Casts an SD1x18 number into uint40.
/// @dev Requirements:
/// - x ≥ 0
/// - x ≤ MAX_UINT40
function intoUint40(SD1x18 x) pure returns (uint40 result) {
int64 xInt = SD1x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD1x18_ToUint40_Underflow(x);
}
if (xInt > int64(uint64(Common.MAX_UINT40))) {
revert CastingErrors.PRBMath_SD1x18_ToUint40_Overflow(x);
}
result = uint40(uint64(xInt));
}
/// @notice Alias for {wrap}.
function sd1x18(int64 x) pure returns (SD1x18 result) {
result = SD1x18.wrap(x);
}
/// @notice Unwraps an SD1x18 number into int64.
function unwrap(SD1x18 x) pure returns (int64 result) {
result = SD1x18.unwrap(x);
}
/// @notice Wraps an int64 number into SD1x18.
function wrap(int64 x) pure returns (SD1x18 result) {
result = SD1x18.wrap(x);
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { SD1x18 } from "./ValueType.sol";
/// @dev Euler's number as an SD1x18 number.
SD1x18 constant E = SD1x18.wrap(2_718281828459045235);
/// @dev The maximum value an SD1x18 number can have.
int64 constant uMAX_SD1x18 = 9_223372036854775807;
SD1x18 constant MAX_SD1x18 = SD1x18.wrap(uMAX_SD1x18);
/// @dev The minimum value an SD1x18 number can have.
int64 constant uMIN_SD1x18 = -9_223372036854775808;
SD1x18 constant MIN_SD1x18 = SD1x18.wrap(uMIN_SD1x18);
/// @dev PI as an SD1x18 number.
SD1x18 constant PI = SD1x18.wrap(3_141592653589793238);
/// @dev The unit number, which gives the decimal precision of SD1x18.
SD1x18 constant UNIT = SD1x18.wrap(1e18);
int64 constant uUNIT = 1e18;// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { SD1x18 } from "./ValueType.sol";
/// @notice Thrown when trying to cast an SD1x18 number that doesn't fit in UD60x18.
error PRBMath_SD1x18_ToUD60x18_Underflow(SD1x18 x);
/// @notice Thrown when trying to cast an SD1x18 number that doesn't fit in uint128.
error PRBMath_SD1x18_ToUint128_Underflow(SD1x18 x);
/// @notice Thrown when trying to cast an SD1x18 number that doesn't fit in uint256.
error PRBMath_SD1x18_ToUint256_Underflow(SD1x18 x);
/// @notice Thrown when trying to cast an SD1x18 number that doesn't fit in uint40.
error PRBMath_SD1x18_ToUint40_Overflow(SD1x18 x);
/// @notice Thrown when trying to cast an SD1x18 number that doesn't fit in uint40.
error PRBMath_SD1x18_ToUint40_Underflow(SD1x18 x);// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "./Casting.sol" as Casting;
/// @notice The signed 1.18-decimal fixed-point number representation, which can have up to 1 digit and up to 18
/// decimals. The values of this are bound by the minimum and the maximum values permitted by the underlying Solidity
/// type int64. This is useful when end users want to use int64 to save gas, e.g. with tight variable packing in contract
/// storage.
type SD1x18 is int64;
/*//////////////////////////////////////////////////////////////////////////
CASTING
//////////////////////////////////////////////////////////////////////////*/
using {
Casting.intoSD59x18,
Casting.intoUD60x18,
Casting.intoUint128,
Casting.intoUint256,
Casting.intoUint40,
Casting.unwrap
} for SD1x18 global;// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "../Common.sol" as Common;
import "./Errors.sol" as CastingErrors;
import { SD59x18 } from "../sd59x18/ValueType.sol";
import { UD60x18 } from "../ud60x18/ValueType.sol";
import { SD21x18 } from "./ValueType.sol";
/// @notice Casts an SD21x18 number into SD59x18.
/// @dev There is no overflow check because SD21x18 ⊆ SD59x18.
function intoSD59x18(SD21x18 x) pure returns (SD59x18 result) {
result = SD59x18.wrap(int256(SD21x18.unwrap(x)));
}
/// @notice Casts an SD21x18 number into UD60x18.
/// @dev Requirements:
/// - x ≥ 0
function intoUD60x18(SD21x18 x) pure returns (UD60x18 result) {
int128 xInt = SD21x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD21x18_ToUD60x18_Underflow(x);
}
result = UD60x18.wrap(uint128(xInt));
}
/// @notice Casts an SD21x18 number into uint128.
/// @dev Requirements:
/// - x ≥ 0
function intoUint128(SD21x18 x) pure returns (uint128 result) {
int128 xInt = SD21x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD21x18_ToUint128_Underflow(x);
}
result = uint128(xInt);
}
/// @notice Casts an SD21x18 number into uint256.
/// @dev Requirements:
/// - x ≥ 0
function intoUint256(SD21x18 x) pure returns (uint256 result) {
int128 xInt = SD21x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD21x18_ToUint256_Underflow(x);
}
result = uint256(uint128(xInt));
}
/// @notice Casts an SD21x18 number into uint40.
/// @dev Requirements:
/// - x ≥ 0
/// - x ≤ MAX_UINT40
function intoUint40(SD21x18 x) pure returns (uint40 result) {
int128 xInt = SD21x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD21x18_ToUint40_Underflow(x);
}
if (xInt > int128(uint128(Common.MAX_UINT40))) {
revert CastingErrors.PRBMath_SD21x18_ToUint40_Overflow(x);
}
result = uint40(uint128(xInt));
}
/// @notice Alias for {wrap}.
function sd21x18(int128 x) pure returns (SD21x18 result) {
result = SD21x18.wrap(x);
}
/// @notice Unwraps an SD21x18 number into int128.
function unwrap(SD21x18 x) pure returns (int128 result) {
result = SD21x18.unwrap(x);
}
/// @notice Wraps an int128 number into SD21x18.
function wrap(int128 x) pure returns (SD21x18 result) {
result = SD21x18.wrap(x);
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { SD21x18 } from "./ValueType.sol";
/// @dev Euler's number as an SD21x18 number.
SD21x18 constant E = SD21x18.wrap(2_718281828459045235);
/// @dev The maximum value an SD21x18 number can have.
int128 constant uMAX_SD21x18 = 170141183460469231731_687303715884105727;
SD21x18 constant MAX_SD21x18 = SD21x18.wrap(uMAX_SD21x18);
/// @dev The minimum value an SD21x18 number can have.
int128 constant uMIN_SD21x18 = -170141183460469231731_687303715884105728;
SD21x18 constant MIN_SD21x18 = SD21x18.wrap(uMIN_SD21x18);
/// @dev PI as an SD21x18 number.
SD21x18 constant PI = SD21x18.wrap(3_141592653589793238);
/// @dev The unit number, which gives the decimal precision of SD21x18.
SD21x18 constant UNIT = SD21x18.wrap(1e18);
int128 constant uUNIT = 1e18;// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { SD21x18 } from "./ValueType.sol";
/// @notice Thrown when trying to cast an SD21x18 number that doesn't fit in uint128.
error PRBMath_SD21x18_ToUint128_Underflow(SD21x18 x);
/// @notice Thrown when trying to cast an SD21x18 number that doesn't fit in UD60x18.
error PRBMath_SD21x18_ToUD60x18_Underflow(SD21x18 x);
/// @notice Thrown when trying to cast an SD21x18 number that doesn't fit in uint256.
error PRBMath_SD21x18_ToUint256_Underflow(SD21x18 x);
/// @notice Thrown when trying to cast an SD21x18 number that doesn't fit in uint40.
error PRBMath_SD21x18_ToUint40_Overflow(SD21x18 x);
/// @notice Thrown when trying to cast an SD21x18 number that doesn't fit in uint40.
error PRBMath_SD21x18_ToUint40_Underflow(SD21x18 x);// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "./Casting.sol" as Casting;
/// @notice The signed 21.18-decimal fixed-point number representation, which can have up to 21 digits and up to 18
/// decimals. The values of this are bound by the minimum and the maximum values permitted by the underlying Solidity
/// type int128. This is useful when end users want to use int128 to save gas, e.g. with tight variable packing in contract
/// storage.
type SD21x18 is int128;
/*//////////////////////////////////////////////////////////////////////////
CASTING
//////////////////////////////////////////////////////////////////////////*/
using {
Casting.intoSD59x18,
Casting.intoUD60x18,
Casting.intoUint128,
Casting.intoUint256,
Casting.intoUint40,
Casting.unwrap
} for SD21x18 global;// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; /* ██████╗ ██████╗ ██████╗ ███╗ ███╗ █████╗ ████████╗██╗ ██╗ ██╔══██╗██╔══██╗██╔══██╗████╗ ████║██╔══██╗╚══██╔══╝██║ ██║ ██████╔╝██████╔╝██████╔╝██╔████╔██║███████║ ██║ ███████║ ██╔═══╝ ██╔══██╗██╔══██╗██║╚██╔╝██║██╔══██║ ██║ ██╔══██║ ██║ ██║ ██║██████╔╝██║ ╚═╝ ██║██║ ██║ ██║ ██║ ██║ ╚═╝ ╚═╝ ╚═╝╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ███████╗██████╗ ███████╗ █████╗ ██╗ ██╗ ██╗ █████╗ ██╔════╝██╔══██╗██╔════╝██╔══██╗╚██╗██╔╝███║██╔══██╗ ███████╗██║ ██║███████╗╚██████║ ╚███╔╝ ╚██║╚█████╔╝ ╚════██║██║ ██║╚════██║ ╚═══██║ ██╔██╗ ██║██╔══██╗ ███████║██████╔╝███████║ █████╔╝██╔╝ ██╗ ██║╚█████╔╝ ╚══════╝╚═════╝ ╚══════╝ ╚════╝ ╚═╝ ╚═╝ ╚═╝ ╚════╝ */ import "./sd59x18/Casting.sol"; import "./sd59x18/Constants.sol"; import "./sd59x18/Conversions.sol"; import "./sd59x18/Errors.sol"; import "./sd59x18/Helpers.sol"; import "./sd59x18/Math.sol"; import "./sd59x18/ValueType.sol";
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "./Errors.sol" as CastingErrors;
import { MAX_UINT128, MAX_UINT40 } from "../Common.sol";
import { uMAX_SD1x18, uMIN_SD1x18 } from "../sd1x18/Constants.sol";
import { SD1x18 } from "../sd1x18/ValueType.sol";
import { uMAX_SD21x18, uMIN_SD21x18 } from "../sd21x18/Constants.sol";
import { SD21x18 } from "../sd21x18/ValueType.sol";
import { uMAX_UD2x18 } from "../ud2x18/Constants.sol";
import { UD2x18 } from "../ud2x18/ValueType.sol";
import { uMAX_UD21x18 } from "../ud21x18/Constants.sol";
import { UD21x18 } from "../ud21x18/ValueType.sol";
import { UD60x18 } from "../ud60x18/ValueType.sol";
import { SD59x18 } from "./ValueType.sol";
/// @notice Casts an SD59x18 number into int256.
/// @dev This is basically a functional alias for {unwrap}.
function intoInt256(SD59x18 x) pure returns (int256 result) {
result = SD59x18.unwrap(x);
}
/// @notice Casts an SD59x18 number into SD1x18.
/// @dev Requirements:
/// - x ≥ uMIN_SD1x18
/// - x ≤ uMAX_SD1x18
function intoSD1x18(SD59x18 x) pure returns (SD1x18 result) {
int256 xInt = SD59x18.unwrap(x);
if (xInt < uMIN_SD1x18) {
revert CastingErrors.PRBMath_SD59x18_IntoSD1x18_Underflow(x);
}
if (xInt > uMAX_SD1x18) {
revert CastingErrors.PRBMath_SD59x18_IntoSD1x18_Overflow(x);
}
result = SD1x18.wrap(int64(xInt));
}
/// @notice Casts an SD59x18 number into SD21x18.
/// @dev Requirements:
/// - x ≥ uMIN_SD21x18
/// - x ≤ uMAX_SD21x18
function intoSD21x18(SD59x18 x) pure returns (SD21x18 result) {
int256 xInt = SD59x18.unwrap(x);
if (xInt < uMIN_SD21x18) {
revert CastingErrors.PRBMath_SD59x18_IntoSD21x18_Underflow(x);
}
if (xInt > uMAX_SD21x18) {
revert CastingErrors.PRBMath_SD59x18_IntoSD21x18_Overflow(x);
}
result = SD21x18.wrap(int128(xInt));
}
/// @notice Casts an SD59x18 number into UD2x18.
/// @dev Requirements:
/// - x ≥ 0
/// - x ≤ uMAX_UD2x18
function intoUD2x18(SD59x18 x) pure returns (UD2x18 result) {
int256 xInt = SD59x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD59x18_IntoUD2x18_Underflow(x);
}
if (xInt > int256(uint256(uMAX_UD2x18))) {
revert CastingErrors.PRBMath_SD59x18_IntoUD2x18_Overflow(x);
}
result = UD2x18.wrap(uint64(uint256(xInt)));
}
/// @notice Casts an SD59x18 number into UD21x18.
/// @dev Requirements:
/// - x ≥ 0
/// - x ≤ uMAX_UD21x18
function intoUD21x18(SD59x18 x) pure returns (UD21x18 result) {
int256 xInt = SD59x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD59x18_IntoUD21x18_Underflow(x);
}
if (xInt > int256(uint256(uMAX_UD21x18))) {
revert CastingErrors.PRBMath_SD59x18_IntoUD21x18_Overflow(x);
}
result = UD21x18.wrap(uint128(uint256(xInt)));
}
/// @notice Casts an SD59x18 number into UD60x18.
/// @dev Requirements:
/// - x ≥ 0
function intoUD60x18(SD59x18 x) pure returns (UD60x18 result) {
int256 xInt = SD59x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD59x18_IntoUD60x18_Underflow(x);
}
result = UD60x18.wrap(uint256(xInt));
}
/// @notice Casts an SD59x18 number into uint256.
/// @dev Requirements:
/// - x ≥ 0
function intoUint256(SD59x18 x) pure returns (uint256 result) {
int256 xInt = SD59x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD59x18_IntoUint256_Underflow(x);
}
result = uint256(xInt);
}
/// @notice Casts an SD59x18 number into uint128.
/// @dev Requirements:
/// - x ≥ 0
/// - x ≤ uMAX_UINT128
function intoUint128(SD59x18 x) pure returns (uint128 result) {
int256 xInt = SD59x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD59x18_IntoUint128_Underflow(x);
}
if (xInt > int256(uint256(MAX_UINT128))) {
revert CastingErrors.PRBMath_SD59x18_IntoUint128_Overflow(x);
}
result = uint128(uint256(xInt));
}
/// @notice Casts an SD59x18 number into uint40.
/// @dev Requirements:
/// - x ≥ 0
/// - x ≤ MAX_UINT40
function intoUint40(SD59x18 x) pure returns (uint40 result) {
int256 xInt = SD59x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD59x18_IntoUint40_Underflow(x);
}
if (xInt > int256(uint256(MAX_UINT40))) {
revert CastingErrors.PRBMath_SD59x18_IntoUint40_Overflow(x);
}
result = uint40(uint256(xInt));
}
/// @notice Alias for {wrap}.
function sd(int256 x) pure returns (SD59x18 result) {
result = SD59x18.wrap(x);
}
/// @notice Alias for {wrap}.
function sd59x18(int256 x) pure returns (SD59x18 result) {
result = SD59x18.wrap(x);
}
/// @notice Unwraps an SD59x18 number into int256.
function unwrap(SD59x18 x) pure returns (int256 result) {
result = SD59x18.unwrap(x);
}
/// @notice Wraps an int256 number into SD59x18.
function wrap(int256 x) pure returns (SD59x18 result) {
result = SD59x18.wrap(x);
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { SD59x18 } from "./ValueType.sol";
// NOTICE: the "u" prefix stands for "unwrapped".
/// @dev Euler's number as an SD59x18 number.
SD59x18 constant E = SD59x18.wrap(2_718281828459045235);
/// @dev The maximum input permitted in {exp}.
int256 constant uEXP_MAX_INPUT = 133_084258667509499440;
SD59x18 constant EXP_MAX_INPUT = SD59x18.wrap(uEXP_MAX_INPUT);
/// @dev Any value less than this returns 0 in {exp}.
int256 constant uEXP_MIN_THRESHOLD = -41_446531673892822322;
SD59x18 constant EXP_MIN_THRESHOLD = SD59x18.wrap(uEXP_MIN_THRESHOLD);
/// @dev The maximum input permitted in {exp2}.
int256 constant uEXP2_MAX_INPUT = 192e18 - 1;
SD59x18 constant EXP2_MAX_INPUT = SD59x18.wrap(uEXP2_MAX_INPUT);
/// @dev Any value less than this returns 0 in {exp2}.
int256 constant uEXP2_MIN_THRESHOLD = -59_794705707972522261;
SD59x18 constant EXP2_MIN_THRESHOLD = SD59x18.wrap(uEXP2_MIN_THRESHOLD);
/// @dev Half the UNIT number.
int256 constant uHALF_UNIT = 0.5e18;
SD59x18 constant HALF_UNIT = SD59x18.wrap(uHALF_UNIT);
/// @dev $log_2(10)$ as an SD59x18 number.
int256 constant uLOG2_10 = 3_321928094887362347;
SD59x18 constant LOG2_10 = SD59x18.wrap(uLOG2_10);
/// @dev $log_2(e)$ as an SD59x18 number.
int256 constant uLOG2_E = 1_442695040888963407;
SD59x18 constant LOG2_E = SD59x18.wrap(uLOG2_E);
/// @dev The maximum value an SD59x18 number can have.
int256 constant uMAX_SD59x18 = 57896044618658097711785492504343953926634992332820282019728_792003956564819967;
SD59x18 constant MAX_SD59x18 = SD59x18.wrap(uMAX_SD59x18);
/// @dev The maximum whole value an SD59x18 number can have.
int256 constant uMAX_WHOLE_SD59x18 = 57896044618658097711785492504343953926634992332820282019728_000000000000000000;
SD59x18 constant MAX_WHOLE_SD59x18 = SD59x18.wrap(uMAX_WHOLE_SD59x18);
/// @dev The minimum value an SD59x18 number can have.
int256 constant uMIN_SD59x18 = -57896044618658097711785492504343953926634992332820282019728_792003956564819968;
SD59x18 constant MIN_SD59x18 = SD59x18.wrap(uMIN_SD59x18);
/// @dev The minimum whole value an SD59x18 number can have.
int256 constant uMIN_WHOLE_SD59x18 = -57896044618658097711785492504343953926634992332820282019728_000000000000000000;
SD59x18 constant MIN_WHOLE_SD59x18 = SD59x18.wrap(uMIN_WHOLE_SD59x18);
/// @dev PI as an SD59x18 number.
SD59x18 constant PI = SD59x18.wrap(3_141592653589793238);
/// @dev The unit number, which gives the decimal precision of SD59x18.
int256 constant uUNIT = 1e18;
SD59x18 constant UNIT = SD59x18.wrap(1e18);
/// @dev The unit number squared.
int256 constant uUNIT_SQUARED = 1e36;
SD59x18 constant UNIT_SQUARED = SD59x18.wrap(uUNIT_SQUARED);
/// @dev Zero as an SD59x18 number.
SD59x18 constant ZERO = SD59x18.wrap(0);// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { uMAX_SD59x18, uMIN_SD59x18, uUNIT } from "./Constants.sol";
import { PRBMath_SD59x18_Convert_Overflow, PRBMath_SD59x18_Convert_Underflow } from "./Errors.sol";
import { SD59x18 } from "./ValueType.sol";
/// @notice Converts a simple integer to SD59x18 by multiplying it by `UNIT`.
///
/// @dev Requirements:
/// - x ≥ `MIN_SD59x18 / UNIT`
/// - x ≤ `MAX_SD59x18 / UNIT`
///
/// @param x The basic integer to convert.
/// @return result The same number converted to SD59x18.
function convert(int256 x) pure returns (SD59x18 result) {
if (x < uMIN_SD59x18 / uUNIT) {
revert PRBMath_SD59x18_Convert_Underflow(x);
}
if (x > uMAX_SD59x18 / uUNIT) {
revert PRBMath_SD59x18_Convert_Overflow(x);
}
unchecked {
result = SD59x18.wrap(x * uUNIT);
}
}
/// @notice Converts an SD59x18 number to a simple integer by dividing it by `UNIT`.
/// @dev The result is rounded toward zero.
/// @param x The SD59x18 number to convert.
/// @return result The same number as a simple integer.
function convert(SD59x18 x) pure returns (int256 result) {
result = SD59x18.unwrap(x) / uUNIT;
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { SD59x18 } from "./ValueType.sol";
/// @notice Thrown when taking the absolute value of `MIN_SD59x18`.
error PRBMath_SD59x18_Abs_MinSD59x18();
/// @notice Thrown when ceiling a number overflows SD59x18.
error PRBMath_SD59x18_Ceil_Overflow(SD59x18 x);
/// @notice Thrown when converting a basic integer to the fixed-point format overflows SD59x18.
error PRBMath_SD59x18_Convert_Overflow(int256 x);
/// @notice Thrown when converting a basic integer to the fixed-point format underflows SD59x18.
error PRBMath_SD59x18_Convert_Underflow(int256 x);
/// @notice Thrown when dividing two numbers and one of them is `MIN_SD59x18`.
error PRBMath_SD59x18_Div_InputTooSmall();
/// @notice Thrown when dividing two numbers and one of the intermediary unsigned results overflows SD59x18.
error PRBMath_SD59x18_Div_Overflow(SD59x18 x, SD59x18 y);
/// @notice Thrown when taking the natural exponent of a base greater than 133_084258667509499441.
error PRBMath_SD59x18_Exp_InputTooBig(SD59x18 x);
/// @notice Thrown when taking the binary exponent of a base greater than 192e18.
error PRBMath_SD59x18_Exp2_InputTooBig(SD59x18 x);
/// @notice Thrown when flooring a number underflows SD59x18.
error PRBMath_SD59x18_Floor_Underflow(SD59x18 x);
/// @notice Thrown when taking the geometric mean of two numbers and their product is negative.
error PRBMath_SD59x18_Gm_NegativeProduct(SD59x18 x, SD59x18 y);
/// @notice Thrown when taking the geometric mean of two numbers and multiplying them overflows SD59x18.
error PRBMath_SD59x18_Gm_Overflow(SD59x18 x, SD59x18 y);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in SD1x18.
error PRBMath_SD59x18_IntoSD1x18_Overflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in SD1x18.
error PRBMath_SD59x18_IntoSD1x18_Underflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in SD21x18.
error PRBMath_SD59x18_IntoSD21x18_Overflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in SD21x18.
error PRBMath_SD59x18_IntoSD21x18_Underflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in UD2x18.
error PRBMath_SD59x18_IntoUD2x18_Overflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in UD2x18.
error PRBMath_SD59x18_IntoUD2x18_Underflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in UD21x18.
error PRBMath_SD59x18_IntoUD21x18_Overflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in UD21x18.
error PRBMath_SD59x18_IntoUD21x18_Underflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in UD60x18.
error PRBMath_SD59x18_IntoUD60x18_Underflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in uint128.
error PRBMath_SD59x18_IntoUint128_Overflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in uint128.
error PRBMath_SD59x18_IntoUint128_Underflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in uint256.
error PRBMath_SD59x18_IntoUint256_Underflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in uint40.
error PRBMath_SD59x18_IntoUint40_Overflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in uint40.
error PRBMath_SD59x18_IntoUint40_Underflow(SD59x18 x);
/// @notice Thrown when taking the logarithm of a number less than or equal to zero.
error PRBMath_SD59x18_Log_InputTooSmall(SD59x18 x);
/// @notice Thrown when multiplying two numbers and one of the inputs is `MIN_SD59x18`.
error PRBMath_SD59x18_Mul_InputTooSmall();
/// @notice Thrown when multiplying two numbers and the intermediary absolute result overflows SD59x18.
error PRBMath_SD59x18_Mul_Overflow(SD59x18 x, SD59x18 y);
/// @notice Thrown when raising a number to a power and the intermediary absolute result overflows SD59x18.
error PRBMath_SD59x18_Powu_Overflow(SD59x18 x, uint256 y);
/// @notice Thrown when taking the square root of a negative number.
error PRBMath_SD59x18_Sqrt_NegativeInput(SD59x18 x);
/// @notice Thrown when the calculating the square root overflows SD59x18.
error PRBMath_SD59x18_Sqrt_Overflow(SD59x18 x);// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { wrap } from "./Casting.sol";
import { SD59x18 } from "./ValueType.sol";
/// @notice Implements the checked addition operation (+) in the SD59x18 type.
function add(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
return wrap(x.unwrap() + y.unwrap());
}
/// @notice Implements the AND (&) bitwise operation in the SD59x18 type.
function and(SD59x18 x, int256 bits) pure returns (SD59x18 result) {
return wrap(x.unwrap() & bits);
}
/// @notice Implements the AND (&) bitwise operation in the SD59x18 type.
function and2(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
return wrap(x.unwrap() & y.unwrap());
}
/// @notice Implements the equal (=) operation in the SD59x18 type.
function eq(SD59x18 x, SD59x18 y) pure returns (bool result) {
result = x.unwrap() == y.unwrap();
}
/// @notice Implements the greater than operation (>) in the SD59x18 type.
function gt(SD59x18 x, SD59x18 y) pure returns (bool result) {
result = x.unwrap() > y.unwrap();
}
/// @notice Implements the greater than or equal to operation (>=) in the SD59x18 type.
function gte(SD59x18 x, SD59x18 y) pure returns (bool result) {
result = x.unwrap() >= y.unwrap();
}
/// @notice Implements a zero comparison check function in the SD59x18 type.
function isZero(SD59x18 x) pure returns (bool result) {
result = x.unwrap() == 0;
}
/// @notice Implements the left shift operation (<<) in the SD59x18 type.
function lshift(SD59x18 x, uint256 bits) pure returns (SD59x18 result) {
result = wrap(x.unwrap() << bits);
}
/// @notice Implements the lower than operation (<) in the SD59x18 type.
function lt(SD59x18 x, SD59x18 y) pure returns (bool result) {
result = x.unwrap() < y.unwrap();
}
/// @notice Implements the lower than or equal to operation (<=) in the SD59x18 type.
function lte(SD59x18 x, SD59x18 y) pure returns (bool result) {
result = x.unwrap() <= y.unwrap();
}
/// @notice Implements the unchecked modulo operation (%) in the SD59x18 type.
function mod(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
result = wrap(x.unwrap() % y.unwrap());
}
/// @notice Implements the not equal operation (!=) in the SD59x18 type.
function neq(SD59x18 x, SD59x18 y) pure returns (bool result) {
result = x.unwrap() != y.unwrap();
}
/// @notice Implements the NOT (~) bitwise operation in the SD59x18 type.
function not(SD59x18 x) pure returns (SD59x18 result) {
result = wrap(~x.unwrap());
}
/// @notice Implements the OR (|) bitwise operation in the SD59x18 type.
function or(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
result = wrap(x.unwrap() | y.unwrap());
}
/// @notice Implements the right shift operation (>>) in the SD59x18 type.
function rshift(SD59x18 x, uint256 bits) pure returns (SD59x18 result) {
result = wrap(x.unwrap() >> bits);
}
/// @notice Implements the checked subtraction operation (-) in the SD59x18 type.
function sub(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
result = wrap(x.unwrap() - y.unwrap());
}
/// @notice Implements the checked unary minus operation (-) in the SD59x18 type.
function unary(SD59x18 x) pure returns (SD59x18 result) {
result = wrap(-x.unwrap());
}
/// @notice Implements the unchecked addition operation (+) in the SD59x18 type.
function uncheckedAdd(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
unchecked {
result = wrap(x.unwrap() + y.unwrap());
}
}
/// @notice Implements the unchecked subtraction operation (-) in the SD59x18 type.
function uncheckedSub(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
unchecked {
result = wrap(x.unwrap() - y.unwrap());
}
}
/// @notice Implements the unchecked unary minus operation (-) in the SD59x18 type.
function uncheckedUnary(SD59x18 x) pure returns (SD59x18 result) {
unchecked {
result = wrap(-x.unwrap());
}
}
/// @notice Implements the XOR (^) bitwise operation in the SD59x18 type.
function xor(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
result = wrap(x.unwrap() ^ y.unwrap());
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "../Common.sol" as Common;
import "./Errors.sol" as Errors;
import {
uEXP_MAX_INPUT,
uEXP2_MAX_INPUT,
uEXP_MIN_THRESHOLD,
uEXP2_MIN_THRESHOLD,
uHALF_UNIT,
uLOG2_10,
uLOG2_E,
uMAX_SD59x18,
uMAX_WHOLE_SD59x18,
uMIN_SD59x18,
uMIN_WHOLE_SD59x18,
UNIT,
uUNIT,
uUNIT_SQUARED,
ZERO
} from "./Constants.sol";
import { wrap } from "./Helpers.sol";
import { SD59x18 } from "./ValueType.sol";
/// @notice Calculates the absolute value of x.
///
/// @dev Requirements:
/// - x > MIN_SD59x18.
///
/// @param x The SD59x18 number for which to calculate the absolute value.
/// @return result The absolute value of x as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function abs(SD59x18 x) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
if (xInt == uMIN_SD59x18) {
revert Errors.PRBMath_SD59x18_Abs_MinSD59x18();
}
result = xInt < 0 ? wrap(-xInt) : x;
}
/// @notice Calculates the arithmetic average of x and y.
///
/// @dev Notes:
/// - The result is rounded toward zero.
///
/// @param x The first operand as an SD59x18 number.
/// @param y The second operand as an SD59x18 number.
/// @return result The arithmetic average as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function avg(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
int256 yInt = y.unwrap();
unchecked {
// This operation is equivalent to `x / 2 + y / 2`, and it can never overflow.
int256 sum = (xInt >> 1) + (yInt >> 1);
if (sum < 0) {
// If at least one of x and y is odd, add 1 to the result, because shifting negative numbers to the right
// rounds toward negative infinity. The right part is equivalent to `sum + (x % 2 == 1 || y % 2 == 1)`.
assembly ("memory-safe") {
result := add(sum, and(or(xInt, yInt), 1))
}
} else {
// Add 1 if both x and y are odd to account for the double 0.5 remainder truncated after shifting.
result = wrap(sum + (xInt & yInt & 1));
}
}
}
/// @notice Yields the smallest whole number greater than or equal to x.
///
/// @dev Optimized for fractional value inputs, because every whole value has (1e18 - 1) fractional counterparts.
/// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.
///
/// Requirements:
/// - x ≤ MAX_WHOLE_SD59x18
///
/// @param x The SD59x18 number to ceil.
/// @return result The smallest whole number greater than or equal to x, as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function ceil(SD59x18 x) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
if (xInt > uMAX_WHOLE_SD59x18) {
revert Errors.PRBMath_SD59x18_Ceil_Overflow(x);
}
int256 remainder = xInt % uUNIT;
if (remainder == 0) {
result = x;
} else {
unchecked {
// Solidity uses C fmod style, which returns a modulus with the same sign as x.
int256 resultInt = xInt - remainder;
if (xInt > 0) {
resultInt += uUNIT;
}
result = wrap(resultInt);
}
}
}
/// @notice Divides two SD59x18 numbers, returning a new SD59x18 number.
///
/// @dev This is an extension of {Common.mulDiv} for signed numbers, which works by computing the signs and the absolute
/// values separately.
///
/// Notes:
/// - Refer to the notes in {Common.mulDiv}.
/// - The result is rounded toward zero.
///
/// Requirements:
/// - Refer to the requirements in {Common.mulDiv}.
/// - None of the inputs can be `MIN_SD59x18`.
/// - The denominator must not be zero.
/// - The result must fit in SD59x18.
///
/// @param x The numerator as an SD59x18 number.
/// @param y The denominator as an SD59x18 number.
/// @return result The quotient as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function div(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
int256 yInt = y.unwrap();
if (xInt == uMIN_SD59x18 || yInt == uMIN_SD59x18) {
revert Errors.PRBMath_SD59x18_Div_InputTooSmall();
}
// Get hold of the absolute values of x and y.
uint256 xAbs;
uint256 yAbs;
unchecked {
xAbs = xInt < 0 ? uint256(-xInt) : uint256(xInt);
yAbs = yInt < 0 ? uint256(-yInt) : uint256(yInt);
}
// Compute the absolute value (x*UNIT÷y). The resulting value must fit in SD59x18.
uint256 resultAbs = Common.mulDiv(xAbs, uint256(uUNIT), yAbs);
if (resultAbs > uint256(uMAX_SD59x18)) {
revert Errors.PRBMath_SD59x18_Div_Overflow(x, y);
}
// Check if x and y have the same sign using two's complement representation. The left-most bit represents the sign (1 for
// negative, 0 for positive or zero).
bool sameSign = (xInt ^ yInt) > -1;
// If the inputs have the same sign, the result should be positive. Otherwise, it should be negative.
unchecked {
result = wrap(sameSign ? int256(resultAbs) : -int256(resultAbs));
}
}
/// @notice Calculates the natural exponent of x using the following formula:
///
/// $$
/// e^x = 2^{x * log_2{e}}
/// $$
///
/// @dev Notes:
/// - Refer to the notes in {exp2}.
///
/// Requirements:
/// - Refer to the requirements in {exp2}.
/// - x < 133_084258667509499441.
///
/// @param x The exponent as an SD59x18 number.
/// @return result The result as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function exp(SD59x18 x) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
// Any input less than the threshold returns zero.
// This check also prevents an overflow for very small numbers.
if (xInt < uEXP_MIN_THRESHOLD) {
return ZERO;
}
// This check prevents values greater than 192e18 from being passed to {exp2}.
if (xInt > uEXP_MAX_INPUT) {
revert Errors.PRBMath_SD59x18_Exp_InputTooBig(x);
}
unchecked {
// Inline the fixed-point multiplication to save gas.
int256 doubleUnitProduct = xInt * uLOG2_E;
result = exp2(wrap(doubleUnitProduct / uUNIT));
}
}
/// @notice Calculates the binary exponent of x using the binary fraction method using the following formula:
///
/// $$
/// 2^{-x} = \frac{1}{2^x}
/// $$
///
/// @dev See https://ethereum.stackexchange.com/q/79903/24693.
///
/// Notes:
/// - If x < -59_794705707972522261, the result is zero.
///
/// Requirements:
/// - x < 192e18.
/// - The result must fit in SD59x18.
///
/// @param x The exponent as an SD59x18 number.
/// @return result The result as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function exp2(SD59x18 x) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
if (xInt < 0) {
// The inverse of any number less than the threshold is truncated to zero.
if (xInt < uEXP2_MIN_THRESHOLD) {
return ZERO;
}
unchecked {
// Inline the fixed-point inversion to save gas.
result = wrap(uUNIT_SQUARED / exp2(wrap(-xInt)).unwrap());
}
} else {
// Numbers greater than or equal to 192e18 don't fit in the 192.64-bit format.
if (xInt > uEXP2_MAX_INPUT) {
revert Errors.PRBMath_SD59x18_Exp2_InputTooBig(x);
}
unchecked {
// Convert x to the 192.64-bit fixed-point format.
uint256 x_192x64 = uint256((xInt << 64) / uUNIT);
// It is safe to cast the result to int256 due to the checks above.
result = wrap(int256(Common.exp2(x_192x64)));
}
}
}
/// @notice Yields the greatest whole number less than or equal to x.
///
/// @dev Optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional
/// counterparts. See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.
///
/// Requirements:
/// - x ≥ MIN_WHOLE_SD59x18
///
/// @param x The SD59x18 number to floor.
/// @return result The greatest whole number less than or equal to x, as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function floor(SD59x18 x) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
if (xInt < uMIN_WHOLE_SD59x18) {
revert Errors.PRBMath_SD59x18_Floor_Underflow(x);
}
int256 remainder = xInt % uUNIT;
if (remainder == 0) {
result = x;
} else {
unchecked {
// Solidity uses C fmod style, which returns a modulus with the same sign as x.
int256 resultInt = xInt - remainder;
if (xInt < 0) {
resultInt -= uUNIT;
}
result = wrap(resultInt);
}
}
}
/// @notice Yields the excess beyond the floor of x for positive numbers and the part of the number to the right.
/// of the radix point for negative numbers.
/// @dev Based on the odd function definition. https://en.wikipedia.org/wiki/Fractional_part
/// @param x The SD59x18 number to get the fractional part of.
/// @return result The fractional part of x as an SD59x18 number.
function frac(SD59x18 x) pure returns (SD59x18 result) {
result = wrap(x.unwrap() % uUNIT);
}
/// @notice Calculates the geometric mean of x and y, i.e. $\sqrt{x * y}$.
///
/// @dev Notes:
/// - The result is rounded toward zero.
///
/// Requirements:
/// - x * y must fit in SD59x18.
/// - x * y must not be negative, since complex numbers are not supported.
///
/// @param x The first operand as an SD59x18 number.
/// @param y The second operand as an SD59x18 number.
/// @return result The result as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function gm(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
int256 yInt = y.unwrap();
if (xInt == 0 || yInt == 0) {
return ZERO;
}
unchecked {
// Equivalent to `xy / x != y`. Checking for overflow this way is faster than letting Solidity do it.
int256 xyInt = xInt * yInt;
if (xyInt / xInt != yInt) {
revert Errors.PRBMath_SD59x18_Gm_Overflow(x, y);
}
// The product must not be negative, since complex numbers are not supported.
if (xyInt < 0) {
revert Errors.PRBMath_SD59x18_Gm_NegativeProduct(x, y);
}
// We don't need to multiply the result by `UNIT` here because the x*y product picked up a factor of `UNIT`
// during multiplication. See the comments in {Common.sqrt}.
uint256 resultUint = Common.sqrt(uint256(xyInt));
result = wrap(int256(resultUint));
}
}
/// @notice Calculates the inverse of x.
///
/// @dev Notes:
/// - The result is rounded toward zero.
///
/// Requirements:
/// - x must not be zero.
///
/// @param x The SD59x18 number for which to calculate the inverse.
/// @return result The inverse as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function inv(SD59x18 x) pure returns (SD59x18 result) {
result = wrap(uUNIT_SQUARED / x.unwrap());
}
/// @notice Calculates the natural logarithm of x using the following formula:
///
/// $$
/// ln{x} = log_2{x} / log_2{e}
/// $$
///
/// @dev Notes:
/// - Refer to the notes in {log2}.
/// - The precision isn't sufficiently fine-grained to return exactly `UNIT` when the input is `E`.
///
/// Requirements:
/// - Refer to the requirements in {log2}.
///
/// @param x The SD59x18 number for which to calculate the natural logarithm.
/// @return result The natural logarithm as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function ln(SD59x18 x) pure returns (SD59x18 result) {
// Inline the fixed-point multiplication to save gas. This is overflow-safe because the maximum value that
// {log2} can return is ~195_205294292027477728.
result = wrap(log2(x).unwrap() * uUNIT / uLOG2_E);
}
/// @notice Calculates the common logarithm of x using the following formula:
///
/// $$
/// log_{10}{x} = log_2{x} / log_2{10}
/// $$
///
/// However, if x is an exact power of ten, a hard coded value is returned.
///
/// @dev Notes:
/// - Refer to the notes in {log2}.
///
/// Requirements:
/// - Refer to the requirements in {log2}.
///
/// @param x The SD59x18 number for which to calculate the common logarithm.
/// @return result The common logarithm as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function log10(SD59x18 x) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
if (xInt < 0) {
revert Errors.PRBMath_SD59x18_Log_InputTooSmall(x);
}
// Note that the `mul` in this block is the standard multiplication operation, not {SD59x18.mul}.
// prettier-ignore
assembly ("memory-safe") {
switch x
case 1 { result := mul(uUNIT, sub(0, 18)) }
case 10 { result := mul(uUNIT, sub(1, 18)) }
case 100 { result := mul(uUNIT, sub(2, 18)) }
case 1000 { result := mul(uUNIT, sub(3, 18)) }
case 10000 { result := mul(uUNIT, sub(4, 18)) }
case 100000 { result := mul(uUNIT, sub(5, 18)) }
case 1000000 { result := mul(uUNIT, sub(6, 18)) }
case 10000000 { result := mul(uUNIT, sub(7, 18)) }
case 100000000 { result := mul(uUNIT, sub(8, 18)) }
case 1000000000 { result := mul(uUNIT, sub(9, 18)) }
case 10000000000 { result := mul(uUNIT, sub(10, 18)) }
case 100000000000 { result := mul(uUNIT, sub(11, 18)) }
case 1000000000000 { result := mul(uUNIT, sub(12, 18)) }
case 10000000000000 { result := mul(uUNIT, sub(13, 18)) }
case 100000000000000 { result := mul(uUNIT, sub(14, 18)) }
case 1000000000000000 { result := mul(uUNIT, sub(15, 18)) }
case 10000000000000000 { result := mul(uUNIT, sub(16, 18)) }
case 100000000000000000 { result := mul(uUNIT, sub(17, 18)) }
case 1000000000000000000 { result := 0 }
case 10000000000000000000 { result := uUNIT }
case 100000000000000000000 { result := mul(uUNIT, 2) }
case 1000000000000000000000 { result := mul(uUNIT, 3) }
case 10000000000000000000000 { result := mul(uUNIT, 4) }
case 100000000000000000000000 { result := mul(uUNIT, 5) }
case 1000000000000000000000000 { result := mul(uUNIT, 6) }
case 10000000000000000000000000 { result := mul(uUNIT, 7) }
case 100000000000000000000000000 { result := mul(uUNIT, 8) }
case 1000000000000000000000000000 { result := mul(uUNIT, 9) }
case 10000000000000000000000000000 { result := mul(uUNIT, 10) }
case 100000000000000000000000000000 { result := mul(uUNIT, 11) }
case 1000000000000000000000000000000 { result := mul(uUNIT, 12) }
case 10000000000000000000000000000000 { result := mul(uUNIT, 13) }
case 100000000000000000000000000000000 { result := mul(uUNIT, 14) }
case 1000000000000000000000000000000000 { result := mul(uUNIT, 15) }
case 10000000000000000000000000000000000 { result := mul(uUNIT, 16) }
case 100000000000000000000000000000000000 { result := mul(uUNIT, 17) }
case 1000000000000000000000000000000000000 { result := mul(uUNIT, 18) }
case 10000000000000000000000000000000000000 { result := mul(uUNIT, 19) }
case 100000000000000000000000000000000000000 { result := mul(uUNIT, 20) }
case 1000000000000000000000000000000000000000 { result := mul(uUNIT, 21) }
case 10000000000000000000000000000000000000000 { result := mul(uUNIT, 22) }
case 100000000000000000000000000000000000000000 { result := mul(uUNIT, 23) }
case 1000000000000000000000000000000000000000000 { result := mul(uUNIT, 24) }
case 10000000000000000000000000000000000000000000 { result := mul(uUNIT, 25) }
case 100000000000000000000000000000000000000000000 { result := mul(uUNIT, 26) }
case 1000000000000000000000000000000000000000000000 { result := mul(uUNIT, 27) }
case 10000000000000000000000000000000000000000000000 { result := mul(uUNIT, 28) }
case 100000000000000000000000000000000000000000000000 { result := mul(uUNIT, 29) }
case 1000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 30) }
case 10000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 31) }
case 100000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 32) }
case 1000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 33) }
case 10000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 34) }
case 100000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 35) }
case 1000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 36) }
case 10000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 37) }
case 100000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 38) }
case 1000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 39) }
case 10000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 40) }
case 100000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 41) }
case 1000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 42) }
case 10000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 43) }
case 100000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 44) }
case 1000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 45) }
case 10000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 46) }
case 100000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 47) }
case 1000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 48) }
case 10000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 49) }
case 100000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 50) }
case 1000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 51) }
case 10000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 52) }
case 100000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 53) }
case 1000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 54) }
case 10000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 55) }
case 100000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 56) }
case 1000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 57) }
case 10000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 58) }
default { result := uMAX_SD59x18 }
}
if (result.unwrap() == uMAX_SD59x18) {
unchecked {
// Inline the fixed-point division to save gas.
result = wrap(log2(x).unwrap() * uUNIT / uLOG2_10);
}
}
}
/// @notice Calculates the binary logarithm of x using the iterative approximation algorithm:
///
/// $$
/// log_2{x} = n + log_2{y}, \text{ where } y = x*2^{-n}, \ y \in [1, 2)
/// $$
///
/// For $0 \leq x \lt 1$, the input is inverted:
///
/// $$
/// log_2{x} = -log_2{\frac{1}{x}}
/// $$
///
/// @dev See https://en.wikipedia.org/wiki/Binary_logarithm#Iterative_approximation.
///
/// Notes:
/// - Due to the lossy precision of the iterative approximation, the results are not perfectly accurate to the last decimal.
///
/// Requirements:
/// - x > 0
///
/// @param x The SD59x18 number for which to calculate the binary logarithm.
/// @return result The binary logarithm as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function log2(SD59x18 x) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
if (xInt <= 0) {
revert Errors.PRBMath_SD59x18_Log_InputTooSmall(x);
}
unchecked {
int256 sign;
if (xInt >= uUNIT) {
sign = 1;
} else {
sign = -1;
// Inline the fixed-point inversion to save gas.
xInt = uUNIT_SQUARED / xInt;
}
// Calculate the integer part of the logarithm.
uint256 n = Common.msb(uint256(xInt / uUNIT));
// This is the integer part of the logarithm as an SD59x18 number. The operation can't overflow
// because n is at most 255, `UNIT` is 1e18, and the sign is either 1 or -1.
int256 resultInt = int256(n) * uUNIT;
// Calculate $y = x * 2^{-n}$.
int256 y = xInt >> n;
// If y is the unit number, the fractional part is zero.
if (y == uUNIT) {
return wrap(resultInt * sign);
}
// Calculate the fractional part via the iterative approximation.
// The `delta >>= 1` part is equivalent to `delta /= 2`, but shifting bits is more gas efficient.
int256 DOUBLE_UNIT = 2e18;
for (int256 delta = uHALF_UNIT; delta > 0; delta >>= 1) {
y = (y * y) / uUNIT;
// Is y^2 >= 2e18 and so in the range [2e18, 4e18)?
if (y >= DOUBLE_UNIT) {
// Add the 2^{-m} factor to the logarithm.
resultInt = resultInt + delta;
// Halve y, which corresponds to z/2 in the Wikipedia article.
y >>= 1;
}
}
resultInt *= sign;
result = wrap(resultInt);
}
}
/// @notice Multiplies two SD59x18 numbers together, returning a new SD59x18 number.
///
/// @dev Notes:
/// - Refer to the notes in {Common.mulDiv18}.
///
/// Requirements:
/// - Refer to the requirements in {Common.mulDiv18}.
/// - None of the inputs can be `MIN_SD59x18`.
/// - The result must fit in SD59x18.
///
/// @param x The multiplicand as an SD59x18 number.
/// @param y The multiplier as an SD59x18 number.
/// @return result The product as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function mul(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
int256 yInt = y.unwrap();
if (xInt == uMIN_SD59x18 || yInt == uMIN_SD59x18) {
revert Errors.PRBMath_SD59x18_Mul_InputTooSmall();
}
// Get hold of the absolute values of x and y.
uint256 xAbs;
uint256 yAbs;
unchecked {
xAbs = xInt < 0 ? uint256(-xInt) : uint256(xInt);
yAbs = yInt < 0 ? uint256(-yInt) : uint256(yInt);
}
// Compute the absolute value (x*y÷UNIT). The resulting value must fit in SD59x18.
uint256 resultAbs = Common.mulDiv18(xAbs, yAbs);
if (resultAbs > uint256(uMAX_SD59x18)) {
revert Errors.PRBMath_SD59x18_Mul_Overflow(x, y);
}
// Check if x and y have the same sign using two's complement representation. The left-most bit represents the sign (1 for
// negative, 0 for positive or zero).
bool sameSign = (xInt ^ yInt) > -1;
// If the inputs have the same sign, the result should be positive. Otherwise, it should be negative.
unchecked {
result = wrap(sameSign ? int256(resultAbs) : -int256(resultAbs));
}
}
/// @notice Raises x to the power of y using the following formula:
///
/// $$
/// x^y = 2^{log_2{x} * y}
/// $$
///
/// @dev Notes:
/// - Refer to the notes in {exp2}, {log2}, and {mul}.
/// - Returns `UNIT` for 0^0.
///
/// Requirements:
/// - Refer to the requirements in {exp2}, {log2}, and {mul}.
///
/// @param x The base as an SD59x18 number.
/// @param y Exponent to raise x to, as an SD59x18 number
/// @return result x raised to power y, as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function pow(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
int256 yInt = y.unwrap();
// If both x and y are zero, the result is `UNIT`. If just x is zero, the result is always zero.
if (xInt == 0) {
return yInt == 0 ? UNIT : ZERO;
}
// If x is `UNIT`, the result is always `UNIT`.
else if (xInt == uUNIT) {
return UNIT;
}
// If y is zero, the result is always `UNIT`.
if (yInt == 0) {
return UNIT;
}
// If y is `UNIT`, the result is always x.
else if (yInt == uUNIT) {
return x;
}
// Calculate the result using the formula.
result = exp2(mul(log2(x), y));
}
/// @notice Raises x (an SD59x18 number) to the power y (an unsigned basic integer) using the well-known
/// algorithm "exponentiation by squaring".
///
/// @dev See https://en.wikipedia.org/wiki/Exponentiation_by_squaring.
///
/// Notes:
/// - Refer to the notes in {Common.mulDiv18}.
/// - Returns `UNIT` for 0^0.
///
/// Requirements:
/// - Refer to the requirements in {abs} and {Common.mulDiv18}.
/// - The result must fit in SD59x18.
///
/// @param x The base as an SD59x18 number.
/// @param y The exponent as a uint256.
/// @return result The result as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function powu(SD59x18 x, uint256 y) pure returns (SD59x18 result) {
uint256 xAbs = uint256(abs(x).unwrap());
// Calculate the first iteration of the loop in advance.
uint256 resultAbs = y & 1 > 0 ? xAbs : uint256(uUNIT);
// Equivalent to `for(y /= 2; y > 0; y /= 2)`.
uint256 yAux = y;
for (yAux >>= 1; yAux > 0; yAux >>= 1) {
xAbs = Common.mulDiv18(xAbs, xAbs);
// Equivalent to `y % 2 == 1`.
if (yAux & 1 > 0) {
resultAbs = Common.mulDiv18(resultAbs, xAbs);
}
}
// The result must fit in SD59x18.
if (resultAbs > uint256(uMAX_SD59x18)) {
revert Errors.PRBMath_SD59x18_Powu_Overflow(x, y);
}
unchecked {
// Is the base negative and the exponent odd? If yes, the result should be negative.
int256 resultInt = int256(resultAbs);
bool isNegative = x.unwrap() < 0 && y & 1 == 1;
if (isNegative) {
resultInt = -resultInt;
}
result = wrap(resultInt);
}
}
/// @notice Calculates the square root of x using the Babylonian method.
///
/// @dev See https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.
///
/// Notes:
/// - Only the positive root is returned.
/// - The result is rounded toward zero.
///
/// Requirements:
/// - x ≥ 0, since complex numbers are not supported.
/// - x ≤ MAX_SD59x18 / UNIT
///
/// @param x The SD59x18 number for which to calculate the square root.
/// @return result The result as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function sqrt(SD59x18 x) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
if (xInt < 0) {
revert Errors.PRBMath_SD59x18_Sqrt_NegativeInput(x);
}
if (xInt > uMAX_SD59x18 / uUNIT) {
revert Errors.PRBMath_SD59x18_Sqrt_Overflow(x);
}
unchecked {
// Multiply x by `UNIT` to account for the factor of `UNIT` picked up when multiplying two SD59x18 numbers.
// In this case, the two numbers are both the square root.
uint256 resultUint = Common.sqrt(uint256(xInt * uUNIT));
result = wrap(int256(resultUint));
}
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "./Casting.sol" as Casting;
import "./Helpers.sol" as Helpers;
import "./Math.sol" as Math;
/// @notice The signed 59.18-decimal fixed-point number representation, which can have up to 59 digits and up to 18
/// decimals. The values of this are bound by the minimum and the maximum values permitted by the underlying Solidity
/// type int256.
type SD59x18 is int256;
/*//////////////////////////////////////////////////////////////////////////
CASTING
//////////////////////////////////////////////////////////////////////////*/
using {
Casting.intoInt256,
Casting.intoSD1x18,
Casting.intoSD21x18,
Casting.intoUD2x18,
Casting.intoUD21x18,
Casting.intoUD60x18,
Casting.intoUint256,
Casting.intoUint128,
Casting.intoUint40,
Casting.unwrap
} for SD59x18 global;
/*//////////////////////////////////////////////////////////////////////////
MATHEMATICAL FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
using {
Math.abs,
Math.avg,
Math.ceil,
Math.div,
Math.exp,
Math.exp2,
Math.floor,
Math.frac,
Math.gm,
Math.inv,
Math.log10,
Math.log2,
Math.ln,
Math.mul,
Math.pow,
Math.powu,
Math.sqrt
} for SD59x18 global;
/*//////////////////////////////////////////////////////////////////////////
HELPER FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
using {
Helpers.add,
Helpers.and,
Helpers.eq,
Helpers.gt,
Helpers.gte,
Helpers.isZero,
Helpers.lshift,
Helpers.lt,
Helpers.lte,
Helpers.mod,
Helpers.neq,
Helpers.not,
Helpers.or,
Helpers.rshift,
Helpers.sub,
Helpers.uncheckedAdd,
Helpers.uncheckedSub,
Helpers.uncheckedUnary,
Helpers.xor
} for SD59x18 global;
/*//////////////////////////////////////////////////////////////////////////
OPERATORS
//////////////////////////////////////////////////////////////////////////*/
// The global "using for" directive makes it possible to use these operators on the SD59x18 type.
using {
Helpers.add as +,
Helpers.and2 as &,
Math.div as /,
Helpers.eq as ==,
Helpers.gt as >,
Helpers.gte as >=,
Helpers.lt as <,
Helpers.lte as <=,
Helpers.mod as %,
Math.mul as *,
Helpers.neq as !=,
Helpers.not as ~,
Helpers.or as |,
Helpers.sub as -,
Helpers.unary as -,
Helpers.xor as ^
} for SD59x18 global;// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "../Common.sol" as Common;
import "./Errors.sol" as Errors;
import { SD59x18 } from "../sd59x18/ValueType.sol";
import { UD60x18 } from "../ud60x18/ValueType.sol";
import { UD21x18 } from "./ValueType.sol";
/// @notice Casts a UD21x18 number into SD59x18.
/// @dev There is no overflow check because UD21x18 ⊆ SD59x18.
function intoSD59x18(UD21x18 x) pure returns (SD59x18 result) {
result = SD59x18.wrap(int256(uint256(UD21x18.unwrap(x))));
}
/// @notice Casts a UD21x18 number into UD60x18.
/// @dev There is no overflow check because UD21x18 ⊆ UD60x18.
function intoUD60x18(UD21x18 x) pure returns (UD60x18 result) {
result = UD60x18.wrap(UD21x18.unwrap(x));
}
/// @notice Casts a UD21x18 number into uint128.
/// @dev This is basically an alias for {unwrap}.
function intoUint128(UD21x18 x) pure returns (uint128 result) {
result = UD21x18.unwrap(x);
}
/// @notice Casts a UD21x18 number into uint256.
/// @dev There is no overflow check because UD21x18 ⊆ uint256.
function intoUint256(UD21x18 x) pure returns (uint256 result) {
result = uint256(UD21x18.unwrap(x));
}
/// @notice Casts a UD21x18 number into uint40.
/// @dev Requirements:
/// - x ≤ MAX_UINT40
function intoUint40(UD21x18 x) pure returns (uint40 result) {
uint128 xUint = UD21x18.unwrap(x);
if (xUint > uint128(Common.MAX_UINT40)) {
revert Errors.PRBMath_UD21x18_IntoUint40_Overflow(x);
}
result = uint40(xUint);
}
/// @notice Alias for {wrap}.
function ud21x18(uint128 x) pure returns (UD21x18 result) {
result = UD21x18.wrap(x);
}
/// @notice Unwrap a UD21x18 number into uint128.
function unwrap(UD21x18 x) pure returns (uint128 result) {
result = UD21x18.unwrap(x);
}
/// @notice Wraps a uint128 number into UD21x18.
function wrap(uint128 x) pure returns (UD21x18 result) {
result = UD21x18.wrap(x);
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { UD21x18 } from "./ValueType.sol";
/// @dev Euler's number as a UD21x18 number.
UD21x18 constant E = UD21x18.wrap(2_718281828459045235);
/// @dev The maximum value a UD21x18 number can have.
uint128 constant uMAX_UD21x18 = 340282366920938463463_374607431768211455;
UD21x18 constant MAX_UD21x18 = UD21x18.wrap(uMAX_UD21x18);
/// @dev PI as a UD21x18 number.
UD21x18 constant PI = UD21x18.wrap(3_141592653589793238);
/// @dev The unit number, which gives the decimal precision of UD21x18.
uint256 constant uUNIT = 1e18;
UD21x18 constant UNIT = UD21x18.wrap(1e18);// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { UD21x18 } from "./ValueType.sol";
/// @notice Thrown when trying to cast a UD21x18 number that doesn't fit in uint40.
error PRBMath_UD21x18_IntoUint40_Overflow(UD21x18 x);// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "./Casting.sol" as Casting;
/// @notice The unsigned 21.18-decimal fixed-point number representation, which can have up to 21 digits and up to 18
/// decimals. The values of this are bound by the minimum and the maximum values permitted by the underlying Solidity
/// type uint128. This is useful when end users want to use uint128 to save gas, e.g. with tight variable packing in contract
/// storage.
type UD21x18 is uint128;
/*//////////////////////////////////////////////////////////////////////////
CASTING
//////////////////////////////////////////////////////////////////////////*/
using {
Casting.intoSD59x18,
Casting.intoUD60x18,
Casting.intoUint128,
Casting.intoUint256,
Casting.intoUint40,
Casting.unwrap
} for UD21x18 global;// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "../Common.sol" as Common;
import "./Errors.sol" as Errors;
import { SD59x18 } from "../sd59x18/ValueType.sol";
import { UD60x18 } from "../ud60x18/ValueType.sol";
import { UD2x18 } from "./ValueType.sol";
/// @notice Casts a UD2x18 number into SD59x18.
/// @dev There is no overflow check because UD2x18 ⊆ SD59x18.
function intoSD59x18(UD2x18 x) pure returns (SD59x18 result) {
result = SD59x18.wrap(int256(uint256(UD2x18.unwrap(x))));
}
/// @notice Casts a UD2x18 number into UD60x18.
/// @dev There is no overflow check because UD2x18 ⊆ UD60x18.
function intoUD60x18(UD2x18 x) pure returns (UD60x18 result) {
result = UD60x18.wrap(UD2x18.unwrap(x));
}
/// @notice Casts a UD2x18 number into uint128.
/// @dev There is no overflow check because UD2x18 ⊆ uint128.
function intoUint128(UD2x18 x) pure returns (uint128 result) {
result = uint128(UD2x18.unwrap(x));
}
/// @notice Casts a UD2x18 number into uint256.
/// @dev There is no overflow check because UD2x18 ⊆ uint256.
function intoUint256(UD2x18 x) pure returns (uint256 result) {
result = uint256(UD2x18.unwrap(x));
}
/// @notice Casts a UD2x18 number into uint40.
/// @dev Requirements:
/// - x ≤ MAX_UINT40
function intoUint40(UD2x18 x) pure returns (uint40 result) {
uint64 xUint = UD2x18.unwrap(x);
if (xUint > uint64(Common.MAX_UINT40)) {
revert Errors.PRBMath_UD2x18_IntoUint40_Overflow(x);
}
result = uint40(xUint);
}
/// @notice Alias for {wrap}.
function ud2x18(uint64 x) pure returns (UD2x18 result) {
result = UD2x18.wrap(x);
}
/// @notice Unwrap a UD2x18 number into uint64.
function unwrap(UD2x18 x) pure returns (uint64 result) {
result = UD2x18.unwrap(x);
}
/// @notice Wraps a uint64 number into UD2x18.
function wrap(uint64 x) pure returns (UD2x18 result) {
result = UD2x18.wrap(x);
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { UD2x18 } from "./ValueType.sol";
/// @dev Euler's number as a UD2x18 number.
UD2x18 constant E = UD2x18.wrap(2_718281828459045235);
/// @dev The maximum value a UD2x18 number can have.
uint64 constant uMAX_UD2x18 = 18_446744073709551615;
UD2x18 constant MAX_UD2x18 = UD2x18.wrap(uMAX_UD2x18);
/// @dev PI as a UD2x18 number.
UD2x18 constant PI = UD2x18.wrap(3_141592653589793238);
/// @dev The unit number, which gives the decimal precision of UD2x18.
UD2x18 constant UNIT = UD2x18.wrap(1e18);
uint64 constant uUNIT = 1e18;// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { UD2x18 } from "./ValueType.sol";
/// @notice Thrown when trying to cast a UD2x18 number that doesn't fit in uint40.
error PRBMath_UD2x18_IntoUint40_Overflow(UD2x18 x);// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "./Casting.sol" as Casting;
/// @notice The unsigned 2.18-decimal fixed-point number representation, which can have up to 2 digits and up to 18
/// decimals. The values of this are bound by the minimum and the maximum values permitted by the underlying Solidity
/// type uint64. This is useful when end users want to use uint64 to save gas, e.g. with tight variable packing in contract
/// storage.
type UD2x18 is uint64;
/*//////////////////////////////////////////////////////////////////////////
CASTING
//////////////////////////////////////////////////////////////////////////*/
using {
Casting.intoSD59x18,
Casting.intoUD60x18,
Casting.intoUint128,
Casting.intoUint256,
Casting.intoUint40,
Casting.unwrap
} for UD2x18 global;// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "./Errors.sol" as CastingErrors;
import { MAX_UINT128, MAX_UINT40 } from "../Common.sol";
import { uMAX_SD1x18 } from "../sd1x18/Constants.sol";
import { SD1x18 } from "../sd1x18/ValueType.sol";
import { uMAX_SD21x18 } from "../sd21x18/Constants.sol";
import { SD21x18 } from "../sd21x18/ValueType.sol";
import { uMAX_SD59x18 } from "../sd59x18/Constants.sol";
import { SD59x18 } from "../sd59x18/ValueType.sol";
import { uMAX_UD2x18 } from "../ud2x18/Constants.sol";
import { uMAX_UD21x18 } from "../ud21x18/Constants.sol";
import { UD2x18 } from "../ud2x18/ValueType.sol";
import { UD21x18 } from "../ud21x18/ValueType.sol";
import { UD60x18 } from "./ValueType.sol";
/// @notice Casts a UD60x18 number into SD1x18.
/// @dev Requirements:
/// - x ≤ uMAX_SD1x18
function intoSD1x18(UD60x18 x) pure returns (SD1x18 result) {
uint256 xUint = UD60x18.unwrap(x);
if (xUint > uint256(int256(uMAX_SD1x18))) {
revert CastingErrors.PRBMath_UD60x18_IntoSD1x18_Overflow(x);
}
result = SD1x18.wrap(int64(uint64(xUint)));
}
/// @notice Casts a UD60x18 number into SD21x18.
/// @dev Requirements:
/// - x ≤ uMAX_SD21x18
function intoSD21x18(UD60x18 x) pure returns (SD21x18 result) {
uint256 xUint = UD60x18.unwrap(x);
if (xUint > uint256(int256(uMAX_SD21x18))) {
revert CastingErrors.PRBMath_UD60x18_IntoSD21x18_Overflow(x);
}
result = SD21x18.wrap(int128(uint128(xUint)));
}
/// @notice Casts a UD60x18 number into UD2x18.
/// @dev Requirements:
/// - x ≤ uMAX_UD2x18
function intoUD2x18(UD60x18 x) pure returns (UD2x18 result) {
uint256 xUint = UD60x18.unwrap(x);
if (xUint > uMAX_UD2x18) {
revert CastingErrors.PRBMath_UD60x18_IntoUD2x18_Overflow(x);
}
result = UD2x18.wrap(uint64(xUint));
}
/// @notice Casts a UD60x18 number into UD21x18.
/// @dev Requirements:
/// - x ≤ uMAX_UD21x18
function intoUD21x18(UD60x18 x) pure returns (UD21x18 result) {
uint256 xUint = UD60x18.unwrap(x);
if (xUint > uMAX_UD21x18) {
revert CastingErrors.PRBMath_UD60x18_IntoUD21x18_Overflow(x);
}
result = UD21x18.wrap(uint128(xUint));
}
/// @notice Casts a UD60x18 number into SD59x18.
/// @dev Requirements:
/// - x ≤ uMAX_SD59x18
function intoSD59x18(UD60x18 x) pure returns (SD59x18 result) {
uint256 xUint = UD60x18.unwrap(x);
if (xUint > uint256(uMAX_SD59x18)) {
revert CastingErrors.PRBMath_UD60x18_IntoSD59x18_Overflow(x);
}
result = SD59x18.wrap(int256(xUint));
}
/// @notice Casts a UD60x18 number into uint128.
/// @dev This is basically an alias for {unwrap}.
function intoUint256(UD60x18 x) pure returns (uint256 result) {
result = UD60x18.unwrap(x);
}
/// @notice Casts a UD60x18 number into uint128.
/// @dev Requirements:
/// - x ≤ MAX_UINT128
function intoUint128(UD60x18 x) pure returns (uint128 result) {
uint256 xUint = UD60x18.unwrap(x);
if (xUint > MAX_UINT128) {
revert CastingErrors.PRBMath_UD60x18_IntoUint128_Overflow(x);
}
result = uint128(xUint);
}
/// @notice Casts a UD60x18 number into uint40.
/// @dev Requirements:
/// - x ≤ MAX_UINT40
function intoUint40(UD60x18 x) pure returns (uint40 result) {
uint256 xUint = UD60x18.unwrap(x);
if (xUint > MAX_UINT40) {
revert CastingErrors.PRBMath_UD60x18_IntoUint40_Overflow(x);
}
result = uint40(xUint);
}
/// @notice Alias for {wrap}.
function ud(uint256 x) pure returns (UD60x18 result) {
result = UD60x18.wrap(x);
}
/// @notice Alias for {wrap}.
function ud60x18(uint256 x) pure returns (UD60x18 result) {
result = UD60x18.wrap(x);
}
/// @notice Unwraps a UD60x18 number into uint256.
function unwrap(UD60x18 x) pure returns (uint256 result) {
result = UD60x18.unwrap(x);
}
/// @notice Wraps a uint256 number into the UD60x18 value type.
function wrap(uint256 x) pure returns (UD60x18 result) {
result = UD60x18.wrap(x);
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { UD60x18 } from "./ValueType.sol";
// NOTICE: the "u" prefix stands for "unwrapped".
/// @dev Euler's number as a UD60x18 number.
UD60x18 constant E = UD60x18.wrap(2_718281828459045235);
/// @dev The maximum input permitted in {exp}.
uint256 constant uEXP_MAX_INPUT = 133_084258667509499440;
UD60x18 constant EXP_MAX_INPUT = UD60x18.wrap(uEXP_MAX_INPUT);
/// @dev The maximum input permitted in {exp2}.
uint256 constant uEXP2_MAX_INPUT = 192e18 - 1;
UD60x18 constant EXP2_MAX_INPUT = UD60x18.wrap(uEXP2_MAX_INPUT);
/// @dev Half the UNIT number.
uint256 constant uHALF_UNIT = 0.5e18;
UD60x18 constant HALF_UNIT = UD60x18.wrap(uHALF_UNIT);
/// @dev $log_2(10)$ as a UD60x18 number.
uint256 constant uLOG2_10 = 3_321928094887362347;
UD60x18 constant LOG2_10 = UD60x18.wrap(uLOG2_10);
/// @dev $log_2(e)$ as a UD60x18 number.
uint256 constant uLOG2_E = 1_442695040888963407;
UD60x18 constant LOG2_E = UD60x18.wrap(uLOG2_E);
/// @dev The maximum value a UD60x18 number can have.
uint256 constant uMAX_UD60x18 = 115792089237316195423570985008687907853269984665640564039457_584007913129639935;
UD60x18 constant MAX_UD60x18 = UD60x18.wrap(uMAX_UD60x18);
/// @dev The maximum whole value a UD60x18 number can have.
uint256 constant uMAX_WHOLE_UD60x18 = 115792089237316195423570985008687907853269984665640564039457_000000000000000000;
UD60x18 constant MAX_WHOLE_UD60x18 = UD60x18.wrap(uMAX_WHOLE_UD60x18);
/// @dev PI as a UD60x18 number.
UD60x18 constant PI = UD60x18.wrap(3_141592653589793238);
/// @dev The unit number, which gives the decimal precision of UD60x18.
uint256 constant uUNIT = 1e18;
UD60x18 constant UNIT = UD60x18.wrap(uUNIT);
/// @dev The unit number squared.
uint256 constant uUNIT_SQUARED = 1e36;
UD60x18 constant UNIT_SQUARED = UD60x18.wrap(uUNIT_SQUARED);
/// @dev Zero as a UD60x18 number.
UD60x18 constant ZERO = UD60x18.wrap(0);// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { UD60x18 } from "./ValueType.sol";
/// @notice Thrown when ceiling a number overflows UD60x18.
error PRBMath_UD60x18_Ceil_Overflow(UD60x18 x);
/// @notice Thrown when converting a basic integer to the fixed-point format overflows UD60x18.
error PRBMath_UD60x18_Convert_Overflow(uint256 x);
/// @notice Thrown when taking the natural exponent of a base greater than 133_084258667509499441.
error PRBMath_UD60x18_Exp_InputTooBig(UD60x18 x);
/// @notice Thrown when taking the binary exponent of a base greater than 192e18.
error PRBMath_UD60x18_Exp2_InputTooBig(UD60x18 x);
/// @notice Thrown when taking the geometric mean of two numbers and multiplying them overflows UD60x18.
error PRBMath_UD60x18_Gm_Overflow(UD60x18 x, UD60x18 y);
/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in SD1x18.
error PRBMath_UD60x18_IntoSD1x18_Overflow(UD60x18 x);
/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in SD21x18.
error PRBMath_UD60x18_IntoSD21x18_Overflow(UD60x18 x);
/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in SD59x18.
error PRBMath_UD60x18_IntoSD59x18_Overflow(UD60x18 x);
/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in UD2x18.
error PRBMath_UD60x18_IntoUD2x18_Overflow(UD60x18 x);
/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in UD21x18.
error PRBMath_UD60x18_IntoUD21x18_Overflow(UD60x18 x);
/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in uint128.
error PRBMath_UD60x18_IntoUint128_Overflow(UD60x18 x);
/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in uint40.
error PRBMath_UD60x18_IntoUint40_Overflow(UD60x18 x);
/// @notice Thrown when taking the logarithm of a number less than UNIT.
error PRBMath_UD60x18_Log_InputTooSmall(UD60x18 x);
/// @notice Thrown when calculating the square root overflows UD60x18.
error PRBMath_UD60x18_Sqrt_Overflow(UD60x18 x);// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { wrap } from "./Casting.sol";
import { UD60x18 } from "./ValueType.sol";
/// @notice Implements the checked addition operation (+) in the UD60x18 type.
function add(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
result = wrap(x.unwrap() + y.unwrap());
}
/// @notice Implements the AND (&) bitwise operation in the UD60x18 type.
function and(UD60x18 x, uint256 bits) pure returns (UD60x18 result) {
result = wrap(x.unwrap() & bits);
}
/// @notice Implements the AND (&) bitwise operation in the UD60x18 type.
function and2(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
result = wrap(x.unwrap() & y.unwrap());
}
/// @notice Implements the equal operation (==) in the UD60x18 type.
function eq(UD60x18 x, UD60x18 y) pure returns (bool result) {
result = x.unwrap() == y.unwrap();
}
/// @notice Implements the greater than operation (>) in the UD60x18 type.
function gt(UD60x18 x, UD60x18 y) pure returns (bool result) {
result = x.unwrap() > y.unwrap();
}
/// @notice Implements the greater than or equal to operation (>=) in the UD60x18 type.
function gte(UD60x18 x, UD60x18 y) pure returns (bool result) {
result = x.unwrap() >= y.unwrap();
}
/// @notice Implements a zero comparison check function in the UD60x18 type.
function isZero(UD60x18 x) pure returns (bool result) {
// This wouldn't work if x could be negative.
result = x.unwrap() == 0;
}
/// @notice Implements the left shift operation (<<) in the UD60x18 type.
function lshift(UD60x18 x, uint256 bits) pure returns (UD60x18 result) {
result = wrap(x.unwrap() << bits);
}
/// @notice Implements the lower than operation (<) in the UD60x18 type.
function lt(UD60x18 x, UD60x18 y) pure returns (bool result) {
result = x.unwrap() < y.unwrap();
}
/// @notice Implements the lower than or equal to operation (<=) in the UD60x18 type.
function lte(UD60x18 x, UD60x18 y) pure returns (bool result) {
result = x.unwrap() <= y.unwrap();
}
/// @notice Implements the checked modulo operation (%) in the UD60x18 type.
function mod(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
result = wrap(x.unwrap() % y.unwrap());
}
/// @notice Implements the not equal operation (!=) in the UD60x18 type.
function neq(UD60x18 x, UD60x18 y) pure returns (bool result) {
result = x.unwrap() != y.unwrap();
}
/// @notice Implements the NOT (~) bitwise operation in the UD60x18 type.
function not(UD60x18 x) pure returns (UD60x18 result) {
result = wrap(~x.unwrap());
}
/// @notice Implements the OR (|) bitwise operation in the UD60x18 type.
function or(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
result = wrap(x.unwrap() | y.unwrap());
}
/// @notice Implements the right shift operation (>>) in the UD60x18 type.
function rshift(UD60x18 x, uint256 bits) pure returns (UD60x18 result) {
result = wrap(x.unwrap() >> bits);
}
/// @notice Implements the checked subtraction operation (-) in the UD60x18 type.
function sub(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
result = wrap(x.unwrap() - y.unwrap());
}
/// @notice Implements the unchecked addition operation (+) in the UD60x18 type.
function uncheckedAdd(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
unchecked {
result = wrap(x.unwrap() + y.unwrap());
}
}
/// @notice Implements the unchecked subtraction operation (-) in the UD60x18 type.
function uncheckedSub(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
unchecked {
result = wrap(x.unwrap() - y.unwrap());
}
}
/// @notice Implements the XOR (^) bitwise operation in the UD60x18 type.
function xor(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
result = wrap(x.unwrap() ^ y.unwrap());
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "../Common.sol" as Common;
import "./Errors.sol" as Errors;
import { wrap } from "./Casting.sol";
import {
uEXP_MAX_INPUT,
uEXP2_MAX_INPUT,
uHALF_UNIT,
uLOG2_10,
uLOG2_E,
uMAX_UD60x18,
uMAX_WHOLE_UD60x18,
UNIT,
uUNIT,
uUNIT_SQUARED,
ZERO
} from "./Constants.sol";
import { UD60x18 } from "./ValueType.sol";
/*//////////////////////////////////////////////////////////////////////////
MATHEMATICAL FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
/// @notice Calculates the arithmetic average of x and y using the following formula:
///
/// $$
/// avg(x, y) = (x & y) + ((xUint ^ yUint) / 2)
/// $$
///
/// In English, this is what this formula does:
///
/// 1. AND x and y.
/// 2. Calculate half of XOR x and y.
/// 3. Add the two results together.
///
/// This technique is known as SWAR, which stands for "SIMD within a register". You can read more about it here:
/// https://devblogs.microsoft.com/oldnewthing/20220207-00/?p=106223
///
/// @dev Notes:
/// - The result is rounded toward zero.
///
/// @param x The first operand as a UD60x18 number.
/// @param y The second operand as a UD60x18 number.
/// @return result The arithmetic average as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function avg(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
uint256 xUint = x.unwrap();
uint256 yUint = y.unwrap();
unchecked {
result = wrap((xUint & yUint) + ((xUint ^ yUint) >> 1));
}
}
/// @notice Yields the smallest whole number greater than or equal to x.
///
/// @dev This is optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional
/// counterparts. See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.
///
/// Requirements:
/// - x ≤ MAX_WHOLE_UD60x18
///
/// @param x The UD60x18 number to ceil.
/// @return result The smallest whole number greater than or equal to x, as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function ceil(UD60x18 x) pure returns (UD60x18 result) {
uint256 xUint = x.unwrap();
if (xUint > uMAX_WHOLE_UD60x18) {
revert Errors.PRBMath_UD60x18_Ceil_Overflow(x);
}
assembly ("memory-safe") {
// Equivalent to `x % UNIT`.
let remainder := mod(x, uUNIT)
// Equivalent to `UNIT - remainder`.
let delta := sub(uUNIT, remainder)
// Equivalent to `x + remainder > 0 ? delta : 0`.
result := add(x, mul(delta, gt(remainder, 0)))
}
}
/// @notice Divides two UD60x18 numbers, returning a new UD60x18 number.
///
/// @dev Uses {Common.mulDiv} to enable overflow-safe multiplication and division.
///
/// Notes:
/// - Refer to the notes in {Common.mulDiv}.
///
/// Requirements:
/// - Refer to the requirements in {Common.mulDiv}.
///
/// @param x The numerator as a UD60x18 number.
/// @param y The denominator as a UD60x18 number.
/// @return result The quotient as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function div(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
result = wrap(Common.mulDiv(x.unwrap(), uUNIT, y.unwrap()));
}
/// @notice Calculates the natural exponent of x using the following formula:
///
/// $$
/// e^x = 2^{x * log_2{e}}
/// $$
///
/// @dev Requirements:
/// - x ≤ 133_084258667509499440
///
/// @param x The exponent as a UD60x18 number.
/// @return result The result as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function exp(UD60x18 x) pure returns (UD60x18 result) {
uint256 xUint = x.unwrap();
// This check prevents values greater than 192e18 from being passed to {exp2}.
if (xUint > uEXP_MAX_INPUT) {
revert Errors.PRBMath_UD60x18_Exp_InputTooBig(x);
}
unchecked {
// Inline the fixed-point multiplication to save gas.
uint256 doubleUnitProduct = xUint * uLOG2_E;
result = exp2(wrap(doubleUnitProduct / uUNIT));
}
}
/// @notice Calculates the binary exponent of x using the binary fraction method.
///
/// @dev See https://ethereum.stackexchange.com/q/79903/24693
///
/// Requirements:
/// - x < 192e18
/// - The result must fit in UD60x18.
///
/// @param x The exponent as a UD60x18 number.
/// @return result The result as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function exp2(UD60x18 x) pure returns (UD60x18 result) {
uint256 xUint = x.unwrap();
// Numbers greater than or equal to 192e18 don't fit in the 192.64-bit format.
if (xUint > uEXP2_MAX_INPUT) {
revert Errors.PRBMath_UD60x18_Exp2_InputTooBig(x);
}
// Convert x to the 192.64-bit fixed-point format.
uint256 x_192x64 = (xUint << 64) / uUNIT;
// Pass x to the {Common.exp2} function, which uses the 192.64-bit fixed-point number representation.
result = wrap(Common.exp2(x_192x64));
}
/// @notice Yields the greatest whole number less than or equal to x.
/// @dev Optimized for fractional value inputs, because every whole value has (1e18 - 1) fractional counterparts.
/// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.
/// @param x The UD60x18 number to floor.
/// @return result The greatest whole number less than or equal to x, as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function floor(UD60x18 x) pure returns (UD60x18 result) {
assembly ("memory-safe") {
// Equivalent to `x % UNIT`.
let remainder := mod(x, uUNIT)
// Equivalent to `x - remainder > 0 ? remainder : 0)`.
result := sub(x, mul(remainder, gt(remainder, 0)))
}
}
/// @notice Yields the excess beyond the floor of x using the odd function definition.
/// @dev See https://en.wikipedia.org/wiki/Fractional_part.
/// @param x The UD60x18 number to get the fractional part of.
/// @return result The fractional part of x as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function frac(UD60x18 x) pure returns (UD60x18 result) {
assembly ("memory-safe") {
result := mod(x, uUNIT)
}
}
/// @notice Calculates the geometric mean of x and y, i.e. $\sqrt{x * y}$, rounding down.
///
/// @dev Requirements:
/// - x * y must fit in UD60x18.
///
/// @param x The first operand as a UD60x18 number.
/// @param y The second operand as a UD60x18 number.
/// @return result The result as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function gm(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
uint256 xUint = x.unwrap();
uint256 yUint = y.unwrap();
if (xUint == 0 || yUint == 0) {
return ZERO;
}
unchecked {
// Checking for overflow this way is faster than letting Solidity do it.
uint256 xyUint = xUint * yUint;
if (xyUint / xUint != yUint) {
revert Errors.PRBMath_UD60x18_Gm_Overflow(x, y);
}
// We don't need to multiply the result by `UNIT` here because the x*y product picked up a factor of `UNIT`
// during multiplication. See the comments in {Common.sqrt}.
result = wrap(Common.sqrt(xyUint));
}
}
/// @notice Calculates the inverse of x.
///
/// @dev Notes:
/// - The result is rounded toward zero.
///
/// Requirements:
/// - x must not be zero.
///
/// @param x The UD60x18 number for which to calculate the inverse.
/// @return result The inverse as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function inv(UD60x18 x) pure returns (UD60x18 result) {
unchecked {
result = wrap(uUNIT_SQUARED / x.unwrap());
}
}
/// @notice Calculates the natural logarithm of x using the following formula:
///
/// $$
/// ln{x} = log_2{x} / log_2{e}
/// $$
///
/// @dev Notes:
/// - Refer to the notes in {log2}.
/// - The precision isn't sufficiently fine-grained to return exactly `UNIT` when the input is `E`.
///
/// Requirements:
/// - Refer to the requirements in {log2}.
///
/// @param x The UD60x18 number for which to calculate the natural logarithm.
/// @return result The natural logarithm as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function ln(UD60x18 x) pure returns (UD60x18 result) {
unchecked {
// Inline the fixed-point multiplication to save gas. This is overflow-safe because the maximum value that
// {log2} can return is ~196_205294292027477728.
result = wrap(log2(x).unwrap() * uUNIT / uLOG2_E);
}
}
/// @notice Calculates the common logarithm of x using the following formula:
///
/// $$
/// log_{10}{x} = log_2{x} / log_2{10}
/// $$
///
/// However, if x is an exact power of ten, a hard coded value is returned.
///
/// @dev Notes:
/// - Refer to the notes in {log2}.
///
/// Requirements:
/// - Refer to the requirements in {log2}.
///
/// @param x The UD60x18 number for which to calculate the common logarithm.
/// @return result The common logarithm as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function log10(UD60x18 x) pure returns (UD60x18 result) {
uint256 xUint = x.unwrap();
if (xUint < uUNIT) {
revert Errors.PRBMath_UD60x18_Log_InputTooSmall(x);
}
// Note that the `mul` in this assembly block is the standard multiplication operation, not {UD60x18.mul}.
// prettier-ignore
assembly ("memory-safe") {
switch x
case 1 { result := mul(uUNIT, sub(0, 18)) }
case 10 { result := mul(uUNIT, sub(1, 18)) }
case 100 { result := mul(uUNIT, sub(2, 18)) }
case 1000 { result := mul(uUNIT, sub(3, 18)) }
case 10000 { result := mul(uUNIT, sub(4, 18)) }
case 100000 { result := mul(uUNIT, sub(5, 18)) }
case 1000000 { result := mul(uUNIT, sub(6, 18)) }
case 10000000 { result := mul(uUNIT, sub(7, 18)) }
case 100000000 { result := mul(uUNIT, sub(8, 18)) }
case 1000000000 { result := mul(uUNIT, sub(9, 18)) }
case 10000000000 { result := mul(uUNIT, sub(10, 18)) }
case 100000000000 { result := mul(uUNIT, sub(11, 18)) }
case 1000000000000 { result := mul(uUNIT, sub(12, 18)) }
case 10000000000000 { result := mul(uUNIT, sub(13, 18)) }
case 100000000000000 { result := mul(uUNIT, sub(14, 18)) }
case 1000000000000000 { result := mul(uUNIT, sub(15, 18)) }
case 10000000000000000 { result := mul(uUNIT, sub(16, 18)) }
case 100000000000000000 { result := mul(uUNIT, sub(17, 18)) }
case 1000000000000000000 { result := 0 }
case 10000000000000000000 { result := uUNIT }
case 100000000000000000000 { result := mul(uUNIT, 2) }
case 1000000000000000000000 { result := mul(uUNIT, 3) }
case 10000000000000000000000 { result := mul(uUNIT, 4) }
case 100000000000000000000000 { result := mul(uUNIT, 5) }
case 1000000000000000000000000 { result := mul(uUNIT, 6) }
case 10000000000000000000000000 { result := mul(uUNIT, 7) }
case 100000000000000000000000000 { result := mul(uUNIT, 8) }
case 1000000000000000000000000000 { result := mul(uUNIT, 9) }
case 10000000000000000000000000000 { result := mul(uUNIT, 10) }
case 100000000000000000000000000000 { result := mul(uUNIT, 11) }
case 1000000000000000000000000000000 { result := mul(uUNIT, 12) }
case 10000000000000000000000000000000 { result := mul(uUNIT, 13) }
case 100000000000000000000000000000000 { result := mul(uUNIT, 14) }
case 1000000000000000000000000000000000 { result := mul(uUNIT, 15) }
case 10000000000000000000000000000000000 { result := mul(uUNIT, 16) }
case 100000000000000000000000000000000000 { result := mul(uUNIT, 17) }
case 1000000000000000000000000000000000000 { result := mul(uUNIT, 18) }
case 10000000000000000000000000000000000000 { result := mul(uUNIT, 19) }
case 100000000000000000000000000000000000000 { result := mul(uUNIT, 20) }
case 1000000000000000000000000000000000000000 { result := mul(uUNIT, 21) }
case 10000000000000000000000000000000000000000 { result := mul(uUNIT, 22) }
case 100000000000000000000000000000000000000000 { result := mul(uUNIT, 23) }
case 1000000000000000000000000000000000000000000 { result := mul(uUNIT, 24) }
case 10000000000000000000000000000000000000000000 { result := mul(uUNIT, 25) }
case 100000000000000000000000000000000000000000000 { result := mul(uUNIT, 26) }
case 1000000000000000000000000000000000000000000000 { result := mul(uUNIT, 27) }
case 10000000000000000000000000000000000000000000000 { result := mul(uUNIT, 28) }
case 100000000000000000000000000000000000000000000000 { result := mul(uUNIT, 29) }
case 1000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 30) }
case 10000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 31) }
case 100000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 32) }
case 1000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 33) }
case 10000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 34) }
case 100000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 35) }
case 1000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 36) }
case 10000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 37) }
case 100000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 38) }
case 1000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 39) }
case 10000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 40) }
case 100000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 41) }
case 1000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 42) }
case 10000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 43) }
case 100000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 44) }
case 1000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 45) }
case 10000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 46) }
case 100000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 47) }
case 1000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 48) }
case 10000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 49) }
case 100000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 50) }
case 1000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 51) }
case 10000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 52) }
case 100000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 53) }
case 1000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 54) }
case 10000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 55) }
case 100000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 56) }
case 1000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 57) }
case 10000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 58) }
case 100000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 59) }
default { result := uMAX_UD60x18 }
}
if (result.unwrap() == uMAX_UD60x18) {
unchecked {
// Inline the fixed-point division to save gas.
result = wrap(log2(x).unwrap() * uUNIT / uLOG2_10);
}
}
}
/// @notice Calculates the binary logarithm of x using the iterative approximation algorithm:
///
/// $$
/// log_2{x} = n + log_2{y}, \text{ where } y = x*2^{-n}, \ y \in [1, 2)
/// $$
///
/// For $0 \leq x \lt 1$, the input is inverted:
///
/// $$
/// log_2{x} = -log_2{\frac{1}{x}}
/// $$
///
/// @dev See https://en.wikipedia.org/wiki/Binary_logarithm#Iterative_approximation
///
/// Notes:
/// - Due to the lossy precision of the iterative approximation, the results are not perfectly accurate to the last decimal.
///
/// Requirements:
/// - x ≥ UNIT
///
/// @param x The UD60x18 number for which to calculate the binary logarithm.
/// @return result The binary logarithm as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function log2(UD60x18 x) pure returns (UD60x18 result) {
uint256 xUint = x.unwrap();
if (xUint < uUNIT) {
revert Errors.PRBMath_UD60x18_Log_InputTooSmall(x);
}
unchecked {
// Calculate the integer part of the logarithm.
uint256 n = Common.msb(xUint / uUNIT);
// This is the integer part of the logarithm as a UD60x18 number. The operation can't overflow because n
// n is at most 255 and UNIT is 1e18.
uint256 resultUint = n * uUNIT;
// Calculate $y = x * 2^{-n}$.
uint256 y = xUint >> n;
// If y is the unit number, the fractional part is zero.
if (y == uUNIT) {
return wrap(resultUint);
}
// Calculate the fractional part via the iterative approximation.
// The `delta >>= 1` part is equivalent to `delta /= 2`, but shifting bits is more gas efficient.
uint256 DOUBLE_UNIT = 2e18;
for (uint256 delta = uHALF_UNIT; delta > 0; delta >>= 1) {
y = (y * y) / uUNIT;
// Is y^2 >= 2e18 and so in the range [2e18, 4e18)?
if (y >= DOUBLE_UNIT) {
// Add the 2^{-m} factor to the logarithm.
resultUint += delta;
// Halve y, which corresponds to z/2 in the Wikipedia article.
y >>= 1;
}
}
result = wrap(resultUint);
}
}
/// @notice Multiplies two UD60x18 numbers together, returning a new UD60x18 number.
///
/// @dev Uses {Common.mulDiv} to enable overflow-safe multiplication and division.
///
/// Notes:
/// - Refer to the notes in {Common.mulDiv}.
///
/// Requirements:
/// - Refer to the requirements in {Common.mulDiv}.
///
/// @dev See the documentation in {Common.mulDiv18}.
/// @param x The multiplicand as a UD60x18 number.
/// @param y The multiplier as a UD60x18 number.
/// @return result The product as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function mul(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
result = wrap(Common.mulDiv18(x.unwrap(), y.unwrap()));
}
/// @notice Raises x to the power of y.
///
/// For $1 \leq x \leq \infty$, the following standard formula is used:
///
/// $$
/// x^y = 2^{log_2{x} * y}
/// $$
///
/// For $0 \leq x \lt 1$, since the unsigned {log2} is undefined, an equivalent formula is used:
///
/// $$
/// i = \frac{1}{x}
/// w = 2^{log_2{i} * y}
/// x^y = \frac{1}{w}
/// $$
///
/// @dev Notes:
/// - Refer to the notes in {log2} and {mul}.
/// - Returns `UNIT` for 0^0.
/// - It may not perform well with very small values of x. Consider using SD59x18 as an alternative.
///
/// Requirements:
/// - Refer to the requirements in {exp2}, {log2}, and {mul}.
///
/// @param x The base as a UD60x18 number.
/// @param y The exponent as a UD60x18 number.
/// @return result The result as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function pow(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
uint256 xUint = x.unwrap();
uint256 yUint = y.unwrap();
// If both x and y are zero, the result is `UNIT`. If just x is zero, the result is always zero.
if (xUint == 0) {
return yUint == 0 ? UNIT : ZERO;
}
// If x is `UNIT`, the result is always `UNIT`.
else if (xUint == uUNIT) {
return UNIT;
}
// If y is zero, the result is always `UNIT`.
if (yUint == 0) {
return UNIT;
}
// If y is `UNIT`, the result is always x.
else if (yUint == uUNIT) {
return x;
}
// If x is > UNIT, use the standard formula.
if (xUint > uUNIT) {
result = exp2(mul(log2(x), y));
}
// Conversely, if x < UNIT, use the equivalent formula.
else {
UD60x18 i = wrap(uUNIT_SQUARED / xUint);
UD60x18 w = exp2(mul(log2(i), y));
result = wrap(uUNIT_SQUARED / w.unwrap());
}
}
/// @notice Raises x (a UD60x18 number) to the power y (an unsigned basic integer) using the well-known
/// algorithm "exponentiation by squaring".
///
/// @dev See https://en.wikipedia.org/wiki/Exponentiation_by_squaring.
///
/// Notes:
/// - Refer to the notes in {Common.mulDiv18}.
/// - Returns `UNIT` for 0^0.
///
/// Requirements:
/// - The result must fit in UD60x18.
///
/// @param x The base as a UD60x18 number.
/// @param y The exponent as a uint256.
/// @return result The result as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function powu(UD60x18 x, uint256 y) pure returns (UD60x18 result) {
// Calculate the first iteration of the loop in advance.
uint256 xUint = x.unwrap();
uint256 resultUint = y & 1 > 0 ? xUint : uUNIT;
// Equivalent to `for(y /= 2; y > 0; y /= 2)`.
for (y >>= 1; y > 0; y >>= 1) {
xUint = Common.mulDiv18(xUint, xUint);
// Equivalent to `y % 2 == 1`.
if (y & 1 > 0) {
resultUint = Common.mulDiv18(resultUint, xUint);
}
}
result = wrap(resultUint);
}
/// @notice Calculates the square root of x using the Babylonian method.
///
/// @dev See https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.
///
/// Notes:
/// - The result is rounded toward zero.
///
/// Requirements:
/// - x ≤ MAX_UD60x18 / UNIT
///
/// @param x The UD60x18 number for which to calculate the square root.
/// @return result The result as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function sqrt(UD60x18 x) pure returns (UD60x18 result) {
uint256 xUint = x.unwrap();
unchecked {
if (xUint > uMAX_UD60x18 / uUNIT) {
revert Errors.PRBMath_UD60x18_Sqrt_Overflow(x);
}
// Multiply x by `UNIT` to account for the factor of `UNIT` picked up when multiplying two UD60x18 numbers.
// In this case, the two numbers are both the square root.
result = wrap(Common.sqrt(xUint * uUNIT));
}
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "./Casting.sol" as Casting;
import "./Helpers.sol" as Helpers;
import "./Math.sol" as Math;
/// @notice The unsigned 60.18-decimal fixed-point number representation, which can have up to 60 digits and up to 18
/// decimals. The values of this are bound by the minimum and the maximum values permitted by the Solidity type uint256.
/// @dev The value type is defined here so it can be imported in all other files.
type UD60x18 is uint256;
/*//////////////////////////////////////////////////////////////////////////
CASTING
//////////////////////////////////////////////////////////////////////////*/
using {
Casting.intoSD1x18,
Casting.intoSD21x18,
Casting.intoSD59x18,
Casting.intoUD2x18,
Casting.intoUD21x18,
Casting.intoUint128,
Casting.intoUint256,
Casting.intoUint40,
Casting.unwrap
} for UD60x18 global;
/*//////////////////////////////////////////////////////////////////////////
MATHEMATICAL FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
// The global "using for" directive makes the functions in this library callable on the UD60x18 type.
using {
Math.avg,
Math.ceil,
Math.div,
Math.exp,
Math.exp2,
Math.floor,
Math.frac,
Math.gm,
Math.inv,
Math.ln,
Math.log10,
Math.log2,
Math.mul,
Math.pow,
Math.powu,
Math.sqrt
} for UD60x18 global;
/*//////////////////////////////////////////////////////////////////////////
HELPER FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
// The global "using for" directive makes the functions in this library callable on the UD60x18 type.
using {
Helpers.add,
Helpers.and,
Helpers.eq,
Helpers.gt,
Helpers.gte,
Helpers.isZero,
Helpers.lshift,
Helpers.lt,
Helpers.lte,
Helpers.mod,
Helpers.neq,
Helpers.not,
Helpers.or,
Helpers.rshift,
Helpers.sub,
Helpers.uncheckedAdd,
Helpers.uncheckedSub,
Helpers.xor
} for UD60x18 global;
/*//////////////////////////////////////////////////////////////////////////
OPERATORS
//////////////////////////////////////////////////////////////////////////*/
// The global "using for" directive makes it possible to use these operators on the UD60x18 type.
using {
Helpers.add as +,
Helpers.and2 as &,
Math.div as /,
Helpers.eq as ==,
Helpers.gt as >,
Helpers.gte as >=,
Helpers.lt as <,
Helpers.lte as <=,
Helpers.or as |,
Helpers.mod as %,
Math.mul as *,
Helpers.neq as !=,
Helpers.not as ~,
Helpers.sub as -,
Helpers.xor as ^
} for UD60x18 global;// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.20;
import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import { EnumerableSet } from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import "../base/BladeErrors.sol";
import { Signature, Deposit } from "../types/BladeTypes.sol";
import {Constants} from "../base/Constants.sol";
import { IBladeExchange } from "../interfaces/IBladeExchange.sol";
import { BladeSignatureLib } from "../libraries/BladeSignatureLib.sol";
abstract contract BladeCommonExchange is IBladeExchange, ERC20, ReentrancyGuard, Ownable {
using SafeERC20 for IERC20;
using EnumerableSet for EnumerableSet.AddressSet;
using SafeCast for uint256;
using SafeCast for int256;
uint256 constant ONE_IN_TEN_DECIMALS = 1e10;
uint256 constant ONE_IN_PRICE_DECIMALS = 1e8;
uint256 constant ONE_BASIS_POINT_IN_TEN_DECIMALS = 1e6;
address constant ETH_SIGIL = address(0);
uint256 constant MAXIMUM_FEE_WITHDRAWAL_IN_TEN_DECIMALS = ONE_IN_TEN_DECIMALS / 20;
uint256 constant MINIMUM_DURATION_BETWEEN_FEE_WITHDRAWAL = 7 days;
// Allow for inputs up to 0.5% more than quoted values to have scaled output.
// Inputs higher than this value just get 0.5% more.
uint256 constant MAX_ALLOWED_OVER_TEN_DECIMALS = ONE_IN_TEN_DECIMALS+50*ONE_BASIS_POINT_IN_TEN_DECIMALS;
// LP token price deviation in basis points
uint8 constant PRICE_TOLERANCE_IN_BPS = 10;
// Constant values for EIP-712 signing
string constant VERSION = "2.0.0";
string constant NAME = "Blade";
bytes32 immutable DOMAIN_SEPARATOR;
// Signer is passed in on construction, hence "immutable"
address immutable public DESIGNATED_SIGNER;
address immutable public WRAPPER_CONTRACT;
//uint256 public lastDaoWithdrawal;
uint256 public lastFeeWithdrawal;
// Halt market
address public triageRole;
bool private _marketHalted;
// Assets
// lastBalances: used for "transmit then swap then sync" modality
// assetSet is a set of keys that have lastBalances
mapping(address => uint256) public lastBalances;
mapping(address => uint8) tokenDecimals;
EnumerableSet.AddressSet assetSet;
// Allows lookup
mapping(address => Deposit) public vestingDeposits;
modifier marketIsRunning {
_requireMarketIsRunning();
_;
}
modifier OnlyTriage() {
_requireOnlyTriage();
_;
}
modifier validLockTime(uint256 lockTime) {
if (lockTime < 1) {
revert InvalidLockTime();
}
_;
}
modifier receivedInTime(uint256 goodUntil) {
if (goodUntil < block.timestamp) {
revert ExpiredMessage();
}
_;
}
modifier onlyTokenHolder(address tokenHolder) {
if (msg.sender != tokenHolder) {
revert UnauthorizedCaller();
}
_;
}
// Take in the designated signer address and the token list
constructor(
address theSigner,
address theWrapper,
address[] memory tokens,
address initialOwner
)
ERC20(tokenName(), tokenSymbol())
Ownable(initialOwner)
{
DESIGNATED_SIGNER = theSigner;
uint i;
uint n = tokens.length;
while(i < n) {
address token = tokens[i];
assetSet.add(token);
// Cache token decimals
uint8 decimals = IERC20Metadata(token).decimals();
if (decimals > 18) {
revert TokenDecimalsNotSupported();
}
tokenDecimals[token] = decimals;
i++;
}
DOMAIN_SEPARATOR = BladeSignatureLib.createDomainSeparator(NAME, VERSION, address(this));
WRAPPER_CONTRACT = theWrapper;
}
// Allows the receipt of ETH directly
receive() external payable {}
function _verifyDigestSignature(
bytes32 digest,
Signature memory sig
) internal view {
BladeSignatureLib.verifyDigestSignature(digest, sig, DESIGNATED_SIGNER);
}
function deposit(
address depositor,
uint256[] calldata depositAmounts,
uint256 lockTime,
uint256 poolTokens,
uint256 goodUntil,
Signature calldata theSignature,
bytes calldata extraData
) public payable virtual;
/*
Triage emergency functionality.
owner can set an address that has the ability to halt trade.
Only proportional withdrawals are allowed if trade is halted.
*/
function setTriageRole(address newTriage) external onlyOwner {
triageRole = newTriage;
emit TriageAddressChanged(newTriage);
}
function isTradeHalted() external view virtual returns (bool) {
return _marketHalted;
}
function stopTrade() external OnlyTriage {
_marketHalted = true;
emit MarketHalted(msg.sender);
}
function resumeTrade() external OnlyTriage {
_marketHalted = false;
emit MarketResumed(msg.sender);
}
function _requireOnlyTriage() private view {
if (msg.sender != triageRole) {
revert UnauthorizedCaller();
}
}
function _requireMarketIsRunning() private view {
if (_marketHalted) {
revert MarketTradeHalted();
}
}
function tokenName() internal pure virtual returns (string memory) {
return "Blade LP Token";
}
function tokenSymbol() internal pure virtual returns (string memory) {
return "BladeLP";
}
function safeEthSend(address recipient, uint256 howMuch) internal {
(bool success, ) = payable(recipient).call{value: howMuch}("");
if (!success) revert EthTransferFailed();
}
/* TOKEN AND ASSET FUNCTIONS */
function nTokens() public view returns (uint) {
return assetSet.length();
}
function tokenAt(uint i) public view returns (address) {
return assetSet.at(i);
}
function isToken(address token) public view returns (bool) {
return assetSet.contains(token);
}
function _sync(address token) internal virtual;
// Can be overridden
function getLastBalance(address token) public view virtual returns (uint256) {
return lastBalances[token];
}
function getTokenBalance(address token) internal view returns (uint256) {
return IERC20(token).balanceOf(address(this));
}
function allTokensBalance() external view returns (uint256[] memory, address[] memory, uint256) {
uint n = nTokens();
uint256[] memory balances = new uint256[](n);
address[] memory tokens = new address[](n);
for (uint i = 0; i < n; i++) {
address token = tokenAt(i);
balances[i] = getLastBalance(token);
tokens[i] = token;
}
return (balances, tokens, totalSupply());
}
function allTokensStateBalance() external view returns (uint256[] memory, address[] memory, uint256) {
uint n = nTokens();
uint256[] memory balances = new uint256[](n);
address[] memory tokens = new address[](n);
for (uint i = 0; i < n; i++) {
address token = tokenAt(i);
balances[i] = getTokenBalance(token);
tokens[i] = token;
}
return (balances, tokens, totalSupply());
}
function transmitAndDeposit(
uint256[] calldata depositAmounts,
uint256 lockTime,
uint256 poolTokens,
uint256 goodUntil,
Signature calldata theSignature,
bytes calldata extraData
)
external
marketIsRunning
{
uint i = 0;
uint n = depositAmounts.length;
while(i < n) {
uint256 transferAmount = depositAmounts[i];
if(transferAmount > 0){
IERC20(tokenAt(i)).safeTransferFrom(msg.sender, address(this), transferAmount);
}
i++;
}
deposit(msg.sender, depositAmounts, lockTime, poolTokens, goodUntil, theSignature, extraData);
}
/**
* @notice Verifies that the on-chain LP token price is within acceptable bounds of the provided reference price.
* @dev Uses external token prices (all with 18 decimals) to recompute the LP token price on-chain.
* If the deviation exceeds the predefined tolerance (in BPS), the transaction reverts.
* This protects against large valuation mismatches.
* @param lpTokenPrice The expected LP token price, computed off-chain and provided as reference. Must use 18 decimals.
* @param prices External token prices used to calculate the current on-chain LP token price. Each must use 18 decimals.
* @custom:conditions Skips verification if total LP token supply is zero.
*/
function _verifyLpTokenStatePool(
uint256 lpTokenPrice,
uint256[] memory prices
)
private view
{
uint256 lpTotalSupply = totalSupply();
if (lpTotalSupply == 0) {
return; // No validation needed on first deposit
}
if (lpTokenPrice == 0) {
revert InvalidLPTokenValue();
}
uint256 n = nTokens();
uint256 totalValue;
for (uint i = 0; i < n; ++i) {
address token = tokenAt(i);
uint256 decimalMultiplier = 10 ** (18 - tokenDecimals[token]);
uint256 tokenBalance = getTokenBalance(token) * decimalMultiplier;
uint256 tokenValue = (tokenBalance * prices[i]) / Constants.ONE_IN_DEFAULT_DECIMALS;
totalValue += tokenValue;
}
uint256 onChainLpTokenPrice = (totalValue * Constants.ONE_IN_DEFAULT_DECIMALS) / lpTotalSupply;
// Nothing to do if they match exactly
if (onChainLpTokenPrice == lpTokenPrice) {
return;
}
// Calculate how much deviation is allowed (referenceValue * toleranceBps / 10 000)
uint256 maxAllowedDeviation = (lpTokenPrice * Constants.PRICE_TOLERANCE_IN_BPS) / Constants.ONE_IN_BASIS_POINTS;
// Compute the absolute difference between actual and reference
uint256 absoluteDifference = onChainLpTokenPrice > lpTokenPrice
? onChainLpTokenPrice - lpTokenPrice
: lpTokenPrice - onChainLpTokenPrice;
// Revert if the difference exceeds the allowed tolerance
if (absoluteDifference > maxAllowedDeviation) {
revert PoolStateDeviation();
}
}
// nonReentrant asset transfer
function transferAsset(address token, address recipient, uint256 amount) internal nonReentrant {
IERC20(token).safeTransfer(recipient, amount);
// We never want to transfer an asset without sync'ing
_sync(token);
}
function calculateFairOutput(uint256 statedInput, uint256 actualInput, uint256 statedOutput) internal pure returns (uint256) {
if (actualInput == statedInput) {
return statedOutput;
} else {
uint256 theFraction = (ONE_IN_TEN_DECIMALS*actualInput)/statedInput;
if (theFraction >= MAX_ALLOWED_OVER_TEN_DECIMALS) {
return (MAX_ALLOWED_OVER_TEN_DECIMALS*statedOutput)/ONE_IN_TEN_DECIMALS;
} else {
return (theFraction*statedOutput)/ONE_IN_TEN_DECIMALS;
}
}
}
/* DEPOSIT FUNCTIONALITY */
function canUnlockDeposit(address depositor) public view returns (bool) {
Deposit storage myDeposit = vestingDeposits[depositor];
return (myDeposit.poolTokenAmount > 0) && (myDeposit.lockedUntil <= block.timestamp);
}
function unlockDeposit() external returns (uint256 poolTokens) {
if (!canUnlockDeposit(msg.sender)) {
revert UnlockDepositFailed();
}
poolTokens = vestingDeposits[msg.sender].poolTokenAmount;
delete vestingDeposits[msg.sender];
_transfer(address(this), msg.sender, poolTokens);
}
// Mints tokens to this contract to hold for vesting
function _createVestingDeposit(address depositor, uint256 lockTime, uint256 poolTokens) private {
if (lockTime < 1) {
revert InvalidLockTime();
}
if (vestingDeposits[depositor].poolTokenAmount != 0) {
revert ExistingVestingDeposit();
}
Deposit memory myDeposit = Deposit({
lockedUntil: block.timestamp + (lockTime * 1 minutes),
poolTokenAmount: poolTokens
});
vestingDeposits[depositor] = myDeposit;
_mint(address(this), poolTokens);
}
function takeFees(
uint256 entitledFeesInDollars,
uint256 averagePoolBalanceInDollars
)
external onlyOwner
{
// calculate fraction in base ten
uint256 theFraction = (ONE_IN_TEN_DECIMALS * entitledFeesInDollars) / averagePoolBalanceInDollars;
// Validates is less thant max allowed
if(theFraction > MAXIMUM_FEE_WITHDRAWAL_IN_TEN_DECIMALS) {
revert InvalidFeeSplitTooMuch();
}
// Validates withdrawal time
if(block.timestamp < lastFeeWithdrawal + MINIMUM_DURATION_BETWEEN_FEE_WITHDRAWAL) {
revert InvalidFeeSplitTooSoon();
}
lastFeeWithdrawal = block.timestamp;
// Calculates tokens to mint
uint256 tokensToMint = (theFraction * totalSupply()) / ONE_IN_TEN_DECIMALS;
_mint(msg.sender, tokensToMint);
emit FeesTaken(entitledFeesInDollars, averagePoolBalanceInDollars, tokensToMint);
}
function _decodeAndValidatePrices(bytes memory extraData)
private view
returns (uint256 lpTokenPrice, uint256[] memory prices)
{
// Decode extra data
(lpTokenPrice, prices) = abi.decode(extraData, (uint256, uint256[]));
uint256 n = nTokens();
if (prices.length != n) {
revert MismatchedArrayLengths();
}
}
function _depositChecks(
address depositor,
uint256[] memory depositAmounts,
uint256 lockTime,
uint256 poolTokens,
uint256 goodUntil,
Signature memory sig,
bytes memory extraData
)
internal view
returns (bytes32 digest)
{
uint n = nTokens();
if (n != depositAmounts.length) {
revert MismatchedArrayLengths();
}
// Decode extra data
(uint256 lpTokenPrice, uint256[] memory prices) = _decodeAndValidatePrices(extraData);
// Check the signature
digest = BladeSignatureLib.createDepositDigest(
DOMAIN_SEPARATOR,
depositor,
depositAmounts,
lockTime,
poolTokens,
goodUntil,
lpTokenPrice,
prices
);
// Verify signature
_verifyDigestSignature(digest, sig);
// Revert if the pool state has changed
_verifyLpTokenStatePool(lpTokenPrice, prices);
}
function _singleDepositChecks(
address depositor,
address inputToken,
uint256 inputAmount,
uint256 lockTime,
uint256 poolTokens,
uint256 goodUntil,
Signature memory sig,
bytes memory extraData
)
internal view
returns (bytes32 digest)
{
// Decode extra data
(uint256 lpTokenPrice, uint256[] memory prices) = _decodeAndValidatePrices(extraData);
// Check the signature
digest = BladeSignatureLib.createSingleDepositDigest(
DOMAIN_SEPARATOR,
depositor,
inputToken,
inputAmount,
lockTime,
poolTokens,
goodUntil,
lpTokenPrice,
prices
);
// Verify signature
_verifyDigestSignature(digest, sig);
// Revert if the pool state has changed
_verifyLpTokenStatePool(lpTokenPrice, prices);
}
function _singleWithdrawChecks(
address tokenHolder,
uint256 poolTokenAmountToBurn,
address assetAddress,
uint256 assetAmount,
uint256 goodUntil,
Signature calldata sig,
bytes calldata extraData
)
internal view
returns (bytes32 digest)
{
// Decode extra data
(uint256 lpTokenPrice, uint256[] memory prices) = _decodeAndValidatePrices(extraData);
// Check the signature
digest = BladeSignatureLib.createWithdrawalDigest(
DOMAIN_SEPARATOR,
tokenHolder,
poolTokenAmountToBurn,
assetAddress,
assetAmount,
goodUntil,
lpTokenPrice,
prices
);
// Revert if it's signed by the wrong address
// Revert if it's a replay, or if the timestamp is too late
_verifyDigestSignature(digest, sig);
// Revert if the pool state has changed
_verifyLpTokenStatePool(lpTokenPrice, prices);
}
function _finalizeDeposit(
address depositor,
uint256 lockTime,
uint256 poolTokens
)
internal
{
_createVestingDeposit(depositor, lockTime, poolTokens);
emit Deposited(depositor, poolTokens, lockTime);
}
/* WITHDRAWAL FUNCTIONALITY */
function _proportionalWithdrawal(uint256 myFraction) private {
uint256 toTransfer;
uint i;
uint n = nTokens();
while(i < n) {
address theToken = tokenAt(i);
toTransfer = (myFraction * getLastBalance(theToken)) / ONE_IN_TEN_DECIMALS;
// syncs done automatically on transfer
transferAsset(theToken, msg.sender, toTransfer);
i++;
}
}
function burnToWithdraw(uint256 amount) external {
// Capture the fraction first, before burning
uint256 theFractionBaseTen = (ONE_IN_TEN_DECIMALS * amount) / totalSupply();
// Reverts if balance is insufficient
_burn(msg.sender, amount);
_proportionalWithdrawal(theFractionBaseTen);
emit Withdrawn(msg.sender, amount, theFractionBaseTen);
}
function _verifySwapSignature(
address inputToken,
address outputToken,
uint256 inputAmount,
uint256 outputAmount,
uint256 goodUntil,
address destinationAddress,
Signature memory sig
)
internal view
returns (bytes32 digest)
{
digest = BladeSignatureLib.createSwapDigest(
DOMAIN_SEPARATOR,
inputToken,
outputToken,
inputAmount,
outputAmount,
goodUntil,
destinationAddress
);
_verifyDigestSignature(digest, sig);
}
function _wrapMsgValue() internal {
if (msg.value > 0) {
safeEthSend(WRAPPER_CONTRACT, msg.value);
}
}
}// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.20; error InvariantCheckFailed(); error InsufficientInput(); error InvalidFeeSplitTooMuch(); error InvalidFeeSplitTooSoon(); error InvalidLockTime(); error PoolStateDeviation(); error MarketTradeHalted(); error MismatchedArrayLengths(); error UnauthorizedCaller(); error ExistingVestingDeposit(); error UnlockDepositFailed(); error ExpiredMessage(); error EthTransferFailed(); error TokenNotInPool(); error InvalidLPTokenValue(); error TokenDecimalsNotSupported();
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.20;
library Constants {
uint256 constant ONE_IN_BASIS_POINTS = 10000;
uint8 constant PRICE_TOLERANCE_IN_BPS = 10;
uint256 constant ONE_IN_DEFAULT_DECIMALS = 1e18;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { Signature } from "../types/BladeTypes.sol";
/// @title Blade Exchange Interface
/// @notice Shared interface for all Blade exchange implementations
interface IBladeExchange {
event Swapped(
address indexed inAsset,
address indexed outAsset,
address indexed recipient,
uint256 inAmount,
uint256 outAmount,
bytes auxiliaryData
);
event Deposited(
address indexed depositor,
uint256 poolTokens,
uint256 lockTime
);
event Withdrawn(
address indexed withdrawer,
uint256 poolTokens,
uint256 fractionOfPool
);
event AssetWithdrawn(
address indexed withdrawer,
uint256 poolTokens,
address indexed assetAddress,
uint256 assetAmount
);
event FeesTaken(
uint256 entitledFeesInDollars,
uint256 averagePoolBalanceInDollars,
uint256 tokensTransferred
);
event TriageAddressChanged(address indexed newAddress);
event MarketHalted(address indexed by);
event MarketResumed(address indexed by);
function WRAPPER_CONTRACT() external view returns (address);
function tokenAt(uint index) external view returns (address);
function nTokens() external view returns (uint);
function isToken(address token) external view returns (bool);
function burnToWithdraw(uint256 amount) external;
function sellEthForToken(
address outputToken,
uint256 inputAmount,
uint256 outputAmount,
uint256 goodUntil,
address destinationAddress,
Signature calldata theSignature,
bytes calldata auxiliaryData
) external payable;
function sellTokenForEth(
address inputToken,
uint256 inputAmount,
uint256 outputAmount,
uint256 goodUntil,
address destinationAddress,
Signature calldata theSignature,
bytes calldata auxiliaryData
) external;
function transmitAndSellTokenForEth(
address inputToken,
uint256 inputAmount,
uint256 outputAmount,
uint256 goodUntil,
address destinationAddress,
Signature calldata theSignature,
bytes calldata auxiliaryData
) external;
function transmitAndSwap(
address inputToken,
address outputToken,
uint256 inputAmount,
uint256 outputAmount,
uint256 goodUntil,
address destinationAddress,
Signature calldata theSignature,
bytes calldata auxiliaryData
) external;
function swap(
address inputToken,
address outputToken,
uint256 inputAmount,
uint256 outputAmount,
uint256 goodUntil,
address destinationAddress,
Signature calldata theSignature,
bytes calldata auxiliaryData
) external;
function transmitAndDepositSingleAsset(
address inputToken,
uint256 inputAmount,
uint256 lockTime,
uint256 poolTokens,
uint256 goodUntil,
Signature calldata theSignature,
bytes calldata extraData
) external;
function deposit(
address depositor,
uint256[] calldata depositAmounts,
uint256 lockTime,
uint256 poolTokens,
uint256 goodUntil,
Signature calldata theSignature,
bytes calldata extraData
) external payable;
function depositSingleAsset(
address depositor,
address inputToken,
uint256 inputAmount,
uint256 lockTime,
uint256 poolTokens,
uint256 goodUntil,
Signature calldata theSignature,
bytes calldata extraData
) external payable;
function withdrawSingleAsset(
address tokenHolder,
uint256 poolTokenAmountToBurn,
address assetAddress,
uint256 assetAmount,
uint256 goodUntil,
Signature calldata theSignature,
bytes calldata extraData
) external;
}// SPDX-License-Identifier: UNLICENSED
// Copyright 2023 Shipyard Software, Inc.
pragma solidity ^0.8.20;
interface WrapperContractInterface {
function withdraw(uint256 amount) external;
}// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.20;
import {MessageHashUtils} from "@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol";
import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {Signature} from "../types/BladeTypes.sol";
library BladeSignatureLib {
error SignatureValidation();
bytes32 internal constant EIP712DOMAIN_TYPEHASH =
keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
bytes32 internal constant OFFERSTRUCT_TYPEHASH =
keccak256(
abi.encodePacked(
"OfferStruct(address input_token,address output_token,uint256 input_amount,uint256 output_amount,uint256 good_until,address destination_address)"
)
);
bytes32 internal constant DEPOSITSTRUCT_TYPEHASH =
keccak256(
abi.encodePacked(
"DepositStruct(address depositor,uint256[] deposit_amounts,uint256 lock_time,uint256 pool_tokens,uint256 good_until,uint256 lp_token_price,uint256[] prices)"
)
);
bytes32 internal constant SINGLEDEPOSITSTRUCT_TYPEHASH =
keccak256(
abi.encodePacked(
"SingleDepositStruct(address depositor,address token,uint256 amount,uint256 lock_time,uint256 pool_tokens,uint256 good_until,uint256 lp_token_price,uint256[] prices)"
)
);
bytes32 internal constant WITHDRAWALSTRUCT_TYPEHASH =
keccak256(
abi.encodePacked(
"WithdrawalStruct(address token_holder,uint256 pool_token_amount_to_burn,address asset_address,uint256 asset_amount,uint256 good_until,uint256 lp_token_price,uint256[] prices)"
)
);
function createDomainSeparator(
string memory name,
string memory version,
address theSigner
)
internal view
returns (bytes32)
{
return
keccak256(
abi.encode(
EIP712DOMAIN_TYPEHASH,
keccak256(abi.encodePacked(name)),
keccak256(abi.encodePacked(version)),
uint256(block.chainid),
theSigner
)
);
}
function hashInputOffer(
address inputToken,
address outputToken,
uint256 inputAmount,
uint256 outputAmount,
uint256 goodUntil,
address destinationAddress
)
internal pure
returns (bytes32)
{
return
keccak256(
abi.encode(
OFFERSTRUCT_TYPEHASH,
inputToken,
outputToken,
inputAmount,
outputAmount,
goodUntil,
destinationAddress
)
);
}
function hashDeposit(
address depositor,
uint256[] memory depositAmounts,
uint256 minutesLocked,
uint256 poolTokens,
uint256 goodUntil,
uint256 lpTokenPrice,
uint256[] memory prices
)
internal pure
returns (bytes32)
{
bytes32 depositAmountsHash = keccak256(
abi.encodePacked(depositAmounts)
);
bytes32 pricesHash = keccak256(abi.encodePacked(prices));
return
keccak256(
abi.encode(
DEPOSITSTRUCT_TYPEHASH,
depositor,
depositAmountsHash,
minutesLocked,
poolTokens,
goodUntil,
lpTokenPrice,
pricesHash
)
);
}
function hashSingleDeposit(
address depositor,
address inputToken,
uint256 inputAmount,
uint256 minutesLocked,
uint256 poolTokens,
uint256 goodUntil,
uint256 lpTokenPrice,
uint256[] memory prices
)
internal pure
returns (bytes32)
{
bytes32 pricesHash = keccak256(abi.encodePacked(prices));
return
keccak256(
abi.encode(
SINGLEDEPOSITSTRUCT_TYPEHASH,
depositor,
inputToken,
inputAmount,
minutesLocked,
poolTokens,
goodUntil,
lpTokenPrice,
pricesHash
)
);
}
function hashWithdrawal(
address tokenHolder,
uint256 poolTokenAmountToBurn,
address assetAddress,
uint256 assetAmount,
uint256 goodUntil,
uint256 lpTokenPrice,
uint256[] memory prices
)
internal pure
returns (bytes32)
{
bytes32 pricesHash = keccak256(abi.encodePacked(prices));
return
keccak256(
abi.encode(
WITHDRAWALSTRUCT_TYPEHASH,
tokenHolder,
poolTokenAmountToBurn,
assetAddress,
assetAmount,
goodUntil,
lpTokenPrice,
pricesHash
)
);
}
function createSwapDigest(
bytes32 domainSeparator,
address inputToken,
address outputToken,
uint256 inputAmount,
uint256 outputAmount,
uint256 goodUntil,
address destinationAddress
)
internal pure
returns (bytes32 digest)
{
bytes32 hashedInput = hashInputOffer(
inputToken,
outputToken,
inputAmount,
outputAmount,
goodUntil,
destinationAddress
);
digest = MessageHashUtils.toTypedDataHash(domainSeparator, hashedInput);
}
function createDepositDigest(
bytes32 domainSeparator,
address depositor,
uint256[] memory depositAmounts,
uint256 lockTime,
uint256 poolTokens,
uint256 goodUntil,
uint256 lpTokenPrice,
uint256[] memory prices
)
internal pure
returns (bytes32 depositDigest)
{
bytes32 hashedInput = hashDeposit(
depositor,
depositAmounts,
lockTime,
poolTokens,
goodUntil,
lpTokenPrice,
prices
);
depositDigest = MessageHashUtils.toTypedDataHash(
domainSeparator,
hashedInput
);
}
function createSingleDepositDigest(
bytes32 domainSeparator,
address depositor,
address inputToken,
uint256 inputAmount,
uint256 lockTime,
uint256 poolTokens,
uint256 goodUntil,
uint256 lpTokenPrice,
uint256[] memory prices
)
internal pure
returns (bytes32 depositDigest)
{
bytes32 hashedInput = hashSingleDeposit(
depositor,
inputToken,
inputAmount,
lockTime,
poolTokens,
goodUntil,
lpTokenPrice,
prices
);
depositDigest = MessageHashUtils.toTypedDataHash(
domainSeparator,
hashedInput
);
}
function createWithdrawalDigest(
bytes32 domainSeparator,
address tokenHolder,
uint256 poolTokenAmountToBurn,
address assetAddress,
uint256 assetAmount,
uint256 goodUntil,
uint256 lpTokenPrice,
uint256[] memory prices
)
internal pure
returns (bytes32 withdrawalDigest)
{
bytes32 hashedInput = hashWithdrawal(
tokenHolder,
poolTokenAmountToBurn,
assetAddress,
assetAmount,
goodUntil,
lpTokenPrice,
prices
);
withdrawalDigest = MessageHashUtils.toTypedDataHash(
domainSeparator,
hashedInput
);
}
function verifyDigestSignature(
bytes32 digest,
Signature memory sig,
address expectedSigner
)
internal view
{
address signer = ECDSA.recover(digest, sig.v, sig.r, sig.s);
if (signer != expectedSigner) {
// Check for signing with embedded tx.origin
signer = ECDSA.recover(
keccak256(abi.encodePacked(digest, tx.origin)),
sig.v,
sig.r,
sig.s
);
if (signer != expectedSigner) {
revert SignatureValidation();
}
}
}
}// SPDX-License-Identifier: UNLICENSED
// Copyright 2024 Shipyard Software, Inc.
pragma solidity ^0.8.20;
import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol";
// solhint-disable-next-line interface-starts-with-i
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function latestRoundData()
external
view
returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
}
library SafeAggregatorInterface {
using SafeCast for int256;
error OracleStalePrice();
// Returns the latest price from the oracle as a uint256, reverting if invalid or older than minimumTime
function safeUnsignedLatest(address oracle, uint256 minimumTime) internal view returns (uint256) {
(uint80 roundId, int256 answer, , uint256 updatedAt, uint80 answeredInRound) = AggregatorV3Interface(oracle).latestRoundData();
if (roundId != answeredInRound || updatedAt + minimumTime <= block.timestamp) {
revert OracleStalePrice();
}
return answer.toUint256();
}
}// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.20;
struct Signature {
uint8 v;
bytes32 r;
bytes32 s;
}
struct Deposit {
uint lockedUntil;
uint256 poolTokenAmount;
}
struct UtilStruct {
uint256 qX;
uint256 qY;
uint256 decimalMultiplierX;
uint256 decimalMultiplierY;
}// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.20;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import "../base/BladeErrors.sol";
import {Constants} from "../base/Constants.sol";
import {UtilStruct} from "../types/BladeTypes.sol";
import {SafeAggregatorInterface, AggregatorV3Interface} from "../libraries/SafeAggregatorInterface.sol";
abstract contract OracleManager is Ownable {
using SafeERC20 for IERC20;
using SafeCast for uint256;
using SafeCast for int256;
struct OracleInfo {
address oracleAddress;
uint256 minTimeTolerance;
uint8 decimals;
}
address public sequencerUptimeFeed;
uint256 private constant GRACE_PERIOD_TIME = 3600;
mapping(address => OracleInfo) oracles;
uint8 constant ORACLE_TOLERANCE_IN_BPS = 200; // 2% tolerance in basis points;
uint8 constant LP_VALUE_TOLERANCE_IN_BPS = 20; // 0.2 %;
event OracleAdded(
address indexed token,
address oracleAddress,
uint256 minTimeTolerance
);
event OracleRemoved(address indexed token);
event SequencerUptimeFeedAdded(
address sequencerUptimeFeed
);
error OracleSwapDeviation();
error OracleValueDeviation();
error OracleNotSet();
error InvalidOracle();
error InvalidSequencerFeed();
error SequencerDown();
error GracePeriodNotOver();
constructor(
address[] memory tokens,
address[] memory _oracles,
uint256[] memory minTimeTolerances
)
{
if (_oracles.length > 0) {
if (
tokens.length != _oracles.length ||
tokens.length != minTimeTolerances.length
) {
revert MismatchedArrayLengths();
}
for (uint i = 0; i < tokens.length; i++) {
oracles[tokens[i]] = OracleInfo({
oracleAddress: _oracles[i],
minTimeTolerance: minTimeTolerances[i],
decimals: AggregatorV3Interface(_oracles[i]).decimals()
});
}
}
}
function _isToken(address token) internal view virtual returns (bool);
function _nTokens() internal view virtual returns (uint);
function _tokenAt(uint index) internal view virtual returns (address);
function _getLastBalance(address token) internal view virtual returns (uint256);
function _getTokenDecimals(address token) internal view virtual returns (uint8);
/// @notice Set or update the Chainlink sequencer uptime feed
function setSequencerUptimeFeed(
address feedAddress
)
external
onlyOwner
{
_validateFeedAddress(feedAddress);
sequencerUptimeFeed = feedAddress;
emit SequencerUptimeFeedAdded(feedAddress);
}
/// @notice Validates that the feed implements latestRoundData
function _validateFeedAddress(address feed) internal view {
if (feed == address(0)) revert InvalidSequencerFeed();
// Try-catch to ensure interface call does not revert
try AggregatorV3Interface(feed).latestRoundData() returns (
uint80, int256, uint256, uint256, uint80
) {
// pass
} catch {
revert InvalidSequencerFeed();
}
}
/// @notice Validate that the sequencer is up and grace period has passed
function _enforceSequencerIsUp() internal view {
if (sequencerUptimeFeed == address(0)) {
// No sequencer feed set, skip validation
return;
}
// prettier-ignore
(
/*uint80 roundID*/,
int256 answer,
uint256 startedAt,
/*uint256 updatedAt*/,
/*uint80 answeredInRound*/
) = AggregatorV3Interface(sequencerUptimeFeed).latestRoundData();
// Answer == 0: Sequencer is up
// Answer == 1: Sequencer is down
if (answer != 0) {
revert SequencerDown();
}
// Make sure the grace period has passed after the
// sequencer is back up.
uint256 timeSinceUp = block.timestamp - startedAt;
if (timeSinceUp <= GRACE_PERIOD_TIME) {
revert GracePeriodNotOver();
}
}
function addOracle(
address token,
address oracleAddress,
uint256 minTimeTolerance
)
external
onlyOwner
{
if (minTimeTolerance <= 0) {
revert InvalidOracle();
}
if (!_isToken(token)) {
revert TokenNotInPool();
}
uint256 latestPrice = SafeAggregatorInterface.safeUnsignedLatest(
oracleAddress,
minTimeTolerance
);
if (latestPrice <= 0) {
revert InvalidOracle();
}
oracles[token] = OracleInfo({
oracleAddress: oracleAddress,
minTimeTolerance: minTimeTolerance,
decimals: AggregatorV3Interface(oracleAddress).decimals()
});
emit OracleAdded(token, oracleAddress, minTimeTolerance);
}
function removeOracle(address token) external onlyOwner {
if (oracles[token].oracleAddress == address(0)) {
revert OracleNotSet();
}
delete oracles[token];
emit OracleRemoved(token);
}
/**
* @notice Returns the USD value of a given token amount using the current oracle price.
* @dev Prices must use 18 decimals. Token amounts are normalized to 18 decimals before multiplying by price.
* @param inputToken The address of the token to value.
* @param inputAmount The amount of the token, using its native decimals.
* @return The USD value of the token amount, using 18 decimals.
*/
function _getAssetAmountUsdValue(
address inputToken,
uint256 inputAmount
)
internal view
returns (uint256)
{
(uint256 inputPrice, uint8 priceDecimals) = currentOraclePriceWithDecimals(inputToken);
uint256 tokenMultiplier = 10 ** (18 - _getTokenDecimals(inputToken));
uint256 normalizedAmount = inputAmount * tokenMultiplier;
// Normalize to 18 decimals and calculate the deposit value
uint256 usdValue = (normalizedAmount * inputPrice) / (10 ** priceDecimals);
return usdValue;
}
/**
* @notice Calculates the current LP token price and total pool value using oracle prices.
* @dev If no LP tokens exist yet, returns a base price. Prices must use 18 decimals.
* @return lpPrice The LP token price in USD using 18 decimals.
*/
function _getLpTokenPrice(uint256 _totalSupply) internal view returns (uint256 lpPrice) {
uint256 n = _nTokens();
uint256 totalValue;
for (uint i = 0; i < n; ++i) {
address token = _tokenAt(i);
totalValue += _getAssetAmountUsdValue(token, _getLastBalance(token));
}
if (_totalSupply > 0) {
lpPrice = (totalValue * Constants.ONE_IN_DEFAULT_DECIMALS) / _totalSupply;
} else {
lpPrice = Constants.ONE_IN_DEFAULT_DECIMALS;
}
}
/**
* @notice Reverts if the actual value exceeds the reference value plus allowed tolerance.
* @param actualValue The actual USD value (e.g., LP tokens).
* @param referenceValue The expected USD value (e.g., tokens deposit).
*/
function _revertIfDeviationTooHigh(uint256 actualValue, uint256 referenceValue) internal pure {
uint256 tolerance = (referenceValue * LP_VALUE_TOLERANCE_IN_BPS) /
Constants.ONE_IN_BASIS_POINTS;
if (actualValue > referenceValue + tolerance) {
revert OracleValueDeviation();
}
}
/**
* @notice Returns the oracle address and minimum time tolerance for a given token.
* @param token The token address.
* @return oracleAddress The Chainlink oracle contract for this token.
* @return minTimeTolerance The required minimum freshness in seconds for the price feed.
*/
function getOracleInfo(
address token
)
public view
returns (
address oracleAddress,
uint256 minTimeTolerance
)
{
OracleInfo memory info = oracles[token];
return (info.oracleAddress, info.minTimeTolerance);
}
/**
* @notice Returns the latest oracle price and its decimals for a given token.
* @dev The price must be scaled to 18 decimals before use in calculations.
* @param token The token to fetch the oracle price for.
* @return price The current token price from the oracle.
* @return decimals The number of decimals used by the price feed.
*/
function currentOraclePriceWithDecimals(
address token
)
internal view
returns (
uint256 price,
uint8 decimals
)
{
_enforceSequencerIsUp();
OracleInfo memory info = oracles[token];
price = SafeAggregatorInterface.safeUnsignedLatest(
info.oracleAddress,
info.minTimeTolerance
);
decimals = info.decimals;
}
/**
* @notice Validates that an output amount falls within acceptable range of the fair price based on oracles.
* @dev Uses current oracle prices and token decimals to compute an expected fair output amount,
* then applies a tolerance defined by `ORACLE_TOLERANCE_IN_BPS`.
* @param inputAmount The input token amount used for the swap.
* @param outputAmount The actual output token amount being validated.
* @param inputToken The token address of the input.
* @param outputToken The token address of the output.
* @custom:reverts Reverts if the output amount exceeds the upper bound of the expected amount.
*/
function validatePrice(
uint256 inputAmount,
uint256 outputAmount,
address inputToken,
address outputToken
)
internal view
{
(
uint256 inputPrice,
uint8 inputPriceDecimals
) = currentOraclePriceWithDecimals(inputToken);
(
uint256 outputPrice,
uint8 outputPriceDecimals
) = currentOraclePriceWithDecimals(outputToken);
UtilStruct memory s;
s.decimalMultiplierX = 10 ** (18 - _getTokenDecimals(inputToken));
s.decimalMultiplierY = 10 ** (18 - _getTokenDecimals(outputToken));
s.qX = inputAmount * s.decimalMultiplierX;
// Normalize prices to 18 decimals
uint256 inputPriceNorm = inputPrice * (10 ** (18 - inputPriceDecimals));
uint256 outputPriceNorm = outputPrice * (10 ** (18 - outputPriceDecimals));
uint256 oracleFairOutputAmount = ((s.qX * inputPriceNorm) / outputPriceNorm) / s.decimalMultiplierY;
uint256 upperBound = oracleFairOutputAmount * (Constants.ONE_IN_BASIS_POINTS + ORACLE_TOLERANCE_IN_BPS) / Constants.ONE_IN_BASIS_POINTS;
if (outputAmount > upperBound) {
revert OracleSwapDeviation();
}
}
function _areAllOraclesSet() internal view returns (bool) {
uint256 n = _nTokens();
for (uint256 i = 0; i < n; ++i) {
if (oracles[_tokenAt(i)].oracleAddress == address(0)) {
return false;
}
}
return true;
}
}{
"optimizer": {
"enabled": true,
"runs": 1000
},
"evmVersion": "cancun",
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"metadata": {
"useLiteralContent": true
}
}Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
Contract ABI
API[{"inputs":[{"internalType":"address","name":"theSigner","type":"address"},{"internalType":"address","name":"theWrapper","type":"address"},{"internalType":"address[]","name":"tokens","type":"address[]"},{"internalType":"address[]","name":"_oracles","type":"address[]"},{"internalType":"uint256[]","name":"minTimeTolerances","type":"uint256[]"},{"internalType":"address","name":"initialOwner","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"DigestAlreadyUsed","type":"error"},{"inputs":[],"name":"ECDSAInvalidSignature","type":"error"},{"inputs":[{"internalType":"uint256","name":"length","type":"uint256"}],"name":"ECDSAInvalidSignatureLength","type":"error"},{"inputs":[{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"ECDSAInvalidSignatureS","type":"error"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"allowance","type":"uint256"},{"internalType":"uint256","name":"needed","type":"uint256"}],"name":"ERC20InsufficientAllowance","type":"error"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"uint256","name":"balance","type":"uint256"},{"internalType":"uint256","name":"needed","type":"uint256"}],"name":"ERC20InsufficientBalance","type":"error"},{"inputs":[{"internalType":"address","name":"approver","type":"address"}],"name":"ERC20InvalidApprover","type":"error"},{"inputs":[{"internalType":"address","name":"receiver","type":"address"}],"name":"ERC20InvalidReceiver","type":"error"},{"inputs":[{"internalType":"address","name":"sender","type":"address"}],"name":"ERC20InvalidSender","type":"error"},{"inputs":[{"internalType":"address","name":"spender","type":"address"}],"name":"ERC20InvalidSpender","type":"error"},{"inputs":[],"name":"EthTransferFailed","type":"error"},{"inputs":[],"name":"ExistingVestingDeposit","type":"error"},{"inputs":[],"name":"ExpiredMessage","type":"error"},{"inputs":[],"name":"GracePeriodNotOver","type":"error"},{"inputs":[],"name":"InsufficientInput","type":"error"},{"inputs":[],"name":"InvalidFeeSplitTooMuch","type":"error"},{"inputs":[],"name":"InvalidFeeSplitTooSoon","type":"error"},{"inputs":[],"name":"InvalidLPTokenValue","type":"error"},{"inputs":[],"name":"InvalidLockTime","type":"error"},{"inputs":[],"name":"InvalidOracle","type":"error"},{"inputs":[],"name":"InvalidSequencerFeed","type":"error"},{"inputs":[],"name":"InvariantCheckFailed","type":"error"},{"inputs":[],"name":"MarketTradeHalted","type":"error"},{"inputs":[],"name":"MismatchedArrayLengths","type":"error"},{"inputs":[],"name":"OracleNotSet","type":"error"},{"inputs":[],"name":"OracleStalePrice","type":"error"},{"inputs":[],"name":"OracleSwapDeviation","type":"error"},{"inputs":[],"name":"OracleValueDeviation","type":"error"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"OwnableInvalidOwner","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"OwnableUnauthorizedAccount","type":"error"},{"inputs":[{"internalType":"uint256","name":"x","type":"uint256"},{"internalType":"uint256","name":"y","type":"uint256"}],"name":"PRBMath_MulDiv18_Overflow","type":"error"},{"inputs":[{"internalType":"uint256","name":"x","type":"uint256"},{"internalType":"uint256","name":"y","type":"uint256"},{"internalType":"uint256","name":"denominator","type":"uint256"}],"name":"PRBMath_MulDiv_Overflow","type":"error"},{"inputs":[],"name":"PRBMath_SD59x18_Div_InputTooSmall","type":"error"},{"inputs":[{"internalType":"SD59x18","name":"x","type":"int256"},{"internalType":"SD59x18","name":"y","type":"int256"}],"name":"PRBMath_SD59x18_Div_Overflow","type":"error"},{"inputs":[{"internalType":"SD59x18","name":"x","type":"int256"}],"name":"PRBMath_SD59x18_Exp2_InputTooBig","type":"error"},{"inputs":[{"internalType":"SD59x18","name":"x","type":"int256"}],"name":"PRBMath_SD59x18_Log_InputTooSmall","type":"error"},{"inputs":[],"name":"PRBMath_SD59x18_Mul_InputTooSmall","type":"error"},{"inputs":[{"internalType":"SD59x18","name":"x","type":"int256"},{"internalType":"SD59x18","name":"y","type":"int256"}],"name":"PRBMath_SD59x18_Mul_Overflow","type":"error"},{"inputs":[],"name":"PoolStateDeviation","type":"error"},{"inputs":[],"name":"ReentrancyGuardReentrantCall","type":"error"},{"inputs":[{"internalType":"int256","name":"value","type":"int256"}],"name":"SafeCastOverflowedIntToUint","type":"error"},{"inputs":[{"internalType":"uint256","name":"value","type":"uint256"}],"name":"SafeCastOverflowedUintToInt","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"inputs":[],"name":"SequencerDown","type":"error"},{"inputs":[],"name":"SignatureValidation","type":"error"},{"inputs":[],"name":"TokenDecimalsNotSupported","type":"error"},{"inputs":[],"name":"TokenNotInPool","type":"error"},{"inputs":[],"name":"UnauthorizedCaller","type":"error"},{"inputs":[],"name":"UnlockDepositFailed","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"withdrawer","type":"address"},{"indexed":false,"internalType":"uint256","name":"poolTokens","type":"uint256"},{"indexed":true,"internalType":"address","name":"assetAddress","type":"address"},{"indexed":false,"internalType":"uint256","name":"assetAmount","type":"uint256"}],"name":"AssetWithdrawn","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"depositor","type":"address"},{"indexed":false,"internalType":"uint256","name":"poolTokens","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"lockTime","type":"uint256"}],"name":"Deposited","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"entitledFeesInDollars","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"averagePoolBalanceInDollars","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"tokensTransferred","type":"uint256"}],"name":"FeesTaken","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"by","type":"address"}],"name":"MarketHalted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"by","type":"address"}],"name":"MarketResumed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"address","name":"oracleAddress","type":"address"},{"indexed":false,"internalType":"uint256","name":"minTimeTolerance","type":"uint256"}],"name":"OracleAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"}],"name":"OracleRemoved","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"sequencerUptimeFeed","type":"address"}],"name":"SequencerUptimeFeedAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"inAsset","type":"address"},{"indexed":true,"internalType":"address","name":"outAsset","type":"address"},{"indexed":true,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"inAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"outAmount","type":"uint256"},{"indexed":false,"internalType":"bytes","name":"auxiliaryData","type":"bytes"}],"name":"Swapped","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"newAddress","type":"address"}],"name":"TriageAddressChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"withdrawer","type":"address"},{"indexed":false,"internalType":"uint256","name":"poolTokens","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"fractionOfPool","type":"uint256"}],"name":"Withdrawn","type":"event"},{"inputs":[],"name":"DESIGNATED_SIGNER","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"WRAPPER_CONTRACT","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"address","name":"oracleAddress","type":"address"},{"internalType":"uint256","name":"minTimeTolerance","type":"uint256"}],"name":"addOracle","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"allTokensBalance","outputs":[{"internalType":"uint256[]","name":"","type":"uint256[]"},{"internalType":"address[]","name":"","type":"address[]"},{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"allTokensStateBalance","outputs":[{"internalType":"uint256[]","name":"","type":"uint256[]"},{"internalType":"address[]","name":"","type":"address[]"},{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"burnToWithdraw","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"depositor","type":"address"}],"name":"canUnlockDeposit","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"depositor","type":"address"},{"internalType":"uint256[]","name":"depositAmounts","type":"uint256[]"},{"internalType":"uint256","name":"lockTime","type":"uint256"},{"internalType":"uint256","name":"poolTokens","type":"uint256"},{"internalType":"uint256","name":"goodUntil","type":"uint256"},{"components":[{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"internalType":"struct Signature","name":"theSignature","type":"tuple"},{"internalType":"bytes","name":"extraData","type":"bytes"}],"name":"deposit","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"depositor","type":"address"},{"internalType":"address","name":"inputToken","type":"address"},{"internalType":"uint256","name":"inputAmount","type":"uint256"},{"internalType":"uint256","name":"lockTime","type":"uint256"},{"internalType":"uint256","name":"poolTokens","type":"uint256"},{"internalType":"uint256","name":"goodUntil","type":"uint256"},{"components":[{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"internalType":"struct Signature","name":"theSignature","type":"tuple"},{"internalType":"bytes","name":"extraData","type":"bytes"}],"name":"depositSingleAsset","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"getLastBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"getOracleInfo","outputs":[{"internalType":"address","name":"oracleAddress","type":"address"},{"internalType":"uint256","name":"minTimeTolerance","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"isToken","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"isTradeHalted","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"lastBalances","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lastFeeWithdrawal","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"nTokens","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"packedInput","type":"uint256"},{"internalType":"uint256","name":"packedOutput","type":"uint256"},{"internalType":"uint256","name":"packedGoodUntil","type":"uint256"},{"internalType":"bytes32","name":"auxData","type":"bytes32"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"vs","type":"bytes32"}],"name":"packedSwap","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"packedInput","type":"uint256"},{"internalType":"uint256","name":"packedConfig","type":"uint256"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"},{"internalType":"bytes","name":"extraData","type":"bytes"}],"name":"packedTransmitAndDepositSingleAsset","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"packedInput","type":"uint256"},{"internalType":"uint256","name":"packedOutput","type":"uint256"},{"internalType":"uint256","name":"packedGoodUntil","type":"uint256"},{"internalType":"bytes32","name":"auxData","type":"bytes32"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"vs","type":"bytes32"}],"name":"packedTransmitAndSwap","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"removeOracle","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"resumeTrade","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"outputToken","type":"address"},{"internalType":"uint256","name":"inputAmount","type":"uint256"},{"internalType":"uint256","name":"outputAmount","type":"uint256"},{"internalType":"uint256","name":"goodUntil","type":"uint256"},{"internalType":"address","name":"destinationAddress","type":"address"},{"components":[{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"internalType":"struct Signature","name":"theSignature","type":"tuple"},{"internalType":"bytes","name":"auxiliaryData","type":"bytes"}],"name":"sellEthForToken","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"inputToken","type":"address"},{"internalType":"uint256","name":"inputAmount","type":"uint256"},{"internalType":"uint256","name":"outputAmount","type":"uint256"},{"internalType":"uint256","name":"goodUntil","type":"uint256"},{"internalType":"address","name":"destinationAddress","type":"address"},{"components":[{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"internalType":"struct Signature","name":"theSignature","type":"tuple"},{"internalType":"bytes","name":"auxiliaryData","type":"bytes"}],"name":"sellTokenForEth","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"sequencerUptimeFeed","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"feedAddress","type":"address"}],"name":"setSequencerUptimeFeed","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newTriage","type":"address"}],"name":"setTriageRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"stopTrade","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"inputToken","type":"address"},{"internalType":"address","name":"outputToken","type":"address"},{"internalType":"uint256","name":"inputAmount","type":"uint256"},{"internalType":"uint256","name":"outputAmount","type":"uint256"},{"internalType":"uint256","name":"goodUntil","type":"uint256"},{"internalType":"address","name":"destinationAddress","type":"address"},{"components":[{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"internalType":"struct Signature","name":"theSignature","type":"tuple"},{"internalType":"bytes","name":"auxiliaryData","type":"bytes"}],"name":"swap","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"entitledFeesInDollars","type":"uint256"},{"internalType":"uint256","name":"averagePoolBalanceInDollars","type":"uint256"}],"name":"takeFees","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"i","type":"uint256"}],"name":"tokenAt","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256[]","name":"depositAmounts","type":"uint256[]"},{"internalType":"uint256","name":"lockTime","type":"uint256"},{"internalType":"uint256","name":"poolTokens","type":"uint256"},{"internalType":"uint256","name":"goodUntil","type":"uint256"},{"components":[{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"internalType":"struct Signature","name":"theSignature","type":"tuple"},{"internalType":"bytes","name":"extraData","type":"bytes"}],"name":"transmitAndDeposit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"inputToken","type":"address"},{"internalType":"uint256","name":"inputAmount","type":"uint256"},{"internalType":"uint256","name":"lockTime","type":"uint256"},{"internalType":"uint256","name":"poolTokens","type":"uint256"},{"internalType":"uint256","name":"goodUntil","type":"uint256"},{"components":[{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"internalType":"struct Signature","name":"theSignature","type":"tuple"},{"internalType":"bytes","name":"extraData","type":"bytes"}],"name":"transmitAndDepositSingleAsset","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"inputToken","type":"address"},{"internalType":"uint256","name":"inputAmount","type":"uint256"},{"internalType":"uint256","name":"outputAmount","type":"uint256"},{"internalType":"uint256","name":"goodUntil","type":"uint256"},{"internalType":"address","name":"destinationAddress","type":"address"},{"components":[{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"internalType":"struct Signature","name":"theSignature","type":"tuple"},{"internalType":"bytes","name":"auxiliaryData","type":"bytes"}],"name":"transmitAndSellTokenForEth","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"inputToken","type":"address"},{"internalType":"address","name":"outputToken","type":"address"},{"internalType":"uint256","name":"inputAmount","type":"uint256"},{"internalType":"uint256","name":"outputAmount","type":"uint256"},{"internalType":"uint256","name":"goodUntil","type":"uint256"},{"internalType":"address","name":"destinationAddress","type":"address"},{"components":[{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"internalType":"struct Signature","name":"theSignature","type":"tuple"},{"internalType":"bytes","name":"auxiliaryData","type":"bytes"}],"name":"transmitAndSwap","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"triageRole","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"unlockDeposit","outputs":[{"internalType":"uint256","name":"poolTokens","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"vestingDeposits","outputs":[{"internalType":"uint256","name":"lockedUntil","type":"uint256"},{"internalType":"uint256","name":"poolTokenAmount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"tokenHolder","type":"address"},{"internalType":"uint256","name":"poolTokenAmountToBurn","type":"uint256"},{"internalType":"address","name":"assetAddress","type":"address"},{"internalType":"uint256","name":"assetAmount","type":"uint256"},{"internalType":"uint256","name":"goodUntil","type":"uint256"},{"components":[{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"internalType":"struct Signature","name":"theSignature","type":"tuple"},{"internalType":"bytes","name":"extraData","type":"bytes"}],"name":"withdrawSingleAsset","outputs":[],"stateMutability":"nonpayable","type":"function"},{"stateMutability":"payable","type":"receive"}]Contract Creation Code
60e060405234801561000f575f5ffd5b5060405161683238038061683283398101604081905261002e91610647565b838383888884868061006160408051808201909152600e81526d213630b232902628102a37b5b2b760911b602082015290565b6040805180820190915260078152660426c6164654c560cc1b6020820152600361008b83826107e3565b50600461009882826107e3565b50506001600555506001600160a01b0381166100cd57604051631e4fbdf760e01b81525f600482015260240160405180910390fd5b6100d6816103dd565b506001600160a01b03841660a05281515f905b808210156101dd575f8483815181106101045761010461089d565b6020908102919091010151905061011c600b8261042e565b505f816001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa15801561015a573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061017e91906108b1565b905060128160ff1611156101a557604051637c10f18b60e11b815260040160405180910390fd5b6001600160a01b0382165f908152600a60205260409020805460ff191660ff8316179055836101d3816108d8565b94505050506100e9565b61022860405180604001604052806005815260200164426c61646560d81b815250604051806040016040528060058152602001640322e302e360dc1b8152503061044b60201b60201c565b608052505050506001600160a01b031660c052508151156103cf578151835114158061025657508051835114155b1561027457604051632b477e7160e11b815260040160405180910390fd5b5f5b83518110156103cd57604051806060016040528084838151811061029c5761029c61089d565b60200260200101516001600160a01b031681526020018383815181106102c4576102c461089d565b602002602001015181526020018483815181106102e3576102e361089d565b60200260200101516001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015610326573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061034a91906108b1565b60ff16815250600f5f8684815181106103655761036561089d565b6020908102919091018101516001600160a01b0390811683528282019390935260409182015f20845181546001600160a01b03191694169390931783558301516001808401919091559201516002909101805460ff191660ff90921691909117905501610276565b505b505050505050505050610912565b600680546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0905f90a35050565b5f610442836001600160a01b038416610509565b90505b92915050565b5f7f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f8460405160200161047e91906108fc565b60405160208183030381529060405280519060200120846040516020016104a591906108fc565b60408051601f1981840301815282825280516020918201209083019490945281019190915260608101919091524660808201526001600160a01b03831660a082015260c0016040516020818303038152906040528051906020012090509392505050565b5f81815260018301602052604081205461054e57508154600181810184555f848152602080822090930184905584548482528286019093526040902091909155610445565b505f610445565b80516001600160a01b038116811461056b575f5ffd5b919050565b634e487b7160e01b5f52604160045260245ffd5b604051601f8201601f191681016001600160401b03811182821017156105ac576105ac610570565b604052919050565b5f6001600160401b038211156105cc576105cc610570565b5060051b60200190565b5f82601f8301126105e5575f5ffd5b81516105f86105f3826105b4565b610584565b8082825260208201915060208360051b860101925085831115610619575f5ffd5b602085015b8381101561063d5761062f81610555565b83526020928301920161061e565b5095945050505050565b5f5f5f5f5f5f60c0878903121561065c575f5ffd5b61066587610555565b955061067360208801610555565b60408801519095506001600160401b0381111561068e575f5ffd5b61069a89828a016105d6565b606089015190955090506001600160401b038111156106b7575f5ffd5b6106c389828a016105d6565b608089015190945090506001600160401b038111156106e0575f5ffd5b8701601f810189136106f0575f5ffd5b80516106fe6105f3826105b4565b8082825260208201915060208360051b85010192508b83111561071f575f5ffd5b6020840193505b82841015610741578351825260209384019390910190610726565b94506107539250505060a08801610555565b90509295509295509295565b600181811c9082168061077357607f821691505b60208210810361079157634e487b7160e01b5f52602260045260245ffd5b50919050565b601f8211156107de57805f5260205f20601f840160051c810160208510156107bc5750805b601f840160051c820191505b818110156107db575f81556001016107c8565b50505b505050565b81516001600160401b038111156107fc576107fc610570565b6108108161080a845461075f565b84610797565b6020601f821160018114610842575f831561082b5750848201515b5f19600385901b1c1916600184901b1784556107db565b5f84815260208120601f198516915b828110156108715787850151825560209485019460019092019101610851565b508482101561088e57868401515f19600387901b60f8161c191681555b50505050600190811b01905550565b634e487b7160e01b5f52603260045260245ffd5b5f602082840312156108c1575f5ffd5b815160ff811681146108d1575f5ffd5b9392505050565b5f600182016108f557634e487b7160e01b5f52601160045260245ffd5b5060010190565b5f82518060208501845e5f920191825250919050565b60805160a05160c051615e9b6109975f395f81816105ae01528181610ebd015281816113c701528181611e2601528181611e50015281816120c4015281816121280152818161225b015281816122a7015261268601525f81816106e00152612c5901525f8181611f72015281816126c00152818161300d015261330f0152615e9b5ff3fe60806040526004361061031c575f3560e01c806370a082311161019c578063b8f44963116100e7578063d9bd8ba411610092578063eb1c64531161006d578063eb1c64531461094f578063ecc7633d1461096e578063f2fde38b14610999578063fdc85fc4146109b8575f5ffd5b8063d9bd8ba4146108cd578063da5014c5146108ec578063dd62ed3e1461090b575f5ffd5b8063c4828729116100c2578063c482872914610870578063c72da66a1461088f578063ceaf4339146108ae575f5ffd5b8063b8f4496314610786578063bfdb6b04146107a5578063c325a54914610829575f5ffd5b80638dda8f3f11610147578063a726470511610122578063a726470514610735578063a7d46c2f14610754578063a9059cbb14610767575f5ffd5b80638dda8f3f146106cf57806392a91a3a1461070257806395d89b4114610721575f5ffd5b80638414efe5116101775780638414efe5146106895780638baeefce1461069e5780638da5cb5b146106b2575f5ffd5b806370a082311461062d578063715018a614610661578063780dd66414610675575f5ffd5b80632e7e1bd3116102675780633b26e4eb116102125780635aecdda5116101ed5780635aecdda51461059d5780635b6f4dce146105e8578063608de8aa146105fb57806365cd6db01461061a575f5ffd5b80633b26e4eb1461054c5780634372328a1461056b5780634cb6864c1461057e575f5ffd5b806334cb3d7f1161024257806334cb3d7f146104e5578063368dfc1814610519578063377a368c14610538575f5ffd5b80632e7e1bd314610497578063313ce567146104ab578063343add83146104c6575f5ffd5b80631b6a8759116102c757806326d9b5b3116102a257806326d9b5b31461044757806327a9b424146104655780632b651a6c14610478575f5ffd5b80631b6a8759146103f15780631dc6f5a51461040557806323b872dd14610428575f5ffd5b80630ce9a63d116102f75780630ce9a63d146103a157806318160ddd146103b457806319f37361146103d2575f5ffd5b806306fdde0314610327578063078795ee14610351578063095ea7b314610372575f5ffd5b3661032357005b5f5ffd5b348015610332575f5ffd5b5061033b6109d7565b60405161034891906153da565b60405180910390f35b34801561035c575f5ffd5b5061037061036b36600461545c565b610a67565b005b34801561037d575f5ffd5b5061039161038c3660046154e4565b610b28565b6040519015158152602001610348565b6103706103af36600461550c565b610b41565b3480156103bf575f5ffd5b506002545b604051908152602001610348565b3480156103dd575f5ffd5b506103916103ec36600461554b565b610b8a565b3480156103fc575f5ffd5b506103c4610b96565b348015610410575f5ffd5b50610419610ba6565b60405161034893929190615564565b348015610433575f5ffd5b506103916104423660046155f5565b610ce1565b348015610452575f5ffd5b50600854600160a01b900460ff16610391565b61037061047336600461562f565b610d06565b348015610483575f5ffd5b50610370610492366004615682565b610d93565b3480156104a2575f5ffd5b50610370610e16565b3480156104b6575f5ffd5b5060405160128152602001610348565b3480156104d1575f5ffd5b506103706104e0366004615723565b610e57565b3480156104f0575f5ffd5b506103c46104ff36600461554b565b6001600160a01b03165f9081526009602052604090205490565b348015610524575f5ffd5b50610370610533366004615776565b610f96565b348015610543575f5ffd5b506103c461100d565b348015610557575f5ffd5b50610370610566366004615682565b61107a565b6103706105793660046157ce565b6110bf565b348015610589575f5ffd5b5061037061059836600461562f565b61119f565b3480156105a8575f5ffd5b506105d07f000000000000000000000000000000000000000000000000000000000000000081565b6040516001600160a01b039091168152602001610348565b6103706105f636600461585b565b611221565b348015610606575f5ffd5b506103706106153660046158b6565b611286565b610370610628366004615933565b611301565b348015610638575f5ffd5b506103c461064736600461554b565b6001600160a01b03165f9081526020819052604090205490565b34801561066c575f5ffd5b50610370611456565b348015610680575f5ffd5b50610419611469565b348015610694575f5ffd5b506103c460075481565b3480156106a9575f5ffd5b50610370611575565b3480156106bd575f5ffd5b506006546001600160a01b03166105d0565b3480156106da575f5ffd5b506105d07f000000000000000000000000000000000000000000000000000000000000000081565b34801561070d575f5ffd5b506105d061071c366004615776565b6115bc565b34801561072c575f5ffd5b5061033b6115c8565b348015610740575f5ffd5b50600e546105d0906001600160a01b031681565b61037061076236600461550c565b6115d7565b348015610772575f5ffd5b506103916107813660046154e4565b611616565b348015610791575f5ffd5b506103706107a036600461554b565b611623565b3480156107b0575f5ffd5b5061080a6107bf36600461554b565b6001600160a01b039081165f908152600f602090815260409182902082516060810184528154909416808552600182015492850183905260029091015460ff16939092019290925291565b604080516001600160a01b039093168352602083019190915201610348565b348015610834575f5ffd5b5061085b61084336600461554b565b600d6020525f90815260409020805460019091015482565b60408051928352602083019190915201610348565b34801561087b575f5ffd5b5061037061088a3660046155f5565b611688565b34801561089a575f5ffd5b506103706108a936600461562f565b61181c565b3480156108b9575f5ffd5b506103706108c836600461554b565b611861565b3480156108d8575f5ffd5b506103706108e7366004615998565b6118b2565b3480156108f7575f5ffd5b506008546105d0906001600160a01b031681565b348015610916575f5ffd5b506103c46109253660046159b8565b6001600160a01b039182165f90815260016020908152604080832093909416825291909152205490565b34801561095a575f5ffd5b5061039161096936600461554b565b6119e5565b348015610979575f5ffd5b506103c461098836600461554b565b60096020525f908152604090205481565b3480156109a4575f5ffd5b506103706109b336600461554b565b611a14565b3480156109c3575f5ffd5b506103706109d236600461554b565b611a6f565b6060600380546109e6906159e9565b80601f0160208091040260200160405190810160405280929190818152602001828054610a12906159e9565b8015610a5d5780601f10610a3457610100808354040283529160200191610a5d565b820191905f5260205f20905b815481529060010190602001808311610a4057829003601f168201915b5050505050905090565b610a6f611b27565b8342811015610a9157604051639a29b6fb60e01b815260040160405180910390fd5b866001811015610ab45760405163abf20e8f60e01b815260040160405180910390fd5b610ac96001600160a01b038b1633308c611b6b565b610b1c338b8b8b8b8b610ae1368d90038d018d615a6e565b8b8b8080601f0160208091040260200160405190810160405280939291908181526020018383808284375f92019190915250611bed92505050565b50505050505050505050565b5f33610b35818585611c56565b60019150505b92915050565b610b49611b27565b8363ffffffff1642811015610b7157604051639a29b6fb60e01b815260040160405180910390fd5b610b818787878787876001611c68565b50505050505050565b5f610b3b600b83611d0b565b5f610ba1600b611d2c565b905090565b6060805f5f610bb3610b96565b90505f8167ffffffffffffffff811115610bcf57610bcf615a1b565b604051908082528060200260200182016040528015610bf8578160200160208202803683370190505b5090505f8267ffffffffffffffff811115610c1557610c15615a1b565b604051908082528060200260200182016040528015610c3e578160200160208202803683370190505b5090505f5b83811015610cc7575f610c55826115bc565b9050610c75816001600160a01b03165f9081526009602052604090205490565b848381518110610c8757610c87615ad0565b60200260200101818152505080838381518110610ca657610ca6615ad0565b6001600160a01b039092166020928302919091019091015250600101610c43565b508181610cd360025490565b955095509550505050909192565b5f33610cee858285611d35565b610cf9858585611dc4565b60019150505b9392505050565b610d0e611b27565b8463ffffffff1642811015610d3657604051639a29b6fb60e01b815260040160405180910390fd5b610d888989898989610d4d368b90038b018b615a6e565b89898080601f0160208091040260200160405190810160405280939291908181526020018383808284375f92019190915250611e2192505050565b505050505050505050565b610d9b611b27565b8463ffffffff1642811015610dc357604051639a29b6fb60e01b815260040160405180910390fd5b610b1c8a8a8a8a8a8a610ddb368c90038c018c615a6e565b8a8a8080601f0160208091040260200160405190810160405280939291908181526020018383808284375f92019190915250611e7792505050565b610e1e611efd565b6008805460ff60a01b1916905560405133907f542e2be6bf739156fc5d022ffac81c0c9b281c19e6491b63bb14281433138b17905f90a2565b610e5f611b27565b87336001600160a01b03821614610e8957604051635c427cd960e01b815260040160405180910390fd5b8442811015610eab57604051639a29b6fb60e01b815260040160405180910390fd5b5f6001600160a01b038916610ee157507f0000000000000000000000000000000000000000000000000000000000000000975060015b5f610ef28c8c8c8c8c8c8c8c611f28565b9050610efd81611fcf565b610f088a8a8d612031565b610f12338c612055565b8115610f2757610f22338a61208d565b610f32565b610f328a338b612160565b896001600160a01b03168c6001600160a01b03167f41e79959bad1d45680578f8a544fb5af76d72b04090e65a51b4d0eaab959a9ab8d8c604051610f80929190918252602082015260400190565b60405180910390a3505050505050505050505050565b5f610fa060025490565b610faf836402540be400615af8565b610fb99190615b23565b9050610fc53383612055565b610fce8161218f565b604080518381526020810183905233917f92ccf450a286a957af52509bc1c9939d1a6a481783e142e41e2499f0bb66ebc6910160405180910390a25050565b5f611017336119e5565b61104d576040517fbb1c8b6500000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b50335f818152600d6020526040812060018101805491839055919091559061107790309083611dc4565b90565b611082611b27565b8463ffffffff16428110156110aa57604051639a29b6fb60e01b815260040160405180910390fd5b610dc36001600160a01b038b1633308b611b6b565b6110c7611b27565b83428110156110e957604051639a29b6fb60e01b815260040160405180910390fd5b86600181101561110c5760405163abf20e8f60e01b815260040160405180910390fd5b6111928b8b8b808060200260200160405190810160405280939291908181526020018383602002808284375f920191909152508d92508c91508b9050611157368c90038c018c615a6e565b8a8a8080601f0160208091040260200160405190810160405280939291908181526020018383808284375f9201919091525061220992505050565b5050505050505050505050565b6111a7611b27565b8463ffffffff16428110156111cf57604051639a29b6fb60e01b815260040160405180910390fd5b610d8889898989896111e6368b90038b018b615a6e565b89898080601f0160208091040260200160405190810160405280939291908181526020018383808284375f9201919091525061225392505050565b611229611b27565b834281101561124b57604051639a29b6fb60e01b815260040160405180910390fd5b86600181101561126e5760405163abf20e8f60e01b815260040160405180910390fd5b6111928b8b8b8b8b8b610ae1368d90038d018d615a6e565b61128e611b27565b5f875b808210156112f0575f8a8a848181106112ac576112ac615ad0565b9050602002013590505f8111156112dd576112dd3330836112cc876115bc565b6001600160a01b0316929190611b6b565b826112e781615b42565b93505050611291565b610b1c338b8b8b8b8b8b8b8b6110bf565b611309611b27565b608085901c6bffffffffffffffffffffffff602087901c1662ffffff600888901c164282101561134c57604051639a29b6fb60e01b815260040160405180910390fd5b600181101561136e5760405163abf20e8f60e01b815260040160405180910390fd5b61139260405180606001604052805f60ff1681526020015f81526020015f81525090565b506040805160608101825260ff8a1681526020810189905290810187905260a08a901c8a5f6001600160a01b0382166113ed577f00000000000000000000000000000000000000000000000000000000000000009150611402565b6114026001600160a01b038316333086611b6b565b50611448338284878a8a898f8f8080601f0160208091040260200160405190810160405280939291908181526020018383808284375f92019190915250611bed92505050565b505050505050505050505050565b61145e61231f565b6114675f612365565b565b6060805f5f611476610b96565b90505f8167ffffffffffffffff81111561149257611492615a1b565b6040519080825280602002602001820160405280156114bb578160200160208202803683370190505b5090505f8267ffffffffffffffff8111156114d8576114d8615a1b565b604051908082528060200260200182016040528015611501578160200160208202803683370190505b5090505f5b83811015610cc7575f611518826115bc565b9050611523816123b6565b84838151811061153557611535615ad0565b6020026020010181815250508083838151811061155457611554615ad0565b6001600160a01b039092166020928302919091019091015250600101611506565b61157d611efd565b6008805460ff60a01b1916600160a01b17905560405133907fcabe820ce05cacdbb20404e8bba2a9cbadaa7ff6e3a3294b6d51525267659420905f90a2565b5f610b3b600b8361241e565b6060600480546109e6906159e9565b6115df611b27565b8363ffffffff164281101561160757604051639a29b6fb60e01b815260040160405180910390fd5b610b818787878787875f611c68565b5f33610b35818585611dc4565b61162b61231f565b61163481612429565b600e80546001600160a01b0319166001600160a01b0383169081179091556040519081527f33fa9d54e48b14392fffa8aa3cfec14c54552fa92d5f44048005ec6437ee97649060200160405180910390a150565b61169061231f565b5f81116116b057604051639589a27d60e01b815260040160405180910390fd5b6116b9836124cf565b6116d657604051630732619560e01b815260040160405180910390fd5b5f6116e183836124d9565b90505f811161170357604051639589a27d60e01b815260040160405180910390fd5b6040518060600160405280846001600160a01b03168152602001838152602001846001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa15801561175f573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906117839190615b5a565b60ff9081169091526001600160a01b038681165f818152600f6020908152604091829020865181546001600160a01b031916908616178155868201516001820155958201516002909601805460ff19169690951695909517909355825191871682529281018590527fc9c48c8a3a63b9d481d1f1dc5a7ca531d0fe9ddfd25f00f6c91090175f7b0053910160405180910390a250505050565b611824611b27565b8463ffffffff164281101561184c57604051639a29b6fb60e01b815260040160405180910390fd5b6111cf6001600160a01b038a1633308b611b6b565b61186961231f565b600880546001600160a01b0319166001600160a01b0383169081179091556040517f7fb818801719b0f482b3e69a97fd8c5a1bddd186808ae2a83bdf1dac62c550ec905f90a250565b6118ba61231f565b5f816118cb846402540be400615af8565b6118d59190615b23565b90506118e760146402540be400615b23565b811115611920576040517f051fb32100000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b62093a806007546119319190615b75565b42101561196a576040517f7bd0a7dd00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b426007555f6402540be40061197e60025490565b6119889084615af8565b6119929190615b23565b905061199e33826125c2565b60408051858152602081018590529081018290527f26092d07f0187f928cdea6737c0e6d7496aea7e4d4fb32daf1ccd48793ce0b8e9060600160405180910390a150505050565b6001600160a01b0381165f908152600d60205260408120600181015415801590610cff57505442101592915050565b611a1c61231f565b6001600160a01b038116611a63576040517f1e4fbdf70000000000000000000000000000000000000000000000000000000081525f60048201526024015b60405180910390fd5b611a6c81612365565b50565b611a7761231f565b6001600160a01b038181165f908152600f602052604090205416611ac7576040517ff8794e0400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6001600160a01b0381165f818152600f602052604080822080546001600160a01b031916815560018101839055600201805460ff19169055517f9c8e7d83025bef8a04c664b2f753f64b8814bdb7e27291d7e50935f18cc3c7129190a250565b600854600160a01b900460ff1615611467576040517f9bd0d8fc00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6040516001600160a01b038481166024830152838116604483015260648201839052611be79186918216906323b872dd906084015b604051602081830303815290604052915060e01b6020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff83818316178352505050506125f6565b50505050565b611bf687610b8a565b611c1357604051630732619560e01b815260040160405180910390fd5b611c1b61267b565b5f611c2c89898989898989896126ab565b9050611c3781611fcf565b611c428888876126f8565b611c4b8861272f565b610d888987876127b0565b611c638383836001612804565b505050565b604080516060810182525f808252602082018190529181019190915260a088811c91899189901c9089906001600160ff1b0387165f611cac60ff8a901c601b615b88565b6040805160608101825260ff9092168252602082018c9052810192909252509050858015611ce257506001600160a01b03841615155b15611cfc57611cfc6001600160a01b038516333088611b6b565b611448848387868e8e87612908565b6001600160a01b0381165f9081526001830160205260408120541515610cff565b5f610b3b825490565b6001600160a01b038381165f908152600160209081526040808320938616835292905220545f19811015611be75781811015611db6576040517ffb8f41b20000000000000000000000000000000000000000000000000000000081526001600160a01b03841660048201526024810182905260448101839052606401611a5a565b611be784848484035f612804565b6001600160a01b038316611ded57604051634b637e8f60e11b81525f6004820152602401611a5a565b6001600160a01b038216611e165760405163ec442f0560e01b81525f6004820152602401611a5a565b611c63838383612981565b611e4b7f000000000000000000000000000000000000000000000000000000000000000087612ac0565b610b817f0000000000000000000000000000000000000000000000000000000000000000888888888888885b5f5f611e888a8a8a8a8a8a8a612b49565b91509150611e988a8a8784612b91565b846001600160a01b0316896001600160a01b03168b6001600160a01b03167f4be05c8d54f5e056ab2cfa033e9f582057001268c3e28561bb999d35d2c8f2c8858588604051611ee993929190615ba1565b60405180910390a450505050505050505050565b6008546001600160a01b0316331461146757604051635c427cd960e01b815260040160405180910390fd5b5f5f5f611f6985858080601f0160208091040260200160405190810160405280939291908181526020018383808284375f92019190915250612bc992505050565b91509150611f9d7f00000000000000000000000000000000000000000000000000000000000000008c8c8c8c8c8888612c17565b9250611fb783611fb236899003890189615a6e565b612c52565b611fc18282612c7d565b505098975050505050505050565b5f8181526010602052604090205460ff1615612017576040517f0ca85bce00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f908152601060205260409020805460ff19166001179055565b612039612e3a565b15611c63575f6120498484612e97565b9050611be78183612f1a565b6001600160a01b03821661207e57604051634b637e8f60e11b81525f6004820152602401611a5a565b612089825f83612981565b5050565b612095612f58565b6040517f2e1a7d4d000000000000000000000000000000000000000000000000000000008152600481018290527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690632e1a7d4d906024015f604051808303815f87803b15801561210d575f5ffd5b505af115801561211f573d5f5f3e3d5ffd5b5050505061214c7f000000000000000000000000000000000000000000000000000000000000000061272f565b6121568282612ac0565b6120896001600555565b612168612f58565b61217c6001600160a01b0384168383612f9b565b6121858361272f565b611c636001600555565b5f5f5f61219a610b96565b90505b80821015611be7575f6121af836115bc565b90506402540be4006121d5826001600160a01b03165f9081526009602052604090205490565b6121df9087615af8565b6121e99190615b23565b93506121f6813386612160565b8261220081615b42565b9350505061219d565b61221161267b565b5f61222188888888888888612fcc565b905061222c81611fcf565b612236878661305c565b61223e6130f7565b6122498887876127b0565b5050505050505050565b5f5f612284897f00000000000000000000000000000000000000000000000000000000000000008a8a8a8a8a612b49565b915091506122918961272f565b61229b858261208d565b846001600160a01b03167f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168a6001600160a01b03167f4be05c8d54f5e056ab2cfa033e9f582057001268c3e28561bb999d35d2c8f2c885858860405161230c93929190615ba1565b60405180910390a4505050505050505050565b6006546001600160a01b03163314611467576040517f118cdaa7000000000000000000000000000000000000000000000000000000008152336004820152602401611a5a565b600680546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0905f90a35050565b6040516370a0823160e01b81523060048201525f906001600160a01b038316906370a0823190602401602060405180830381865afa1580156123fa573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610b3b9190615bc8565b5f610cff8383613131565b6001600160a01b03811661245057604051631c06ca6760e01b815260040160405180910390fd5b806001600160a01b031663feaf968c6040518163ffffffff1660e01b815260040160a060405180830381865afa9250505080156124aa575060408051601f3d908101601f191682019092526124a791810190615bf8565b60015b6124c757604051631c06ca6760e01b815260040160405180910390fd5b505050505050565b5f610b3b82610b8a565b5f5f5f5f5f866001600160a01b031663feaf968c6040518163ffffffff1660e01b815260040160a060405180830381865afa15801561251a573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061253e9190615bf8565b9450945050935093508069ffffffffffffffffffff168469ffffffffffffffffffff161415806125775750426125748784615b75565b11155b156125ae576040517fa9f7344500000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6125b783613157565b979650505050505050565b6001600160a01b0382166125eb5760405163ec442f0560e01b81525f6004820152602401611a5a565b6120895f8383612981565b5f5f60205f8451602086015f885af180612615576040513d5f823e3d81fd5b50505f513d9150811561262c578060011415612639565b6001600160a01b0384163b155b15611be7576040517f5274afe70000000000000000000000000000000000000000000000000000000081526001600160a01b0385166004820152602401611a5a565b3415611467576114677f000000000000000000000000000000000000000000000000000000000000000034612ac0565b5f5f5f6126b784612bc9565b915091506126ec7f00000000000000000000000000000000000000000000000000000000000000008c8c8c8c8c8c8989613199565b9250611fb78386612c52565b5f612701612e3a565b1561270a575060015b5f6127168585846131d6565b90508115612728576127288382612f1a565b5050505050565b6040516370a0823160e01b81523060048201526001600160a01b038216906370a0823190602401602060405180830381865afa158015612771573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906127959190615bc8565b6001600160a01b039091165f90815260096020526040902055565b6127bb838383613238565b60408051828152602081018490526001600160a01b038516917f73a19dd210f1a7f902193214c0ee91dd35ee5b4d920cba8d519eca65a7b488ca910160405180910390a2505050565b6001600160a01b038416612846576040517fe602df050000000000000000000000000000000000000000000000000000000081525f6004820152602401611a5a565b6001600160a01b038316612888576040517f94280d620000000000000000000000000000000000000000000000000000000081525f6004820152602401611a5a565b6001600160a01b038085165f9081526001602090815260408083209387168352929052208290558015611be757826001600160a01b0316846001600160a01b03167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925846040516128fa91815260200190565b60405180910390a350505050565b604080516001600160a01b0319841660208201528151600c818303018152602c909101909152829081906001600160a01b038a166129545761294f89898989878987611e21565b610b1c565b6001600160a01b0389166129715761294f8a898989878987612253565b610b1c8a8a8a8a8a888a88611e77565b6001600160a01b0383166129ab578060025f8282546129a09190615b75565b90915550612a349050565b6001600160a01b0383165f9081526020819052604090205481811015612a16576040517fe450d38c0000000000000000000000000000000000000000000000000000000081526001600160a01b03851660048201526024810182905260448101839052606401611a5a565b6001600160a01b0384165f9081526020819052604090209082900390555b6001600160a01b038216612a5057600280548290039055612a6e565b6001600160a01b0382165f9081526020819052604090208054820190555b816001600160a01b0316836001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef83604051612ab391815260200190565b60405180910390a3505050565b5f826001600160a01b0316826040515f6040518083038185875af1925050503d805f8114612b09576040519150601f19603f3d011682016040523d82523d5f602084013e612b0e565b606091505b5050905080611c63576040517f6d963f8800000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f5f5f612b5b8a8a8a8a8a8a8a613309565b9050612b6681611fcf565b612b728a8a8a8a613345565b9093509150612b848a848b858a6133b4565b5097509795505050505050565b612b99612f58565b612ba28461272f565b612bb66001600160a01b0384168383612f9b565b612bbf8361272f565b611be76001600555565b5f606082806020019051810190612be09190615c46565b90925090505f612bee610b96565b905080825114612c1157604051632b477e7160e11b815260040160405180910390fd5b50915091565b5f5f612c2889898989898989613576565b60405161190160f01b8152600281019b909b5260228b015250506042909720979650505050505050565b61208982827f0000000000000000000000000000000000000000000000000000000000000000613709565b5f612c8760025490565b9050805f03612c9557505050565b825f03612cce576040517faac088f400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f612cd7610b96565b90505f805b82811015612d92575f612cee826115bc565b6001600160a01b0381165f908152600a602052604081205491925090612d189060ff166012615cff565b612d2390600a615dfb565b90505f81612d30846123b6565b612d3a9190615af8565b90505f670de0b6b3a7640000898681518110612d5857612d58615ad0565b602002602001015183612d6b9190615af8565b612d759190615b23565b9050612d818187615b75565b955050505050806001019050612cdc565b505f83612da7670de0b6b3a764000084615af8565b612db19190615b23565b9050858103612dc257505050505050565b5f612710612dd1600a89615af8565b612ddb9190615b23565b90505f878311612df457612def8389615e09565b612dfe565b612dfe8884615e09565b905081811115612249576040517f8175385600000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f5f612e446137e3565b90505f5b81811015612e8e575f600f81612e5d846137ec565b6001600160a01b03908116825260208201929092526040015f20541603612e86575f9250505090565b600101612e48565b50600191505090565b5f5f5f612ea3856137f6565b915091505f612ec9866001600160a01b03165f908152600a602052604090205460ff1690565b612ed4906012615cff565b612edf90600a615dfb565b90505f612eec8287615af8565b90505f612efa84600a615dfb565b612f048684615af8565b612f0e9190615b23565b98975050505050505050565b5f612f2c612f2760025490565b613860565b90505f670de0b6b3a7640000612f428386615af8565b612f4c9190615b23565b9050611be781846138e8565b600260055403612f94576040517f3ee5aeb500000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6002600555565b6040516001600160a01b03838116602483015260448201839052611c6391859182169063a9059cbb90606401611ba0565b5f5f612fd6610b96565b905087518114612ff957604051632b477e7160e11b815260040160405180910390fd5b5f5f61300485612bc9565b915091506130387f00000000000000000000000000000000000000000000000000000000000000008c8c8c8c8c8888613946565b93506130448487612c52565b61304e8282612c7d565b505050979650505050505050565b5f613065612e3a565b1561306e575060015b5f613077610b96565b90505f805b828110156130e6575f86828151811061309757613097615ad0565b602002602001015111156130de576130d16130b1826115bc565b8783815181106130c3576130c3615ad0565b6020026020010151866131d6565b6130db9083615b75565b91505b60010161307c565b508215612728576127288482612f1a565b5f5f613103600b611d2c565b90505b808210156120895761311f61311a836115bc565b61272f565b8161312981615b42565b925050613106565b5f825f01828154811061314657613146615ad0565b905f5260205f200154905092915050565b5f5f821215613195576040517fa8ce443200000000000000000000000000000000000000000000000000000000815260048101839052602401611a5a565b5090565b5f5f6131ab8a8a8a8a8a8a8a8a613957565b60405161190160f01b8152600281019c909c5260228c01525050604290982098975050505050505050565b5f5f6131e185613af1565b90508381101561321d576040517ff8b3bb6100000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b82156132305761322d8582612e97565b91505b509392505050565b600182101561325a5760405163abf20e8f60e01b815260040160405180910390fd5b6001600160a01b0383165f908152600d6020526040902060010154156132ac576040517f53d1b1d200000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f604051806040016040528084603c6132c59190615af8565b6132cf9042615b75565b815260209081018490526001600160a01b0386165f908152600d82526040902082518155908201516001909101559050611be730836125c2565b5f6133397f0000000000000000000000000000000000000000000000000000000000000000898989898989613b72565b90506125b78183612c52565b5f5f61335086610b8a565b61336d57604051630732619560e01b815260040160405180910390fd5b61337685610b8a565b61339357604051630732619560e01b815260040160405180910390fd5b61339c86613af1565b91506133a9848385613bb0565b905094509492505050565b6133db60405180608001604052805f81526020015f81526020015f81526020015f81525090565b6001600160a01b038681165f81815260096020818152604080842054875294891683529081528382205485820152918152600a82528290205460c085901c9267ffffffffffffffff608087901c81169361ffff603089901c8116949189901c169288901c909116906134519060ff166012615cff565b61345c90600a615dfb565b6040808801919091526001600160a01b038a165f908152600a60205220546134889060ff166012615cff565b61349390600a615dfb565b606087015260408601515f906134ec906134ad908d615af8565b6040890151895189916134bf91615af8565b878b606001518e6134d09190615af8565b8a8d606001518e602001516134e59190615af8565b8a8a613c4f565b905080613525576040517f8e7572da00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6001600160a01b038c81165f908152600f6020526040902054161580159061356557506001600160a01b038a81165f908152600f60205260409020541615155b15611448576114488b8a8e8d613dfc565b5f5f826040516020016135899190615e1c565b604051602081830303815290604052805190602001209050604051602001613692907f5769746864726177616c537472756374286164647265737320746f6b656e5f6881527f6f6c6465722c75696e7432353620706f6f6c5f746f6b656e5f616d6f756e745f60208201527f746f5f6275726e2c616464726573732061737365745f616464726573732c756960408201527f6e743235362061737365745f616d6f756e742c75696e7432353620676f6f645f60608201527f756e74696c2c75696e74323536206c705f746f6b656e5f70726963652c75696e60808201527f743235365b5d207072696365732900000000000000000000000000000000000060a082015260ae0190565b60408051808303601f190181528282528051602091820120818401526001600160a01b039b8c1683830152606083019a909a529790991660808a015260a0890195909552505060c086019190915260e085015261010080850191909152815180850390910181526101209093019052815191012090565b5f61372184845f015185602001518660400151613fa4565b9050816001600160a01b0316816001600160a01b031614611be757613796843260405160200161376d92919091825260601b6bffffffffffffffffffffffff1916602082015260340190565b60405160208183030381529060405280519060200120845f015185602001518660400151613fa4565b9050816001600160a01b0316816001600160a01b031614611be7576040517fa66e191800000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f610ba1610b96565b5f610b3b826115bc565b5f5f613800613fd0565b6001600160a01b038084165f908152600f602090815260409182902082516060810184528154909416808552600182015492850183905260029091015460ff169284019290925261385191906124d9565b92508060400151915050915091565b5f5f61386a6137e3565b90505f805b828110156138aa575f613881826137ec565b905061389581613890836140e0565b612e97565b61389f9084615b75565b92505060010161386f565b5083156138d557836138c4670de0b6b3a764000083615af8565b6138ce9190615b23565b92506138e1565b670de0b6b3a764000092505b5050919050565b5f6127106138f7601484615af8565b6139019190615b23565b905061390d8183615b75565b831115611c63576040517fba13eb2800000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f5f612c28898989898989896140fd565b5f5f8260405160200161396a9190615e1c565b604051602081830303815290604052805190602001209050604051602001613a73907f53696e676c654465706f7369745374727563742861646472657373206465706f81527f7369746f722c6164647265737320746f6b656e2c75696e7432353620616d6f7560208201527f6e742c75696e74323536206c6f636b5f74696d652c75696e7432353620706f6f60408201527f6c5f746f6b656e732c75696e7432353620676f6f645f756e74696c2c75696e7460608201527f323536206c705f746f6b656e5f70726963652c75696e743235365b5d2070726960808201527f636573290000000000000000000000000000000000000000000000000000000060a082015260a40190565b60408051808303601f190181528282528051602091820120818401526001600160a01b039c8d16838301529a909b166060820152608081019890985260a0880196909652505060c085019290925260e08401526101008301526101208083019190915283518083039091018152610140909101909252815191012090565b6001600160a01b0381165f818152600960205260408082205490516370a0823160e01b8152306004820152919290916370a0823190602401602060405180830381865afa158015613b44573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613b689190615bc8565b610b3b9190615e09565b5f5f613b8288888888888861429b565b60405161190160f01b8152600281018b905260228101829052604290209091505b9998505050505050505050565b5f838303613bbf575080610cff565b5f84613bd0856402540be400615af8565b613bda9190615b23565b9050613bea620f42406032615af8565b613bf9906402540be400615b75565b8110613c3f576402540be40083613c14620f42406032615af8565b613c23906402540be400615b75565b613c2d9190615af8565b613c379190615b23565b915050610cff565b6402540be400613c2d8483615af8565b5f8080806305f5e100613c628c8e615af8565b613c6c9190615b23565b90505f613c82613c7c8c84615af8565b876143d9565b90508015613cb45780613c9d83670de0b6b3a7640000615af8565b613ca79190615b23565b613cb19085615b75565b93505b5f6305f5e100613cc48a8c615af8565b613cce9190615b23565b90505f613ce4613cde8a84615af8565b896143d9565b90508015613d165780613cff83670de0b6b3a7640000615af8565b613d099190615b23565b613d139087615b75565b95505b505050505f6305f5e1008d8c613d2c9190615b75565b613d36908e615af8565b613d409190615b23565b90505f613d50613c7c8c84615af8565b90508015613d825780613d6b83670de0b6b3a7640000615af8565b613d759190615b23565b613d7f9084615b75565b92505b5f6305f5e100613d928c8b615e09565b613d9c908c615af8565b613da69190615b23565b90505f613db6613cde8a84615af8565b90508015613de85780613dd183670de0b6b3a7640000615af8565b613ddb9190615b23565b613de59086615b75565b94505b50505091109b9a5050505050505050505050565b5f5f613e07846137f6565b915091505f5f613e16856137f6565b91509150613e4160405180608001604052805f81526020015f81526020015f81526020015f81525090565b6001600160a01b0387165f908152600a602052604090205460ff16613e67906012615cff565b613e7290600a615dfb565b6040820152613e98866001600160a01b03165f908152600a602052604090205460ff1690565b613ea3906012615cff565b613eae90600a615dfb565b60608201526040810151613ec2908a615af8565b81525f613ed0856012615cff565b613edb90600a615dfb565b613ee59087615af8565b90505f613ef3846012615cff565b613efe90600a615dfb565b613f089086615af8565b90505f83606001518284865f0151613f209190615af8565b613f2a9190615b23565b613f349190615b23565b90505f612710613f4560c882615b75565b613f4f9084615af8565b613f599190615b23565b9050808c1115613f95576040517f6b4ba5d800000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b50505050505050505050505050565b5f5f5f5f613fb48888888861444c565b925092509250613fc48282614514565b50909695505050505050565b600e546001600160a01b0316613fe257565b5f5f600e5f9054906101000a90046001600160a01b03166001600160a01b031663feaf968c6040518163ffffffff1660e01b815260040160a060405180830381865afa158015614034573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906140589190615bf8565b50509250925050815f14614098576040517f032b3d0000000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f6140a38242615e09565b9050610e108111611c63576040517fd15f73b500000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6001600160a01b0381165f90815260096020526040812054610b3b565b5f5f876040516020016141109190615e1c565b6040516020818303038152906040528051906020012090505f8360405160200161413a9190615e1c565b60405160208183030381529060405280519060200120905060405160200161421d907f4465706f7369745374727563742861646472657373206465706f7369746f722c81527f75696e743235365b5d206465706f7369745f616d6f756e74732c75696e74323560208201527f36206c6f636b5f74696d652c75696e7432353620706f6f6c5f746f6b656e732c60408201527f75696e7432353620676f6f645f756e74696c2c75696e74323536206c705f746f60608201527f6b656e5f70726963652c75696e743235365b5d207072696365732900000000006080820152609b0190565b60408051601f198184030181528282528051602091820120908301526001600160a01b038c1690820152606081018390526080810189905260a0810188905260c0810187905260e081018690526101008101829052610120016040516020818303038152906040528051906020012092505050979650505050505050565b5f604051602001614367907f4f66666572537472756374286164647265737320696e7075745f746f6b656e2c81527f61646472657373206f75747075745f746f6b656e2c75696e7432353620696e7060208201527f75745f616d6f756e742c75696e74323536206f75747075745f616d6f756e742c60408201527f75696e7432353620676f6f645f756e74696c2c6164647265737320646573746960608201527f6e6174696f6e5f616464726573732900000000000000000000000000000000006080820152608f0190565b60408051808303601f190181528282528051602091820120818401526001600160a01b03998a16838301529789166060830152608082019690965260a08101949094525060c083019190915290931660e080850191909152815180850390910181526101009093019052815191012090565b5f825f036143e857505f610b3b565b5f6143fd6143f861107786614617565b61465c565b90505f614428670de0b6b3a76400006144228461441c61107789614617565b906147de565b906148c5565b90505f6144376110778361499d565b905061444281613157565b9350505050610b3b565b5f80807f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a084111561448557505f9150600390508261450a565b604080515f808252602082018084528a905260ff891692820192909252606081018790526080810186905260019060a0016020604051602081039080840390855afa1580156144d6573d5f5f3e3d5ffd5b5050604051601f1901519150506001600160a01b03811661450157505f92506001915082905061450a565b92505f91508190505b9450945094915050565b5f82600381111561452757614527615e51565b03614530575050565b600182600381111561454457614544615e51565b0361457b576040517ff645eedf00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600282600381111561458f5761458f615e51565b036145c9576040517ffce698f700000000000000000000000000000000000000000000000000000000815260048101829052602401611a5a565b60038260038111156145dd576145dd615e51565b03612089576040517fd78bce0c00000000000000000000000000000000000000000000000000000000815260048101829052602401611a5a565b5f6001600160ff1b03821115613195576040517f24775e0600000000000000000000000000000000000000000000000000000000815260048101839052602401611a5a565b5f8181811361469a576040517f059b101b00000000000000000000000000000000000000000000000000000000815260048101849052602401611a5a565b5f670de0b6b3a764000082126146b2575060016146d7565b505f19816ec097ce7bc90715b34b9f1000000000816146d3576146d3615b0f565b0591505b5f614762670de0b6b3a7640000840560016fffffffffffffffffffffffffffffffff821160071b91821c67ffffffffffffffff811160061b90811c63ffffffff811160051b90811c61ffff811160041b90811c60ff8111600390811b91821c600f811160021b90811c918211871b91821c969096119490961792909217171791909117919091171790565b9050670de0b6b3a7640000810283821d670de0b6b3a763ffff19810161478a578184026125b7565b671bc16d674ec800006706f05b59d3b200005b5f8113156147cf57670de0b6b3a76400008380020592508183126147c7579283019260019290921d915b60011d61479d565b50505091909102949350505050565b5f8282600160ff1b8214806147f65750600160ff1b81145b1561482d576040517fa6070c2500000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f5f5f841261483c5783614840565b835f035b91505f831261484f5782614853565b825f035b90505f6148608383614a6b565b90506001600160ff1b038111156148ad576040517f120b5b430000000000000000000000000000000000000000000000000000000081526004810189905260248101889052604401611a5a565b5f1985851813613ba3816148c157825f0390565b8290565b5f8282600160ff1b8214806148dd5750600160ff1b81145b15614914576040517f9fe2b45000000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f5f5f84126149235783614927565b835f035b91505f8312614936578261493a565b825f035b90505f61495083670de0b6b3a764000084614b50565b90506001600160ff1b038111156148ad576040517fd49c26b30000000000000000000000000000000000000000000000000000000081526004810189905260248101889052604401611a5a565b5f8181811215614a005768033dd1780914b97114198112156149c157505f92915050565b6149f96149d86110776149d3845f0390565b61499d565b6ec097ce7bc90715b34b9f1000000000816149f5576149f5615b0f565b0590565b9150614a65565b680a688906bd8affffff811315614a46576040517f0360d02800000000000000000000000000000000000000000000000000000000815260048101849052602401611a5a565b670de0b6b3a7640000604082901b05614a6161107782614c38565b9250505b50919050565b5f80805f19848609848602925082811083820303915050805f03614a9c5750670de0b6b3a764000090049050610b3b565b670de0b6b3a76400008110614ae7576040517f5173648d0000000000000000000000000000000000000000000000000000000081526004810186905260248101859052604401611a5a565b5f670de0b6b3a7640000858709620400008185030493109091037d40000000000000000000000000000000000000000000000000000000000002919091177faccb18165bd6fe31ae1cf318dc5b51eee0e1ba569b88cd74c1773b91fac106690291505092915050565b5f80805f19858709858702925082811083820303915050805f03614b8757838281614b7d57614b7d615b0f565b0492505050610cff565b838110614bd1576040517f63a05778000000000000000000000000000000000000000000000000000000008152600481018790526024810186905260448101859052606401611a5a565b5f8486880960026001871981018816978890046003810283188082028403028082028403028082028403028082028403028082028403029081029092039091025f889003889004909101858311909403939093029303949094049190911702949350505050565b7780000000000000000000000000000000000000000000000067ff00000000000000821615614d5957678000000000000000821615614c805768016a09e667f3bcc9090260401c5b674000000000000000821615614c9f576801306fe0a31b7152df0260401c5b672000000000000000821615614cbe576801172b83c7d517adce0260401c5b671000000000000000821615614cdd5768010b5586cf9890f62a0260401c5b670800000000000000821615614cfc576801059b0d31585743ae0260401c5b670400000000000000821615614d1b57680102c9a3e778060ee70260401c5b670200000000000000821615614d3a5768010163da9fb33356d80260401c5b670100000000000000821615614d5957680100b1afa5abcbed610260401c5b66ff000000000000821615614e58576680000000000000821615614d865768010058c86da1c09ea20260401c5b6640000000000000821615614da4576801002c605e2e8cec500260401c5b6620000000000000821615614dc257680100162f3904051fa10260401c5b6610000000000000821615614de0576801000b175effdc76ba0260401c5b6608000000000000821615614dfe57680100058ba01fb9f96d0260401c5b6604000000000000821615614e1c5768010002c5cc37da94920260401c5b6602000000000000821615614e3a576801000162e525ee05470260401c5b6601000000000000821615614e585768010000b17255775c040260401c5b65ff0000000000821615614f4e5765800000000000821615614e83576801000058b91b5bc9ae0260401c5b65400000000000821615614ea057680100002c5c89d5ec6d0260401c5b65200000000000821615614ebd5768010000162e43f4f8310260401c5b65100000000000821615614eda57680100000b1721bcfc9a0260401c5b65080000000000821615614ef75768010000058b90cf1e6e0260401c5b65040000000000821615614f14576801000002c5c863b73f0260401c5b65020000000000821615614f3157680100000162e430e5a20260401c5b65010000000000821615614f4e576801000000b1721835510260401c5b64ff0000000082161561503b57648000000000821615614f7757680100000058b90c0b490260401c5b644000000000821615614f935768010000002c5c8601cc0260401c5b642000000000821615614faf576801000000162e42fff00260401c5b641000000000821615614fcb5768010000000b17217fbb0260401c5b640800000000821615614fe7576801000000058b90bfce0260401c5b64040000000082161561500357680100000002c5c85fe30260401c5b64020000000082161561501f5768010000000162e42ff10260401c5b64010000000082161561503b57680100000000b17217f80260401c5b63ff00000082161561511f5763800000008216156150625768010000000058b90bfc0260401c5b634000000082161561507d576801000000002c5c85fe0260401c5b632000000082161561509857680100000000162e42ff0260401c5b63100000008216156150b3576801000000000b17217f0260401c5b63080000008216156150ce57680100000000058b90c00260401c5b63040000008216156150e95768010000000002c5c8600260401c5b6302000000821615615104576801000000000162e4300260401c5b630100000082161561511f5768010000000000b172180260401c5b62ff00008216156151fa5762800000821615615144576801000000000058b90c0260401c5b6240000082161561515e57680100000000002c5c860260401c5b622000008216156151785768010000000000162e430260401c5b6210000082161561519257680100000000000b17210260401c5b620800008216156151ac5768010000000000058b910260401c5b620400008216156151c6576801000000000002c5c80260401c5b620200008216156151e057680100000000000162e40260401c5b620100008216156151fa576801000000000000b1720260401c5b61ff008216156152cc5761800082161561521d57680100000000000058b90260401c5b6140008216156152365768010000000000002c5d0260401c5b61200082161561524f576801000000000000162e0260401c5b6110008216156152685768010000000000000b170260401c5b610800821615615281576801000000000000058c0260401c5b61040082161561529a57680100000000000002c60260401c5b6102008216156152b357680100000000000001630260401c5b6101008216156152cc57680100000000000000b10260401c5b60ff8216156153955760808216156152ed57680100000000000000590260401c5b6040821615615305576801000000000000002c0260401c5b602082161561531d57680100000000000000160260401c5b6010821615615335576801000000000000000b0260401c5b600882161561534d57680100000000000000060260401c5b600482161561536557680100000000000000030260401c5b600282161561537d57680100000000000000010260401c5b600182161561539557680100000000000000010260401c5b670de0b6b3a76400000260409190911c60bf031c90565b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b602081525f610cff60208301846153ac565b80356001600160a01b0381168114615402575f5ffd5b919050565b5f60608284031215614a65575f5ffd5b5f5f83601f840112615427575f5ffd5b50813567ffffffffffffffff81111561543e575f5ffd5b602083019150836020828501011115615455575f5ffd5b9250929050565b5f5f5f5f5f5f5f5f610120898b031215615474575f5ffd5b61547d896153ec565b9750602089013596506040890135955060608901359450608089013593506154a88a60a08b01615407565b925061010089013567ffffffffffffffff8111156154c4575f5ffd5b6154d08b828c01615417565b999c989b5096995094979396929594505050565b5f5f604083850312156154f5575f5ffd5b6154fe836153ec565b946020939093013593505050565b5f5f5f5f5f5f60c08789031215615521575f5ffd5b505084359660208601359650604086013595606081013595506080810135945060a0013592509050565b5f6020828403121561555b575f5ffd5b610cff826153ec565b606080825284519082018190525f9060208601906080840190835b8181101561559d57835183526020938401939092019160010161557f565b5050838103602080860191909152865180835291810192508601905f5b818110156155e15782516001600160a01b03168452602093840193909201916001016155ba565b505050604092909201929092529392505050565b5f5f5f60608486031215615607575f5ffd5b615610846153ec565b925061561e602085016153ec565b929592945050506040919091013590565b5f5f5f5f5f5f5f5f610120898b031215615647575f5ffd5b615650896153ec565b975060208901359650604089013595506060890135945061567360808a016153ec565b93506154a88a60a08b01615407565b5f5f5f5f5f5f5f5f5f6101408a8c03121561569b575f5ffd5b6156a48a6153ec565b98506156b260208b016153ec565b975060408a0135965060608a0135955060808a013594506156d560a08b016153ec565b93506156e48b60c08c01615407565b92506101208a013567ffffffffffffffff811115615700575f5ffd5b61570c8c828d01615417565b915080935050809150509295985092959850929598565b5f5f5f5f5f5f5f5f610120898b03121561573b575f5ffd5b615744896153ec565b97506020890135965061575960408a016153ec565b955060608901359450608089013593506154a88a60a08b01615407565b5f60208284031215615786575f5ffd5b5035919050565b5f5f83601f84011261579d575f5ffd5b50813567ffffffffffffffff8111156157b4575f5ffd5b6020830191508360208260051b8501011115615455575f5ffd5b5f5f5f5f5f5f5f5f5f6101208a8c0312156157e7575f5ffd5b6157f08a6153ec565b985060208a013567ffffffffffffffff81111561580b575f5ffd5b6158178c828d0161578d565b90995097505060408a0135955060608a0135945060808a0135935061583f8b60a08c01615407565b92506101008a013567ffffffffffffffff811115615700575f5ffd5b5f5f5f5f5f5f5f5f5f6101408a8c031215615874575f5ffd5b61587d8a6153ec565b985061588b60208b016153ec565b975060408a0135965060608a0135955060808a0135945060a08a013593506156e48b60c08c01615407565b5f5f5f5f5f5f5f5f610100898b0312156158ce575f5ffd5b883567ffffffffffffffff8111156158e4575f5ffd5b6158f08b828c0161578d565b9099509750506020890135955060408901359450606089013593506159188a60808b01615407565b925060e089013567ffffffffffffffff8111156154c4575f5ffd5b5f5f5f5f5f5f60a08789031215615948575f5ffd5b86359550602087013594506040870135935060608701359250608087013567ffffffffffffffff81111561597a575f5ffd5b61598689828a01615417565b979a9699509497509295939492505050565b5f5f604083850312156159a9575f5ffd5b50508035926020909101359150565b5f5f604083850312156159c9575f5ffd5b6159d2836153ec565b91506159e0602084016153ec565b90509250929050565b600181811c908216806159fd57607f821691505b602082108103614a6557634e487b7160e01b5f52602260045260245ffd5b634e487b7160e01b5f52604160045260245ffd5b604051601f8201601f1916810167ffffffffffffffff81118282101715615a5857615a58615a1b565b604052919050565b60ff81168114611a6c575f5ffd5b5f6060828403128015615a7f575f5ffd5b506040516060810167ffffffffffffffff81118282101715615aa357615aa3615a1b565b6040528235615ab181615a60565b8152602083810135908201526040928301359281019290925250919050565b634e487b7160e01b5f52603260045260245ffd5b634e487b7160e01b5f52601160045260245ffd5b8082028115828204841417610b3b57610b3b615ae4565b634e487b7160e01b5f52601260045260245ffd5b5f82615b3d57634e487b7160e01b5f52601260045260245ffd5b500490565b5f60018201615b5357615b53615ae4565b5060010190565b5f60208284031215615b6a575f5ffd5b8151610cff81615a60565b80820180821115610b3b57610b3b615ae4565b60ff8181168382160190811115610b3b57610b3b615ae4565b838152826020820152606060408201525f615bbf60608301846153ac565b95945050505050565b5f60208284031215615bd8575f5ffd5b5051919050565b805169ffffffffffffffffffff81168114615402575f5ffd5b5f5f5f5f5f60a08688031215615c0c575f5ffd5b615c1586615bdf565b60208701516040880151606089015192975090955093509150615c3a60808701615bdf565b90509295509295909350565b5f5f60408385031215615c57575f5ffd5b8251602084015190925067ffffffffffffffff811115615c75575f5ffd5b8301601f81018513615c85575f5ffd5b805167ffffffffffffffff811115615c9f57615c9f615a1b565b8060051b615caf60208201615a2f565b91825260208184018101929081019088841115615cca575f5ffd5b6020850194505b83851015615cf057845180835260209586019590935090910190615cd1565b80955050505050509250929050565b60ff8281168282160390811115610b3b57610b3b615ae4565b6001815b6001841115615d5357808504811115615d3757615d37615ae4565b6001841615615d4557908102905b60019390931c928002615d1c565b935093915050565b5f82615d6957506001610b3b565b81615d7557505f610b3b565b8160018114615d8b5760028114615d9557615db1565b6001915050610b3b565b60ff841115615da657615da6615ae4565b50506001821b610b3b565b5060208310610133831016604e8410600b8410161715615dd4575081810a610b3b565b615de05f198484615d18565b805f1904821115615df357615df3615ae4565b029392505050565b5f610cff60ff841683615d5b565b81810381811115610b3b57610b3b615ae4565b81515f90829060208501835b82811015615e46578151845260209384019390910190600101615e28565b509195945050505050565b634e487b7160e01b5f52602160045260245ffdfea264697066735822122087110682112f93f731b96de206515815b6a394f76063ca9ed3d7681d781859e764736f6c634300081c003300000000000000000000000008938a61ba9523298dbcacee0cda5b371fb7f1f8000000000000000000000000ee7d8bcfb72bc1880d0cf19822eb0a2e6577ab6200000000000000000000000000000000000000000000000000000000000000c000000000000000000000000000000000000000000000000000000000000001200000000000000000000000000000000000000000000000000000000000000180000000000000000000000000a372e7f8ba1f0377667c8c52fea2bc3e271a0e680000000000000000000000000000000000000000000000000000000000000002000000000000000000000000ee7d8bcfb72bc1880d0cf19822eb0a2e6577ab62000000000000000000000000203a662b0bd271a6ed5a60edfbd04bfce608fd3600000000000000000000000000000000000000000000000000000000000000020000000000000000000000007bdbdb772f4a073badd676a567c6ed82049a8eee000000000000000000000000be5ce90e16b9d9d988d64b0e1f6ed46ebafb960600000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000e100000000000000000000000000000000000000000000000000000000000015180
Deployed Bytecode
0x60806040526004361061031c575f3560e01c806370a082311161019c578063b8f44963116100e7578063d9bd8ba411610092578063eb1c64531161006d578063eb1c64531461094f578063ecc7633d1461096e578063f2fde38b14610999578063fdc85fc4146109b8575f5ffd5b8063d9bd8ba4146108cd578063da5014c5146108ec578063dd62ed3e1461090b575f5ffd5b8063c4828729116100c2578063c482872914610870578063c72da66a1461088f578063ceaf4339146108ae575f5ffd5b8063b8f4496314610786578063bfdb6b04146107a5578063c325a54914610829575f5ffd5b80638dda8f3f11610147578063a726470511610122578063a726470514610735578063a7d46c2f14610754578063a9059cbb14610767575f5ffd5b80638dda8f3f146106cf57806392a91a3a1461070257806395d89b4114610721575f5ffd5b80638414efe5116101775780638414efe5146106895780638baeefce1461069e5780638da5cb5b146106b2575f5ffd5b806370a082311461062d578063715018a614610661578063780dd66414610675575f5ffd5b80632e7e1bd3116102675780633b26e4eb116102125780635aecdda5116101ed5780635aecdda51461059d5780635b6f4dce146105e8578063608de8aa146105fb57806365cd6db01461061a575f5ffd5b80633b26e4eb1461054c5780634372328a1461056b5780634cb6864c1461057e575f5ffd5b806334cb3d7f1161024257806334cb3d7f146104e5578063368dfc1814610519578063377a368c14610538575f5ffd5b80632e7e1bd314610497578063313ce567146104ab578063343add83146104c6575f5ffd5b80631b6a8759116102c757806326d9b5b3116102a257806326d9b5b31461044757806327a9b424146104655780632b651a6c14610478575f5ffd5b80631b6a8759146103f15780631dc6f5a51461040557806323b872dd14610428575f5ffd5b80630ce9a63d116102f75780630ce9a63d146103a157806318160ddd146103b457806319f37361146103d2575f5ffd5b806306fdde0314610327578063078795ee14610351578063095ea7b314610372575f5ffd5b3661032357005b5f5ffd5b348015610332575f5ffd5b5061033b6109d7565b60405161034891906153da565b60405180910390f35b34801561035c575f5ffd5b5061037061036b36600461545c565b610a67565b005b34801561037d575f5ffd5b5061039161038c3660046154e4565b610b28565b6040519015158152602001610348565b6103706103af36600461550c565b610b41565b3480156103bf575f5ffd5b506002545b604051908152602001610348565b3480156103dd575f5ffd5b506103916103ec36600461554b565b610b8a565b3480156103fc575f5ffd5b506103c4610b96565b348015610410575f5ffd5b50610419610ba6565b60405161034893929190615564565b348015610433575f5ffd5b506103916104423660046155f5565b610ce1565b348015610452575f5ffd5b50600854600160a01b900460ff16610391565b61037061047336600461562f565b610d06565b348015610483575f5ffd5b50610370610492366004615682565b610d93565b3480156104a2575f5ffd5b50610370610e16565b3480156104b6575f5ffd5b5060405160128152602001610348565b3480156104d1575f5ffd5b506103706104e0366004615723565b610e57565b3480156104f0575f5ffd5b506103c46104ff36600461554b565b6001600160a01b03165f9081526009602052604090205490565b348015610524575f5ffd5b50610370610533366004615776565b610f96565b348015610543575f5ffd5b506103c461100d565b348015610557575f5ffd5b50610370610566366004615682565b61107a565b6103706105793660046157ce565b6110bf565b348015610589575f5ffd5b5061037061059836600461562f565b61119f565b3480156105a8575f5ffd5b506105d07f000000000000000000000000ee7d8bcfb72bc1880d0cf19822eb0a2e6577ab6281565b6040516001600160a01b039091168152602001610348565b6103706105f636600461585b565b611221565b348015610606575f5ffd5b506103706106153660046158b6565b611286565b610370610628366004615933565b611301565b348015610638575f5ffd5b506103c461064736600461554b565b6001600160a01b03165f9081526020819052604090205490565b34801561066c575f5ffd5b50610370611456565b348015610680575f5ffd5b50610419611469565b348015610694575f5ffd5b506103c460075481565b3480156106a9575f5ffd5b50610370611575565b3480156106bd575f5ffd5b506006546001600160a01b03166105d0565b3480156106da575f5ffd5b506105d07f00000000000000000000000008938a61ba9523298dbcacee0cda5b371fb7f1f881565b34801561070d575f5ffd5b506105d061071c366004615776565b6115bc565b34801561072c575f5ffd5b5061033b6115c8565b348015610740575f5ffd5b50600e546105d0906001600160a01b031681565b61037061076236600461550c565b6115d7565b348015610772575f5ffd5b506103916107813660046154e4565b611616565b348015610791575f5ffd5b506103706107a036600461554b565b611623565b3480156107b0575f5ffd5b5061080a6107bf36600461554b565b6001600160a01b039081165f908152600f602090815260409182902082516060810184528154909416808552600182015492850183905260029091015460ff16939092019290925291565b604080516001600160a01b039093168352602083019190915201610348565b348015610834575f5ffd5b5061085b61084336600461554b565b600d6020525f90815260409020805460019091015482565b60408051928352602083019190915201610348565b34801561087b575f5ffd5b5061037061088a3660046155f5565b611688565b34801561089a575f5ffd5b506103706108a936600461562f565b61181c565b3480156108b9575f5ffd5b506103706108c836600461554b565b611861565b3480156108d8575f5ffd5b506103706108e7366004615998565b6118b2565b3480156108f7575f5ffd5b506008546105d0906001600160a01b031681565b348015610916575f5ffd5b506103c46109253660046159b8565b6001600160a01b039182165f90815260016020908152604080832093909416825291909152205490565b34801561095a575f5ffd5b5061039161096936600461554b565b6119e5565b348015610979575f5ffd5b506103c461098836600461554b565b60096020525f908152604090205481565b3480156109a4575f5ffd5b506103706109b336600461554b565b611a14565b3480156109c3575f5ffd5b506103706109d236600461554b565b611a6f565b6060600380546109e6906159e9565b80601f0160208091040260200160405190810160405280929190818152602001828054610a12906159e9565b8015610a5d5780601f10610a3457610100808354040283529160200191610a5d565b820191905f5260205f20905b815481529060010190602001808311610a4057829003601f168201915b5050505050905090565b610a6f611b27565b8342811015610a9157604051639a29b6fb60e01b815260040160405180910390fd5b866001811015610ab45760405163abf20e8f60e01b815260040160405180910390fd5b610ac96001600160a01b038b1633308c611b6b565b610b1c338b8b8b8b8b610ae1368d90038d018d615a6e565b8b8b8080601f0160208091040260200160405190810160405280939291908181526020018383808284375f92019190915250611bed92505050565b50505050505050505050565b5f33610b35818585611c56565b60019150505b92915050565b610b49611b27565b8363ffffffff1642811015610b7157604051639a29b6fb60e01b815260040160405180910390fd5b610b818787878787876001611c68565b50505050505050565b5f610b3b600b83611d0b565b5f610ba1600b611d2c565b905090565b6060805f5f610bb3610b96565b90505f8167ffffffffffffffff811115610bcf57610bcf615a1b565b604051908082528060200260200182016040528015610bf8578160200160208202803683370190505b5090505f8267ffffffffffffffff811115610c1557610c15615a1b565b604051908082528060200260200182016040528015610c3e578160200160208202803683370190505b5090505f5b83811015610cc7575f610c55826115bc565b9050610c75816001600160a01b03165f9081526009602052604090205490565b848381518110610c8757610c87615ad0565b60200260200101818152505080838381518110610ca657610ca6615ad0565b6001600160a01b039092166020928302919091019091015250600101610c43565b508181610cd360025490565b955095509550505050909192565b5f33610cee858285611d35565b610cf9858585611dc4565b60019150505b9392505050565b610d0e611b27565b8463ffffffff1642811015610d3657604051639a29b6fb60e01b815260040160405180910390fd5b610d888989898989610d4d368b90038b018b615a6e565b89898080601f0160208091040260200160405190810160405280939291908181526020018383808284375f92019190915250611e2192505050565b505050505050505050565b610d9b611b27565b8463ffffffff1642811015610dc357604051639a29b6fb60e01b815260040160405180910390fd5b610b1c8a8a8a8a8a8a610ddb368c90038c018c615a6e565b8a8a8080601f0160208091040260200160405190810160405280939291908181526020018383808284375f92019190915250611e7792505050565b610e1e611efd565b6008805460ff60a01b1916905560405133907f542e2be6bf739156fc5d022ffac81c0c9b281c19e6491b63bb14281433138b17905f90a2565b610e5f611b27565b87336001600160a01b03821614610e8957604051635c427cd960e01b815260040160405180910390fd5b8442811015610eab57604051639a29b6fb60e01b815260040160405180910390fd5b5f6001600160a01b038916610ee157507f000000000000000000000000ee7d8bcfb72bc1880d0cf19822eb0a2e6577ab62975060015b5f610ef28c8c8c8c8c8c8c8c611f28565b9050610efd81611fcf565b610f088a8a8d612031565b610f12338c612055565b8115610f2757610f22338a61208d565b610f32565b610f328a338b612160565b896001600160a01b03168c6001600160a01b03167f41e79959bad1d45680578f8a544fb5af76d72b04090e65a51b4d0eaab959a9ab8d8c604051610f80929190918252602082015260400190565b60405180910390a3505050505050505050505050565b5f610fa060025490565b610faf836402540be400615af8565b610fb99190615b23565b9050610fc53383612055565b610fce8161218f565b604080518381526020810183905233917f92ccf450a286a957af52509bc1c9939d1a6a481783e142e41e2499f0bb66ebc6910160405180910390a25050565b5f611017336119e5565b61104d576040517fbb1c8b6500000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b50335f818152600d6020526040812060018101805491839055919091559061107790309083611dc4565b90565b611082611b27565b8463ffffffff16428110156110aa57604051639a29b6fb60e01b815260040160405180910390fd5b610dc36001600160a01b038b1633308b611b6b565b6110c7611b27565b83428110156110e957604051639a29b6fb60e01b815260040160405180910390fd5b86600181101561110c5760405163abf20e8f60e01b815260040160405180910390fd5b6111928b8b8b808060200260200160405190810160405280939291908181526020018383602002808284375f920191909152508d92508c91508b9050611157368c90038c018c615a6e565b8a8a8080601f0160208091040260200160405190810160405280939291908181526020018383808284375f9201919091525061220992505050565b5050505050505050505050565b6111a7611b27565b8463ffffffff16428110156111cf57604051639a29b6fb60e01b815260040160405180910390fd5b610d8889898989896111e6368b90038b018b615a6e565b89898080601f0160208091040260200160405190810160405280939291908181526020018383808284375f9201919091525061225392505050565b611229611b27565b834281101561124b57604051639a29b6fb60e01b815260040160405180910390fd5b86600181101561126e5760405163abf20e8f60e01b815260040160405180910390fd5b6111928b8b8b8b8b8b610ae1368d90038d018d615a6e565b61128e611b27565b5f875b808210156112f0575f8a8a848181106112ac576112ac615ad0565b9050602002013590505f8111156112dd576112dd3330836112cc876115bc565b6001600160a01b0316929190611b6b565b826112e781615b42565b93505050611291565b610b1c338b8b8b8b8b8b8b8b6110bf565b611309611b27565b608085901c6bffffffffffffffffffffffff602087901c1662ffffff600888901c164282101561134c57604051639a29b6fb60e01b815260040160405180910390fd5b600181101561136e5760405163abf20e8f60e01b815260040160405180910390fd5b61139260405180606001604052805f60ff1681526020015f81526020015f81525090565b506040805160608101825260ff8a1681526020810189905290810187905260a08a901c8a5f6001600160a01b0382166113ed577f000000000000000000000000ee7d8bcfb72bc1880d0cf19822eb0a2e6577ab629150611402565b6114026001600160a01b038316333086611b6b565b50611448338284878a8a898f8f8080601f0160208091040260200160405190810160405280939291908181526020018383808284375f92019190915250611bed92505050565b505050505050505050505050565b61145e61231f565b6114675f612365565b565b6060805f5f611476610b96565b90505f8167ffffffffffffffff81111561149257611492615a1b565b6040519080825280602002602001820160405280156114bb578160200160208202803683370190505b5090505f8267ffffffffffffffff8111156114d8576114d8615a1b565b604051908082528060200260200182016040528015611501578160200160208202803683370190505b5090505f5b83811015610cc7575f611518826115bc565b9050611523816123b6565b84838151811061153557611535615ad0565b6020026020010181815250508083838151811061155457611554615ad0565b6001600160a01b039092166020928302919091019091015250600101611506565b61157d611efd565b6008805460ff60a01b1916600160a01b17905560405133907fcabe820ce05cacdbb20404e8bba2a9cbadaa7ff6e3a3294b6d51525267659420905f90a2565b5f610b3b600b8361241e565b6060600480546109e6906159e9565b6115df611b27565b8363ffffffff164281101561160757604051639a29b6fb60e01b815260040160405180910390fd5b610b818787878787875f611c68565b5f33610b35818585611dc4565b61162b61231f565b61163481612429565b600e80546001600160a01b0319166001600160a01b0383169081179091556040519081527f33fa9d54e48b14392fffa8aa3cfec14c54552fa92d5f44048005ec6437ee97649060200160405180910390a150565b61169061231f565b5f81116116b057604051639589a27d60e01b815260040160405180910390fd5b6116b9836124cf565b6116d657604051630732619560e01b815260040160405180910390fd5b5f6116e183836124d9565b90505f811161170357604051639589a27d60e01b815260040160405180910390fd5b6040518060600160405280846001600160a01b03168152602001838152602001846001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa15801561175f573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906117839190615b5a565b60ff9081169091526001600160a01b038681165f818152600f6020908152604091829020865181546001600160a01b031916908616178155868201516001820155958201516002909601805460ff19169690951695909517909355825191871682529281018590527fc9c48c8a3a63b9d481d1f1dc5a7ca531d0fe9ddfd25f00f6c91090175f7b0053910160405180910390a250505050565b611824611b27565b8463ffffffff164281101561184c57604051639a29b6fb60e01b815260040160405180910390fd5b6111cf6001600160a01b038a1633308b611b6b565b61186961231f565b600880546001600160a01b0319166001600160a01b0383169081179091556040517f7fb818801719b0f482b3e69a97fd8c5a1bddd186808ae2a83bdf1dac62c550ec905f90a250565b6118ba61231f565b5f816118cb846402540be400615af8565b6118d59190615b23565b90506118e760146402540be400615b23565b811115611920576040517f051fb32100000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b62093a806007546119319190615b75565b42101561196a576040517f7bd0a7dd00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b426007555f6402540be40061197e60025490565b6119889084615af8565b6119929190615b23565b905061199e33826125c2565b60408051858152602081018590529081018290527f26092d07f0187f928cdea6737c0e6d7496aea7e4d4fb32daf1ccd48793ce0b8e9060600160405180910390a150505050565b6001600160a01b0381165f908152600d60205260408120600181015415801590610cff57505442101592915050565b611a1c61231f565b6001600160a01b038116611a63576040517f1e4fbdf70000000000000000000000000000000000000000000000000000000081525f60048201526024015b60405180910390fd5b611a6c81612365565b50565b611a7761231f565b6001600160a01b038181165f908152600f602052604090205416611ac7576040517ff8794e0400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6001600160a01b0381165f818152600f602052604080822080546001600160a01b031916815560018101839055600201805460ff19169055517f9c8e7d83025bef8a04c664b2f753f64b8814bdb7e27291d7e50935f18cc3c7129190a250565b600854600160a01b900460ff1615611467576040517f9bd0d8fc00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6040516001600160a01b038481166024830152838116604483015260648201839052611be79186918216906323b872dd906084015b604051602081830303815290604052915060e01b6020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff83818316178352505050506125f6565b50505050565b611bf687610b8a565b611c1357604051630732619560e01b815260040160405180910390fd5b611c1b61267b565b5f611c2c89898989898989896126ab565b9050611c3781611fcf565b611c428888876126f8565b611c4b8861272f565b610d888987876127b0565b611c638383836001612804565b505050565b604080516060810182525f808252602082018190529181019190915260a088811c91899189901c9089906001600160ff1b0387165f611cac60ff8a901c601b615b88565b6040805160608101825260ff9092168252602082018c9052810192909252509050858015611ce257506001600160a01b03841615155b15611cfc57611cfc6001600160a01b038516333088611b6b565b611448848387868e8e87612908565b6001600160a01b0381165f9081526001830160205260408120541515610cff565b5f610b3b825490565b6001600160a01b038381165f908152600160209081526040808320938616835292905220545f19811015611be75781811015611db6576040517ffb8f41b20000000000000000000000000000000000000000000000000000000081526001600160a01b03841660048201526024810182905260448101839052606401611a5a565b611be784848484035f612804565b6001600160a01b038316611ded57604051634b637e8f60e11b81525f6004820152602401611a5a565b6001600160a01b038216611e165760405163ec442f0560e01b81525f6004820152602401611a5a565b611c63838383612981565b611e4b7f000000000000000000000000ee7d8bcfb72bc1880d0cf19822eb0a2e6577ab6287612ac0565b610b817f000000000000000000000000ee7d8bcfb72bc1880d0cf19822eb0a2e6577ab62888888888888885b5f5f611e888a8a8a8a8a8a8a612b49565b91509150611e988a8a8784612b91565b846001600160a01b0316896001600160a01b03168b6001600160a01b03167f4be05c8d54f5e056ab2cfa033e9f582057001268c3e28561bb999d35d2c8f2c8858588604051611ee993929190615ba1565b60405180910390a450505050505050505050565b6008546001600160a01b0316331461146757604051635c427cd960e01b815260040160405180910390fd5b5f5f5f611f6985858080601f0160208091040260200160405190810160405280939291908181526020018383808284375f92019190915250612bc992505050565b91509150611f9d7f05324cbcf9ac04abf61ba4b51fcd40742cf6e4e1e24685ab6577a7cd6b0723a08c8c8c8c8c8888612c17565b9250611fb783611fb236899003890189615a6e565b612c52565b611fc18282612c7d565b505098975050505050505050565b5f8181526010602052604090205460ff1615612017576040517f0ca85bce00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f908152601060205260409020805460ff19166001179055565b612039612e3a565b15611c63575f6120498484612e97565b9050611be78183612f1a565b6001600160a01b03821661207e57604051634b637e8f60e11b81525f6004820152602401611a5a565b612089825f83612981565b5050565b612095612f58565b6040517f2e1a7d4d000000000000000000000000000000000000000000000000000000008152600481018290527f000000000000000000000000ee7d8bcfb72bc1880d0cf19822eb0a2e6577ab626001600160a01b031690632e1a7d4d906024015f604051808303815f87803b15801561210d575f5ffd5b505af115801561211f573d5f5f3e3d5ffd5b5050505061214c7f000000000000000000000000ee7d8bcfb72bc1880d0cf19822eb0a2e6577ab6261272f565b6121568282612ac0565b6120896001600555565b612168612f58565b61217c6001600160a01b0384168383612f9b565b6121858361272f565b611c636001600555565b5f5f5f61219a610b96565b90505b80821015611be7575f6121af836115bc565b90506402540be4006121d5826001600160a01b03165f9081526009602052604090205490565b6121df9087615af8565b6121e99190615b23565b93506121f6813386612160565b8261220081615b42565b9350505061219d565b61221161267b565b5f61222188888888888888612fcc565b905061222c81611fcf565b612236878661305c565b61223e6130f7565b6122498887876127b0565b5050505050505050565b5f5f612284897f000000000000000000000000ee7d8bcfb72bc1880d0cf19822eb0a2e6577ab628a8a8a8a8a612b49565b915091506122918961272f565b61229b858261208d565b846001600160a01b03167f000000000000000000000000ee7d8bcfb72bc1880d0cf19822eb0a2e6577ab626001600160a01b03168a6001600160a01b03167f4be05c8d54f5e056ab2cfa033e9f582057001268c3e28561bb999d35d2c8f2c885858860405161230c93929190615ba1565b60405180910390a4505050505050505050565b6006546001600160a01b03163314611467576040517f118cdaa7000000000000000000000000000000000000000000000000000000008152336004820152602401611a5a565b600680546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0905f90a35050565b6040516370a0823160e01b81523060048201525f906001600160a01b038316906370a0823190602401602060405180830381865afa1580156123fa573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610b3b9190615bc8565b5f610cff8383613131565b6001600160a01b03811661245057604051631c06ca6760e01b815260040160405180910390fd5b806001600160a01b031663feaf968c6040518163ffffffff1660e01b815260040160a060405180830381865afa9250505080156124aa575060408051601f3d908101601f191682019092526124a791810190615bf8565b60015b6124c757604051631c06ca6760e01b815260040160405180910390fd5b505050505050565b5f610b3b82610b8a565b5f5f5f5f5f866001600160a01b031663feaf968c6040518163ffffffff1660e01b815260040160a060405180830381865afa15801561251a573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061253e9190615bf8565b9450945050935093508069ffffffffffffffffffff168469ffffffffffffffffffff161415806125775750426125748784615b75565b11155b156125ae576040517fa9f7344500000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6125b783613157565b979650505050505050565b6001600160a01b0382166125eb5760405163ec442f0560e01b81525f6004820152602401611a5a565b6120895f8383612981565b5f5f60205f8451602086015f885af180612615576040513d5f823e3d81fd5b50505f513d9150811561262c578060011415612639565b6001600160a01b0384163b155b15611be7576040517f5274afe70000000000000000000000000000000000000000000000000000000081526001600160a01b0385166004820152602401611a5a565b3415611467576114677f000000000000000000000000ee7d8bcfb72bc1880d0cf19822eb0a2e6577ab6234612ac0565b5f5f5f6126b784612bc9565b915091506126ec7f05324cbcf9ac04abf61ba4b51fcd40742cf6e4e1e24685ab6577a7cd6b0723a08c8c8c8c8c8c8989613199565b9250611fb78386612c52565b5f612701612e3a565b1561270a575060015b5f6127168585846131d6565b90508115612728576127288382612f1a565b5050505050565b6040516370a0823160e01b81523060048201526001600160a01b038216906370a0823190602401602060405180830381865afa158015612771573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906127959190615bc8565b6001600160a01b039091165f90815260096020526040902055565b6127bb838383613238565b60408051828152602081018490526001600160a01b038516917f73a19dd210f1a7f902193214c0ee91dd35ee5b4d920cba8d519eca65a7b488ca910160405180910390a2505050565b6001600160a01b038416612846576040517fe602df050000000000000000000000000000000000000000000000000000000081525f6004820152602401611a5a565b6001600160a01b038316612888576040517f94280d620000000000000000000000000000000000000000000000000000000081525f6004820152602401611a5a565b6001600160a01b038085165f9081526001602090815260408083209387168352929052208290558015611be757826001600160a01b0316846001600160a01b03167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925846040516128fa91815260200190565b60405180910390a350505050565b604080516001600160a01b0319841660208201528151600c818303018152602c909101909152829081906001600160a01b038a166129545761294f89898989878987611e21565b610b1c565b6001600160a01b0389166129715761294f8a898989878987612253565b610b1c8a8a8a8a8a888a88611e77565b6001600160a01b0383166129ab578060025f8282546129a09190615b75565b90915550612a349050565b6001600160a01b0383165f9081526020819052604090205481811015612a16576040517fe450d38c0000000000000000000000000000000000000000000000000000000081526001600160a01b03851660048201526024810182905260448101839052606401611a5a565b6001600160a01b0384165f9081526020819052604090209082900390555b6001600160a01b038216612a5057600280548290039055612a6e565b6001600160a01b0382165f9081526020819052604090208054820190555b816001600160a01b0316836001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef83604051612ab391815260200190565b60405180910390a3505050565b5f826001600160a01b0316826040515f6040518083038185875af1925050503d805f8114612b09576040519150601f19603f3d011682016040523d82523d5f602084013e612b0e565b606091505b5050905080611c63576040517f6d963f8800000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f5f5f612b5b8a8a8a8a8a8a8a613309565b9050612b6681611fcf565b612b728a8a8a8a613345565b9093509150612b848a848b858a6133b4565b5097509795505050505050565b612b99612f58565b612ba28461272f565b612bb66001600160a01b0384168383612f9b565b612bbf8361272f565b611be76001600555565b5f606082806020019051810190612be09190615c46565b90925090505f612bee610b96565b905080825114612c1157604051632b477e7160e11b815260040160405180910390fd5b50915091565b5f5f612c2889898989898989613576565b60405161190160f01b8152600281019b909b5260228b015250506042909720979650505050505050565b61208982827f00000000000000000000000008938a61ba9523298dbcacee0cda5b371fb7f1f8613709565b5f612c8760025490565b9050805f03612c9557505050565b825f03612cce576040517faac088f400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f612cd7610b96565b90505f805b82811015612d92575f612cee826115bc565b6001600160a01b0381165f908152600a602052604081205491925090612d189060ff166012615cff565b612d2390600a615dfb565b90505f81612d30846123b6565b612d3a9190615af8565b90505f670de0b6b3a7640000898681518110612d5857612d58615ad0565b602002602001015183612d6b9190615af8565b612d759190615b23565b9050612d818187615b75565b955050505050806001019050612cdc565b505f83612da7670de0b6b3a764000084615af8565b612db19190615b23565b9050858103612dc257505050505050565b5f612710612dd1600a89615af8565b612ddb9190615b23565b90505f878311612df457612def8389615e09565b612dfe565b612dfe8884615e09565b905081811115612249576040517f8175385600000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f5f612e446137e3565b90505f5b81811015612e8e575f600f81612e5d846137ec565b6001600160a01b03908116825260208201929092526040015f20541603612e86575f9250505090565b600101612e48565b50600191505090565b5f5f5f612ea3856137f6565b915091505f612ec9866001600160a01b03165f908152600a602052604090205460ff1690565b612ed4906012615cff565b612edf90600a615dfb565b90505f612eec8287615af8565b90505f612efa84600a615dfb565b612f048684615af8565b612f0e9190615b23565b98975050505050505050565b5f612f2c612f2760025490565b613860565b90505f670de0b6b3a7640000612f428386615af8565b612f4c9190615b23565b9050611be781846138e8565b600260055403612f94576040517f3ee5aeb500000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6002600555565b6040516001600160a01b03838116602483015260448201839052611c6391859182169063a9059cbb90606401611ba0565b5f5f612fd6610b96565b905087518114612ff957604051632b477e7160e11b815260040160405180910390fd5b5f5f61300485612bc9565b915091506130387f05324cbcf9ac04abf61ba4b51fcd40742cf6e4e1e24685ab6577a7cd6b0723a08c8c8c8c8c8888613946565b93506130448487612c52565b61304e8282612c7d565b505050979650505050505050565b5f613065612e3a565b1561306e575060015b5f613077610b96565b90505f805b828110156130e6575f86828151811061309757613097615ad0565b602002602001015111156130de576130d16130b1826115bc565b8783815181106130c3576130c3615ad0565b6020026020010151866131d6565b6130db9083615b75565b91505b60010161307c565b508215612728576127288482612f1a565b5f5f613103600b611d2c565b90505b808210156120895761311f61311a836115bc565b61272f565b8161312981615b42565b925050613106565b5f825f01828154811061314657613146615ad0565b905f5260205f200154905092915050565b5f5f821215613195576040517fa8ce443200000000000000000000000000000000000000000000000000000000815260048101839052602401611a5a565b5090565b5f5f6131ab8a8a8a8a8a8a8a8a613957565b60405161190160f01b8152600281019c909c5260228c01525050604290982098975050505050505050565b5f5f6131e185613af1565b90508381101561321d576040517ff8b3bb6100000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b82156132305761322d8582612e97565b91505b509392505050565b600182101561325a5760405163abf20e8f60e01b815260040160405180910390fd5b6001600160a01b0383165f908152600d6020526040902060010154156132ac576040517f53d1b1d200000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f604051806040016040528084603c6132c59190615af8565b6132cf9042615b75565b815260209081018490526001600160a01b0386165f908152600d82526040902082518155908201516001909101559050611be730836125c2565b5f6133397f05324cbcf9ac04abf61ba4b51fcd40742cf6e4e1e24685ab6577a7cd6b0723a0898989898989613b72565b90506125b78183612c52565b5f5f61335086610b8a565b61336d57604051630732619560e01b815260040160405180910390fd5b61337685610b8a565b61339357604051630732619560e01b815260040160405180910390fd5b61339c86613af1565b91506133a9848385613bb0565b905094509492505050565b6133db60405180608001604052805f81526020015f81526020015f81526020015f81525090565b6001600160a01b038681165f81815260096020818152604080842054875294891683529081528382205485820152918152600a82528290205460c085901c9267ffffffffffffffff608087901c81169361ffff603089901c8116949189901c169288901c909116906134519060ff166012615cff565b61345c90600a615dfb565b6040808801919091526001600160a01b038a165f908152600a60205220546134889060ff166012615cff565b61349390600a615dfb565b606087015260408601515f906134ec906134ad908d615af8565b6040890151895189916134bf91615af8565b878b606001518e6134d09190615af8565b8a8d606001518e602001516134e59190615af8565b8a8a613c4f565b905080613525576040517f8e7572da00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6001600160a01b038c81165f908152600f6020526040902054161580159061356557506001600160a01b038a81165f908152600f60205260409020541615155b15611448576114488b8a8e8d613dfc565b5f5f826040516020016135899190615e1c565b604051602081830303815290604052805190602001209050604051602001613692907f5769746864726177616c537472756374286164647265737320746f6b656e5f6881527f6f6c6465722c75696e7432353620706f6f6c5f746f6b656e5f616d6f756e745f60208201527f746f5f6275726e2c616464726573732061737365745f616464726573732c756960408201527f6e743235362061737365745f616d6f756e742c75696e7432353620676f6f645f60608201527f756e74696c2c75696e74323536206c705f746f6b656e5f70726963652c75696e60808201527f743235365b5d207072696365732900000000000000000000000000000000000060a082015260ae0190565b60408051808303601f190181528282528051602091820120818401526001600160a01b039b8c1683830152606083019a909a529790991660808a015260a0890195909552505060c086019190915260e085015261010080850191909152815180850390910181526101209093019052815191012090565b5f61372184845f015185602001518660400151613fa4565b9050816001600160a01b0316816001600160a01b031614611be757613796843260405160200161376d92919091825260601b6bffffffffffffffffffffffff1916602082015260340190565b60405160208183030381529060405280519060200120845f015185602001518660400151613fa4565b9050816001600160a01b0316816001600160a01b031614611be7576040517fa66e191800000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f610ba1610b96565b5f610b3b826115bc565b5f5f613800613fd0565b6001600160a01b038084165f908152600f602090815260409182902082516060810184528154909416808552600182015492850183905260029091015460ff169284019290925261385191906124d9565b92508060400151915050915091565b5f5f61386a6137e3565b90505f805b828110156138aa575f613881826137ec565b905061389581613890836140e0565b612e97565b61389f9084615b75565b92505060010161386f565b5083156138d557836138c4670de0b6b3a764000083615af8565b6138ce9190615b23565b92506138e1565b670de0b6b3a764000092505b5050919050565b5f6127106138f7601484615af8565b6139019190615b23565b905061390d8183615b75565b831115611c63576040517fba13eb2800000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f5f612c28898989898989896140fd565b5f5f8260405160200161396a9190615e1c565b604051602081830303815290604052805190602001209050604051602001613a73907f53696e676c654465706f7369745374727563742861646472657373206465706f81527f7369746f722c6164647265737320746f6b656e2c75696e7432353620616d6f7560208201527f6e742c75696e74323536206c6f636b5f74696d652c75696e7432353620706f6f60408201527f6c5f746f6b656e732c75696e7432353620676f6f645f756e74696c2c75696e7460608201527f323536206c705f746f6b656e5f70726963652c75696e743235365b5d2070726960808201527f636573290000000000000000000000000000000000000000000000000000000060a082015260a40190565b60408051808303601f190181528282528051602091820120818401526001600160a01b039c8d16838301529a909b166060820152608081019890985260a0880196909652505060c085019290925260e08401526101008301526101208083019190915283518083039091018152610140909101909252815191012090565b6001600160a01b0381165f818152600960205260408082205490516370a0823160e01b8152306004820152919290916370a0823190602401602060405180830381865afa158015613b44573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613b689190615bc8565b610b3b9190615e09565b5f5f613b8288888888888861429b565b60405161190160f01b8152600281018b905260228101829052604290209091505b9998505050505050505050565b5f838303613bbf575080610cff565b5f84613bd0856402540be400615af8565b613bda9190615b23565b9050613bea620f42406032615af8565b613bf9906402540be400615b75565b8110613c3f576402540be40083613c14620f42406032615af8565b613c23906402540be400615b75565b613c2d9190615af8565b613c379190615b23565b915050610cff565b6402540be400613c2d8483615af8565b5f8080806305f5e100613c628c8e615af8565b613c6c9190615b23565b90505f613c82613c7c8c84615af8565b876143d9565b90508015613cb45780613c9d83670de0b6b3a7640000615af8565b613ca79190615b23565b613cb19085615b75565b93505b5f6305f5e100613cc48a8c615af8565b613cce9190615b23565b90505f613ce4613cde8a84615af8565b896143d9565b90508015613d165780613cff83670de0b6b3a7640000615af8565b613d099190615b23565b613d139087615b75565b95505b505050505f6305f5e1008d8c613d2c9190615b75565b613d36908e615af8565b613d409190615b23565b90505f613d50613c7c8c84615af8565b90508015613d825780613d6b83670de0b6b3a7640000615af8565b613d759190615b23565b613d7f9084615b75565b92505b5f6305f5e100613d928c8b615e09565b613d9c908c615af8565b613da69190615b23565b90505f613db6613cde8a84615af8565b90508015613de85780613dd183670de0b6b3a7640000615af8565b613ddb9190615b23565b613de59086615b75565b94505b50505091109b9a5050505050505050505050565b5f5f613e07846137f6565b915091505f5f613e16856137f6565b91509150613e4160405180608001604052805f81526020015f81526020015f81526020015f81525090565b6001600160a01b0387165f908152600a602052604090205460ff16613e67906012615cff565b613e7290600a615dfb565b6040820152613e98866001600160a01b03165f908152600a602052604090205460ff1690565b613ea3906012615cff565b613eae90600a615dfb565b60608201526040810151613ec2908a615af8565b81525f613ed0856012615cff565b613edb90600a615dfb565b613ee59087615af8565b90505f613ef3846012615cff565b613efe90600a615dfb565b613f089086615af8565b90505f83606001518284865f0151613f209190615af8565b613f2a9190615b23565b613f349190615b23565b90505f612710613f4560c882615b75565b613f4f9084615af8565b613f599190615b23565b9050808c1115613f95576040517f6b4ba5d800000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b50505050505050505050505050565b5f5f5f5f613fb48888888861444c565b925092509250613fc48282614514565b50909695505050505050565b600e546001600160a01b0316613fe257565b5f5f600e5f9054906101000a90046001600160a01b03166001600160a01b031663feaf968c6040518163ffffffff1660e01b815260040160a060405180830381865afa158015614034573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906140589190615bf8565b50509250925050815f14614098576040517f032b3d0000000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f6140a38242615e09565b9050610e108111611c63576040517fd15f73b500000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6001600160a01b0381165f90815260096020526040812054610b3b565b5f5f876040516020016141109190615e1c565b6040516020818303038152906040528051906020012090505f8360405160200161413a9190615e1c565b60405160208183030381529060405280519060200120905060405160200161421d907f4465706f7369745374727563742861646472657373206465706f7369746f722c81527f75696e743235365b5d206465706f7369745f616d6f756e74732c75696e74323560208201527f36206c6f636b5f74696d652c75696e7432353620706f6f6c5f746f6b656e732c60408201527f75696e7432353620676f6f645f756e74696c2c75696e74323536206c705f746f60608201527f6b656e5f70726963652c75696e743235365b5d207072696365732900000000006080820152609b0190565b60408051601f198184030181528282528051602091820120908301526001600160a01b038c1690820152606081018390526080810189905260a0810188905260c0810187905260e081018690526101008101829052610120016040516020818303038152906040528051906020012092505050979650505050505050565b5f604051602001614367907f4f66666572537472756374286164647265737320696e7075745f746f6b656e2c81527f61646472657373206f75747075745f746f6b656e2c75696e7432353620696e7060208201527f75745f616d6f756e742c75696e74323536206f75747075745f616d6f756e742c60408201527f75696e7432353620676f6f645f756e74696c2c6164647265737320646573746960608201527f6e6174696f6e5f616464726573732900000000000000000000000000000000006080820152608f0190565b60408051808303601f190181528282528051602091820120818401526001600160a01b03998a16838301529789166060830152608082019690965260a08101949094525060c083019190915290931660e080850191909152815180850390910181526101009093019052815191012090565b5f825f036143e857505f610b3b565b5f6143fd6143f861107786614617565b61465c565b90505f614428670de0b6b3a76400006144228461441c61107789614617565b906147de565b906148c5565b90505f6144376110778361499d565b905061444281613157565b9350505050610b3b565b5f80807f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a084111561448557505f9150600390508261450a565b604080515f808252602082018084528a905260ff891692820192909252606081018790526080810186905260019060a0016020604051602081039080840390855afa1580156144d6573d5f5f3e3d5ffd5b5050604051601f1901519150506001600160a01b03811661450157505f92506001915082905061450a565b92505f91508190505b9450945094915050565b5f82600381111561452757614527615e51565b03614530575050565b600182600381111561454457614544615e51565b0361457b576040517ff645eedf00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600282600381111561458f5761458f615e51565b036145c9576040517ffce698f700000000000000000000000000000000000000000000000000000000815260048101829052602401611a5a565b60038260038111156145dd576145dd615e51565b03612089576040517fd78bce0c00000000000000000000000000000000000000000000000000000000815260048101829052602401611a5a565b5f6001600160ff1b03821115613195576040517f24775e0600000000000000000000000000000000000000000000000000000000815260048101839052602401611a5a565b5f8181811361469a576040517f059b101b00000000000000000000000000000000000000000000000000000000815260048101849052602401611a5a565b5f670de0b6b3a764000082126146b2575060016146d7565b505f19816ec097ce7bc90715b34b9f1000000000816146d3576146d3615b0f565b0591505b5f614762670de0b6b3a7640000840560016fffffffffffffffffffffffffffffffff821160071b91821c67ffffffffffffffff811160061b90811c63ffffffff811160051b90811c61ffff811160041b90811c60ff8111600390811b91821c600f811160021b90811c918211871b91821c969096119490961792909217171791909117919091171790565b9050670de0b6b3a7640000810283821d670de0b6b3a763ffff19810161478a578184026125b7565b671bc16d674ec800006706f05b59d3b200005b5f8113156147cf57670de0b6b3a76400008380020592508183126147c7579283019260019290921d915b60011d61479d565b50505091909102949350505050565b5f8282600160ff1b8214806147f65750600160ff1b81145b1561482d576040517fa6070c2500000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f5f5f841261483c5783614840565b835f035b91505f831261484f5782614853565b825f035b90505f6148608383614a6b565b90506001600160ff1b038111156148ad576040517f120b5b430000000000000000000000000000000000000000000000000000000081526004810189905260248101889052604401611a5a565b5f1985851813613ba3816148c157825f0390565b8290565b5f8282600160ff1b8214806148dd5750600160ff1b81145b15614914576040517f9fe2b45000000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f5f5f84126149235783614927565b835f035b91505f8312614936578261493a565b825f035b90505f61495083670de0b6b3a764000084614b50565b90506001600160ff1b038111156148ad576040517fd49c26b30000000000000000000000000000000000000000000000000000000081526004810189905260248101889052604401611a5a565b5f8181811215614a005768033dd1780914b97114198112156149c157505f92915050565b6149f96149d86110776149d3845f0390565b61499d565b6ec097ce7bc90715b34b9f1000000000816149f5576149f5615b0f565b0590565b9150614a65565b680a688906bd8affffff811315614a46576040517f0360d02800000000000000000000000000000000000000000000000000000000815260048101849052602401611a5a565b670de0b6b3a7640000604082901b05614a6161107782614c38565b9250505b50919050565b5f80805f19848609848602925082811083820303915050805f03614a9c5750670de0b6b3a764000090049050610b3b565b670de0b6b3a76400008110614ae7576040517f5173648d0000000000000000000000000000000000000000000000000000000081526004810186905260248101859052604401611a5a565b5f670de0b6b3a7640000858709620400008185030493109091037d40000000000000000000000000000000000000000000000000000000000002919091177faccb18165bd6fe31ae1cf318dc5b51eee0e1ba569b88cd74c1773b91fac106690291505092915050565b5f80805f19858709858702925082811083820303915050805f03614b8757838281614b7d57614b7d615b0f565b0492505050610cff565b838110614bd1576040517f63a05778000000000000000000000000000000000000000000000000000000008152600481018790526024810186905260448101859052606401611a5a565b5f8486880960026001871981018816978890046003810283188082028403028082028403028082028403028082028403028082028403029081029092039091025f889003889004909101858311909403939093029303949094049190911702949350505050565b7780000000000000000000000000000000000000000000000067ff00000000000000821615614d5957678000000000000000821615614c805768016a09e667f3bcc9090260401c5b674000000000000000821615614c9f576801306fe0a31b7152df0260401c5b672000000000000000821615614cbe576801172b83c7d517adce0260401c5b671000000000000000821615614cdd5768010b5586cf9890f62a0260401c5b670800000000000000821615614cfc576801059b0d31585743ae0260401c5b670400000000000000821615614d1b57680102c9a3e778060ee70260401c5b670200000000000000821615614d3a5768010163da9fb33356d80260401c5b670100000000000000821615614d5957680100b1afa5abcbed610260401c5b66ff000000000000821615614e58576680000000000000821615614d865768010058c86da1c09ea20260401c5b6640000000000000821615614da4576801002c605e2e8cec500260401c5b6620000000000000821615614dc257680100162f3904051fa10260401c5b6610000000000000821615614de0576801000b175effdc76ba0260401c5b6608000000000000821615614dfe57680100058ba01fb9f96d0260401c5b6604000000000000821615614e1c5768010002c5cc37da94920260401c5b6602000000000000821615614e3a576801000162e525ee05470260401c5b6601000000000000821615614e585768010000b17255775c040260401c5b65ff0000000000821615614f4e5765800000000000821615614e83576801000058b91b5bc9ae0260401c5b65400000000000821615614ea057680100002c5c89d5ec6d0260401c5b65200000000000821615614ebd5768010000162e43f4f8310260401c5b65100000000000821615614eda57680100000b1721bcfc9a0260401c5b65080000000000821615614ef75768010000058b90cf1e6e0260401c5b65040000000000821615614f14576801000002c5c863b73f0260401c5b65020000000000821615614f3157680100000162e430e5a20260401c5b65010000000000821615614f4e576801000000b1721835510260401c5b64ff0000000082161561503b57648000000000821615614f7757680100000058b90c0b490260401c5b644000000000821615614f935768010000002c5c8601cc0260401c5b642000000000821615614faf576801000000162e42fff00260401c5b641000000000821615614fcb5768010000000b17217fbb0260401c5b640800000000821615614fe7576801000000058b90bfce0260401c5b64040000000082161561500357680100000002c5c85fe30260401c5b64020000000082161561501f5768010000000162e42ff10260401c5b64010000000082161561503b57680100000000b17217f80260401c5b63ff00000082161561511f5763800000008216156150625768010000000058b90bfc0260401c5b634000000082161561507d576801000000002c5c85fe0260401c5b632000000082161561509857680100000000162e42ff0260401c5b63100000008216156150b3576801000000000b17217f0260401c5b63080000008216156150ce57680100000000058b90c00260401c5b63040000008216156150e95768010000000002c5c8600260401c5b6302000000821615615104576801000000000162e4300260401c5b630100000082161561511f5768010000000000b172180260401c5b62ff00008216156151fa5762800000821615615144576801000000000058b90c0260401c5b6240000082161561515e57680100000000002c5c860260401c5b622000008216156151785768010000000000162e430260401c5b6210000082161561519257680100000000000b17210260401c5b620800008216156151ac5768010000000000058b910260401c5b620400008216156151c6576801000000000002c5c80260401c5b620200008216156151e057680100000000000162e40260401c5b620100008216156151fa576801000000000000b1720260401c5b61ff008216156152cc5761800082161561521d57680100000000000058b90260401c5b6140008216156152365768010000000000002c5d0260401c5b61200082161561524f576801000000000000162e0260401c5b6110008216156152685768010000000000000b170260401c5b610800821615615281576801000000000000058c0260401c5b61040082161561529a57680100000000000002c60260401c5b6102008216156152b357680100000000000001630260401c5b6101008216156152cc57680100000000000000b10260401c5b60ff8216156153955760808216156152ed57680100000000000000590260401c5b6040821615615305576801000000000000002c0260401c5b602082161561531d57680100000000000000160260401c5b6010821615615335576801000000000000000b0260401c5b600882161561534d57680100000000000000060260401c5b600482161561536557680100000000000000030260401c5b600282161561537d57680100000000000000010260401c5b600182161561539557680100000000000000010260401c5b670de0b6b3a76400000260409190911c60bf031c90565b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b602081525f610cff60208301846153ac565b80356001600160a01b0381168114615402575f5ffd5b919050565b5f60608284031215614a65575f5ffd5b5f5f83601f840112615427575f5ffd5b50813567ffffffffffffffff81111561543e575f5ffd5b602083019150836020828501011115615455575f5ffd5b9250929050565b5f5f5f5f5f5f5f5f610120898b031215615474575f5ffd5b61547d896153ec565b9750602089013596506040890135955060608901359450608089013593506154a88a60a08b01615407565b925061010089013567ffffffffffffffff8111156154c4575f5ffd5b6154d08b828c01615417565b999c989b5096995094979396929594505050565b5f5f604083850312156154f5575f5ffd5b6154fe836153ec565b946020939093013593505050565b5f5f5f5f5f5f60c08789031215615521575f5ffd5b505084359660208601359650604086013595606081013595506080810135945060a0013592509050565b5f6020828403121561555b575f5ffd5b610cff826153ec565b606080825284519082018190525f9060208601906080840190835b8181101561559d57835183526020938401939092019160010161557f565b5050838103602080860191909152865180835291810192508601905f5b818110156155e15782516001600160a01b03168452602093840193909201916001016155ba565b505050604092909201929092529392505050565b5f5f5f60608486031215615607575f5ffd5b615610846153ec565b925061561e602085016153ec565b929592945050506040919091013590565b5f5f5f5f5f5f5f5f610120898b031215615647575f5ffd5b615650896153ec565b975060208901359650604089013595506060890135945061567360808a016153ec565b93506154a88a60a08b01615407565b5f5f5f5f5f5f5f5f5f6101408a8c03121561569b575f5ffd5b6156a48a6153ec565b98506156b260208b016153ec565b975060408a0135965060608a0135955060808a013594506156d560a08b016153ec565b93506156e48b60c08c01615407565b92506101208a013567ffffffffffffffff811115615700575f5ffd5b61570c8c828d01615417565b915080935050809150509295985092959850929598565b5f5f5f5f5f5f5f5f610120898b03121561573b575f5ffd5b615744896153ec565b97506020890135965061575960408a016153ec565b955060608901359450608089013593506154a88a60a08b01615407565b5f60208284031215615786575f5ffd5b5035919050565b5f5f83601f84011261579d575f5ffd5b50813567ffffffffffffffff8111156157b4575f5ffd5b6020830191508360208260051b8501011115615455575f5ffd5b5f5f5f5f5f5f5f5f5f6101208a8c0312156157e7575f5ffd5b6157f08a6153ec565b985060208a013567ffffffffffffffff81111561580b575f5ffd5b6158178c828d0161578d565b90995097505060408a0135955060608a0135945060808a0135935061583f8b60a08c01615407565b92506101008a013567ffffffffffffffff811115615700575f5ffd5b5f5f5f5f5f5f5f5f5f6101408a8c031215615874575f5ffd5b61587d8a6153ec565b985061588b60208b016153ec565b975060408a0135965060608a0135955060808a0135945060a08a013593506156e48b60c08c01615407565b5f5f5f5f5f5f5f5f610100898b0312156158ce575f5ffd5b883567ffffffffffffffff8111156158e4575f5ffd5b6158f08b828c0161578d565b9099509750506020890135955060408901359450606089013593506159188a60808b01615407565b925060e089013567ffffffffffffffff8111156154c4575f5ffd5b5f5f5f5f5f5f60a08789031215615948575f5ffd5b86359550602087013594506040870135935060608701359250608087013567ffffffffffffffff81111561597a575f5ffd5b61598689828a01615417565b979a9699509497509295939492505050565b5f5f604083850312156159a9575f5ffd5b50508035926020909101359150565b5f5f604083850312156159c9575f5ffd5b6159d2836153ec565b91506159e0602084016153ec565b90509250929050565b600181811c908216806159fd57607f821691505b602082108103614a6557634e487b7160e01b5f52602260045260245ffd5b634e487b7160e01b5f52604160045260245ffd5b604051601f8201601f1916810167ffffffffffffffff81118282101715615a5857615a58615a1b565b604052919050565b60ff81168114611a6c575f5ffd5b5f6060828403128015615a7f575f5ffd5b506040516060810167ffffffffffffffff81118282101715615aa357615aa3615a1b565b6040528235615ab181615a60565b8152602083810135908201526040928301359281019290925250919050565b634e487b7160e01b5f52603260045260245ffd5b634e487b7160e01b5f52601160045260245ffd5b8082028115828204841417610b3b57610b3b615ae4565b634e487b7160e01b5f52601260045260245ffd5b5f82615b3d57634e487b7160e01b5f52601260045260245ffd5b500490565b5f60018201615b5357615b53615ae4565b5060010190565b5f60208284031215615b6a575f5ffd5b8151610cff81615a60565b80820180821115610b3b57610b3b615ae4565b60ff8181168382160190811115610b3b57610b3b615ae4565b838152826020820152606060408201525f615bbf60608301846153ac565b95945050505050565b5f60208284031215615bd8575f5ffd5b5051919050565b805169ffffffffffffffffffff81168114615402575f5ffd5b5f5f5f5f5f60a08688031215615c0c575f5ffd5b615c1586615bdf565b60208701516040880151606089015192975090955093509150615c3a60808701615bdf565b90509295509295909350565b5f5f60408385031215615c57575f5ffd5b8251602084015190925067ffffffffffffffff811115615c75575f5ffd5b8301601f81018513615c85575f5ffd5b805167ffffffffffffffff811115615c9f57615c9f615a1b565b8060051b615caf60208201615a2f565b91825260208184018101929081019088841115615cca575f5ffd5b6020850194505b83851015615cf057845180835260209586019590935090910190615cd1565b80955050505050509250929050565b60ff8281168282160390811115610b3b57610b3b615ae4565b6001815b6001841115615d5357808504811115615d3757615d37615ae4565b6001841615615d4557908102905b60019390931c928002615d1c565b935093915050565b5f82615d6957506001610b3b565b81615d7557505f610b3b565b8160018114615d8b5760028114615d9557615db1565b6001915050610b3b565b60ff841115615da657615da6615ae4565b50506001821b610b3b565b5060208310610133831016604e8410600b8410161715615dd4575081810a610b3b565b615de05f198484615d18565b805f1904821115615df357615df3615ae4565b029392505050565b5f610cff60ff841683615d5b565b81810381811115610b3b57610b3b615ae4565b81515f90829060208501835b82811015615e46578151845260209384019390910190600101615e28565b509195945050505050565b634e487b7160e01b5f52602160045260245ffdfea264697066735822122087110682112f93f731b96de206515815b6a394f76063ca9ed3d7681d781859e764736f6c634300081c0033
Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)
00000000000000000000000008938a61ba9523298dbcacee0cda5b371fb7f1f8000000000000000000000000ee7d8bcfb72bc1880d0cf19822eb0a2e6577ab6200000000000000000000000000000000000000000000000000000000000000c000000000000000000000000000000000000000000000000000000000000001200000000000000000000000000000000000000000000000000000000000000180000000000000000000000000a372e7f8ba1f0377667c8c52fea2bc3e271a0e680000000000000000000000000000000000000000000000000000000000000002000000000000000000000000ee7d8bcfb72bc1880d0cf19822eb0a2e6577ab62000000000000000000000000203a662b0bd271a6ed5a60edfbd04bfce608fd3600000000000000000000000000000000000000000000000000000000000000020000000000000000000000007bdbdb772f4a073badd676a567c6ed82049a8eee000000000000000000000000be5ce90e16b9d9d988d64b0e1f6ed46ebafb960600000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000e100000000000000000000000000000000000000000000000000000000000015180
-----Decoded View---------------
Arg [0] : theSigner (address): 0x08938a61BA9523298dbCAceE0cda5B371FB7f1F8
Arg [1] : theWrapper (address): 0xEE7D8BCFb72bC1880D0Cf19822eB0A2e6577aB62
Arg [2] : tokens (address[]): 0xEE7D8BCFb72bC1880D0Cf19822eB0A2e6577aB62,0x203A662b0BD271A6ed5a60EdFbd04bFce608FD36
Arg [3] : _oracles (address[]): 0x7BdBDB772f4a073BadD676A567C6ED82049a8eEE,0xbe5CE90e16B9d9d988D64b0E1f6ed46EbAfb9606
Arg [4] : minTimeTolerances (uint256[]): 3600,86400
Arg [5] : initialOwner (address): 0xA372e7f8bA1F0377667C8c52FEA2BC3E271a0e68
-----Encoded View---------------
15 Constructor Arguments found :
Arg [0] : 00000000000000000000000008938a61ba9523298dbcacee0cda5b371fb7f1f8
Arg [1] : 000000000000000000000000ee7d8bcfb72bc1880d0cf19822eb0a2e6577ab62
Arg [2] : 00000000000000000000000000000000000000000000000000000000000000c0
Arg [3] : 0000000000000000000000000000000000000000000000000000000000000120
Arg [4] : 0000000000000000000000000000000000000000000000000000000000000180
Arg [5] : 000000000000000000000000a372e7f8ba1f0377667c8c52fea2bc3e271a0e68
Arg [6] : 0000000000000000000000000000000000000000000000000000000000000002
Arg [7] : 000000000000000000000000ee7d8bcfb72bc1880d0cf19822eb0a2e6577ab62
Arg [8] : 000000000000000000000000203a662b0bd271a6ed5a60edfbd04bfce608fd36
Arg [9] : 0000000000000000000000000000000000000000000000000000000000000002
Arg [10] : 0000000000000000000000007bdbdb772f4a073badd676a567c6ed82049a8eee
Arg [11] : 000000000000000000000000be5ce90e16b9d9d988d64b0e1f6ed46ebafb9606
Arg [12] : 0000000000000000000000000000000000000000000000000000000000000002
Arg [13] : 0000000000000000000000000000000000000000000000000000000000000e10
Arg [14] : 0000000000000000000000000000000000000000000000000000000000015180
Loading...
Loading
Loading...
Loading
Multichain Portfolio | 34 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.