Source Code
More Info
Private Name Tags
ContractCreator
TokenTracker
Latest 25 from a total of 18,527 transactions
| Transaction Hash |
Method
|
Block
|
From
|
To
|
|||||
|---|---|---|---|---|---|---|---|---|---|
| Redeem | 38043433 | 2 days ago | IN | 0 ETH | 0.00000112 | ||||
| Redeem | 38032572 | 2 days ago | IN | 0 ETH | 0.00000039 | ||||
| Redeem | 38001284 | 3 days ago | IN | 0 ETH | 0.00000083 | ||||
| Redeem | 38000653 | 3 days ago | IN | 0 ETH | 0.00000064 | ||||
| Redeem | 37999881 | 3 days ago | IN | 0 ETH | 0.00000048 | ||||
| Redeem | 37991489 | 3 days ago | IN | 0 ETH | 0.00000013 | ||||
| Redeem | 37989994 | 3 days ago | IN | 0 ETH | 0.0000001 | ||||
| Redeem | 37982900 | 4 days ago | IN | 0 ETH | 0.00000004 | ||||
| End Pools | 37980839 | 4 days ago | IN | 0 ETH | 0.00000007 | ||||
| Fill Orders | 37908199 | 5 days ago | IN | 0 ETH | 0.00000036 | ||||
| Fill Orders | 37815098 | 8 days ago | IN | 0 ETH | 0.00000211 | ||||
| Redeem | 37815067 | 8 days ago | IN | 0 ETH | 0.00000066 | ||||
| Redeem | 37815062 | 8 days ago | IN | 0 ETH | 0.00000072 | ||||
| Fill Orders | 37792155 | 8 days ago | IN | 0 ETH | 0.00000304 | ||||
| Redeem | 37742490 | 9 days ago | IN | 0 ETH | 0.00000308 | ||||
| Redeem | 37742487 | 9 days ago | IN | 0 ETH | 0.00000309 | ||||
| Redeem | 37742486 | 9 days ago | IN | 0 ETH | 0.00000236 | ||||
| Redeem | 37702549 | 10 days ago | IN | 0 ETH | 0.00000066 | ||||
| Fill Orders | 37700064 | 10 days ago | IN | 0 ETH | 0.00000152 | ||||
| Redeem | 37700051 | 10 days ago | IN | 0 ETH | 0.00000048 | ||||
| Redeem | 37697183 | 10 days ago | IN | 0 ETH | 0.00000694 | ||||
| Fill Orders | 37691638 | 10 days ago | IN | 0 ETH | 0.00001117 | ||||
| Redeem | 37686177 | 10 days ago | IN | 0 ETH | 0.00000139 | ||||
| Fill Orders | 37685254 | 11 days ago | IN | 0 ETH | 0.00000258 | ||||
| Redeem | 37685237 | 11 days ago | IN | 0 ETH | 0.00000078 |
Cross-Chain Transactions
Loading...
Loading
Contract Source Code Verified (Exact Match)
Contract Name:
SilicaPools
Compiler Version
v0.8.27+commit.40a35a09
Optimization Enabled:
Yes with 200 runs
Other Settings:
paris EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* _ _ _ _ _
* / \ | | | _(_)_ __ ___ (_)_ _ __ _
* / _ \ | | |/ / | '_ ` _ \| | | | |/ _` |
* / ___ \| | <| | | | | | | | |_| | (_| |
* /_/__ \_\_|_|\_\_|_| |_| |_|_|\__, |\__,_|_
* / ___|(_) (_) ___ __ _ | _ \|___/ ___ | |___
* \___ \| | | |/ __/ _` | | |_) / _ \ / _ \| / __|
* ___) | | | | (_| (_| | | __/ (_) | (_) | \__ \
* |____/|_|_|_|\___\__,_| |_| \___/ \___/|_|___/
*/
import {Ownable} from "@openzeppelin/access/Ownable.sol";
import {ERC20} from "@openzeppelin/token/ERC20/ERC20.sol";
import {IERC20} from "@openzeppelin/token/ERC20/IERC20.sol";
import {SafeCast} from "@openzeppelin/utils/math/SafeCast.sol";
import {ERC1155} from "@openzeppelin/token/ERC1155/ERC1155.sol";
import {ECDSA} from "@openzeppelin/utils/cryptography/ECDSA.sol";
import {EIP712} from "@openzeppelin/utils/cryptography/EIP712.sol";
import {Ownable2Step} from "@openzeppelin/access/Ownable2Step.sol";
import {ReentrancyGuard} from "@openzeppelin/utils/ReentrancyGuard.sol";
import {SafeERC20} from "@openzeppelin/token/ERC20/utils/SafeERC20.sol";
import {MessageHashUtils} from "@openzeppelin/utils/cryptography/MessageHashUtils.sol";
import {PoolMaths} from "../libraries/PoolMaths.sol";
import {ISilicaPools} from "./interfaces/ISilicaPools.sol";
import {ISilicaIndex} from "../index/interfaces/ISilicaIndex.sol";
contract SilicaPools is ISilicaPools, ERC1155, EIP712, Ownable2Step, ReentrancyGuard {
using SafeCast for uint256;
using SafeCast for uint128;
using SafeERC20 for IERC20;
/*//////////////////////////////////////////////////////////////
STATE VARIABLES
//////////////////////////////////////////////////////////////*/
bytes32 constant SILICA_POOL_TYPEHASH = keccak256(
"PoolParams(uint128 floor,uint128 cap,address index,uint48 targetStartTimestamp,uint48 targetEndTimestamp,address payoutToken)"
); // The typehash for the PoolParams struct
bytes32 constant SILICA_ORDER_TYPEHASH = keccak256(
"SilicaOrder(address maker,address taker,uint48 expiry,address offeredUpfrontToken,uint128 offeredUpfrontAmount,uint128 offeredLongShares,PoolParams offeredLongSharesParams,address requestedUpfrontToken,uint128 requestedUpfrontAmount,uint128 requestedLongShares,PoolParams requestedLongSharesParams)PoolParams(uint128 floor,uint128 cap,address index,uint48 targetStartTimestamp,uint48 targetEndTimestamp,address payoutToken)"
); // The typehash for the SilicaOrder struct
bytes32 public constant TOKENID_SALT = bytes32(uint256(0xAC1D));
// The salt for token ID derivation
// Mint fee = mintFeeBps / INVERSE_BASIS_POINT
// 1 basis point = 0.01% of the collateral
// 10_000 basis points make up 100%
uint256 public constant INVERSE_BASIS_POINT = 10_000;
uint256 private sFillFeeBps; // The fee in basis points for minting long and short tokens
uint256 public constant MAX_FILL_FEE_BPS = 1000; // 10%
address private sAlkimiyaTreasury; // The address to which mint fees are sent
mapping(bytes32 poolHash => PoolState state) private sPoolState;
mapping(bytes32 orderHash => bool isCancelled) private sOrderCancelled;
mapping(bytes32 orderHash => uint256 fraction) private sFilledFraction;
mapping(address silicaIndex => bool isWhitelisted) private isIndexWhitelisted;
uint256 public sBountyGracePeriod; // The grace period before bounties are paid out, in seconds
uint256 public sMaxBountyFraction; // The maximum fraction of collateral that can be paid out as a bounty
uint256 public sBountyFractionIncreasePerSecond; // The rate at which the bounty fraction increases per second, until it reached sMaxBountyFraction.
bool public paused;
bool public partialFillsEnabled = false;
constructor(
uint256 startFeeBps,
address initialOwner,
address alkimiyaTreasury,
uint256 gracePeriod,
uint256 maxBountyFrac,
uint256 bountyIncreasePerSecond
) ERC1155("") Ownable(initialOwner) EIP712("SilicaPools", "1") {
assert(alkimiyaTreasury != address(0));
sAlkimiyaTreasury = alkimiyaTreasury;
assert(startFeeBps <= MAX_FILL_FEE_BPS);
sFillFeeBps = startFeeBps;
sBountyGracePeriod = gracePeriod;
sMaxBountyFraction = maxBountyFrac;
sBountyFractionIncreasePerSecond = bountyIncreasePerSecond;
emit SilicaPools__FillFeeChanged(startFeeBps);
emit SilicaPools__GracePeriodChanged(sBountyGracePeriod);
emit SilicaPools__TreasuryAddressChanged(alkimiyaTreasury);
emit SilicaPools__MaxBountyFractionChanged(sMaxBountyFraction);
emit SilicaPools__BountyIncreaseRateChanged(sBountyFractionIncreasePerSecond);
}
/*//////////////////////////////////////////////////////////////
OWNER FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @inheritdoc ISilicaPools
function setFillFeeBps(uint256 newFillFeeBps) external onlyOwner {
if (newFillFeeBps > MAX_FILL_FEE_BPS) {
revert("Cannot exceed max fee BPS");
}
sFillFeeBps = newFillFeeBps;
emit SilicaPools__FillFeeChanged(newFillFeeBps);
}
/// @inheritdoc ISilicaPools
function setTreasuryAddress(address newTreasury) external onlyOwner {
assert(newTreasury != address(0));
sAlkimiyaTreasury = newTreasury;
emit SilicaPools__TreasuryAddressChanged(newTreasury);
}
/// @inheritdoc ISilicaPools
function setBountyGracePeriod(uint256 newGracePeriod) external onlyOwner {
sBountyGracePeriod = newGracePeriod;
emit SilicaPools__GracePeriodChanged(sBountyGracePeriod);
}
/// @inheritdoc ISilicaPools
function setMaxBountyFraction(uint256 newMaxFraction) external onlyOwner {
sMaxBountyFraction = newMaxFraction;
emit SilicaPools__MaxBountyFractionChanged(sMaxBountyFraction);
}
/// @inheritdoc ISilicaPools
function setBountyFractionIncreasePerSecond(uint256 newIncreaseAmount) external onlyOwner {
sBountyFractionIncreasePerSecond = newIncreaseAmount;
emit SilicaPools__BountyIncreaseRateChanged(sBountyFractionIncreasePerSecond);
}
/// @inheritdoc ISilicaPools
function pause() external onlyOwner {
paused = true;
emit SilicaPools__PauseProtocol();
}
/// @inheritdoc ISilicaPools
function unpause() external onlyOwner {
paused = false;
emit SilicaPools__UnpauseProtocol();
}
function enablePartialFills() external onlyOwner {
partialFillsEnabled = true;
}
function disablePartialFills() external onlyOwner {
partialFillsEnabled = false;
}
function whitelistSilicaIndex(address addressToWhitelist) external onlyOwner {
ISilicaIndex index = ISilicaIndex(addressToWhitelist);
require(isIndexWhitelisted[address(index)] == false, "already whitelisted");
isIndexWhitelisted[address(index)] = true;
emit SilicaIndexWhitelisted(address(index));
}
function blacklistSilicaIndex(address addressToBlacklist) external onlyOwner {
ISilicaIndex index = ISilicaIndex(addressToBlacklist);
require(isIndexWhitelisted[address(index)] == true, "already blacklisted");
isIndexWhitelisted[address(index)] = false;
emit SilicaIndexBlacklisted(address(index));
}
/*//////////////////////////////////////////////////////////////
EXTERNAL FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @inheritdoc ISilicaPools
function startPools(PoolParams[] calldata poolParams) external {
for (uint256 i = 0; i < poolParams.length; ++i) {
startPool(poolParams[i]);
}
}
/// @dev calls `_collateralizedMint` with `msg.sender` as `payer`
/// @inheritdoc ISilicaPools
function collateralizedMint(
PoolParams calldata poolParams,
uint256 shares,
address longRecipient,
address shortRecipient
) external {
if (paused) {
revert SilicaPools__Paused();
}
SilicaPools.SilicaOrder memory zeroOrder;
_collateralizedMint(
poolParams, _hashOrder(zeroOrder, _domainSeparatorV4()), shares, msg.sender, longRecipient, shortRecipient
);
}
/// @inheritdoc ISilicaPools
function maxCollateralRefund(PoolParams[] calldata poolParams) external nonReentrant {
for (uint256 i; i < poolParams.length; ++i) {
bytes32 poolHash = hashPool(poolParams[i]);
uint256 longBalance = balanceOf(msg.sender, toLongTokenId(poolHash));
uint256 shortBalance = balanceOf(msg.sender, toShortTokenId(poolHash));
_collateralRefund(poolParams[i], longBalance < shortBalance ? longBalance : shortBalance);
}
}
/// @inheritdoc ISilicaPools
function cancelOrders(SilicaOrder[] calldata orders) external {
for (uint256 i = 0; i < orders.length; ++i) {
SilicaOrder calldata order = orders[i];
if (order.maker != msg.sender) {
revert SilicaPools__InvalidCaller(msg.sender, order.maker);
}
bytes32 orderHash = hashOrder(order, _domainSeparatorV4());
sOrderCancelled[orderHash] = true;
emit SilicaPools__OrderCancelled(orderHash);
}
}
/// @inheritdoc ISilicaPools
function fillOrders(SilicaOrder[] calldata orders, bytes[] calldata signatures, uint256[] calldata fractions)
external
{
if (orders.length != signatures.length || orders.length != fractions.length) {
revert SilicaPools__ArrayLengthMismatch();
}
for (uint256 i = 0; i < orders.length; ++i) {
fillOrder(orders[i], signatures[i], fractions[i]);
}
}
/// @inheritdoc ISilicaPools
function endPools(PoolParams[] calldata poolParams) external {
for (uint256 i = 0; i < poolParams.length; ++i) {
endPool(poolParams[i]);
}
}
/// @inheritdoc ISilicaPools
function redeem(PoolParams[] calldata longPoolParams, PoolParams[] calldata shortPoolParams) external {
for (uint256 i = 0; i < longPoolParams.length; ++i) {
redeemLong(longPoolParams[i]);
}
for (uint256 i = 0; i < shortPoolParams.length; ++i) {
redeemShort(shortPoolParams[i]);
}
}
/*//////////////////////////////////////////////////////////////
EXTERNAL VIEW FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @inheritdoc ISilicaPools
function poolState(bytes32 poolHash) external view returns (PoolState memory) {
return sPoolState[poolHash];
}
/// @inheritdoc ISilicaPools
function startBounty(PoolParams[] calldata poolParams) external view returns (uint256[] memory) {
uint256[] memory bounties = new uint256[](poolParams.length);
for (uint256 i = 0; i < poolParams.length; ++i) {
bounties[i] = _startBounty(poolParams[i]);
}
return bounties;
}
/// @inheritdoc ISilicaPools
function endBounty(PoolParams[] calldata poolParams) external view returns (uint256[] memory) {
uint256[] memory bounties = new uint256[](poolParams.length);
for (uint256 i = 0; i < poolParams.length; ++i) {
bounties[i] = _endBounty(poolParams[i]);
}
return bounties;
}
/// @inheritdoc ISilicaPools
function viewRedeemShort(PoolParams calldata shortParams, address account)
external
view
returns (uint256 expectedPayout)
{
bytes32 poolHash = hashPool(shortParams);
PoolState storage sState = sPoolState[poolHash];
if (sState.actualEndTimestamp == 0) {
revert SilicaPools__PoolNotEnded(poolHash);
}
uint256 shortTokenId = toShortTokenId(poolHash);
uint256 shortSharesBalance = balanceOf(account, shortTokenId);
expectedPayout = PoolMaths.shortPayout(shortParams, sState, shortSharesBalance);
}
/// @inheritdoc ISilicaPools
function viewRedeemLong(PoolParams calldata longParams, address account)
external
view
returns (uint256 expectedPayout)
{
bytes32 poolHash = hashPool(longParams);
PoolState storage sState = sPoolState[poolHash];
if (sState.actualEndTimestamp == 0) {
revert SilicaPools__PoolNotEnded(poolHash);
}
uint256 longTokenId = toLongTokenId(poolHash);
uint256 longSharesBalance = balanceOf(account, longTokenId);
expectedPayout = PoolMaths.longPayout(longParams, sState, longSharesBalance);
}
/// @inheritdoc ISilicaPools
function viewCollateralRefund(PoolParams[] calldata poolParams, uint256[] calldata shares)
external
view
returns (uint256[] memory expectedRefunds)
{
if (poolParams.length != shares.length) {
revert SilicaPools__ArrayLengthMismatch();
}
expectedRefunds = new uint256[](poolParams.length);
for (uint256 i; i < poolParams.length; ++i) {
bytes32 poolHash = hashPool(poolParams[i]);
ISilicaPools.PoolState storage sState = sPoolState[poolHash];
uint256 refundCollateral = (uint256(sState.collateralMinted) * shares[i]) / uint256(sState.sharesMinted);
expectedRefunds[i] = refundCollateral;
}
}
/// @inheritdoc ISilicaPools
function viewMaxCollateralRefund(PoolParams[] calldata poolParams, address[] calldata accounts)
external
view
returns (uint256[] memory expectedRefund)
{
if (poolParams.length != accounts.length) {
revert SilicaPools__ArrayLengthMismatch();
}
expectedRefund = new uint256[](poolParams.length);
for (uint256 i; i < poolParams.length; ++i) {
bytes32 poolHash = hashPool(poolParams[i]);
uint256 longBalance = balanceOf(msg.sender, toLongTokenId(poolHash));
uint256 shortBalance = balanceOf(msg.sender, toShortTokenId(poolHash));
ISilicaPools.PoolState storage sState = sPoolState[poolHash];
if (longBalance < shortBalance) {
expectedRefund[i] = (uint256(sState.collateralMinted) * longBalance) / uint256(sState.sharesMinted);
} else {
expectedRefund[i] = (uint256(sState.collateralMinted) * shortBalance) / uint256(sState.sharesMinted);
}
}
}
/// @inheritdoc ISilicaPools
function fillFeeBps() external view returns (uint256) {
return sFillFeeBps;
}
/// @inheritdoc ISilicaPools
function treasuryAddress() external view returns (address) {
return sAlkimiyaTreasury;
}
/// @inheritdoc ISilicaPools
function bountyGracePeriod() external view returns (uint256) {
return sBountyGracePeriod;
}
/// @inheritdoc ISilicaPools
function maxBountyFraction() external view returns (uint256) {
return sMaxBountyFraction;
}
/// @inheritdoc ISilicaPools
function bountyFractionIncreasePerSecond() external view returns (uint256) {
return sBountyFractionIncreasePerSecond;
}
/// @inheritdoc ISilicaPools
function domainSeparatorV4() external view returns (bytes32) {
return _domainSeparatorV4();
}
/// @inheritdoc ISilicaPools
function orderCancelled(bytes32 orderHash) external view returns (bool) {
return sOrderCancelled[orderHash];
}
/*//////////////////////////////////////////////////////////////
PUBLIC FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @notice Starts the pool that matches the given parameters.
/// @notice Records the starting `ISilicaIndex` state for any of
/// the specified pools which have not already been started.
/// Caller will be paid a bounty for each pool which was not
/// already started if called after the grace period.
/// @dev The pool must not have already started.
/// @dev MUST emit a `PoolStarted` event.
/// @dev Can only be called at or after the pools target start timestamp.
/// @param poolParams The paramter struct for the associated pool
function startPool(PoolParams calldata poolParams) public onlyOwner onlyWhitelistedIndex(poolParams.index) {
bytes32 poolHash = hashPool(poolParams);
PoolState storage sState = sPoolState[poolHash];
ISilicaIndex index = ISilicaIndex(poolParams.index);
if (block.timestamp < poolParams.targetStartTimestamp) {
revert SilicaPools__TooEarlyToStart(block.timestamp, poolParams.targetStartTimestamp);
}
if (sState.actualStartTimestamp != 0) {
revert SilicaPools__PoolAlreadyStarted(poolHash);
}
sState.actualStartTimestamp = uint48(block.timestamp);
sState.indexShares = uint128(index.shares());
sState.indexInitialBalance = uint128(index.balance());
uint256 startBountyAmount = _startBounty(poolParams);
sState.collateralMinted -= uint128(startBountyAmount);
SafeERC20.safeTransfer(IERC20(poolParams.payoutToken), msg.sender, startBountyAmount);
emit SilicaPools__BountyPaid(poolHash, startBountyAmount, msg.sender);
emit SilicaPools__PoolStarted(
poolHash,
poolParams.floor,
poolParams.cap,
poolParams.targetStartTimestamp,
poolParams.targetEndTimestamp,
address(index),
poolParams.payoutToken,
sState.indexShares,
sState.indexInitialBalance,
toLongTokenId(poolHash),
toShortTokenId(poolHash)
);
}
/// @notice Ends the pool that matches the given parameters.
/// @notice Records the ending `ISilicaIndex` state for the pool.
/// Caller will be paid a bounty for each pool which was not
/// already ended if called after the grace period.
/// @dev The pool must not have already ended.
/// @dev Can only be called at or after the pools target end timestamp.
/// @dev MUST emit a `PoolEnded` event.
/// @param poolParams The paramter struct for the associated pool
function endPool(PoolParams calldata poolParams) public onlyOwner onlyWhitelistedIndex(poolParams.index) {
bytes32 poolHash = hashPool(poolParams);
PoolState storage sState = sPoolState[poolHash];
ISilicaIndex index = ISilicaIndex(poolParams.index);
if (sState.actualEndTimestamp != 0) {
revert SilicaPools__PoolAlreadyEnded(poolHash);
}
if (block.timestamp < poolParams.targetEndTimestamp) {
revert SilicaPools__TooEarlyToEnd(block.timestamp, poolParams.targetEndTimestamp);
}
uint256 indexBalanceAtEnd = index.balance();
sState.balanceChangePerShare = uint128(
PoolMaths.balanceChangePerShare(
indexBalanceAtEnd,
sState.indexInitialBalance,
sState.indexShares,
index.decimals(),
poolParams.floor,
poolParams.cap
)
);
sState.actualEndTimestamp = uint48(block.timestamp);
uint256 endBountyAmount = _endBounty(poolParams);
sState.collateralMinted -= uint128(endBountyAmount);
SafeERC20.safeTransfer(IERC20(poolParams.payoutToken), msg.sender, endBountyAmount);
emit SilicaPools__BountyPaid(poolHash, endBountyAmount, msg.sender);
emit SilicaPools__PoolEnded(poolHash, indexBalanceAtEnd, sState.balanceChangePerShare);
}
/// @notice Fills the order with the given parameters.
/// @notice Transfers the collateral and mints the long and short tokens
/// @dev Emits a `TradeHistoryEvent` and a `VolumeAccountingEvent`.
/// @dev The order must not have already been filled.
/// @dev The order must not have been cancelled.
/// @dev The order must not have expired.
/// @dev The signature must be valid.
/// @param order The order to fill
/// @param signature The signature of the order
/// @param fraction The fraction of the order to fill. Pass 1e18 to fill 100% of the order.
function fillOrder(SilicaOrder calldata order, bytes calldata signature, uint256 fraction) public nonReentrant {
if (paused) {
revert SilicaPools__Paused();
}
bytes32 orderHash = hashOrder(order, _domainSeparatorV4());
// Order validation
if (partialFillsEnabled == false && fraction != 1e18) {
revert SilicaPools__PartialOrdersNotSupported(orderHash);
}
if (sOrderCancelled[orderHash]) {
revert SilicaPools__OrderIsCancelled(orderHash);
}
if (ECDSA.recover(orderHash, signature) != order.maker) {
revert SilicaPools__InvalidSignature(signature);
}
if (order.taker != address(0) && order.taker != msg.sender) {
revert SilicaPools__InvalidCaller(msg.sender, order.taker);
}
if (order.expiry < block.timestamp) {
revert SilicaPools__OrderExpired(order.expiry, block.timestamp);
}
if (sPoolState[hashPool(order.offeredLongSharesParams)].actualEndTimestamp != 0) {
revert SilicaPools__PoolAlreadyEnded(hashPool(order.offeredLongSharesParams));
}
if (sPoolState[hashPool(order.requestedLongSharesParams)].actualEndTimestamp != 0) {
revert SilicaPools__PoolAlreadyEnded(hashPool(order.requestedLongSharesParams));
}
// Logic for transferring LONG-side collateral for a LONG order
if (order.offeredUpfrontAmount != 0) {
SafeERC20.safeTransferFrom(
IERC20(order.offeredUpfrontToken),
order.maker,
msg.sender,
(uint256(order.offeredUpfrontAmount) * fraction) / 1e18
);
emit SilicaPools__Swap(
hashPool(order.requestedLongSharesParams),
orderHash,
order.maker, // maker = long = receives long token transfer
msg.sender, // taker = short = receives erc20 token transfer
toLongTokenId(hashPool(order.requestedLongSharesParams)),
(uint256(order.requestedLongShares)) * fraction / 1e18,
order.offeredUpfrontToken,
(uint256(order.offeredUpfrontAmount) * fraction) / 1e18
);
}
// Logic for transferring LONG-side collateral for a SHORT order
if (order.requestedUpfrontAmount != 0) {
SafeERC20.safeTransferFrom(
IERC20(order.requestedUpfrontToken),
msg.sender,
order.maker,
(uint256(order.requestedUpfrontAmount) * fraction) / 1e18
);
emit SilicaPools__Swap(
hashPool(order.offeredLongSharesParams),
orderHash,
msg.sender, // taker = long = receives long token transfer
order.maker, // maker = short = receives erc20 token
toLongTokenId(hashPool(order.offeredLongSharesParams)),
(uint256(order.offeredLongShares) * fraction) / 1e18,
order.requestedUpfrontToken,
(uint256(order.requestedUpfrontAmount) * fraction) / 1e18
);
}
// Logic for transferring SHORT-side collateral for a SHORT order
if (order.offeredLongShares != 0) {
require(isIndexWhitelisted[address(order.offeredLongSharesParams.index)], InvalidSilicaIndex());
uint256 indexDecimals = ISilicaIndex(order.offeredLongSharesParams.index).decimals();
uint256 collateral = PoolMaths.collateral(
true,
order.offeredLongSharesParams.floor,
order.offeredLongSharesParams.cap,
(uint256(order.offeredLongShares) * fraction) / 1e18,
indexDecimals
);
// Taker pays the surcharge
uint256 surcharge = (collateral * sFillFeeBps) / INVERSE_BASIS_POINT;
SafeERC20.safeTransferFrom(
IERC20(order.offeredLongSharesParams.payoutToken), msg.sender, sAlkimiyaTreasury, surcharge
);
uint256 tokenId = toShortTokenId(hashPool(order.offeredLongSharesParams));
emit SilicaPools__FillFeePaid(
msg.sender,
hashPool(order.offeredLongSharesParams),
orderHash,
tokenId,
order.offeredLongSharesParams.payoutToken,
surcharge
);
// SHORT side calls collateralizedMint onbehalf of both parties
_collateralizedMint(
order.offeredLongSharesParams,
orderHash,
(uint256(order.offeredLongShares) * fraction) / 1e18,
order.maker,
msg.sender, // e.g. taker = buys yield = longRecipient
order.maker // e.g. maker = sells (offers) yield = shortRecipient
);
// Event capturing exchanging collateral for short tokens
emit SilicaPools__Swap(
hashPool(order.offeredLongSharesParams),
orderHash,
order.maker,
msg.sender,
toShortTokenId(hashPool(order.offeredLongSharesParams)),
(uint256(order.offeredLongShares) * fraction) / 1e18,
order.requestedUpfrontToken,
collateral - ((uint256(order.requestedUpfrontAmount) * fraction) / 1e18)
);
}
// Logic for transferring SHORT-side collateral for a LONG order
if (order.requestedLongShares != 0) {
require(isIndexWhitelisted[address(order.requestedLongSharesParams.index)], InvalidSilicaIndex());
uint256 indexDecimals = ISilicaIndex(order.requestedLongSharesParams.index).decimals();
uint256 collateral = PoolMaths.collateral(
true,
order.requestedLongSharesParams.floor,
order.requestedLongSharesParams.cap,
(uint256(order.requestedLongShares) * fraction) / 1e18,
indexDecimals
);
// Taker pays the surcharge
uint256 surcharge = (collateral * sFillFeeBps) / INVERSE_BASIS_POINT;
SafeERC20.safeTransferFrom(
IERC20(order.requestedLongSharesParams.payoutToken), msg.sender, sAlkimiyaTreasury, surcharge
);
uint256 tokenId = toLongTokenId(hashPool(order.requestedLongSharesParams));
emit SilicaPools__FillFeePaid(
msg.sender,
hashPool(order.requestedLongSharesParams),
orderHash,
tokenId,
order.requestedLongSharesParams.payoutToken,
surcharge
);
_collateralizedMint(
order.requestedLongSharesParams,
orderHash,
(uint256(order.requestedLongShares) * fraction) / 1e18,
msg.sender,
order.maker, // e.g. maker = buys (requests) yield = longRecipient
msg.sender // e.g. taker = sells yield = shortRecipient
);
emit SilicaPools__Swap(
hashPool(order.requestedLongSharesParams),
orderHash,
msg.sender, // taker = short = receives pool token transfer
order.maker, // maker = long = receives erc20 token
toShortTokenId(hashPool(order.requestedLongSharesParams)),
(uint256(order.requestedLongShares) * fraction) / 1e18,
order.offeredUpfrontToken,
collateral - ((uint256(order.offeredUpfrontAmount) * fraction) / 1e18)
);
}
{
uint256 newFilledFraction = sFilledFraction[orderHash] + fraction;
sFilledFraction[orderHash] = newFilledFraction;
emit SilicaPools__TradeHistoryEvent(
orderHash,
order.maker,
msg.sender,
hashPool(order.offeredLongSharesParams),
hashPool(order.requestedLongSharesParams),
order.requestedLongShares,
order.offeredLongShares,
fraction,
1e18 - newFilledFraction
);
}
}
/// @notice Redeems shares for the payout token.
/// @dev MUST emit `SilicaPools__SharesRedeemed`
/// @param longParams The pools to redeem long shares from.
function redeemLong(PoolParams calldata longParams) public {
bytes32 poolHash = hashPool(longParams);
PoolState storage sState = sPoolState[poolHash];
if (sState.actualEndTimestamp == 0) {
revert SilicaPools__PoolNotEnded(poolHash);
}
uint256 longTokenId = toLongTokenId(poolHash);
uint256 longSharesBalance = balanceOf(msg.sender, longTokenId);
uint256 payout = PoolMaths.longPayout(longParams, sState, longSharesBalance);
_burn(msg.sender, longTokenId, longSharesBalance);
SafeERC20.safeTransfer(IERC20(longParams.payoutToken), msg.sender, payout);
emit SilicaPools__SharesRedeemed(
poolHash, msg.sender, longTokenId, longSharesBalance, longParams.payoutToken, payout
);
}
/// @notice Redeems shares for the payout token.
/// @dev MUST emit `SilicaPools__SharesRedeemed`
/// @param shortParams The pools to redeem short shares from.
function redeemShort(PoolParams calldata shortParams) public {
bytes32 poolHash = hashPool(shortParams);
PoolState storage sState = sPoolState[poolHash];
if (sState.actualEndTimestamp == 0) {
revert SilicaPools__PoolNotEnded(poolHash);
}
uint256 shortTokenId = toShortTokenId(poolHash);
uint256 shortSharesBalance = balanceOf(msg.sender, shortTokenId);
uint256 payout = PoolMaths.shortPayout(shortParams, sState, shortSharesBalance);
_burn(msg.sender, shortTokenId, shortSharesBalance);
SafeERC20.safeTransfer(IERC20(shortParams.payoutToken), msg.sender, payout);
emit SilicaPools__SharesRedeemed(
poolHash, msg.sender, shortTokenId, shortSharesBalance, shortParams.payoutToken, payout
);
}
/// @inheritdoc ISilicaPools
function collateralRefund(PoolParams[] calldata poolParams, uint256[] calldata shares) public nonReentrant {
if (poolParams.length != shares.length) {
revert SilicaPools__ArrayLengthMismatch();
}
for (uint256 i; i < poolParams.length; ++i) {
_collateralRefund(poolParams[i], shares[i]);
}
}
/*//////////////////////////////////////////////////////////////
PUBLIC PURE FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @notice Converts a pool hash to a long token ID.
/// @param poolHash The hash of the pool.
/// @return The long token ID.
function toLongTokenId(bytes32 poolHash) public pure returns (uint256) {
return uint256(poolHash);
}
/// @notice Converts a pool hash to a short token ID.
/// @param poolHash The hash of the pool.
/// @return The short token ID.
function toShortTokenId(bytes32 poolHash) public pure returns (uint256) {
return uint256(poolHash ^ TOKENID_SALT);
}
/// @notice Converts a long token ID to a pool hash.
/// @param longTokenId The long token ID.
/// @return The pool hash.
function fromLongTokenId(uint256 longTokenId) public pure returns (bytes32) {
return bytes32(longTokenId);
}
/// @notice Converts a short token ID to a pool hash.
/// @param shortTokenId The short token ID.
/// @return The pool hash.
function fromShortTokenId(uint256 shortTokenId) public pure returns (bytes32) {
return bytes32(shortTokenId) ^ TOKENID_SALT;
}
/// @notice Hashes the pool parameters.
/// @param poolParams The pool parameters.
/// @return The hash of the pool parameters.
function hashPool(PoolParams calldata poolParams) public pure returns (bytes32) {
return keccak256(
abi.encodePacked(
poolParams.floor,
poolParams.cap,
poolParams.index,
poolParams.targetStartTimestamp,
poolParams.targetEndTimestamp,
poolParams.payoutToken
)
);
}
/// @notice Hashes the order parameters.
/// @param order The order parameters.
/// @param domainSeparator The EIP-712 domain separator.
/// @return The hash of the order parameters.
function hashOrder(SilicaOrder calldata order, bytes32 domainSeparator) public pure returns (bytes32) {
// Encode in chunks to circumvent "stack too deep" error
bytes32 offeredStructHash = keccak256(abi.encode(SILICA_POOL_TYPEHASH, order.offeredLongSharesParams));
bytes32 requestedStructHash = keccak256(abi.encode(SILICA_POOL_TYPEHASH, order.requestedLongSharesParams));
bytes32 structHash = keccak256(
abi.encode(
SILICA_ORDER_TYPEHASH,
order.maker,
order.taker,
order.expiry,
order.offeredUpfrontToken,
order.offeredUpfrontAmount,
order.offeredLongShares,
offeredStructHash,
order.requestedUpfrontToken,
order.requestedUpfrontAmount,
order.requestedLongShares,
requestedStructHash
)
);
return MessageHashUtils.toTypedDataHash(domainSeparator, structHash);
}
/// @notice Hashes the order parameters.
/// @param order The order parameters.
/// @return The hash of the order parameters.
function hashOrder(SilicaOrder calldata order) public view returns (bytes32) {
return _hashOrder(order, _domainSeparatorV4());
}
function _hashOrder(SilicaOrder memory order, bytes32 domainSeparator) internal pure returns (bytes32) {
// Encode in chunks to circumvent "stack too deep" error
bytes32 offeredStructHash = keccak256(abi.encode(SILICA_POOL_TYPEHASH, order.offeredLongSharesParams));
bytes32 requestedStructHash = keccak256(abi.encode(SILICA_POOL_TYPEHASH, order.requestedLongSharesParams));
bytes32 structHash = keccak256(
abi.encode(
SILICA_ORDER_TYPEHASH,
order.maker,
order.taker,
order.expiry,
order.offeredUpfrontToken,
order.offeredUpfrontAmount,
order.offeredLongShares,
offeredStructHash,
order.requestedUpfrontToken,
order.requestedUpfrontAmount,
order.requestedLongShares,
requestedStructHash
)
);
return MessageHashUtils.toTypedDataHash(domainSeparator, structHash);
}
/*//////////////////////////////////////////////////////////////
INTERNAL FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @notice Internal function to mint long and short tokens for a pool.
/// @dev This is `internal` because it must be approved by the `payer`.
/// Do not call this function otherwise.
/// @param poolParams The paramter struct for the associated pool
/// @param payer The address that will pay the collateral
/// @param longRecipient The address that will receive `shares` long tokens
/// @param shortRecipient The address that will receive `shares` short tokens
function _collateralizedMint(
PoolParams calldata poolParams,
bytes32 orderHash,
uint256 shares,
address payer,
address longRecipient,
address shortRecipient
) internal onlyWhitelistedIndex(poolParams.index) {
require(shares <= type(uint128).max, "Shares exceed uint128 max");
bytes32 poolHash = hashPool(poolParams);
if (sPoolState[poolHash].actualEndTimestamp != 0) {
revert SilicaPools__PoolAlreadyEnded(poolHash);
}
ISilicaIndex index = ISilicaIndex(poolParams.index);
ISilicaPools.PoolState storage sState = sPoolState[poolHash];
uint256 collateral = PoolMaths.collateral(true, poolParams.floor, poolParams.cap, shares, index.decimals());
sState.collateralMinted += uint128(collateral);
SafeERC20.safeTransferFrom(IERC20(poolParams.payoutToken), payer, address(this), collateral);
if (longRecipient == address(0)) {
longRecipient = msg.sender;
}
if (shortRecipient == address(0)) {
shortRecipient = msg.sender;
}
sState.sharesMinted += uint128(shares);
uint256 longTokenId = toLongTokenId(poolHash);
uint256 shortTokenId = toShortTokenId(poolHash);
_mint(longRecipient, longTokenId, shares, "");
_mint(shortRecipient, shortTokenId, shares, "");
emit SilicaPools__CollateralizedMint(
poolHash,
orderHash,
longTokenId,
shortTokenId,
shortRecipient,
longRecipient,
payer,
shares,
poolParams.payoutToken,
collateral
);
}
/// @notice Internal calculator to determine bounty value for calling startPool()
/// @param poolParams The paramter struct for the associated pool
/// @return bounty The uint256 amount of bounty associated with that pool's collateral
function _startBounty(PoolParams calldata poolParams) internal view returns (uint256 bounty) {
bytes32 poolHash = hashPool(poolParams);
ISilicaPools.PoolState storage sState = sPoolState[poolHash];
uint256 collateral = sState.collateralMinted;
uint256 uncappedBountyFraction = block.timestamp > poolParams.targetStartTimestamp + sBountyGracePeriod
? uint256(block.timestamp - poolParams.targetStartTimestamp - sBountyGracePeriod)
* sBountyFractionIncreasePerSecond
: 0;
uint256 bountyFraction =
uncappedBountyFraction > sMaxBountyFraction ? sMaxBountyFraction : uncappedBountyFraction;
bounty = (bountyFraction * collateral) / 1e18;
}
/// @notice Internal bounty calculator function
/// @param poolParams: The paramter struct for the associated pool
/// @return bounty The uint256 amount of bounty associated with that pool's collateral
function _endBounty(PoolParams calldata poolParams) internal view returns (uint256 bounty) {
bytes32 poolHash = hashPool(poolParams);
uint256 collateral = sPoolState[poolHash].collateralMinted;
uint256 uncappedBountyFraction = block.timestamp > poolParams.targetEndTimestamp + sBountyGracePeriod
? uint256(block.timestamp - poolParams.targetEndTimestamp - sBountyGracePeriod)
* sBountyFractionIncreasePerSecond
: 0;
uint256 bountyFraction =
uncappedBountyFraction > sMaxBountyFraction ? sMaxBountyFraction : uncappedBountyFraction;
bounty = (bountyFraction * collateral) / 1e18;
}
/// @notice Internal function to refund collateral to the user.
/// @dev This is `internal` because it must be approved by the `payer`.
/// Do not call this function otherwise.
/// @dev Called by `collateralRefund()` and `maxCollateralRefund()` with msg.sender as the recipient.
/// @dev Emits a `SilicaPools__SharesRefunded` event.
/// @param poolParams The paramter struct for the associated pool.
/// @param shares The number of shares to refund.
function _collateralRefund(PoolParams calldata poolParams, uint256 shares) internal {
bytes32 poolHash = hashPool(poolParams);
ISilicaPools.PoolState storage sState = sPoolState[poolHash];
uint256 refundCollateral = (uint256(sState.collateralMinted) * shares) / uint256(sState.sharesMinted);
sState.sharesMinted -= uint128(shares);
uint256 longTokenId = toLongTokenId(poolHash);
uint256 shortTokenId = toShortTokenId(poolHash);
_burn(msg.sender, longTokenId, shares);
_burn(msg.sender, shortTokenId, shares);
sState.collateralMinted -= uint128(refundCollateral);
SafeERC20.safeTransfer(IERC20(poolParams.payoutToken), msg.sender, refundCollateral);
emit SilicaPools__SharesRefunded(
poolHash, longTokenId, shortTokenId, msg.sender, poolParams.payoutToken, shares, refundCollateral
);
}
modifier onlyWhitelistedIndex(address indexAddr) {
require(isIndexWhitelisted[indexAddr], "InvalidSilicaIndex");
_;
}
}// 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) (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}.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `value`.
*/
function transfer(address to, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_transfer(owner, to, value);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* 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/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.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) (token/ERC1155/ERC1155.sol)
pragma solidity ^0.8.20;
import {IERC1155} from "./IERC1155.sol";
import {IERC1155MetadataURI} from "./extensions/IERC1155MetadataURI.sol";
import {ERC1155Utils} from "./utils/ERC1155Utils.sol";
import {Context} from "../../utils/Context.sol";
import {IERC165, ERC165} from "../../utils/introspection/ERC165.sol";
import {Arrays} from "../../utils/Arrays.sol";
import {IERC1155Errors} from "../../interfaces/draft-IERC6093.sol";
/**
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*/
abstract contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI, IERC1155Errors {
using Arrays for uint256[];
using Arrays for address[];
mapping(uint256 id => mapping(address account => uint256)) private _balances;
mapping(address account => mapping(address operator => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/**
* @dev See {_setURI}.
*/
constructor(string memory uri_) {
_setURI(uri_);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the ERC].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256 /* id */) public view virtual returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*/
function balanceOf(address account, uint256 id) public view virtual returns (uint256) {
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(
address[] memory accounts,
uint256[] memory ids
) public view virtual returns (uint256[] memory) {
if (accounts.length != ids.length) {
revert ERC1155InvalidArrayLength(ids.length, accounts.length);
}
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts.unsafeMemoryAccess(i), ids.unsafeMemoryAccess(i));
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 id, uint256 value, bytes memory data) public virtual {
address sender = _msgSender();
if (from != sender && !isApprovedForAll(from, sender)) {
revert ERC1155MissingApprovalForAll(sender, from);
}
_safeTransferFrom(from, to, id, value, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory values,
bytes memory data
) public virtual {
address sender = _msgSender();
if (from != sender && !isApprovedForAll(from, sender)) {
revert ERC1155MissingApprovalForAll(sender, from);
}
_safeBatchTransferFrom(from, to, ids, values, data);
}
/**
* @dev Transfers a `value` amount of tokens of type `id` from `from` to `to`. Will mint (or burn) if `from`
* (or `to`) is the zero address.
*
* Emits a {TransferSingle} event if the arrays contain one element, and {TransferBatch} otherwise.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement either {IERC1155Receiver-onERC1155Received}
* or {IERC1155Receiver-onERC1155BatchReceived} and return the acceptance magic value.
* - `ids` and `values` must have the same length.
*
* NOTE: The ERC-1155 acceptance check is not performed in this function. See {_updateWithAcceptanceCheck} instead.
*/
function _update(address from, address to, uint256[] memory ids, uint256[] memory values) internal virtual {
if (ids.length != values.length) {
revert ERC1155InvalidArrayLength(ids.length, values.length);
}
address operator = _msgSender();
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids.unsafeMemoryAccess(i);
uint256 value = values.unsafeMemoryAccess(i);
if (from != address(0)) {
uint256 fromBalance = _balances[id][from];
if (fromBalance < value) {
revert ERC1155InsufficientBalance(from, fromBalance, value, id);
}
unchecked {
// Overflow not possible: value <= fromBalance
_balances[id][from] = fromBalance - value;
}
}
if (to != address(0)) {
_balances[id][to] += value;
}
}
if (ids.length == 1) {
uint256 id = ids.unsafeMemoryAccess(0);
uint256 value = values.unsafeMemoryAccess(0);
emit TransferSingle(operator, from, to, id, value);
} else {
emit TransferBatch(operator, from, to, ids, values);
}
}
/**
* @dev Version of {_update} that performs the token acceptance check by calling
* {IERC1155Receiver-onERC1155Received} or {IERC1155Receiver-onERC1155BatchReceived} on the receiver address if it
* contains code (eg. is a smart contract at the moment of execution).
*
* IMPORTANT: Overriding this function is discouraged because it poses a reentrancy risk from the receiver. So any
* update to the contract state after this function would break the check-effect-interaction pattern. Consider
* overriding {_update} instead.
*/
function _updateWithAcceptanceCheck(
address from,
address to,
uint256[] memory ids,
uint256[] memory values,
bytes memory data
) internal virtual {
_update(from, to, ids, values);
if (to != address(0)) {
address operator = _msgSender();
if (ids.length == 1) {
uint256 id = ids.unsafeMemoryAccess(0);
uint256 value = values.unsafeMemoryAccess(0);
ERC1155Utils.checkOnERC1155Received(operator, from, to, id, value, data);
} else {
ERC1155Utils.checkOnERC1155BatchReceived(operator, from, to, ids, values, data);
}
}
}
/**
* @dev Transfers a `value` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `from` must have a balance of tokens of type `id` of at least `value` amount.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _safeTransferFrom(address from, address to, uint256 id, uint256 value, bytes memory data) internal {
if (to == address(0)) {
revert ERC1155InvalidReceiver(address(0));
}
if (from == address(0)) {
revert ERC1155InvalidSender(address(0));
}
(uint256[] memory ids, uint256[] memory values) = _asSingletonArrays(id, value);
_updateWithAcceptanceCheck(from, to, ids, values, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
* - `ids` and `values` must have the same length.
*/
function _safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory values,
bytes memory data
) internal {
if (to == address(0)) {
revert ERC1155InvalidReceiver(address(0));
}
if (from == address(0)) {
revert ERC1155InvalidSender(address(0));
}
_updateWithAcceptanceCheck(from, to, ids, values, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the ERC].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the values in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates a `value` amount of tokens of type `id`, and assigns them to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(address to, uint256 id, uint256 value, bytes memory data) internal {
if (to == address(0)) {
revert ERC1155InvalidReceiver(address(0));
}
(uint256[] memory ids, uint256[] memory values) = _asSingletonArrays(id, value);
_updateWithAcceptanceCheck(address(0), to, ids, values, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `values` must have the same length.
* - `to` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(address to, uint256[] memory ids, uint256[] memory values, bytes memory data) internal {
if (to == address(0)) {
revert ERC1155InvalidReceiver(address(0));
}
_updateWithAcceptanceCheck(address(0), to, ids, values, data);
}
/**
* @dev Destroys a `value` amount of tokens of type `id` from `from`
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `from` must have at least `value` amount of tokens of type `id`.
*/
function _burn(address from, uint256 id, uint256 value) internal {
if (from == address(0)) {
revert ERC1155InvalidSender(address(0));
}
(uint256[] memory ids, uint256[] memory values) = _asSingletonArrays(id, value);
_updateWithAcceptanceCheck(from, address(0), ids, values, "");
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `from` must have at least `value` amount of tokens of type `id`.
* - `ids` and `values` must have the same length.
*/
function _burnBatch(address from, uint256[] memory ids, uint256[] memory values) internal {
if (from == address(0)) {
revert ERC1155InvalidSender(address(0));
}
_updateWithAcceptanceCheck(from, address(0), ids, values, "");
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the zero address.
*/
function _setApprovalForAll(address owner, address operator, bool approved) internal virtual {
if (operator == address(0)) {
revert ERC1155InvalidOperator(address(0));
}
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Creates an array in memory with only one value for each of the elements provided.
*/
function _asSingletonArrays(
uint256 element1,
uint256 element2
) private pure returns (uint256[] memory array1, uint256[] memory array2) {
assembly ("memory-safe") {
// Load the free memory pointer
array1 := mload(0x40)
// Set array length to 1
mstore(array1, 1)
// Store the single element at the next word after the length (where content starts)
mstore(add(array1, 0x20), element1)
// Repeat for next array locating it right after the first array
array2 := add(array1, 0x40)
mstore(array2, 1)
mstore(add(array2, 0x20), element2)
// Update the free memory pointer by pointing after the second array
mstore(0x40, add(array2, 0x40))
}
}
}// 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.1.0) (utils/cryptography/EIP712.sol)
pragma solidity ^0.8.20;
import {MessageHashUtils} from "./MessageHashUtils.sol";
import {ShortStrings, ShortString} from "../ShortStrings.sol";
import {IERC5267} from "../../interfaces/IERC5267.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP-712] is a standard for hashing and signing of typed structured data.
*
* The encoding scheme specified in the EIP requires a domain separator and a hash of the typed structured data, whose
* encoding is very generic and therefore its implementation in Solidity is not feasible, thus this contract
* does not implement the encoding itself. Protocols need to implement the type-specific encoding they need in order to
* produce the hash of their typed data using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP-712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain
* separator of the implementation contract. This will cause the {_domainSeparatorV4} function to always rebuild the
* separator from the immutable values, which is cheaper than accessing a cached version in cold storage.
*
* @custom:oz-upgrades-unsafe-allow state-variable-immutable
*/
abstract contract EIP712 is IERC5267 {
using ShortStrings for *;
bytes32 private constant TYPE_HASH =
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _cachedDomainSeparator;
uint256 private immutable _cachedChainId;
address private immutable _cachedThis;
bytes32 private immutable _hashedName;
bytes32 private immutable _hashedVersion;
ShortString private immutable _name;
ShortString private immutable _version;
string private _nameFallback;
string private _versionFallback;
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP-712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
_name = name.toShortStringWithFallback(_nameFallback);
_version = version.toShortStringWithFallback(_versionFallback);
_hashedName = keccak256(bytes(name));
_hashedVersion = keccak256(bytes(version));
_cachedChainId = block.chainid;
_cachedDomainSeparator = _buildDomainSeparator();
_cachedThis = address(this);
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
if (address(this) == _cachedThis && block.chainid == _cachedChainId) {
return _cachedDomainSeparator;
} else {
return _buildDomainSeparator();
}
}
function _buildDomainSeparator() private view returns (bytes32) {
return keccak256(abi.encode(TYPE_HASH, _hashedName, _hashedVersion, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return MessageHashUtils.toTypedDataHash(_domainSeparatorV4(), structHash);
}
/**
* @dev See {IERC-5267}.
*/
function eip712Domain()
public
view
virtual
returns (
bytes1 fields,
string memory name,
string memory version,
uint256 chainId,
address verifyingContract,
bytes32 salt,
uint256[] memory extensions
)
{
return (
hex"0f", // 01111
_EIP712Name(),
_EIP712Version(),
block.chainid,
address(this),
bytes32(0),
new uint256[](0)
);
}
/**
* @dev The name parameter for the EIP712 domain.
*
* NOTE: By default this function reads _name which is an immutable value.
* It only reads from storage if necessary (in case the value is too large to fit in a ShortString).
*/
// solhint-disable-next-line func-name-mixedcase
function _EIP712Name() internal view returns (string memory) {
return _name.toStringWithFallback(_nameFallback);
}
/**
* @dev The version parameter for the EIP712 domain.
*
* NOTE: By default this function reads _version which is an immutable value.
* It only reads from storage if necessary (in case the value is too large to fit in a ShortString).
*/
// solhint-disable-next-line func-name-mixedcase
function _EIP712Version() internal view returns (string memory) {
return _version.toStringWithFallback(_versionFallback);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (access/Ownable2Step.sol)
pragma solidity ^0.8.20;
import {Ownable} from "./Ownable.sol";
/**
* @dev Contract module which provides access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This extension of the {Ownable} contract includes a two-step mechanism to transfer
* ownership, where the new owner must call {acceptOwnership} in order to replace the
* old one. This can help prevent common mistakes, such as transfers of ownership to
* incorrect accounts, or to contracts that are unable to interact with the
* permission system.
*
* The initial owner is specified at deployment time in the constructor for `Ownable`. This
* can later be changed with {transferOwnership} and {acceptOwnership}.
*
* This module is used through inheritance. It will make available all functions
* from parent (Ownable).
*/
abstract contract Ownable2Step is Ownable {
address private _pendingOwner;
event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
/**
* @dev Returns the address of the pending owner.
*/
function pendingOwner() public view virtual returns (address) {
return _pendingOwner;
}
/**
* @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
* Can only be called by the current owner.
*
* Setting `newOwner` to the zero address is allowed; this can be used to cancel an initiated ownership transfer.
*/
function transferOwnership(address newOwner) public virtual override onlyOwner {
_pendingOwner = newOwner;
emit OwnershipTransferStarted(owner(), newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual override {
delete _pendingOwner;
super._transferOwnership(newOwner);
}
/**
* @dev The new owner accepts the ownership transfer.
*/
function acceptOwnership() public virtual {
address sender = _msgSender();
if (pendingOwner() != sender) {
revert OwnableUnauthorizedAccount(sender);
}
_transferOwnership(sender);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.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.1.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
import {Address} from "../../../utils/Address.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 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.1.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://eth.wiki/json-rpc/API#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://eth.wiki/json-rpc/API#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 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
pragma solidity ^0.8.0;
import {ISilicaPools} from "../core/interfaces/ISilicaPools.sol";
import {FixedPointMathLib} from "solady/utils/FixedPointMathLib.sol";
/**
* _ _ _ _ _
* / \ | | | _(_)_ __ ___ (_)_ _ __ _
* / _ \ | | |/ / | '_ ` _ \| | | | |/ _` |
* / ___ \| | <| | | | | | | | |_| | (_| |
* /_/ \_\_|_|\_\_|_| |_| |_|_|\__, |\__,_|
* ____ _ __ __ |___/_ _
* | _ \ ___ ___ | | | \/ | __ _| |_| |__ ___
* | |_) / _ \ / _ \| | | |\/| |/ _` | __| '_ \/ __|
* | __/ (_) | (_) | | | | | | (_| | |_| | | \__ \
* |_| \___/ \___/|_| |_| |_|\__,_|\__|_| |_|___/
*/
library PoolMaths {
/// @notice Calculate the collateral required for a given floor, cap, shares, and shareDecimals.
/// @param floor The predetermined lower bound on the Pool’s payout.
/// @param cap The predetermined upper bound on the Pool’s payout.
/// @param shares The number of short and long shares to be minted by the Pool.
/// @param shareDecimals The number of decimal places in the shares.
/// @return The collateral required to cover the Pool's payout for the associated amount of shares.
function collateral(bool isRoundUp, uint128 floor, uint128 cap, uint256 shares, uint256 shareDecimals)
internal
pure
returns (uint256)
{
uint256 intermediateValue = (cap - floor) * shares;
return isRoundUp
? FixedPointMathLib.divUp(intermediateValue, 10 ** shareDecimals)
: intermediateValue / 10 ** shareDecimals;
}
function collateralRequirements(
uint128 floor,
uint128 cap,
uint256 shares,
uint256 shareDecimals,
uint256 upfrontAmount,
uint256 fraction
) internal pure returns (uint256 longCollateral, uint256 shortCollateral) {
require((cap - floor) * shares / 10 ** shareDecimals <= upfrontAmount, "overcollateralized");
longCollateral = upfrontAmount;
shortCollateral = PoolMaths.shortCollateralRequirement(floor, cap, shares, shareDecimals, upfrontAmount);
return (longCollateral, shortCollateral);
}
function shortCollateralRequirement(
uint128 floor,
uint128 cap,
uint256 shares,
uint256 shareDecimals,
uint256 upfrontAmount
) internal pure returns (uint256 shortCollateral) {
uint256 totalCollateral = PoolMaths.collateral(true, floor, cap, shares, shareDecimals);
return totalCollateral - upfrontAmount;
}
/// @notice Function to calculate the short payout when a user calls redeem based on their shares
/// @param shortParams The PoolParams for pool being redeemed from
/// @param sState The PoolState for that pool
/// @param shortSharesBalance The users balance of short shares
/// @return payout The payout for the user
function shortPayout(
ISilicaPools.PoolParams memory shortParams,
ISilicaPools.PoolState memory sState,
uint256 shortSharesBalance
) internal pure returns (uint256 payout) {
// Short payouts pay (cap - balanceChangePerShare) * collateralMinted / (cap - floor) * shortSharesBalance / totalSharesMinted
payout = (
(
(uint256(shortParams.cap - sState.balanceChangePerShare) * uint256(sState.collateralMinted))
/ uint256(shortParams.cap - shortParams.floor)
) * uint256(shortSharesBalance)
) / uint256(sState.sharesMinted);
}
/// @notice Function to calculate the long payout when a user calls redeem based on their shares
/// @param longParams The PoolParams for pool being redeemed from
/// @param sState The PoolState for that pool
/// @param longSharesBalance The users balance of long shares
/// @return payout The payout for the user
function longPayout(
ISilicaPools.PoolParams calldata longParams,
ISilicaPools.PoolState memory sState,
uint256 longSharesBalance
) internal pure returns (uint256 payout) {
// Long payouts pay ((balanceChangePerShare - floor) * collateralMinted) / ((cap - floor) * longSharesBalance) / totalSharesMinted)
payout = (
(
(uint256(sState.balanceChangePerShare - longParams.floor) * uint256(sState.collateralMinted))
/ uint256(longParams.cap - longParams.floor)
) * uint256(longSharesBalance)
) / uint256(sState.sharesMinted);
}
/// @notice Function to calculate grossBalanceChangePerShare
/// @param indexBalance The current balance of the index. The Index is a time-varying benchmark value that reflects market dynamics.
/// @param indexInitialBalance The initial balance of the index.
/// @param indexShares The number of shares of the index.
/// @param indexDecimals The number of decimal places in the index.
/// @return The gross balance change per share.
function grossBalanceChangePerShare(
uint256 indexBalance,
uint256 indexInitialBalance,
uint256 indexShares,
uint256 indexDecimals
) internal pure returns (uint256) {
require(indexShares > 0, "Index shares must be greater than zero");
require(
indexBalance >= indexInitialBalance, "Index balance must be greater than or equal to the initial balance"
);
return ((indexBalance - indexInitialBalance) * 10 ** indexDecimals) / indexShares;
}
/// @notice Function to calculate the balance change per share
/// @param floor The predetermined lower bound on the Pool’s payout.
/// @param cap The predetermined upper bound on the Pool’s payout.
/// @param grossBalanceChangePerShare The gross balance change per share.
/// @return The balance change per share.
function _balanceChangePerShare(uint256 floor, uint256 cap, uint256 grossBalanceChangePerShare)
internal
pure
returns (uint256)
{
return max(floor, min(cap, grossBalanceChangePerShare));
}
// diff
function balanceChangePerShare(
uint256 indexBalance,
uint128 indexInitialBalance,
uint128 indexShares,
uint256 indexDecimals,
uint128 floor,
uint128 cap
) internal pure returns (uint256) {
return _balanceChangePerShare(
floor, cap, grossBalanceChangePerShare(indexBalance, indexInitialBalance, indexShares, indexDecimals)
);
}
// Helper function for min
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
// Helper function for max
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
}///// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* _ _ _ _ _
* / \ | | | _(_)_ __ ___ (_)_ _ __ _
* / _ \ | | |/ / | '_ ` _ \| | | | |/ _` |
* / ___ \| | <| | | | | | | | |_| | (_| |
* /_/__ \_\_|_|\_\_|_| |_| |_|_|\__, |\__,_|_
* / ___|(_) (_) ___ __ _ | _ \|___/ ___ | |___
* \___ \| | | |/ __/ _` | | |_) / _ \ / _ \| / __|
* ___) | | | | (_| (_| | | __/ (_) | (_) | \__ \
* |____/|_|_|_|\___\__,_| |_| \___/ \___/|_|___/
*/
import {IERC20} from "@openzeppelin/token/ERC20/IERC20.sol";
import {IERC1155} from "@openzeppelin/token/ERC1155/IERC1155.sol";
import {ISilicaIndex} from "../../index/interfaces/ISilicaIndex.sol";
/// @title Silica Pools Protocol
/// @author Alkimiya
/// @notice Protocol for allocating tokens into pools which track
/// a balance change over a specified period and pay out
/// accordingly: https://www.investopedia.com/terms/v/verticalspread.asp
/// @custom:example If a pool specifies strikes of 100-200 DAI per share
/// over a 1 year term, and the balance change over the term
/// is 160 DAI per share, then at the end of the pool's term,
/// 60 DAI per share (160 - 100) is paid out to
/// holders of long shares, and 40 DAI per share (200 - 160)
/// is paid out to holders of short shares.
interface ISilicaPools is IERC1155 {
event SilicaPools__FillFeeChanged(uint256 newFeeBps);
event SilicaPools__GracePeriodChanged(uint256 newGracePeriod);
event SilicaPools__BountyIncreaseRateChanged(uint256 newRate);
event SilicaPools__MaxBountyFractionChanged(uint256 newMaxFraction);
event SilicaPools__TreasuryAddressChanged(address newTreasuryAddress);
event SilicaPools__PauseProtocol();
event SilicaPools__UnpauseProtocol();
event SilicaPools__OrderCancelled(bytes32 indexed orderHash);
event SilicaPools__PoolStarted( // NAME CHANGE
bytes32 indexed poolHash,
uint128 floor,
uint128 cap,
uint48 targetStartTime,
uint48 targetEndTime,
address index,
address payoutToken,
uint128 indexSharesAtStart,
uint128 indexBalanceAtStart,
uint256 longTokenId,
uint256 shortTokenId
);
event SilicaPools__BountyPaid(bytes32 indexed poolHash, uint256 bountyAmount, address receiver);
event SilicaPools__PoolEnded(bytes32 indexed poolHash, uint256 indexBalanceAtEnd, uint128 balanceChangePerShare);
event SilicaPools__CollateralizedMint( // zero-hash if not triggered by an order
bytes32 indexed poolHash,
bytes32 orderHash,
uint256 longTokenId,
uint256 shortTokenId,
address shortRecipient,
address longRecipient,
address indexed payer,
uint256 sharesMinted,
address collateralToken,
uint256 collateralAmount
);
event SilicaPools__FillFeePaid(
address indexed payer,
bytes32 indexed poolHash,
bytes32 indexed orderHash,
uint256 tokenId,
address tokenPaid,
uint256 amount
);
event SilicaPools__SharesRefunded(
bytes32 indexed poolHash,
uint256 longTokenId,
uint256 shortTokenId,
address indexed recipient,
address indexed payoutToken,
uint256 sharesRefunded,
uint256 collateralRefunded
);
event SilicaPools__SharesRedeemed(
bytes32 indexed poolHash,
address indexed recipient,
uint256 indexed tokenId,
uint256 sharesRedeemed,
address payoutToken,
uint256 payoutTokenAmount
);
event SilicaPools__TradeHistoryEvent(
bytes32 indexed orderHash,
address indexed maker,
address indexed taker,
bytes32 offeredPoolHash,
bytes32 requestedPoolHash,
uint256 requestedUpfrontAmount,
uint256 offeredUpfrontAmount,
uint256 filledFraction,
uint256 remainingFraction
);
event SilicaPools__Swap(
bytes32 indexed poolHash,
bytes32 orderHash,
address indexed poolTokenRecipient,
address indexed erc20Recipient,
uint256 poolTokenId,
uint256 poolTokenAmount,
address erc20Token,
uint256 erc20Amount
);
event SilicaIndexWhitelisted(address indexed addressToWhitelist);
event SilicaIndexBlacklisted(address indexed addressToBlacklist);
// Thrown when two input arrays have different lengths
error SilicaPools__ArrayLengthMismatch();
// Thrown when the signature of an order is invalid
error SilicaPools__InvalidSignature(bytes signature);
// Thrown when ending a pool that has already finished
error SilicaPools__PoolAlreadyEnded(bytes32 poolHash);
// Thrown when starting a pool that has already begun
error SilicaPools__PoolAlreadyStarted(bytes32 poolHash);
// Thrown when trying to redeem before pool end
error SilicaPools__PoolNotEnded(bytes32 poolHash);
// Thrown when interacting with a cancelled order
error SilicaPools__OrderIsCancelled(bytes32 orderHash);
// Thrown when filling an order partially
error SilicaPools__PartialOrdersNotSupported(bytes32 orderHash);
// Thrown when filling an order that is expired
error SilicaPools__OrderExpired(uint256 expiry, uint256 blockTimestamp);
// Thrown when a caller who is not the maker tries to update an order
error SilicaPools__InvalidCaller(address caller, address expectedCaller);
// Thrown when starting a pool before its target start time
error SilicaPools__TooEarlyToStart(uint256 attemptedTimestamp, uint256 targetTimestamp);
// Thrown when ending a pool before its target end time
error SilicaPools__TooEarlyToEnd(uint256 attemptedTimestamp, uint256 targetTimestamp);
// Thrown when filling an order with protocol that is paused
error SilicaPools__Paused();
// Thrown when non-whitelisted index
error InvalidSilicaIndex();
struct PoolParams {
// 3 storage slots
/// @notice The "balance change per share" below which
/// long shares pay out 0, and short shares pay out the maximum:
/// (cap - floor) * shares
uint128 floor;
/// @notice The "balance change per share" above which
/// short shares pay out 0, and long shares pay out the maximum:
/// (cap - floor) * shares
uint128 cap;
/// @notice The address of the contract which reports the tracked balance
/// @custom:see ISilicaIndex
address index;
/// @notice The timestamp (in UNIX seconds) after which the pool may be started
uint48 targetStartTimestamp;
/// @notice The timestamp (in UNIX seconds) after which the pool may be ended
uint48 targetEndTimestamp;
/// @notice Address of the token in which the payout is denominated
address payoutToken;
}
struct PoolState {
// 3 storage slots
/// @notice The amount of collateral minted for this pool
/// denominated in `SilicaPool.payoutToken`
/// @notice Increases on mints
/// @notice Decreases on bounty payouts
/// @notice Decreases on collateral refunds
/// @notice Does *not* decrease on shares redeemed
/// @dev MUST update at mint, refund, bounty payout
uint128 collateralMinted;
/// @notice The amount of tokens/shares that have minted for this pool
/// @notice Increases on mints
/// @notice Decreases on collateral refunds
/// @notice Does *not* decrease on shares redeemed
/// @dev MUST update at mint, refund
uint128 sharesMinted;
/// @notice The number of shares the `index` represents,
/// as of the pool actual start
/// @dev MUST record at pool actual start
uint128 indexShares;
/// @dev MUST record at pool actual start
uint128 indexInitialBalance;
/// @notice The timestamp (in UNIX seconds) after which the pool was started
/// @dev MUST record at pool actual start
uint48 actualStartTimestamp;
/// @notice The timestamp (in UNIX seconds) after which the pool was ended
/// @dev MUST record at pool actual end
uint48 actualEndTimestamp;
/// @dev MUST record at pool actual end. MUST be pro-rated from
/// `actualEndTimestamp - actualStartTimestamp` to
/// `targetStartTimestamp - targetStartTimestamp`,
/// since the target time range is what the users are buying.
/// MUST be clamped between `floor` and `cap`.
/// @notice Clients SHOULD program defensively in case this failed to be
/// clamped between `floor` and `cap`
uint128 balanceChangePerShare;
}
/// @notice !TRADE OFFER!
/// i receive: requested long shares, requested upfront amount.
/// you receive: offered long shares, offered upfront amount.
/// `SilicaOrder` may not be used to offer/request short shares,
/// since you can offer short shares by requesting long shares,
/// and you can request short shares by offering long shares.
/// @custom:example To sell stETH yield for upfront USDC, set
/// `offeredIndex` to stETH index and
/// `requestedUpfrontToken` to USDC.
/// Set `requestedIndex` and `offeredUpfrontToken` to 0x0.
/// @custom:example To buy stETH yield with upfront USDC, set
/// `requestedIndex` to stETH index
/// and `offeredUpfrontToken` to USDC.
/// Set `offeredIndex` and `requestedUpfrontToken` to 0x0.
/// @custom:example To do a "float-to-float" trade, set both `offeredIndex`
/// and `requestedIndex`. If the `offeredLongShares` is a greater
/// exposure than the `requestedLongShares`, then the
/// `requestedUpfrontAmount` should compensate, and vice versa.
/// @custom:example To "deleverage", i.e. sell the full balance change without
/// subtracting the `floor`: set both `offeredIndex`
/// and `offeredUpfrontToken`. Set `offeredUpfrontAmount` to
/// `offeredfloor * offeredLongShares`.
/// @custom:example For a deleveraged float-to-float trade, set all 4 fields:
/// `offeredIndex`, `offeredUpfrontToken`,
/// `requestedIndex`, `requestedUpfrontToken`.
struct SilicaOrder {
/// @notice The wallet which created and signed the order,
/// i.e. `ecrecover` must return this address.
/// Assets are `offered` from the `maker` to takers,
/// and `requested` by the `maker` from takers.
address maker;
/// @notice If this is 0x0, anyone may fill this order.
/// Otherwise, this is a private order and
/// only `taker` may fill it.
address taker; // 0x0 if public order
uint48 expiry; // UNIX seconds
/// @notice 0x0 if no upfront amount offered
address offeredUpfrontToken;
uint128 offeredUpfrontAmount;
/// @notice 0x0 if no long shares offered
PoolParams offeredLongSharesParams;
uint128 offeredLongShares;
/// @notice 0x0 if no upfront amount requested
address requestedUpfrontToken;
uint128 requestedUpfrontAmount;
/// @notice 0x0 if no long shares requested
PoolParams requestedLongSharesParams;
uint128 requestedLongShares;
}
/// @notice Domain separator for EIP-712.
function domainSeparatorV4() external view returns (bytes32);
/// @notice The fee, in basis points, for minting long and short shares
function fillFeeBps() external returns (uint256);
/// @notice Only callable by owner
/// @dev MUST emit `SilicaPools__MintFeeChanged`
/// @param newFeeBps The new fee, in basis points
function setFillFeeBps(uint256 newFeeBps) external;
/// @notice The address which receives the mint fees
function treasuryAddress() external view returns (address);
/// @notice Only callable by owner
/// @dev MUST emit `SilicaPools__TreasuryAddressChanged`
/// @param newTreasury The new address which receives the mint fees
function setTreasuryAddress(address newTreasury) external;
/// @notice The grace period, in seconds, after the pool's target start & end times during which no bounties are paid
function bountyGracePeriod() external view returns (uint256);
/// @notice Only callable by owner
/// @dev MUST emit `SilicaPools__GracePeriodChanged`
/// @param newGracePeriod The new grace period, in seconds
function setBountyGracePeriod(uint256 newGracePeriod) external;
/// @notice The maximum bounty, as a fraction of the pool's collateral, that can be paid out
function maxBountyFraction() external view returns (uint256);
/// @notice Only callable by owner
/// @dev MUST emit `SilicaPools__MaxBountyFractionChanged`
/// @param newMaxFraction The new maximum bounty, as a fraction of the pool's collateral
function setMaxBountyFraction(uint256 newMaxFraction) external;
/// @notice The rate at which the bounty as a fraction of collateral increases per second
function bountyFractionIncreasePerSecond() external view returns (uint256);
/// @notice Only callable by owner
/// @dev MUST emit `SilicaPools__BountyIncreaseRateChanged`
/// @param newIncreaseAmount The new rate at which the bounty as a fraction of collateral increases per second
function setBountyFractionIncreasePerSecond(uint256 newIncreaseAmount) external;
/// @notice Pause the protocol. Only callable by owner
/// @dev MUST emit `SilicaPools__PauseProtocol`
function pause() external;
/// @notice Unpause the protocol. Only callable by owner
/// @dev MUST emit `SilicaPools__UnpauseProtocol`
function unpause() external;
/// @notice Returns PoolState struct that matched the input hash
/// @param poolHash The hash of the pool
/// @return PoolState struct that matched the input hash
function poolState(bytes32 poolHash) external view returns (PoolState memory);
/// @notice Indicates if a given order has been cancelled
/// @param orderHash The hash of the order
/// @return True if the order has been cancelled, false otherwise
function orderCancelled(bytes32 orderHash) external view returns (bool);
/// @notice Takes collateral from the caller, equal to the maximum payout:
/// (cap - floor) * shares
/// denominated in `SilicaPool.payoutToken`
/// @notice The caller must have approved this contract to transfer `SilicaPool.payoutToken`.
/// @dev MUST emit `SilicaPools__CollateralizedMint`
/// @param poolParams The pool to mint shares from.
/// @param shares The number of long and short shares to mint.
/// @param longRecipient Who should receive the long shares
/// (if 0x0, then `msg.sender` receives)
/// @param shortRecipient Who should receive the short shares
/// (if 0x0, then `msg.sender` receives)
function collateralizedMint(
PoolParams calldata poolParams,
uint256 shares,
address longRecipient,
address shortRecipient
) external;
/// @notice Refunds mint collateral to the caller.
/// @notice The caller must have approved this contract to transfer their long and short shares.
/// @dev MUST emit `SilicaPools__SharesRefunded`
/// @param poolParams The pool to refund from.
/// @param shares Burn this many long shares and short shares.
function collateralRefund(PoolParams[] calldata poolParams, uint256[] calldata shares) external;
/// @notice Refunds mint collateral to the caller from the given pool.
/// @notice The caller must have approved this contract to transfer long and short shares.
/// @dev MUST emit `SilicaPools__SharesRefunded`
/// @param poolParams The pool to refund from.
function maxCollateralRefund(PoolParams[] calldata poolParams) external;
/// @notice Transfers all `offeredLongShares`, `offeredUpfrontAmount`,
/// `requestedLongShares`, `requestedUpfrontAmount` from/to
/// the appropriate parties
/// (`offered` should go from `order.maker` to `msg.sender`,
/// `requested` should go from `msg.sender` to `order.maker`).
/// If `order.taker != 0x0` the order is only fillable by `order.taker`.
/// This function SHOULD revert if any fill fails.
/// `UpfrontAmount`s SHOULD be transferred before any `LongShares` are minted,
/// to reduce the required allowance for minting `LongShares`.
/// @notice The caller must have approved this contract to transfer `requestedUpfrontToken`.
/// @notice If the order is private, the caller must be the taker.
/// @notice The input arrays must match in length.
/// @dev MUST emit `SilicaPools__TradeHistoryEvent`
/// @dev MUST emit `SilicaPools__VolumeAccountingEvent`
/// @param orders The orders to fill.
/// @param signatures The signature of the order maker.
/// @param fractions Pass 1e18 to fill 100% of the order.
function fillOrders(SilicaOrder[] calldata orders, bytes[] calldata signatures, uint256[] calldata fractions)
external;
/// @notice Cancels the given orders.
/// @notice The caller must be the maker of each order.
/// @dev MUST emit `SilicaPools__OrderCancelled`
/// @param orders The orders to cancel.
function cancelOrders(SilicaOrder[] calldata orders) external;
/// @notice View function to estimate bounty for timely initialization of index tracking.
/// @return If any of the pools are already started, then returns 0 for all bounties. Otherwise returns each bounty, quoted in the `payoutToken` of the pool.
/// @dev uncappedBountyFraction = block.timestamp > targetEndTimestamp + gracePeriod ? (block.timestamp - targetEndTimestamp - gracePeriod) * bountyFractionIncreasePerSecond : 0;
/// @dev bountyFraction = max(uncappedBountyFraction, maxBountyFraction)
/// @dev bounty = bountyFraction * collateral / 10**18;
function startBounty(PoolParams[] calldata poolParams) external view returns (uint256[] memory);
/// @notice Records the starting `ISilicaIndex` state for any of
/// the specified pools which have not already been started.
/// Caller will be paid a bounty for each pool which was not
/// already started if called after the grace period.
/// @notice Can only be called after pool's target start time.
/// @dev Search `SilicaPool` for "MUST record at pool actual start".
/// @dev MUST emit `SilicaPools__PoolStarted`
/// @param poolParams The pools to start.
function startPools(PoolParams[] calldata poolParams) external;
/// @notice View function to estimate bounty for timely finalization of index tracking.
/// @return If any of the pools are already ended, then returns 0 for all bounties. Otherwise returns each bounty, quoted in the `payoutToken` of the pool.
/// @dev uncappedBountyFraction = block.timestamp > targetEndTimestamp + gracePeriod ? (block.timestamp - targetEndTimestamp - gracePeriod) * bountyFractionIncreasePerSecond : 0;
/// @dev bountyFraction = max(uncappedBountyFraction, maxBountyFraction)
/// @dev bounty = bountyFraction * collateral / 10**18;
function endBounty(PoolParams[] calldata poolParams) external view returns (uint256[] memory);
/// @notice Records the ending `ISilicaIndex` state for any of
/// the specified pools which have not already been ended.
/// Caller will be paid a bounty for each pool which was not
/// already ended if called after the grace period.
/// @notice Can only be called after pool's target end time.
/// @dev Search `SilicaPool` for "MUST record at pool actual end"
/// @dev MUST emit `SilicaPools__PoolEnded`
function endPools(PoolParams[] calldata poolParams) external;
/// @notice Redeems shares for the payout token.
/// @notice The caller must have approved this contract to transfer their long and short shares.
/// @dev MUST emit `SilicaPools__SharesRedeemed`
/// @param longPoolParams The pools to redeem long shares from.
/// @param shortPoolParams The pools to redeem short shares from.
function redeem(PoolParams[] calldata longPoolParams, PoolParams[] calldata shortPoolParams) external;
/// @notice View function to preview the amount that would be returned for calling `redeemShort()` function.
/// @param shortParams The paramters of the pool to redeem short positions from.
/// @param account The address to redeem on behalf of.
/// @return expectedPayout The amount to be redeemed, denoted in the pool's payoutToken.
function viewRedeemShort(PoolParams calldata shortParams, address account)
external
view
returns (uint256 expectedPayout);
/// @notice View function to preview the amount that would be returned for calling `redeemLong()` function.
/// @param longParams The paramters of the pool to redeem long positions from.
/// @param account The addresses to redeem on behalf of.
/// @return expectedPayout The amount to be redeemed, denoted in the pool's payoutToken.
function viewRedeemLong(PoolParams calldata longParams, address account)
external
view
returns (uint256 expectedPayout);
/// @notice View function to preview the amount that would be returned for calling `collateralRefund()` function.
/// @param poolParams The pool to refund from.
/// @param shares The amount of long and short shares to be burnt.
/// @return expectedRefunds The amount to be refunded, denoted in the pool's payoutToken.
function viewCollateralRefund(PoolParams[] calldata poolParams, uint256[] calldata shares)
external
view
returns (uint256[] memory expectedRefunds);
/// @notice View function to preview the amount that would be returned for calling `maxCollateralRefund()` function
/// @param poolparams The pool to refund from.
/// @param accounts The accounts to refund on behalf of.
/// @return expectedRefund The amount to be refunded, denoted in the pool's payoutToken.
function viewMaxCollateralRefund(PoolParams[] calldata poolparams, address[] calldata accounts)
external
view
returns (uint256[] memory expectedRefund);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* _ _ _ _ _
* / \ | | | _(_)_ __ ___ (_)_ _ __ _
* / _ \ | | |/ / | '_ ` _ \| | | | |/ _` |
* / ___ \| | <| | | | | | | | |_| | (_| |
* /_/_ \_\_|_|\_\_|_| |_| |_|_|\__, |\__,_|
* |_ _|_ __ __| | _____ __ |___/
* | || '_ \ / _` |/ _ \ \/ /
* | || | | | (_| | __/> <
* |___|_| |_|\__,_|\___/_/\_\
*/
/// @title Silica Index Protocol
/// @author Alkimiya
/// @notice Required methods for a contract to provide an index to Silica Pools
interface ISilicaIndex {
/// @return A name suitable for display as a page title or heading.
/// @custom:example "Bitcoin Mining Yield"
/// @custom:example "Lido Staked Ethereum Yield"
/// @custom:example "Gas Costs"
/// @custom:since 0.1.0
function name() external view returns (string memory);
/// @return Short name of the display units of `shares()`.
/// @custom:example "PH/s"
/// @custom:example "ystETH"
/// @custom:example "kgas"
/// @custom:since 0.1.0
function symbol() external view returns (string memory);
/// @return Decimal offset of `symbol()` vs indivisible units of `shares()`.
/// @custom:example If 1 `symbol()` (e.g. "PH/s") represents
/// 1e15 `shares()` (e.g. H/s)
/// then `decimals()` should return 15.
/// @custom:example If 1 `symbol()` (e.g. "ystETH") represents
/// 1e18 `shares()` (e.g. wei)
/// then `decimals()` should return 18.
/// @custom:example If 1 `symbol()` (e.g. "kgas") represents
/// 1e6 `shares()` (e.g. milligas per block)
/// then `decimals()` should return 6.
/// @custom:since 0.1.0
function decimals() external view returns (uint256);
/// @notice Size of the position tracked by this index.
/// Clients SHOULD NOT assume that this value is constant.
/// Clients SHOULD denominate pool shares in the same denomination
/// as `ISilicaIndex.shares()` (see: `symbol()`, `decimals()`).
/// @custom:example 1e15 H/s.
/// @custom:example `ILido.getPooledEthByShares(1 ether)` stETH wei.
/// @custom:example 1e3 milligas per block
/// @custom:since 0.1.0
function shares() external view returns (uint256);
/// @notice Clients MAY transact in any token which is pegged to
/// `balanceToken()`, as long as the `decimals()` match.
/// Clients SHOULD NOT transact in a token which is not pegged to
/// `balanceToken()`; the resulting financial contract will not
/// make sense.
/// @custom:example 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599 (WBTC on mainnet)
/// @custom:example 0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84 (stETH on mainnet)
/// @custom:example 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 (WETH on mainnet)
/// @custom:since 0.1.0
function balanceToken() external view returns (address);
/// @return Tracks the balance accumulated by the `shares()`.
/// @notice This is not required to increase over time.
/// Clients SHOULD have defensive programming against underflow
/// when taking `balance() - initialBalance`.
/// @custom:example WBTC earned per PH/s since Jan 1, 2023.
/// @custom:example `ILido.getPooledEthByShares(1 ether)` stETH.
/// @custom:example Running cost to transact 1 gas every block since Jan 1, 2023.
/// @custom:since 0.1.0
function balance() external view returns (uint256);
}// 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) (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) (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) (token/ERC1155/IERC1155.sol)
pragma solidity ^0.8.20;
import {IERC165} from "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC-1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[ERC].
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` amount of tokens of type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the value of tokens of token type `id` owned by `account`.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(
address[] calldata accounts,
uint256[] calldata ids
) external view returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the zero address.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers a `value` amount of tokens of type `id` from `from` to `to`.
*
* WARNING: This function can potentially allow a reentrancy attack when transferring tokens
* to an untrusted contract, when invoking {onERC1155Received} on the receiver.
* Ensure to follow the checks-effects-interactions pattern and consider employing
* reentrancy guards when interacting with untrusted contracts.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `value` amount.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(address from, address to, uint256 id, uint256 value, bytes calldata data) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* WARNING: This function can potentially allow a reentrancy attack when transferring tokens
* to an untrusted contract, when invoking {onERC1155BatchReceived} on the receiver.
* Ensure to follow the checks-effects-interactions pattern and consider employing
* reentrancy guards when interacting with untrusted contracts.
*
* Emits either a {TransferSingle} or a {TransferBatch} event, depending on the length of the array arguments.
*
* Requirements:
*
* - `ids` and `values` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC1155/extensions/IERC1155MetadataURI.sol)
pragma solidity ^0.8.20;
import {IERC1155} from "../IERC1155.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[ERC].
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC1155/utils/ERC1155Utils.sol)
pragma solidity ^0.8.20;
import {IERC1155Receiver} from "../IERC1155Receiver.sol";
import {IERC1155Errors} from "../../../interfaces/draft-IERC6093.sol";
/**
* @dev Library that provide common ERC-1155 utility functions.
*
* See https://eips.ethereum.org/EIPS/eip-1155[ERC-1155].
*
* _Available since v5.1._
*/
library ERC1155Utils {
/**
* @dev Performs an acceptance check for the provided `operator` by calling {IERC1155-onERC1155Received}
* on the `to` address. The `operator` is generally the address that initiated the token transfer (i.e. `msg.sender`).
*
* The acceptance call is not executed and treated as a no-op if the target address doesn't contain code (i.e. an EOA).
* Otherwise, the recipient must implement {IERC1155Receiver-onERC1155Received} and return the acceptance magic value to accept
* the transfer.
*/
function checkOnERC1155Received(
address operator,
address from,
address to,
uint256 id,
uint256 value,
bytes memory data
) internal {
if (to.code.length > 0) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, value, data) returns (bytes4 response) {
if (response != IERC1155Receiver.onERC1155Received.selector) {
// Tokens rejected
revert IERC1155Errors.ERC1155InvalidReceiver(to);
}
} catch (bytes memory reason) {
if (reason.length == 0) {
// non-IERC1155Receiver implementer
revert IERC1155Errors.ERC1155InvalidReceiver(to);
} else {
assembly ("memory-safe") {
revert(add(32, reason), mload(reason))
}
}
}
}
}
/**
* @dev Performs a batch acceptance check for the provided `operator` by calling {IERC1155-onERC1155BatchReceived}
* on the `to` address. The `operator` is generally the address that initiated the token transfer (i.e. `msg.sender`).
*
* The acceptance call is not executed and treated as a no-op if the target address doesn't contain code (i.e. an EOA).
* Otherwise, the recipient must implement {IERC1155Receiver-onERC1155Received} and return the acceptance magic value to accept
* the transfer.
*/
function checkOnERC1155BatchReceived(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory values,
bytes memory data
) internal {
if (to.code.length > 0) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, values, data) returns (
bytes4 response
) {
if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {
// Tokens rejected
revert IERC1155Errors.ERC1155InvalidReceiver(to);
}
} catch (bytes memory reason) {
if (reason.length == 0) {
// non-IERC1155Receiver implementer
revert IERC1155Errors.ERC1155InvalidReceiver(to);
} else {
assembly ("memory-safe") {
revert(add(32, reason), mload(reason))
}
}
}
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/ERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.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 an 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 an 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 an 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/ShortStrings.sol)
pragma solidity ^0.8.20;
import {StorageSlot} from "./StorageSlot.sol";
// | string | 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA |
// | length | 0x BB |
type ShortString is bytes32;
/**
* @dev This library provides functions to convert short memory strings
* into a `ShortString` type that can be used as an immutable variable.
*
* Strings of arbitrary length can be optimized using this library if
* they are short enough (up to 31 bytes) by packing them with their
* length (1 byte) in a single EVM word (32 bytes). Additionally, a
* fallback mechanism can be used for every other case.
*
* Usage example:
*
* ```solidity
* contract Named {
* using ShortStrings for *;
*
* ShortString private immutable _name;
* string private _nameFallback;
*
* constructor(string memory contractName) {
* _name = contractName.toShortStringWithFallback(_nameFallback);
* }
*
* function name() external view returns (string memory) {
* return _name.toStringWithFallback(_nameFallback);
* }
* }
* ```
*/
library ShortStrings {
// Used as an identifier for strings longer than 31 bytes.
bytes32 private constant FALLBACK_SENTINEL = 0x00000000000000000000000000000000000000000000000000000000000000FF;
error StringTooLong(string str);
error InvalidShortString();
/**
* @dev Encode a string of at most 31 chars into a `ShortString`.
*
* This will trigger a `StringTooLong` error is the input string is too long.
*/
function toShortString(string memory str) internal pure returns (ShortString) {
bytes memory bstr = bytes(str);
if (bstr.length > 31) {
revert StringTooLong(str);
}
return ShortString.wrap(bytes32(uint256(bytes32(bstr)) | bstr.length));
}
/**
* @dev Decode a `ShortString` back to a "normal" string.
*/
function toString(ShortString sstr) internal pure returns (string memory) {
uint256 len = byteLength(sstr);
// using `new string(len)` would work locally but is not memory safe.
string memory str = new string(32);
assembly ("memory-safe") {
mstore(str, len)
mstore(add(str, 0x20), sstr)
}
return str;
}
/**
* @dev Return the length of a `ShortString`.
*/
function byteLength(ShortString sstr) internal pure returns (uint256) {
uint256 result = uint256(ShortString.unwrap(sstr)) & 0xFF;
if (result > 31) {
revert InvalidShortString();
}
return result;
}
/**
* @dev Encode a string into a `ShortString`, or write it to storage if it is too long.
*/
function toShortStringWithFallback(string memory value, string storage store) internal returns (ShortString) {
if (bytes(value).length < 32) {
return toShortString(value);
} else {
StorageSlot.getStringSlot(store).value = value;
return ShortString.wrap(FALLBACK_SENTINEL);
}
}
/**
* @dev Decode a string that was encoded to `ShortString` or written to storage using {setWithFallback}.
*/
function toStringWithFallback(ShortString value, string storage store) internal pure returns (string memory) {
if (ShortString.unwrap(value) != FALLBACK_SENTINEL) {
return toString(value);
} else {
return store;
}
}
/**
* @dev Return the length of a string that was encoded to `ShortString` or written to storage using
* {setWithFallback}.
*
* WARNING: This will return the "byte length" of the string. This may not reflect the actual length in terms of
* actual characters as the UTF-8 encoding of a single character can span over multiple bytes.
*/
function byteLengthWithFallback(ShortString value, string storage store) internal view returns (uint256) {
if (ShortString.unwrap(value) != FALLBACK_SENTINEL) {
return byteLength(value);
} else {
return bytes(store).length;
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC5267.sol)
pragma solidity ^0.8.20;
interface IERC5267 {
/**
* @dev MAY be emitted to signal that the domain could have changed.
*/
event EIP712DomainChanged();
/**
* @dev returns the fields and values that describe the domain separator used by this contract for EIP-712
* signature.
*/
function eip712Domain()
external
view
returns (
bytes1 fields,
string memory name,
string memory version,
uint256 chainId,
address verifyingContract,
bytes32 salt,
uint256[] memory extensions
);
}// 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.1.0) (utils/Address.sol)
pragma solidity ^0.8.20;
import {Errors} from "./Errors.sol";
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert Errors.InsufficientBalance(address(this).balance, amount);
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert Errors.FailedCall();
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {Errors.FailedCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert Errors.InsufficientBalance(address(this).balance, value);
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
* of an unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {Errors.FailedCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly ("memory-safe") {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert Errors.FailedCall();
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.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;
/**
* @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} 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 tryParseUint(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) {
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 tryParseInt(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) {
bytes memory buffer = bytes(input);
// Check presence of a negative sign.
bytes1 sign = bytes1(_unsafeReadBytesOffset(buffer, begin));
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} 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 tryParseHexUint(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) {
bytes memory buffer = bytes(input);
// skip 0x prefix if present
bool hasPrefix = bytes2(_unsafeReadBytesOffset(buffer, begin)) == bytes2("0x");
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 guaratees 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} 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} 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} requirements.
*/
function tryParseAddress(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, address value) {
// check that input is the correct length
bool hasPrefix = bytes2(_unsafeReadBytesOffset(bytes(input), begin)) == bytes2("0x");
uint256 expectedLength = 40 + hasPrefix.toUint() * 2;
if (end - begin == expectedLength) {
// length guarantees that this does not overflow, and value is at most type(uint160).max
(bool s, uint256 v) = tryParseHexUint(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 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
pragma solidity ^0.8.4;
/// @notice Arithmetic library with operations for fixed-point numbers.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/FixedPointMathLib.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)
library FixedPointMathLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The operation failed, as the output exceeds the maximum value of uint256.
error ExpOverflow();
/// @dev The operation failed, as the output exceeds the maximum value of uint256.
error FactorialOverflow();
/// @dev The operation failed, due to an overflow.
error RPowOverflow();
/// @dev The mantissa is too big to fit.
error MantissaOverflow();
/// @dev The operation failed, due to an multiplication overflow.
error MulWadFailed();
/// @dev The operation failed, due to an multiplication overflow.
error SMulWadFailed();
/// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
error DivWadFailed();
/// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
error SDivWadFailed();
/// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
error MulDivFailed();
/// @dev The division failed, as the denominator is zero.
error DivFailed();
/// @dev The full precision multiply-divide operation failed, either due
/// to the result being larger than 256 bits, or a division by a zero.
error FullMulDivFailed();
/// @dev The output is undefined, as the input is less-than-or-equal to zero.
error LnWadUndefined();
/// @dev The input outside the acceptable domain.
error OutOfDomain();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The scalar of ETH and most ERC20s.
uint256 internal constant WAD = 1e18;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* SIMPLIFIED FIXED POINT OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Equivalent to `(x * y) / WAD` rounded down.
function mulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
if gt(x, div(not(0), y)) {
if y {
mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.
revert(0x1c, 0x04)
}
}
z := div(mul(x, y), WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded down.
function sMulWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require((x == 0 || z / x == y) && !(x == -1 && y == type(int256).min))`.
if iszero(gt(or(iszero(x), eq(sdiv(z, x), y)), lt(not(x), eq(y, shl(255, 1))))) {
mstore(0x00, 0xedcd4dd4) // `SMulWadFailed()`.
revert(0x1c, 0x04)
}
z := sdiv(z, WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks.
function rawMulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := div(mul(x, y), WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks.
function rawSMulWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := sdiv(mul(x, y), WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded up.
function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
if iszero(eq(div(z, y), x)) {
if y {
mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.
revert(0x1c, 0x04)
}
}
z := add(iszero(iszero(mod(z, WAD))), div(z, WAD))
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded up, but without overflow checks.
function rawMulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(iszero(iszero(mod(mul(x, y), WAD))), div(mul(x, y), WAD))
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down.
function divWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to `require(y != 0 && x <= type(uint256).max / WAD)`.
if iszero(mul(y, lt(x, add(1, div(not(0), WAD))))) {
mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.
revert(0x1c, 0x04)
}
z := div(mul(x, WAD), y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down.
function sDivWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, WAD)
// Equivalent to `require(y != 0 && ((x * WAD) / WAD == x))`.
if iszero(mul(y, eq(sdiv(z, WAD), x))) {
mstore(0x00, 0x5c43740d) // `SDivWadFailed()`.
revert(0x1c, 0x04)
}
z := sdiv(z, y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks.
function rawDivWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := div(mul(x, WAD), y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks.
function rawSDivWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := sdiv(mul(x, WAD), y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded up.
function divWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to `require(y != 0 && x <= type(uint256).max / WAD)`.
if iszero(mul(y, lt(x, add(1, div(not(0), WAD))))) {
mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.
revert(0x1c, 0x04)
}
z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded up, but without overflow and divide by zero checks.
function rawDivWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
}
}
/// @dev Equivalent to `x` to the power of `y`.
/// because `x ** y = (e ** ln(x)) ** y = e ** (ln(x) * y)`.
/// Note: This function is an approximation.
function powWad(int256 x, int256 y) internal pure returns (int256) {
// Using `ln(x)` means `x` must be greater than 0.
return expWad((lnWad(x) * y) / int256(WAD));
}
/// @dev Returns `exp(x)`, denominated in `WAD`.
/// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
/// Note: This function is an approximation. Monotonically increasing.
function expWad(int256 x) internal pure returns (int256 r) {
unchecked {
// When the result is less than 0.5 we return zero.
// This happens when `x <= (log(1e-18) * 1e18) ~ -4.15e19`.
if (x <= -41446531673892822313) return r;
/// @solidity memory-safe-assembly
assembly {
// When the result is greater than `(2**255 - 1) / 1e18` we can not represent it as
// an int. This happens when `x >= floor(log((2**255 - 1) / 1e18) * 1e18) ≈ 135`.
if iszero(slt(x, 135305999368893231589)) {
mstore(0x00, 0xa37bfec9) // `ExpOverflow()`.
revert(0x1c, 0x04)
}
}
// `x` is now in the range `(-42, 136) * 1e18`. Convert to `(-42, 136) * 2**96`
// for more intermediate precision and a binary basis. This base conversion
// is a multiplication by 1e18 / 2**96 = 5**18 / 2**78.
x = (x << 78) / 5 ** 18;
// Reduce range of x to (-½ ln 2, ½ ln 2) * 2**96 by factoring out powers
// of two such that exp(x) = exp(x') * 2**k, where k is an integer.
// Solving this gives k = round(x / log(2)) and x' = x - k * log(2).
int256 k = ((x << 96) / 54916777467707473351141471128 + 2 ** 95) >> 96;
x = x - k * 54916777467707473351141471128;
// `k` is in the range `[-61, 195]`.
// Evaluate using a (6, 7)-term rational approximation.
// `p` is made monic, we'll multiply by a scale factor later.
int256 y = x + 1346386616545796478920950773328;
y = ((y * x) >> 96) + 57155421227552351082224309758442;
int256 p = y + x - 94201549194550492254356042504812;
p = ((p * y) >> 96) + 28719021644029726153956944680412240;
p = p * x + (4385272521454847904659076985693276 << 96);
// We leave `p` in `2**192` basis so we don't need to scale it back up for the division.
int256 q = x - 2855989394907223263936484059900;
q = ((q * x) >> 96) + 50020603652535783019961831881945;
q = ((q * x) >> 96) - 533845033583426703283633433725380;
q = ((q * x) >> 96) + 3604857256930695427073651918091429;
q = ((q * x) >> 96) - 14423608567350463180887372962807573;
q = ((q * x) >> 96) + 26449188498355588339934803723976023;
/// @solidity memory-safe-assembly
assembly {
// Div in assembly because solidity adds a zero check despite the unchecked.
// The q polynomial won't have zeros in the domain as all its roots are complex.
// No scaling is necessary because p is already `2**96` too large.
r := sdiv(p, q)
}
// r should be in the range `(0.09, 0.25) * 2**96`.
// We now need to multiply r by:
// - The scale factor `s ≈ 6.031367120`.
// - The `2**k` factor from the range reduction.
// - The `1e18 / 2**96` factor for base conversion.
// We do this all at once, with an intermediate result in `2**213`
// basis, so the final right shift is always by a positive amount.
r = int256(
(uint256(r) * 3822833074963236453042738258902158003155416615667) >> uint256(195 - k)
);
}
}
/// @dev Returns `ln(x)`, denominated in `WAD`.
/// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
/// Note: This function is an approximation. Monotonically increasing.
function lnWad(int256 x) internal pure returns (int256 r) {
/// @solidity memory-safe-assembly
assembly {
// We want to convert `x` from `10**18` fixed point to `2**96` fixed point.
// We do this by multiplying by `2**96 / 10**18`. But since
// `ln(x * C) = ln(x) + ln(C)`, we can simply do nothing here
// and add `ln(2**96 / 10**18)` at the end.
// Compute `k = log2(x) - 96`, `r = 159 - k = 255 - log2(x) = 255 ^ log2(x)`.
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// We place the check here for more optimal stack operations.
if iszero(sgt(x, 0)) {
mstore(0x00, 0x1615e638) // `LnWadUndefined()`.
revert(0x1c, 0x04)
}
// forgefmt: disable-next-item
r := xor(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
0xf8f9f9faf9fdfafbf9fdfcfdfafbfcfef9fafdfafcfcfbfefafafcfbffffffff))
// Reduce range of x to (1, 2) * 2**96
// ln(2^k * x) = k * ln(2) + ln(x)
x := shr(159, shl(r, x))
// Evaluate using a (8, 8)-term rational approximation.
// `p` is made monic, we will multiply by a scale factor later.
// forgefmt: disable-next-item
let p := sub( // This heavily nested expression is to avoid stack-too-deep for via-ir.
sar(96, mul(add(43456485725739037958740375743393,
sar(96, mul(add(24828157081833163892658089445524,
sar(96, mul(add(3273285459638523848632254066296,
x), x))), x))), x)), 11111509109440967052023855526967)
p := sub(sar(96, mul(p, x)), 45023709667254063763336534515857)
p := sub(sar(96, mul(p, x)), 14706773417378608786704636184526)
p := sub(mul(p, x), shl(96, 795164235651350426258249787498))
// We leave `p` in `2**192` basis so we don't need to scale it back up for the division.
// `q` is monic by convention.
let q := add(5573035233440673466300451813936, x)
q := add(71694874799317883764090561454958, sar(96, mul(x, q)))
q := add(283447036172924575727196451306956, sar(96, mul(x, q)))
q := add(401686690394027663651624208769553, sar(96, mul(x, q)))
q := add(204048457590392012362485061816622, sar(96, mul(x, q)))
q := add(31853899698501571402653359427138, sar(96, mul(x, q)))
q := add(909429971244387300277376558375, sar(96, mul(x, q)))
// `p / q` is in the range `(0, 0.125) * 2**96`.
// Finalization, we need to:
// - Multiply by the scale factor `s = 5.549…`.
// - Add `ln(2**96 / 10**18)`.
// - Add `k * ln(2)`.
// - Multiply by `10**18 / 2**96 = 5**18 >> 78`.
// The q polynomial is known not to have zeros in the domain.
// No scaling required because p is already `2**96` too large.
p := sdiv(p, q)
// Multiply by the scaling factor: `s * 5**18 * 2**96`, base is now `5**18 * 2**192`.
p := mul(1677202110996718588342820967067443963516166, p)
// Add `ln(2) * k * 5**18 * 2**192`.
// forgefmt: disable-next-item
p := add(mul(16597577552685614221487285958193947469193820559219878177908093499208371, sub(159, r)), p)
// Add `ln(2**96 / 10**18) * 5**18 * 2**192`.
p := add(600920179829731861736702779321621459595472258049074101567377883020018308, p)
// Base conversion: mul `2**18 / 2**192`.
r := sar(174, p)
}
}
/// @dev Returns `W_0(x)`, denominated in `WAD`.
/// See: https://en.wikipedia.org/wiki/Lambert_W_function
/// a.k.a. Product log function. This is an approximation of the principal branch.
/// Note: This function is an approximation. Monotonically increasing.
function lambertW0Wad(int256 x) internal pure returns (int256 w) {
// forgefmt: disable-next-item
unchecked {
if ((w = x) <= -367879441171442322) revert OutOfDomain(); // `x` less than `-1/e`.
(int256 wad, int256 p) = (int256(WAD), x);
uint256 c; // Whether we need to avoid catastrophic cancellation.
uint256 i = 4; // Number of iterations.
if (w <= 0x1ffffffffffff) {
if (-0x4000000000000 <= w) {
i = 1; // Inputs near zero only take one step to converge.
} else if (w <= -0x3ffffffffffffff) {
i = 32; // Inputs near `-1/e` take very long to converge.
}
} else if (uint256(w >> 63) == uint256(0)) {
/// @solidity memory-safe-assembly
assembly {
// Inline log2 for more performance, since the range is small.
let v := shr(49, w)
let l := shl(3, lt(0xff, v))
l := add(or(l, byte(and(0x1f, shr(shr(l, v), 0x8421084210842108cc6318c6db6d54be)),
0x0706060506020504060203020504030106050205030304010505030400000000)), 49)
w := sdiv(shl(l, 7), byte(sub(l, 31), 0x0303030303030303040506080c13))
c := gt(l, 60)
i := add(2, add(gt(l, 53), c))
}
} else {
int256 ll = lnWad(w = lnWad(w));
/// @solidity memory-safe-assembly
assembly {
// `w = ln(x) - ln(ln(x)) + b * ln(ln(x)) / ln(x)`.
w := add(sdiv(mul(ll, 1023715080943847266), w), sub(w, ll))
i := add(3, iszero(shr(68, x)))
c := iszero(shr(143, x))
}
if (c == uint256(0)) {
do { // If `x` is big, use Newton's so that intermediate values won't overflow.
int256 e = expWad(w);
/// @solidity memory-safe-assembly
assembly {
let t := mul(w, div(e, wad))
w := sub(w, sdiv(sub(t, x), div(add(e, t), wad)))
}
if (p <= w) break;
p = w;
} while (--i != uint256(0));
/// @solidity memory-safe-assembly
assembly {
w := sub(w, sgt(w, 2))
}
return w;
}
}
do { // Otherwise, use Halley's for faster convergence.
int256 e = expWad(w);
/// @solidity memory-safe-assembly
assembly {
let t := add(w, wad)
let s := sub(mul(w, e), mul(x, wad))
w := sub(w, sdiv(mul(s, wad), sub(mul(e, t), sdiv(mul(add(t, wad), s), add(t, t)))))
}
if (p <= w) break;
p = w;
} while (--i != c);
/// @solidity memory-safe-assembly
assembly {
w := sub(w, sgt(w, 2))
}
// For certain ranges of `x`, we'll use the quadratic-rate recursive formula of
// R. Iacono and J.P. Boyd for the last iteration, to avoid catastrophic cancellation.
if (c == uint256(0)) return w;
int256 t = w | 1;
/// @solidity memory-safe-assembly
assembly {
x := sdiv(mul(x, wad), t)
}
x = (t * (wad + lnWad(x)));
/// @solidity memory-safe-assembly
assembly {
w := sdiv(x, add(wad, t))
}
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* GENERAL NUMBER UTILITIES */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Calculates `floor(x * y / d)` with full precision.
/// Throws if result overflows a uint256 or when `d` is zero.
/// Credit to Remco Bloemen under MIT license: https://2π.com/21/muldiv
function fullMulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
// 512-bit multiply `[p1 p0] = x * y`.
// Compute the product mod `2**256` and mod `2**256 - 1`
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that `product = p1 * 2**256 + p0`.
// Temporarily use `result` as `p0` to save gas.
result := mul(x, y) // Lower 256 bits of `x * y`.
for {} 1 {} {
// If overflows.
if iszero(mul(or(iszero(x), eq(div(result, x), y)), d)) {
let mm := mulmod(x, y, not(0))
let p1 := sub(mm, add(result, lt(mm, result))) // Upper 256 bits of `x * y`.
/*------------------- 512 by 256 division --------------------*/
// Make division exact by subtracting the remainder from `[p1 p0]`.
let r := mulmod(x, y, d) // Compute remainder using mulmod.
let t := and(d, sub(0, d)) // The least significant bit of `d`. `t >= 1`.
// Make sure the result is less than `2**256`. Also prevents `d == 0`.
// Placing the check here seems to give more optimal stack operations.
if iszero(gt(d, p1)) {
mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
revert(0x1c, 0x04)
}
d := div(d, t) // Divide `d` by `t`, which is a power of two.
// Invert `d mod 2**256`
// Now that `d` is an odd number, it has an inverse
// modulo `2**256` such that `d * inv = 1 mod 2**256`.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, `d * inv = 1 mod 2**4`.
let inv := xor(2, mul(3, d))
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**8
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**16
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**32
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**64
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**128
result :=
mul(
// Divide [p1 p0] by the factors of two.
// Shift in bits from `p1` into `p0`. For this we need
// to flip `t` such that it is `2**256 / t`.
or(
mul(sub(p1, gt(r, result)), add(div(sub(0, t), t), 1)),
div(sub(result, r), t)
),
mul(sub(2, mul(d, inv)), inv) // inverse mod 2**256
)
break
}
result := div(result, d)
break
}
}
}
/// @dev Calculates `floor(x * y / d)` with full precision.
/// Behavior is undefined if `d` is zero or the final result cannot fit in 256 bits.
/// Performs the full 512 bit calculation regardless.
function fullMulDivUnchecked(uint256 x, uint256 y, uint256 d)
internal
pure
returns (uint256 result)
{
/// @solidity memory-safe-assembly
assembly {
result := mul(x, y)
let mm := mulmod(x, y, not(0))
let p1 := sub(mm, add(result, lt(mm, result)))
let t := and(d, sub(0, d))
let r := mulmod(x, y, d)
d := div(d, t)
let inv := xor(2, mul(3, d))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
result :=
mul(
or(mul(sub(p1, gt(r, result)), add(div(sub(0, t), t), 1)), div(sub(result, r), t)),
mul(sub(2, mul(d, inv)), inv)
)
}
}
/// @dev Calculates `floor(x * y / d)` with full precision, rounded up.
/// Throws if result overflows a uint256 or when `d` is zero.
/// Credit to Uniswap-v3-core under MIT license:
/// https://github.com/Uniswap/v3-core/blob/main/contracts/libraries/FullMath.sol
function fullMulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 result) {
result = fullMulDiv(x, y, d);
/// @solidity memory-safe-assembly
assembly {
if mulmod(x, y, d) {
result := add(result, 1)
if iszero(result) {
mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
revert(0x1c, 0x04)
}
}
}
}
/// @dev Returns `floor(x * y / d)`.
/// Reverts if `x * y` overflows, or `d` is zero.
function mulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require(d != 0 && (y == 0 || x <= type(uint256).max / y))`.
if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
mstore(0x00, 0xad251c27) // `MulDivFailed()`.
revert(0x1c, 0x04)
}
z := div(z, d)
}
}
/// @dev Returns `ceil(x * y / d)`.
/// Reverts if `x * y` overflows, or `d` is zero.
function mulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require(d != 0 && (y == 0 || x <= type(uint256).max / y))`.
if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
mstore(0x00, 0xad251c27) // `MulDivFailed()`.
revert(0x1c, 0x04)
}
z := add(iszero(iszero(mod(z, d))), div(z, d))
}
}
/// @dev Returns `ceil(x / d)`.
/// Reverts if `d` is zero.
function divUp(uint256 x, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
if iszero(d) {
mstore(0x00, 0x65244e4e) // `DivFailed()`.
revert(0x1c, 0x04)
}
z := add(iszero(iszero(mod(x, d))), div(x, d))
}
}
/// @dev Returns `max(0, x - y)`.
function zeroFloorSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(gt(x, y), sub(x, y))
}
}
/// @dev Returns `condition ? x : y`, without branching.
function ternary(bool condition, uint256 x, uint256 y) internal pure returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
result := xor(x, mul(xor(x, y), iszero(condition)))
}
}
/// @dev Exponentiate `x` to `y` by squaring, denominated in base `b`.
/// Reverts if the computation overflows.
function rpow(uint256 x, uint256 y, uint256 b) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(b, iszero(y)) // `0 ** 0 = 1`. Otherwise, `0 ** n = 0`.
if x {
z := xor(b, mul(xor(b, x), and(y, 1))) // `z = isEven(y) ? scale : x`
let half := shr(1, b) // Divide `b` by 2.
// Divide `y` by 2 every iteration.
for { y := shr(1, y) } y { y := shr(1, y) } {
let xx := mul(x, x) // Store x squared.
let xxRound := add(xx, half) // Round to the nearest number.
// Revert if `xx + half` overflowed, or if `x ** 2` overflows.
if or(lt(xxRound, xx), shr(128, x)) {
mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
revert(0x1c, 0x04)
}
x := div(xxRound, b) // Set `x` to scaled `xxRound`.
// If `y` is odd:
if and(y, 1) {
let zx := mul(z, x) // Compute `z * x`.
let zxRound := add(zx, half) // Round to the nearest number.
// If `z * x` overflowed or `zx + half` overflowed:
if or(xor(div(zx, x), z), lt(zxRound, zx)) {
// Revert if `x` is non-zero.
if x {
mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
revert(0x1c, 0x04)
}
}
z := div(zxRound, b) // Return properly scaled `zxRound`.
}
}
}
}
}
/// @dev Returns the square root of `x`, rounded down.
function sqrt(uint256 x) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// `floor(sqrt(2**15)) = 181`. `sqrt(2**15) - 181 = 2.84`.
z := 181 // The "correct" value is 1, but this saves a multiplication later.
// This segment is to get a reasonable initial estimate for the Babylonian method. With a bad
// start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.
// Let `y = x / 2**r`. We check `y >= 2**(k + 8)`
// but shift right by `k` bits to ensure that if `x >= 256`, then `y >= 256`.
let r := shl(7, lt(0xffffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffffff, shr(r, x))))
z := shl(shr(1, r), z)
// Goal was to get `z*z*y` within a small factor of `x`. More iterations could
// get y in a tighter range. Currently, we will have y in `[256, 256*(2**16))`.
// We ensured `y >= 256` so that the relative difference between `y` and `y+1` is small.
// That's not possible if `x < 256` but we can just verify those cases exhaustively.
// Now, `z*z*y <= x < z*z*(y+1)`, and `y <= 2**(16+8)`, and either `y >= 256`, or `x < 256`.
// Correctness can be checked exhaustively for `x < 256`, so we assume `y >= 256`.
// Then `z*sqrt(y)` is within `sqrt(257)/sqrt(256)` of `sqrt(x)`, or about 20bps.
// For `s` in the range `[1/256, 256]`, the estimate `f(s) = (181/1024) * (s+1)`
// is in the range `(1/2.84 * sqrt(s), 2.84 * sqrt(s))`,
// with largest error when `s = 1` and when `s = 256` or `1/256`.
// Since `y` is in `[256, 256*(2**16))`, let `a = y/65536`, so that `a` is in `[1/256, 256)`.
// Then we can estimate `sqrt(y)` using
// `sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2**18`.
// There is no overflow risk here since `y < 2**136` after the first branch above.
z := shr(18, mul(z, add(shr(r, x), 65536))) // A `mul()` is saved from starting `z` at 181.
// Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
// If `x+1` is a perfect square, the Babylonian method cycles between
// `floor(sqrt(x))` and `ceil(sqrt(x))`. This statement ensures we return floor.
// See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division
z := sub(z, lt(div(x, z), z))
}
}
/// @dev Returns the cube root of `x`, rounded down.
/// Credit to bout3fiddy and pcaversaccio under AGPLv3 license:
/// https://github.com/pcaversaccio/snekmate/blob/main/src/utils/Math.vy
/// Formally verified by xuwinnie:
/// https://github.com/vectorized/solady/blob/main/audits/xuwinnie-solady-cbrt-proof.pdf
function cbrt(uint256 x) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
let r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// Makeshift lookup table to nudge the approximate log2 result.
z := div(shl(div(r, 3), shl(lt(0xf, shr(r, x)), 0xf)), xor(7, mod(r, 3)))
// Newton-Raphson's.
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
// Round down.
z := sub(z, lt(div(x, mul(z, z)), z))
}
}
/// @dev Returns the square root of `x`, denominated in `WAD`, rounded down.
function sqrtWad(uint256 x) internal pure returns (uint256 z) {
unchecked {
if (x <= type(uint256).max / 10 ** 18) return sqrt(x * 10 ** 18);
z = (1 + sqrt(x)) * 10 ** 9;
z = (fullMulDivUnchecked(x, 10 ** 18, z) + z) >> 1;
}
/// @solidity memory-safe-assembly
assembly {
z := sub(z, gt(999999999999999999, sub(mulmod(z, z, x), 1))) // Round down.
}
}
/// @dev Returns the cube root of `x`, denominated in `WAD`, rounded down.
/// Formally verified by xuwinnie:
/// https://github.com/vectorized/solady/blob/main/audits/xuwinnie-solady-cbrt-proof.pdf
function cbrtWad(uint256 x) internal pure returns (uint256 z) {
unchecked {
if (x <= type(uint256).max / 10 ** 36) return cbrt(x * 10 ** 36);
z = (1 + cbrt(x)) * 10 ** 12;
z = (fullMulDivUnchecked(x, 10 ** 36, z * z) + z + z) / 3;
}
/// @solidity memory-safe-assembly
assembly {
let p := x
for {} 1 {} {
if iszero(shr(229, p)) {
if iszero(shr(199, p)) {
p := mul(p, 100000000000000000) // 10 ** 17.
break
}
p := mul(p, 100000000) // 10 ** 8.
break
}
if iszero(shr(249, p)) { p := mul(p, 100) }
break
}
let t := mulmod(mul(z, z), z, p)
z := sub(z, gt(lt(t, shr(1, p)), iszero(t))) // Round down.
}
}
/// @dev Returns the factorial of `x`.
function factorial(uint256 x) internal pure returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
result := 1
if iszero(lt(x, 58)) {
mstore(0x00, 0xaba0f2a2) // `FactorialOverflow()`.
revert(0x1c, 0x04)
}
for {} x { x := sub(x, 1) } { result := mul(result, x) }
}
}
/// @dev Returns the log2 of `x`.
/// Equivalent to computing the index of the most significant bit (MSB) of `x`.
/// Returns 0 if `x` is zero.
function log2(uint256 x) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// forgefmt: disable-next-item
r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
0x0706060506020504060203020504030106050205030304010505030400000000))
}
}
/// @dev Returns the log2 of `x`, rounded up.
/// Returns 0 if `x` is zero.
function log2Up(uint256 x) internal pure returns (uint256 r) {
r = log2(x);
/// @solidity memory-safe-assembly
assembly {
r := add(r, lt(shl(r, 1), x))
}
}
/// @dev Returns the log10 of `x`.
/// Returns 0 if `x` is zero.
function log10(uint256 x) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
if iszero(lt(x, 100000000000000000000000000000000000000)) {
x := div(x, 100000000000000000000000000000000000000)
r := 38
}
if iszero(lt(x, 100000000000000000000)) {
x := div(x, 100000000000000000000)
r := add(r, 20)
}
if iszero(lt(x, 10000000000)) {
x := div(x, 10000000000)
r := add(r, 10)
}
if iszero(lt(x, 100000)) {
x := div(x, 100000)
r := add(r, 5)
}
r := add(r, add(gt(x, 9), add(gt(x, 99), add(gt(x, 999), gt(x, 9999)))))
}
}
/// @dev Returns the log10 of `x`, rounded up.
/// Returns 0 if `x` is zero.
function log10Up(uint256 x) internal pure returns (uint256 r) {
r = log10(x);
/// @solidity memory-safe-assembly
assembly {
r := add(r, lt(exp(10, r), x))
}
}
/// @dev Returns the log256 of `x`.
/// Returns 0 if `x` is zero.
function log256(uint256 x) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(shr(3, r), lt(0xff, shr(r, x)))
}
}
/// @dev Returns the log256 of `x`, rounded up.
/// Returns 0 if `x` is zero.
function log256Up(uint256 x) internal pure returns (uint256 r) {
r = log256(x);
/// @solidity memory-safe-assembly
assembly {
r := add(r, lt(shl(shl(3, r), 1), x))
}
}
/// @dev Returns the scientific notation format `mantissa * 10 ** exponent` of `x`.
/// Useful for compressing prices (e.g. using 25 bit mantissa and 7 bit exponent).
function sci(uint256 x) internal pure returns (uint256 mantissa, uint256 exponent) {
/// @solidity memory-safe-assembly
assembly {
mantissa := x
if mantissa {
if iszero(mod(mantissa, 1000000000000000000000000000000000)) {
mantissa := div(mantissa, 1000000000000000000000000000000000)
exponent := 33
}
if iszero(mod(mantissa, 10000000000000000000)) {
mantissa := div(mantissa, 10000000000000000000)
exponent := add(exponent, 19)
}
if iszero(mod(mantissa, 1000000000000)) {
mantissa := div(mantissa, 1000000000000)
exponent := add(exponent, 12)
}
if iszero(mod(mantissa, 1000000)) {
mantissa := div(mantissa, 1000000)
exponent := add(exponent, 6)
}
if iszero(mod(mantissa, 10000)) {
mantissa := div(mantissa, 10000)
exponent := add(exponent, 4)
}
if iszero(mod(mantissa, 100)) {
mantissa := div(mantissa, 100)
exponent := add(exponent, 2)
}
if iszero(mod(mantissa, 10)) {
mantissa := div(mantissa, 10)
exponent := add(exponent, 1)
}
}
}
}
/// @dev Convenience function for packing `x` into a smaller number using `sci`.
/// The `mantissa` will be in bits [7..255] (the upper 249 bits).
/// The `exponent` will be in bits [0..6] (the lower 7 bits).
/// Use `SafeCastLib` to safely ensure that the `packed` number is small
/// enough to fit in the desired unsigned integer type:
/// ```
/// uint32 packed = SafeCastLib.toUint32(FixedPointMathLib.packSci(777 ether));
/// ```
function packSci(uint256 x) internal pure returns (uint256 packed) {
(x, packed) = sci(x); // Reuse for `mantissa` and `exponent`.
/// @solidity memory-safe-assembly
assembly {
if shr(249, x) {
mstore(0x00, 0xce30380c) // `MantissaOverflow()`.
revert(0x1c, 0x04)
}
packed := or(shl(7, x), packed)
}
}
/// @dev Convenience function for unpacking a packed number from `packSci`.
function unpackSci(uint256 packed) internal pure returns (uint256 unpacked) {
unchecked {
unpacked = (packed >> 7) * 10 ** (packed & 0x7f);
}
}
/// @dev Returns the average of `x` and `y`. Rounds towards zero.
function avg(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = (x & y) + ((x ^ y) >> 1);
}
}
/// @dev Returns the average of `x` and `y`. Rounds towards negative infinity.
function avg(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = (x >> 1) + (y >> 1) + (x & y & 1);
}
}
/// @dev Returns the absolute value of `x`.
function abs(int256 x) internal pure returns (uint256 z) {
unchecked {
z = (uint256(x) + uint256(x >> 255)) ^ uint256(x >> 255);
}
}
/// @dev Returns the absolute distance between `x` and `y`.
function dist(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(xor(sub(0, gt(x, y)), sub(y, x)), gt(x, y))
}
}
/// @dev Returns the absolute distance between `x` and `y`.
function dist(int256 x, int256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(xor(sub(0, sgt(x, y)), sub(y, x)), sgt(x, y))
}
}
/// @dev Returns the minimum of `x` and `y`.
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), lt(y, x)))
}
}
/// @dev Returns the minimum of `x` and `y`.
function min(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), slt(y, x)))
}
}
/// @dev Returns the maximum of `x` and `y`.
function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), gt(y, x)))
}
}
/// @dev Returns the maximum of `x` and `y`.
function max(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), sgt(y, x)))
}
}
/// @dev Returns `x`, bounded to `minValue` and `maxValue`.
function clamp(uint256 x, uint256 minValue, uint256 maxValue)
internal
pure
returns (uint256 z)
{
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, minValue), gt(minValue, x)))
z := xor(z, mul(xor(z, maxValue), lt(maxValue, z)))
}
}
/// @dev Returns `x`, bounded to `minValue` and `maxValue`.
function clamp(int256 x, int256 minValue, int256 maxValue) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, minValue), sgt(minValue, x)))
z := xor(z, mul(xor(z, maxValue), slt(maxValue, z)))
}
}
/// @dev Returns greatest common divisor of `x` and `y`.
function gcd(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
for { z := x } y {} {
let t := y
y := mod(z, y)
z := t
}
}
}
/// @dev Returns `a + (b - a) * (t - begin) / (end - begin)`,
/// with `t` clamped between `begin` and `end` (inclusive).
/// Agnostic to the order of (`a`, `b`) and (`end`, `begin`).
/// If `begins == end`, returns `t <= begin ? a : b`.
function lerp(uint256 a, uint256 b, uint256 t, uint256 begin, uint256 end)
internal
pure
returns (uint256)
{
if (begin > end) (t, begin, end) = (~t, ~begin, ~end);
if (t <= begin) return a;
if (t >= end) return b;
unchecked {
if (b >= a) return a + fullMulDiv(b - a, t - begin, end - begin);
return a - fullMulDiv(a - b, t - begin, end - begin);
}
}
/// @dev Returns `a + (b - a) * (t - begin) / (end - begin)`.
/// with `t` clamped between `begin` and `end` (inclusive).
/// Agnostic to the order of (`a`, `b`) and (`end`, `begin`).
/// If `begins == end`, returns `t <= begin ? a : b`.
function lerp(int256 a, int256 b, int256 t, int256 begin, int256 end)
internal
pure
returns (int256)
{
if (begin > end) (t, begin, end) = (~t, ~begin, ~end);
if (t <= begin) return a;
if (t >= end) return b;
// forgefmt: disable-next-item
unchecked {
if (b >= a) return int256(uint256(a) + fullMulDiv(uint256(b - a),
uint256(t - begin), uint256(end - begin)));
return int256(uint256(a) - fullMulDiv(uint256(a - b),
uint256(t - begin), uint256(end - begin)));
}
}
/// @dev Returns if `x` is an even number. Some people may need this.
function isEven(uint256 x) internal pure returns (bool) {
return x & uint256(1) == uint256(0);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* RAW NUMBER OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns `x + y`, without checking for overflow.
function rawAdd(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = x + y;
}
}
/// @dev Returns `x + y`, without checking for overflow.
function rawAdd(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = x + y;
}
}
/// @dev Returns `x - y`, without checking for underflow.
function rawSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = x - y;
}
}
/// @dev Returns `x - y`, without checking for underflow.
function rawSub(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = x - y;
}
}
/// @dev Returns `x * y`, without checking for overflow.
function rawMul(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = x * y;
}
}
/// @dev Returns `x * y`, without checking for overflow.
function rawMul(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = x * y;
}
}
/// @dev Returns `x / y`, returning 0 if `y` is zero.
function rawDiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := div(x, y)
}
}
/// @dev Returns `x / y`, returning 0 if `y` is zero.
function rawSDiv(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := sdiv(x, y)
}
}
/// @dev Returns `x % y`, returning 0 if `y` is zero.
function rawMod(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mod(x, y)
}
}
/// @dev Returns `x % y`, returning 0 if `y` is zero.
function rawSMod(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := smod(x, y)
}
}
/// @dev Returns `(x + y) % d`, return 0 if `d` if zero.
function rawAddMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := addmod(x, y, d)
}
}
/// @dev Returns `(x * y) % d`, return 0 if `d` if zero.
function rawMulMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mulmod(x, y, d)
}
}
}// 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.1.0) (token/ERC1155/IERC1155Receiver.sol)
pragma solidity ^0.8.20;
import {IERC165} from "../../utils/introspection/IERC165.sol";
/**
* @dev Interface that must be implemented by smart contracts in order to receive
* ERC-1155 token transfers.
*/
interface IERC1155Receiver is IERC165 {
/**
* @dev Handles the receipt of a single ERC-1155 token type. This function is
* called at the end of a `safeTransferFrom` after the balance has been updated.
*
* NOTE: To accept the transfer, this must return
* `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
* (i.e. 0xf23a6e61, or its own function selector).
*
* @param operator The address which initiated the transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param id The ID of the token being transferred
* @param value The amount of tokens being transferred
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
* @dev Handles the receipt of a multiple ERC-1155 token types. This function
* is called at the end of a `safeBatchTransferFrom` after the balances have
* been updated.
*
* NOTE: To accept the transfer(s), this must return
* `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
* (i.e. 0xbc197c81, or its own function selector).
*
* @param operator The address which initiated the batch transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param ids An array containing ids of each token being transferred (order and length must match values array)
* @param values An array containing amounts of each token being transferred (order and length must match ids array)
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}// 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.1.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.1.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 Returns the addition of two unsigned integers, with an success flag (no overflow).
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with an success flag (no overflow).
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an success flag (no overflow).
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @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 {
if (b == 0) return (false, 0);
return (true, 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 {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @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 {
// 512-bit multiply [prod1 prod0] = 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 = prod1 * 2²⁵⁶ + prod0.
uint256 prod0 = x * y; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 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 prod0 / denominator;
}
// Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
if (denominator <= prod1) {
Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, 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 {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, 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 prod1 into prod0.
prod0 |= prod1 * 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 prod1
// is no longer required.
result = prod0 * 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 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 value) internal pure returns (uint256) {
uint256 result = 0;
uint256 exp;
unchecked {
exp = 128 * SafeCast.toUint(value > (1 << 128) - 1);
value >>= exp;
result += exp;
exp = 64 * SafeCast.toUint(value > (1 << 64) - 1);
value >>= exp;
result += exp;
exp = 32 * SafeCast.toUint(value > (1 << 32) - 1);
value >>= exp;
result += exp;
exp = 16 * SafeCast.toUint(value > (1 << 16) - 1);
value >>= exp;
result += exp;
exp = 8 * SafeCast.toUint(value > (1 << 8) - 1);
value >>= exp;
result += exp;
exp = 4 * SafeCast.toUint(value > (1 << 4) - 1);
value >>= exp;
result += exp;
exp = 2 * SafeCast.toUint(value > (1 << 2) - 1);
value >>= exp;
result += exp;
result += SafeCast.toUint(value > 1);
}
return result;
}
/**
* @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 value) internal pure returns (uint256) {
uint256 result = 0;
uint256 isGt;
unchecked {
isGt = SafeCast.toUint(value > (1 << 128) - 1);
value >>= isGt * 128;
result += isGt * 16;
isGt = SafeCast.toUint(value > (1 << 64) - 1);
value >>= isGt * 64;
result += isGt * 8;
isGt = SafeCast.toUint(value > (1 << 32) - 1);
value >>= isGt * 32;
result += isGt * 4;
isGt = SafeCast.toUint(value > (1 << 16) - 1);
value >>= isGt * 16;
result += isGt * 2;
result += SafeCast.toUint(value > (1 << 8) - 1);
}
return result;
}
/**
* @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.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.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.1.0) (utils/Errors.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of common custom errors used in multiple contracts
*
* IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
* It is recommended to avoid relying on the error API for critical functionality.
*
* _Available since v5.1._
*/
library Errors {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error InsufficientBalance(uint256 balance, uint256 needed);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedCall();
/**
* @dev The deployment failed.
*/
error FailedDeployment();
/**
* @dev A necessary precompile is missing.
*/
error MissingPrecompile(address);
}// 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)
}
}
}{
"remappings": [
"@openzeppelin/=lib/openzeppelin-contracts/contracts/",
"ds-test/=lib/forge-std/lib/ds-test/src/",
"forge-std/=lib/forge-std/src/",
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/",
"solady/=lib/solady/src/"
],
"optimizer": {
"enabled": true,
"runs": 200
},
"metadata": {
"useLiteralContent": false,
"bytecodeHash": "ipfs",
"appendCBOR": true
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"evmVersion": "paris",
"viaIR": true,
"libraries": {}
}Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
Contract ABI
API[{"inputs":[{"internalType":"uint256","name":"startFeeBps","type":"uint256"},{"internalType":"address","name":"initialOwner","type":"address"},{"internalType":"address","name":"alkimiyaTreasury","type":"address"},{"internalType":"uint256","name":"gracePeriod","type":"uint256"},{"internalType":"uint256","name":"maxBountyFrac","type":"uint256"},{"internalType":"uint256","name":"bountyIncreasePerSecond","type":"uint256"}],"stateMutability":"nonpayable","type":"constructor"},{"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":"sender","type":"address"},{"internalType":"uint256","name":"balance","type":"uint256"},{"internalType":"uint256","name":"needed","type":"uint256"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"ERC1155InsufficientBalance","type":"error"},{"inputs":[{"internalType":"address","name":"approver","type":"address"}],"name":"ERC1155InvalidApprover","type":"error"},{"inputs":[{"internalType":"uint256","name":"idsLength","type":"uint256"},{"internalType":"uint256","name":"valuesLength","type":"uint256"}],"name":"ERC1155InvalidArrayLength","type":"error"},{"inputs":[{"internalType":"address","name":"operator","type":"address"}],"name":"ERC1155InvalidOperator","type":"error"},{"inputs":[{"internalType":"address","name":"receiver","type":"address"}],"name":"ERC1155InvalidReceiver","type":"error"},{"inputs":[{"internalType":"address","name":"sender","type":"address"}],"name":"ERC1155InvalidSender","type":"error"},{"inputs":[{"internalType":"address","name":"operator","type":"address"},{"internalType":"address","name":"owner","type":"address"}],"name":"ERC1155MissingApprovalForAll","type":"error"},{"inputs":[],"name":"InvalidShortString","type":"error"},{"inputs":[],"name":"InvalidSilicaIndex","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":[],"name":"ReentrancyGuardReentrantCall","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"inputs":[],"name":"SilicaPools__ArrayLengthMismatch","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"},{"internalType":"address","name":"expectedCaller","type":"address"}],"name":"SilicaPools__InvalidCaller","type":"error"},{"inputs":[{"internalType":"bytes","name":"signature","type":"bytes"}],"name":"SilicaPools__InvalidSignature","type":"error"},{"inputs":[{"internalType":"uint256","name":"expiry","type":"uint256"},{"internalType":"uint256","name":"blockTimestamp","type":"uint256"}],"name":"SilicaPools__OrderExpired","type":"error"},{"inputs":[{"internalType":"bytes32","name":"orderHash","type":"bytes32"}],"name":"SilicaPools__OrderIsCancelled","type":"error"},{"inputs":[{"internalType":"bytes32","name":"orderHash","type":"bytes32"}],"name":"SilicaPools__PartialOrdersNotSupported","type":"error"},{"inputs":[],"name":"SilicaPools__Paused","type":"error"},{"inputs":[{"internalType":"bytes32","name":"poolHash","type":"bytes32"}],"name":"SilicaPools__PoolAlreadyEnded","type":"error"},{"inputs":[{"internalType":"bytes32","name":"poolHash","type":"bytes32"}],"name":"SilicaPools__PoolAlreadyStarted","type":"error"},{"inputs":[{"internalType":"bytes32","name":"poolHash","type":"bytes32"}],"name":"SilicaPools__PoolNotEnded","type":"error"},{"inputs":[{"internalType":"uint256","name":"attemptedTimestamp","type":"uint256"},{"internalType":"uint256","name":"targetTimestamp","type":"uint256"}],"name":"SilicaPools__TooEarlyToEnd","type":"error"},{"inputs":[{"internalType":"uint256","name":"attemptedTimestamp","type":"uint256"},{"internalType":"uint256","name":"targetTimestamp","type":"uint256"}],"name":"SilicaPools__TooEarlyToStart","type":"error"},{"inputs":[{"internalType":"string","name":"str","type":"string"}],"name":"StringTooLong","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"operator","type":"address"},{"indexed":false,"internalType":"bool","name":"approved","type":"bool"}],"name":"ApprovalForAll","type":"event"},{"anonymous":false,"inputs":[],"name":"EIP712DomainChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferStarted","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":true,"internalType":"address","name":"addressToBlacklist","type":"address"}],"name":"SilicaIndexBlacklisted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"addressToWhitelist","type":"address"}],"name":"SilicaIndexWhitelisted","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"newRate","type":"uint256"}],"name":"SilicaPools__BountyIncreaseRateChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"poolHash","type":"bytes32"},{"indexed":false,"internalType":"uint256","name":"bountyAmount","type":"uint256"},{"indexed":false,"internalType":"address","name":"receiver","type":"address"}],"name":"SilicaPools__BountyPaid","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"poolHash","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"orderHash","type":"bytes32"},{"indexed":false,"internalType":"uint256","name":"longTokenId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"shortTokenId","type":"uint256"},{"indexed":false,"internalType":"address","name":"shortRecipient","type":"address"},{"indexed":false,"internalType":"address","name":"longRecipient","type":"address"},{"indexed":true,"internalType":"address","name":"payer","type":"address"},{"indexed":false,"internalType":"uint256","name":"sharesMinted","type":"uint256"},{"indexed":false,"internalType":"address","name":"collateralToken","type":"address"},{"indexed":false,"internalType":"uint256","name":"collateralAmount","type":"uint256"}],"name":"SilicaPools__CollateralizedMint","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"newFeeBps","type":"uint256"}],"name":"SilicaPools__FillFeeChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"payer","type":"address"},{"indexed":true,"internalType":"bytes32","name":"poolHash","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"orderHash","type":"bytes32"},{"indexed":false,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":false,"internalType":"address","name":"tokenPaid","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"SilicaPools__FillFeePaid","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"newGracePeriod","type":"uint256"}],"name":"SilicaPools__GracePeriodChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"newMaxFraction","type":"uint256"}],"name":"SilicaPools__MaxBountyFractionChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"orderHash","type":"bytes32"}],"name":"SilicaPools__OrderCancelled","type":"event"},{"anonymous":false,"inputs":[],"name":"SilicaPools__PauseProtocol","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"poolHash","type":"bytes32"},{"indexed":false,"internalType":"uint256","name":"indexBalanceAtEnd","type":"uint256"},{"indexed":false,"internalType":"uint128","name":"balanceChangePerShare","type":"uint128"}],"name":"SilicaPools__PoolEnded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"poolHash","type":"bytes32"},{"indexed":false,"internalType":"uint128","name":"floor","type":"uint128"},{"indexed":false,"internalType":"uint128","name":"cap","type":"uint128"},{"indexed":false,"internalType":"uint48","name":"targetStartTime","type":"uint48"},{"indexed":false,"internalType":"uint48","name":"targetEndTime","type":"uint48"},{"indexed":false,"internalType":"address","name":"index","type":"address"},{"indexed":false,"internalType":"address","name":"payoutToken","type":"address"},{"indexed":false,"internalType":"uint128","name":"indexSharesAtStart","type":"uint128"},{"indexed":false,"internalType":"uint128","name":"indexBalanceAtStart","type":"uint128"},{"indexed":false,"internalType":"uint256","name":"longTokenId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"shortTokenId","type":"uint256"}],"name":"SilicaPools__PoolStarted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"poolHash","type":"bytes32"},{"indexed":true,"internalType":"address","name":"recipient","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"sharesRedeemed","type":"uint256"},{"indexed":false,"internalType":"address","name":"payoutToken","type":"address"},{"indexed":false,"internalType":"uint256","name":"payoutTokenAmount","type":"uint256"}],"name":"SilicaPools__SharesRedeemed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"poolHash","type":"bytes32"},{"indexed":false,"internalType":"uint256","name":"longTokenId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"shortTokenId","type":"uint256"},{"indexed":true,"internalType":"address","name":"recipient","type":"address"},{"indexed":true,"internalType":"address","name":"payoutToken","type":"address"},{"indexed":false,"internalType":"uint256","name":"sharesRefunded","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"collateralRefunded","type":"uint256"}],"name":"SilicaPools__SharesRefunded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"poolHash","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"orderHash","type":"bytes32"},{"indexed":true,"internalType":"address","name":"poolTokenRecipient","type":"address"},{"indexed":true,"internalType":"address","name":"erc20Recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"poolTokenId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"poolTokenAmount","type":"uint256"},{"indexed":false,"internalType":"address","name":"erc20Token","type":"address"},{"indexed":false,"internalType":"uint256","name":"erc20Amount","type":"uint256"}],"name":"SilicaPools__Swap","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"orderHash","type":"bytes32"},{"indexed":true,"internalType":"address","name":"maker","type":"address"},{"indexed":true,"internalType":"address","name":"taker","type":"address"},{"indexed":false,"internalType":"bytes32","name":"offeredPoolHash","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"requestedPoolHash","type":"bytes32"},{"indexed":false,"internalType":"uint256","name":"requestedUpfrontAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"offeredUpfrontAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"filledFraction","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"remainingFraction","type":"uint256"}],"name":"SilicaPools__TradeHistoryEvent","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"newTreasuryAddress","type":"address"}],"name":"SilicaPools__TreasuryAddressChanged","type":"event"},{"anonymous":false,"inputs":[],"name":"SilicaPools__UnpauseProtocol","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"operator","type":"address"},{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256[]","name":"ids","type":"uint256[]"},{"indexed":false,"internalType":"uint256[]","name":"values","type":"uint256[]"}],"name":"TransferBatch","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"operator","type":"address"},{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"id","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"TransferSingle","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"string","name":"value","type":"string"},{"indexed":true,"internalType":"uint256","name":"id","type":"uint256"}],"name":"URI","type":"event"},{"inputs":[],"name":"INVERSE_BASIS_POINT","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MAX_FILL_FEE_BPS","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"TOKENID_SALT","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"acceptOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"uint256","name":"id","type":"uint256"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address[]","name":"accounts","type":"address[]"},{"internalType":"uint256[]","name":"ids","type":"uint256[]"}],"name":"balanceOfBatch","outputs":[{"internalType":"uint256[]","name":"","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"addressToBlacklist","type":"address"}],"name":"blacklistSilicaIndex","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"bountyFractionIncreasePerSecond","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"bountyGracePeriod","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"maker","type":"address"},{"internalType":"address","name":"taker","type":"address"},{"internalType":"uint48","name":"expiry","type":"uint48"},{"internalType":"address","name":"offeredUpfrontToken","type":"address"},{"internalType":"uint128","name":"offeredUpfrontAmount","type":"uint128"},{"components":[{"internalType":"uint128","name":"floor","type":"uint128"},{"internalType":"uint128","name":"cap","type":"uint128"},{"internalType":"address","name":"index","type":"address"},{"internalType":"uint48","name":"targetStartTimestamp","type":"uint48"},{"internalType":"uint48","name":"targetEndTimestamp","type":"uint48"},{"internalType":"address","name":"payoutToken","type":"address"}],"internalType":"struct ISilicaPools.PoolParams","name":"offeredLongSharesParams","type":"tuple"},{"internalType":"uint128","name":"offeredLongShares","type":"uint128"},{"internalType":"address","name":"requestedUpfrontToken","type":"address"},{"internalType":"uint128","name":"requestedUpfrontAmount","type":"uint128"},{"components":[{"internalType":"uint128","name":"floor","type":"uint128"},{"internalType":"uint128","name":"cap","type":"uint128"},{"internalType":"address","name":"index","type":"address"},{"internalType":"uint48","name":"targetStartTimestamp","type":"uint48"},{"internalType":"uint48","name":"targetEndTimestamp","type":"uint48"},{"internalType":"address","name":"payoutToken","type":"address"}],"internalType":"struct ISilicaPools.PoolParams","name":"requestedLongSharesParams","type":"tuple"},{"internalType":"uint128","name":"requestedLongShares","type":"uint128"}],"internalType":"struct ISilicaPools.SilicaOrder[]","name":"orders","type":"tuple[]"}],"name":"cancelOrders","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"uint128","name":"floor","type":"uint128"},{"internalType":"uint128","name":"cap","type":"uint128"},{"internalType":"address","name":"index","type":"address"},{"internalType":"uint48","name":"targetStartTimestamp","type":"uint48"},{"internalType":"uint48","name":"targetEndTimestamp","type":"uint48"},{"internalType":"address","name":"payoutToken","type":"address"}],"internalType":"struct ISilicaPools.PoolParams[]","name":"poolParams","type":"tuple[]"},{"internalType":"uint256[]","name":"shares","type":"uint256[]"}],"name":"collateralRefund","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"uint128","name":"floor","type":"uint128"},{"internalType":"uint128","name":"cap","type":"uint128"},{"internalType":"address","name":"index","type":"address"},{"internalType":"uint48","name":"targetStartTimestamp","type":"uint48"},{"internalType":"uint48","name":"targetEndTimestamp","type":"uint48"},{"internalType":"address","name":"payoutToken","type":"address"}],"internalType":"struct ISilicaPools.PoolParams","name":"poolParams","type":"tuple"},{"internalType":"uint256","name":"shares","type":"uint256"},{"internalType":"address","name":"longRecipient","type":"address"},{"internalType":"address","name":"shortRecipient","type":"address"}],"name":"collateralizedMint","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"disablePartialFills","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"domainSeparatorV4","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"eip712Domain","outputs":[{"internalType":"bytes1","name":"fields","type":"bytes1"},{"internalType":"string","name":"name","type":"string"},{"internalType":"string","name":"version","type":"string"},{"internalType":"uint256","name":"chainId","type":"uint256"},{"internalType":"address","name":"verifyingContract","type":"address"},{"internalType":"bytes32","name":"salt","type":"bytes32"},{"internalType":"uint256[]","name":"extensions","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"enablePartialFills","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"uint128","name":"floor","type":"uint128"},{"internalType":"uint128","name":"cap","type":"uint128"},{"internalType":"address","name":"index","type":"address"},{"internalType":"uint48","name":"targetStartTimestamp","type":"uint48"},{"internalType":"uint48","name":"targetEndTimestamp","type":"uint48"},{"internalType":"address","name":"payoutToken","type":"address"}],"internalType":"struct ISilicaPools.PoolParams[]","name":"poolParams","type":"tuple[]"}],"name":"endBounty","outputs":[{"internalType":"uint256[]","name":"","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"uint128","name":"floor","type":"uint128"},{"internalType":"uint128","name":"cap","type":"uint128"},{"internalType":"address","name":"index","type":"address"},{"internalType":"uint48","name":"targetStartTimestamp","type":"uint48"},{"internalType":"uint48","name":"targetEndTimestamp","type":"uint48"},{"internalType":"address","name":"payoutToken","type":"address"}],"internalType":"struct ISilicaPools.PoolParams","name":"poolParams","type":"tuple"}],"name":"endPool","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"uint128","name":"floor","type":"uint128"},{"internalType":"uint128","name":"cap","type":"uint128"},{"internalType":"address","name":"index","type":"address"},{"internalType":"uint48","name":"targetStartTimestamp","type":"uint48"},{"internalType":"uint48","name":"targetEndTimestamp","type":"uint48"},{"internalType":"address","name":"payoutToken","type":"address"}],"internalType":"struct ISilicaPools.PoolParams[]","name":"poolParams","type":"tuple[]"}],"name":"endPools","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"fillFeeBps","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"maker","type":"address"},{"internalType":"address","name":"taker","type":"address"},{"internalType":"uint48","name":"expiry","type":"uint48"},{"internalType":"address","name":"offeredUpfrontToken","type":"address"},{"internalType":"uint128","name":"offeredUpfrontAmount","type":"uint128"},{"components":[{"internalType":"uint128","name":"floor","type":"uint128"},{"internalType":"uint128","name":"cap","type":"uint128"},{"internalType":"address","name":"index","type":"address"},{"internalType":"uint48","name":"targetStartTimestamp","type":"uint48"},{"internalType":"uint48","name":"targetEndTimestamp","type":"uint48"},{"internalType":"address","name":"payoutToken","type":"address"}],"internalType":"struct ISilicaPools.PoolParams","name":"offeredLongSharesParams","type":"tuple"},{"internalType":"uint128","name":"offeredLongShares","type":"uint128"},{"internalType":"address","name":"requestedUpfrontToken","type":"address"},{"internalType":"uint128","name":"requestedUpfrontAmount","type":"uint128"},{"components":[{"internalType":"uint128","name":"floor","type":"uint128"},{"internalType":"uint128","name":"cap","type":"uint128"},{"internalType":"address","name":"index","type":"address"},{"internalType":"uint48","name":"targetStartTimestamp","type":"uint48"},{"internalType":"uint48","name":"targetEndTimestamp","type":"uint48"},{"internalType":"address","name":"payoutToken","type":"address"}],"internalType":"struct ISilicaPools.PoolParams","name":"requestedLongSharesParams","type":"tuple"},{"internalType":"uint128","name":"requestedLongShares","type":"uint128"}],"internalType":"struct ISilicaPools.SilicaOrder","name":"order","type":"tuple"},{"internalType":"bytes","name":"signature","type":"bytes"},{"internalType":"uint256","name":"fraction","type":"uint256"}],"name":"fillOrder","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"maker","type":"address"},{"internalType":"address","name":"taker","type":"address"},{"internalType":"uint48","name":"expiry","type":"uint48"},{"internalType":"address","name":"offeredUpfrontToken","type":"address"},{"internalType":"uint128","name":"offeredUpfrontAmount","type":"uint128"},{"components":[{"internalType":"uint128","name":"floor","type":"uint128"},{"internalType":"uint128","name":"cap","type":"uint128"},{"internalType":"address","name":"index","type":"address"},{"internalType":"uint48","name":"targetStartTimestamp","type":"uint48"},{"internalType":"uint48","name":"targetEndTimestamp","type":"uint48"},{"internalType":"address","name":"payoutToken","type":"address"}],"internalType":"struct ISilicaPools.PoolParams","name":"offeredLongSharesParams","type":"tuple"},{"internalType":"uint128","name":"offeredLongShares","type":"uint128"},{"internalType":"address","name":"requestedUpfrontToken","type":"address"},{"internalType":"uint128","name":"requestedUpfrontAmount","type":"uint128"},{"components":[{"internalType":"uint128","name":"floor","type":"uint128"},{"internalType":"uint128","name":"cap","type":"uint128"},{"internalType":"address","name":"index","type":"address"},{"internalType":"uint48","name":"targetStartTimestamp","type":"uint48"},{"internalType":"uint48","name":"targetEndTimestamp","type":"uint48"},{"internalType":"address","name":"payoutToken","type":"address"}],"internalType":"struct ISilicaPools.PoolParams","name":"requestedLongSharesParams","type":"tuple"},{"internalType":"uint128","name":"requestedLongShares","type":"uint128"}],"internalType":"struct ISilicaPools.SilicaOrder[]","name":"orders","type":"tuple[]"},{"internalType":"bytes[]","name":"signatures","type":"bytes[]"},{"internalType":"uint256[]","name":"fractions","type":"uint256[]"}],"name":"fillOrders","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"longTokenId","type":"uint256"}],"name":"fromLongTokenId","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"uint256","name":"shortTokenId","type":"uint256"}],"name":"fromShortTokenId","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"pure","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"maker","type":"address"},{"internalType":"address","name":"taker","type":"address"},{"internalType":"uint48","name":"expiry","type":"uint48"},{"internalType":"address","name":"offeredUpfrontToken","type":"address"},{"internalType":"uint128","name":"offeredUpfrontAmount","type":"uint128"},{"components":[{"internalType":"uint128","name":"floor","type":"uint128"},{"internalType":"uint128","name":"cap","type":"uint128"},{"internalType":"address","name":"index","type":"address"},{"internalType":"uint48","name":"targetStartTimestamp","type":"uint48"},{"internalType":"uint48","name":"targetEndTimestamp","type":"uint48"},{"internalType":"address","name":"payoutToken","type":"address"}],"internalType":"struct ISilicaPools.PoolParams","name":"offeredLongSharesParams","type":"tuple"},{"internalType":"uint128","name":"offeredLongShares","type":"uint128"},{"internalType":"address","name":"requestedUpfrontToken","type":"address"},{"internalType":"uint128","name":"requestedUpfrontAmount","type":"uint128"},{"components":[{"internalType":"uint128","name":"floor","type":"uint128"},{"internalType":"uint128","name":"cap","type":"uint128"},{"internalType":"address","name":"index","type":"address"},{"internalType":"uint48","name":"targetStartTimestamp","type":"uint48"},{"internalType":"uint48","name":"targetEndTimestamp","type":"uint48"},{"internalType":"address","name":"payoutToken","type":"address"}],"internalType":"struct ISilicaPools.PoolParams","name":"requestedLongSharesParams","type":"tuple"},{"internalType":"uint128","name":"requestedLongShares","type":"uint128"}],"internalType":"struct ISilicaPools.SilicaOrder","name":"order","type":"tuple"}],"name":"hashOrder","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"maker","type":"address"},{"internalType":"address","name":"taker","type":"address"},{"internalType":"uint48","name":"expiry","type":"uint48"},{"internalType":"address","name":"offeredUpfrontToken","type":"address"},{"internalType":"uint128","name":"offeredUpfrontAmount","type":"uint128"},{"components":[{"internalType":"uint128","name":"floor","type":"uint128"},{"internalType":"uint128","name":"cap","type":"uint128"},{"internalType":"address","name":"index","type":"address"},{"internalType":"uint48","name":"targetStartTimestamp","type":"uint48"},{"internalType":"uint48","name":"targetEndTimestamp","type":"uint48"},{"internalType":"address","name":"payoutToken","type":"address"}],"internalType":"struct ISilicaPools.PoolParams","name":"offeredLongSharesParams","type":"tuple"},{"internalType":"uint128","name":"offeredLongShares","type":"uint128"},{"internalType":"address","name":"requestedUpfrontToken","type":"address"},{"internalType":"uint128","name":"requestedUpfrontAmount","type":"uint128"},{"components":[{"internalType":"uint128","name":"floor","type":"uint128"},{"internalType":"uint128","name":"cap","type":"uint128"},{"internalType":"address","name":"index","type":"address"},{"internalType":"uint48","name":"targetStartTimestamp","type":"uint48"},{"internalType":"uint48","name":"targetEndTimestamp","type":"uint48"},{"internalType":"address","name":"payoutToken","type":"address"}],"internalType":"struct ISilicaPools.PoolParams","name":"requestedLongSharesParams","type":"tuple"},{"internalType":"uint128","name":"requestedLongShares","type":"uint128"}],"internalType":"struct ISilicaPools.SilicaOrder","name":"order","type":"tuple"},{"internalType":"bytes32","name":"domainSeparator","type":"bytes32"}],"name":"hashOrder","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"pure","type":"function"},{"inputs":[{"components":[{"internalType":"uint128","name":"floor","type":"uint128"},{"internalType":"uint128","name":"cap","type":"uint128"},{"internalType":"address","name":"index","type":"address"},{"internalType":"uint48","name":"targetStartTimestamp","type":"uint48"},{"internalType":"uint48","name":"targetEndTimestamp","type":"uint48"},{"internalType":"address","name":"payoutToken","type":"address"}],"internalType":"struct ISilicaPools.PoolParams","name":"poolParams","type":"tuple"}],"name":"hashPool","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"address","name":"operator","type":"address"}],"name":"isApprovedForAll","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxBountyFraction","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"uint128","name":"floor","type":"uint128"},{"internalType":"uint128","name":"cap","type":"uint128"},{"internalType":"address","name":"index","type":"address"},{"internalType":"uint48","name":"targetStartTimestamp","type":"uint48"},{"internalType":"uint48","name":"targetEndTimestamp","type":"uint48"},{"internalType":"address","name":"payoutToken","type":"address"}],"internalType":"struct ISilicaPools.PoolParams[]","name":"poolParams","type":"tuple[]"}],"name":"maxCollateralRefund","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"orderHash","type":"bytes32"}],"name":"orderCancelled","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"partialFillsEnabled","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"paused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pendingOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"poolHash","type":"bytes32"}],"name":"poolState","outputs":[{"components":[{"internalType":"uint128","name":"collateralMinted","type":"uint128"},{"internalType":"uint128","name":"sharesMinted","type":"uint128"},{"internalType":"uint128","name":"indexShares","type":"uint128"},{"internalType":"uint128","name":"indexInitialBalance","type":"uint128"},{"internalType":"uint48","name":"actualStartTimestamp","type":"uint48"},{"internalType":"uint48","name":"actualEndTimestamp","type":"uint48"},{"internalType":"uint128","name":"balanceChangePerShare","type":"uint128"}],"internalType":"struct ISilicaPools.PoolState","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"uint128","name":"floor","type":"uint128"},{"internalType":"uint128","name":"cap","type":"uint128"},{"internalType":"address","name":"index","type":"address"},{"internalType":"uint48","name":"targetStartTimestamp","type":"uint48"},{"internalType":"uint48","name":"targetEndTimestamp","type":"uint48"},{"internalType":"address","name":"payoutToken","type":"address"}],"internalType":"struct ISilicaPools.PoolParams[]","name":"longPoolParams","type":"tuple[]"},{"components":[{"internalType":"uint128","name":"floor","type":"uint128"},{"internalType":"uint128","name":"cap","type":"uint128"},{"internalType":"address","name":"index","type":"address"},{"internalType":"uint48","name":"targetStartTimestamp","type":"uint48"},{"internalType":"uint48","name":"targetEndTimestamp","type":"uint48"},{"internalType":"address","name":"payoutToken","type":"address"}],"internalType":"struct ISilicaPools.PoolParams[]","name":"shortPoolParams","type":"tuple[]"}],"name":"redeem","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"uint128","name":"floor","type":"uint128"},{"internalType":"uint128","name":"cap","type":"uint128"},{"internalType":"address","name":"index","type":"address"},{"internalType":"uint48","name":"targetStartTimestamp","type":"uint48"},{"internalType":"uint48","name":"targetEndTimestamp","type":"uint48"},{"internalType":"address","name":"payoutToken","type":"address"}],"internalType":"struct ISilicaPools.PoolParams","name":"longParams","type":"tuple"}],"name":"redeemLong","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"uint128","name":"floor","type":"uint128"},{"internalType":"uint128","name":"cap","type":"uint128"},{"internalType":"address","name":"index","type":"address"},{"internalType":"uint48","name":"targetStartTimestamp","type":"uint48"},{"internalType":"uint48","name":"targetEndTimestamp","type":"uint48"},{"internalType":"address","name":"payoutToken","type":"address"}],"internalType":"struct ISilicaPools.PoolParams","name":"shortParams","type":"tuple"}],"name":"redeemShort","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"sBountyFractionIncreasePerSecond","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"sBountyGracePeriod","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"sMaxBountyFraction","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256[]","name":"ids","type":"uint256[]"},{"internalType":"uint256[]","name":"values","type":"uint256[]"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"safeBatchTransferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"id","type":"uint256"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"safeTransferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"operator","type":"address"},{"internalType":"bool","name":"approved","type":"bool"}],"name":"setApprovalForAll","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"newIncreaseAmount","type":"uint256"}],"name":"setBountyFractionIncreasePerSecond","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"newGracePeriod","type":"uint256"}],"name":"setBountyGracePeriod","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"newFillFeeBps","type":"uint256"}],"name":"setFillFeeBps","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"newMaxFraction","type":"uint256"}],"name":"setMaxBountyFraction","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newTreasury","type":"address"}],"name":"setTreasuryAddress","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"uint128","name":"floor","type":"uint128"},{"internalType":"uint128","name":"cap","type":"uint128"},{"internalType":"address","name":"index","type":"address"},{"internalType":"uint48","name":"targetStartTimestamp","type":"uint48"},{"internalType":"uint48","name":"targetEndTimestamp","type":"uint48"},{"internalType":"address","name":"payoutToken","type":"address"}],"internalType":"struct ISilicaPools.PoolParams[]","name":"poolParams","type":"tuple[]"}],"name":"startBounty","outputs":[{"internalType":"uint256[]","name":"","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"uint128","name":"floor","type":"uint128"},{"internalType":"uint128","name":"cap","type":"uint128"},{"internalType":"address","name":"index","type":"address"},{"internalType":"uint48","name":"targetStartTimestamp","type":"uint48"},{"internalType":"uint48","name":"targetEndTimestamp","type":"uint48"},{"internalType":"address","name":"payoutToken","type":"address"}],"internalType":"struct ISilicaPools.PoolParams","name":"poolParams","type":"tuple"}],"name":"startPool","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"uint128","name":"floor","type":"uint128"},{"internalType":"uint128","name":"cap","type":"uint128"},{"internalType":"address","name":"index","type":"address"},{"internalType":"uint48","name":"targetStartTimestamp","type":"uint48"},{"internalType":"uint48","name":"targetEndTimestamp","type":"uint48"},{"internalType":"address","name":"payoutToken","type":"address"}],"internalType":"struct ISilicaPools.PoolParams[]","name":"poolParams","type":"tuple[]"}],"name":"startPools","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"poolHash","type":"bytes32"}],"name":"toLongTokenId","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"bytes32","name":"poolHash","type":"bytes32"}],"name":"toShortTokenId","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"treasuryAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"unpause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"uri","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"uint128","name":"floor","type":"uint128"},{"internalType":"uint128","name":"cap","type":"uint128"},{"internalType":"address","name":"index","type":"address"},{"internalType":"uint48","name":"targetStartTimestamp","type":"uint48"},{"internalType":"uint48","name":"targetEndTimestamp","type":"uint48"},{"internalType":"address","name":"payoutToken","type":"address"}],"internalType":"struct ISilicaPools.PoolParams[]","name":"poolParams","type":"tuple[]"},{"internalType":"uint256[]","name":"shares","type":"uint256[]"}],"name":"viewCollateralRefund","outputs":[{"internalType":"uint256[]","name":"expectedRefunds","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"uint128","name":"floor","type":"uint128"},{"internalType":"uint128","name":"cap","type":"uint128"},{"internalType":"address","name":"index","type":"address"},{"internalType":"uint48","name":"targetStartTimestamp","type":"uint48"},{"internalType":"uint48","name":"targetEndTimestamp","type":"uint48"},{"internalType":"address","name":"payoutToken","type":"address"}],"internalType":"struct ISilicaPools.PoolParams[]","name":"poolParams","type":"tuple[]"},{"internalType":"address[]","name":"accounts","type":"address[]"}],"name":"viewMaxCollateralRefund","outputs":[{"internalType":"uint256[]","name":"expectedRefund","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"uint128","name":"floor","type":"uint128"},{"internalType":"uint128","name":"cap","type":"uint128"},{"internalType":"address","name":"index","type":"address"},{"internalType":"uint48","name":"targetStartTimestamp","type":"uint48"},{"internalType":"uint48","name":"targetEndTimestamp","type":"uint48"},{"internalType":"address","name":"payoutToken","type":"address"}],"internalType":"struct ISilicaPools.PoolParams","name":"longParams","type":"tuple"},{"internalType":"address","name":"account","type":"address"}],"name":"viewRedeemLong","outputs":[{"internalType":"uint256","name":"expectedPayout","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"uint128","name":"floor","type":"uint128"},{"internalType":"uint128","name":"cap","type":"uint128"},{"internalType":"address","name":"index","type":"address"},{"internalType":"uint48","name":"targetStartTimestamp","type":"uint48"},{"internalType":"uint48","name":"targetEndTimestamp","type":"uint48"},{"internalType":"address","name":"payoutToken","type":"address"}],"internalType":"struct ISilicaPools.PoolParams","name":"shortParams","type":"tuple"},{"internalType":"address","name":"account","type":"address"}],"name":"viewRedeemShort","outputs":[{"internalType":"uint256","name":"expectedPayout","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"addressToWhitelist","type":"address"}],"name":"whitelistSilicaIndex","outputs":[],"stateMutability":"nonpayable","type":"function"}]Contract Creation Code
61016080604052346104925760c081615de580380380916100208285610497565b833981010312610492578051610038602083016104ba565b610044604084016104ba565b9160608401519260a0608086015195015192604051610064604082610497565b600b815260208101906a53696c696361506f6f6c7360a81b82526040519161008d604084610497565b600183526020830191603160f81b83526040516100ab602082610497565b60008082529060025490600182811c92168015610472575b602083101461045c5781601f8493116103ec575b50602090601f831160011461038457600092610379575b50508160011b916000199060031b1c1916176002555b61010d816104eb565b6101205261011a84610699565b61014052519020918260e05251902080610100524660a0526040519060208201927f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f8452604083015260608201524660808201523060a082015260a0815261018360c082610497565b5190206080523060c0526001600160a01b0316948515610363577f2c8741c51ef15572035be75af521ed4878a6e3406c7fdea3494b5fbffdc107c660207f9ee70d55a8fb5949bbafdc2c166db4f6b56a7f6827fcfc91202d433174fddd0d947fa8d4f499ed89ed61915e14bec2bd7bea8fb6c9701f14ce893bbc2e847d920d328280997fd5862782a16cfe1b4efd87aa8ff52fe97b1b3300d25bbf2719b5cbd413cd9cd48280997f2e54a66023bd119d7da51cb6619e461b9f2d33f3749d492dcec52d5c6ce5f34b9e60018060a01b0319600654166006556005548160018060a01b031982161760055560018060a01b03167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0600080a360016007556011805461ff00191690556001600160a01b0316956102bf8715156104ce565b600980546001600160a01b031916881790556102df6103e88211156104ce565b8060085583600e5589600f558c601055604051908152a1604051908152a1604051908152a1604051908152a1604051908152a16040516155ad9081610838823960805181614484015260a0518161453b015260c0518161444e015260e051816144d3015261010051816144f901526101205181611dce01526101405181611dfa0152f35b631e4fbdf760e01b600052600060045260246000fd5b0151905038806100ee565b600260009081528281209350601f198516905b8181106103d457509084600195949392106103bb575b505050811b01600255610104565b015160001960f88460031b161c191690553880806103ad565b92936020600181928786015181550195019301610397565b60026000529091507f405787fa12a823e0f2b7631cc41b3ba8828b3321ca811111fa75cd3aa3bb5ace601f840160051c81019160208510610452575b90601f859493920160051c01905b81811061044357506100d7565b60008155849350600101610436565b9091508190610428565b634e487b7160e01b600052602260045260246000fd5b91607f16916100c3565b634e487b7160e01b600052604160045260246000fd5b600080fd5b601f909101601f19168101906001600160401b0382119082101761047c57604052565b51906001600160a01b038216820361049257565b156104d557565b634e487b7160e01b600052600160045260246000fd5b90815160208110600014610583575090601f815111610527576020815191015160208210610517571790565b6000198260200360031b1b161790565b6040519063305a27a960e01b8252602060048301528181519182602483015260005b83811061056b5750508160006044809484010152601f80199101168101030190fd5b60208282018101516044878401015285935001610549565b6001600160401b03811161047c57600354600181811c9116801561068f575b602082101461045c57601f8111610659575b50602092601f82116001146105f457928192936000926105e9575b50508160011b916000199060031b1c19161760035560ff90565b0151905038806105cf565b601f198216936003600052806000209160005b8681106106415750836001959610610628575b505050811b0160035560ff90565b015160001960f88460031b161c1916905538808061061a565b91926020600181928685015181550194019201610607565b6003600052601f6020600020910160051c810190601f830160051c015b81811061068357506105b4565b60008155600101610676565b90607f16906105a2565b90815160208110600014610721575090601f8151116106c5576020815191015160208210610517571790565b6040519063305a27a960e01b8252602060048301528181519182602483015260005b8381106107095750508160006044809484010152601f80199101168101030190fd5b602082820181015160448784010152859350016106e7565b6001600160401b03811161047c57600454600181811c9116801561082d575b602082101461045c57601f81116107f7575b50602092601f82116001146107925792819293600092610787575b50508160011b916000199060031b1c19161760045560ff90565b01519050388061076d565b601f198216936004600052806000209160005b8681106107df57508360019596106107c6575b505050811b0160045560ff90565b015160001960f88460031b161c191690553880806107b8565b919260206001819286850151815501940192016107a5565b6004600052601f6020600020910160051c810190601f830160051c015b8181106108215750610752565b60008155600101610814565b90607f169061074056fe6080604052600436101561001257600080fd5b60003560e01c8062fdd58e1461042d57806301ffc9a7146104285780630e89341c1461042357806313208d1b1461041e57806319b87556146104195780631d0fa9cf1461036a57806324b3e7ec146104145780632556bc151461040f57806329fa8b871461040a5780632eb2c2d6146104055780632fece5ae14610400578063312f14ba146103fb57806332afed8f146103f65780633305d6b1146103f157806334d2efe5146103ec57806337d59827146103e75780633ba1a0df146103e25780633f4ba83a146103dd5780634cd21543146103d85780634e1273f4146103d357806351594173146103ce5780635396fae5146103c95780635889bf5e146103c45780635b72928c146103bf5780635c975abb146103ba5780636605bfda146103b55780636c0dc97914610383578063715018a6146103b057806378e890ba146103ab57806379ba5097146103a65780637d1a7558146103a15780637e28c0521461039c5780638456cb591461039757806384b0196e14610392578063880185401461038d5780638ac86f1a146103885780638c8c29ce146103835780638da5cb5b1461037e5780638f409d2614610379578063934ed73214610374578063992cc7cb1461036f5780639c9b381c1461036a578063a0fadc3514610365578063a22cb46514610360578063a2b597ee1461035b578063bda9f38614610310578063c4cde46b14610356578063c5f956af14610351578063c837a9411461034c578063cae6047f14610347578063ccaaa52014610342578063d6dc6b041461033d578063d7e5ae9f14610329578063de30f4a714610338578063e0b01bac14610333578063e1c6709114610306578063e30c39781461032e578063e5c168a814610329578063e985e9c514610324578063ec9f8ae81461031f578063f0cd67511461031a578063f242432a14610315578063f249958514610310578063f2fde38b1461030b578063f50ec60214610306578063f5d213f2146103015763fe2de08c146102fc57600080fd5b612bd4565b612982565b612695565b612911565b61233e565b6127fa565b612761565b612744565b6126dc565b612556565b6126b3565b61262a565b612574565b61250a565b6123ef565b6123d2565b6123b3565b61238a565b612360565b6122a3565b6121e6565b612108565b610a3b565b61209f565b612047565b611fad565b611f38565b6118ab565b611ec3565b611e77565b611db5565b611d68565b611c93565b6119dd565b611953565b611930565b6118c9565b611820565b6117fd565b61179d565b61176c565b6116a2565b611680565b6115bf565b611524565b6114da565b6113bf565b611338565b6112d8565b611271565b61115e565b610e66565b610e3c565b610da8565b610ba4565b610b29565b610a59565b6106a9565b61064c565b610567565b6104b8565b610455565b6001600160a01b0381160361044357565b600080fd5b359061045382610432565b565b3461044357604036600319011261044357602061049d60043561047781610432565b6024356000526000835260406000209060018060a01b0316600052602052604060002090565b54604051908152f35b6001600160e01b031981160361044357565b346104435760203660031901126104435760206004356104d7816104a6565b63ffffffff60e01b16636cdb3d1360e11b8114908115610515575b8115610504575b506040519015158152f35b6301ffc9a760e01b149050386104f9565b6303a24d0760e21b811491506104f2565b919082519283825260005b848110610552575050826000602080949584010152601f8019910116010190565b80602080928401015182828601015201610531565b3461044357602036600319011261044357604051600060025461058981612c17565b808452906001811690811561062857506001146105c9575b6105c5836105b181850382610c93565b604051918291602083526020830190610526565b0390f35b600260009081527f405787fa12a823e0f2b7631cc41b3ba8828b3321ca811111fa75cd3aa3bb5ace939250905b80821061060e575090915081016020016105b16105a1565b9192600181602092548385880101520191019092916105f6565b60ff191660208086019190915291151560051b840190910191506105b190506105a1565b34610443576020366003190112610443577f2e54a66023bd119d7da51cb6619e461b9f2d33f3749d492dcec52d5c6ce5f34b602060043561068b614094565b80601055604051908152a1005b60c090600319011261044357600490565b346104435760c0366003190112610443576106c336610698565b6106cb614094565b6040810180356106da81610432565b6001600160a01b03166000908152600d60205260409020546106fe9060ff16612cde565b61070782613fb0565b9161073461072861072285600052600a602052604060002090565b93612cd4565b6001600160a01b031690565b606082019061075061074583612d2f565b65ffffffffffff1690565b4210610a10576002840165ffffffffffff610771825465ffffffffffff1690565b166109f957805465ffffffffffff19164265ffffffffffff16179055604051630198a77d60e11b81526001600160a01b03919091169390602081600481885afa9081156109d5576000916109da575b506107ee6001600160801b0360018401921682906001600160801b03166001600160801b0319825416179055565b6040516316d3df1560e31b8152602081600481895afa9283156109d5577f8da731be8204f25f24740734bc94894e24bf5606c951e71acc15bff0e1a68a9f966108666001600160801b036109a1968b956000916109a6575b5086546001600160801b0316911660801b6001600160801b031916178555565b6108b0610872886140a8565b926108966001600160801b03851661089183546001600160801b031690565b612d6a565b6001600160801b03166001600160801b0319825416179055565b826000805160206155388339815191526108f560a08a01946108df816108d861072889612cd4565b3390614149565b6040805191825233602083015290918291820190565b0390a261090187612da0565b93610926610722608061091f61091960208d01612da0565b9a612d2f565b9a01612d2f565b9054604080516001600160801b03978816815298871660208a015265ffffffffffff998a16908901529290971660608701526001600160a01b03908116608087810191909152961660a086015291821660c0850152931c60e0830152610100820183905261ac1d909218610120820152908190610140820190565b0390a2005b6109c8915060203d6020116109ce575b6109c08183610c93565b810190612d39565b38610846565b503d6109b6565b612d48565b6109f3915060203d6020116109ce576109c08183610c93565b386107c0565b6309ed6f7160e11b600052600486905260245b6000fd5b610a0c610a1c83612d2f565b63c7b7b42d60e01b6000524260045265ffffffffffff16602452604490565b34610443576000366003190112610443576020601054604051908152f35b3461044357602036600319011261044357600435610a7681610432565b610a7e614094565b6001600160a01b03166000818152600d602052604090205460ff16610aee576001600160a01b0381166000908152600d60205260409020610ac7905b805460ff19166001179055565b7f5d30d9fe66d95241fa9d52d043504e452639553b3156d29d5c2df6625a246db2600080a2005b60405162461bcd60e51b8152602060048201526013602482015272185b1c9958591e481dda1a5d195b1a5cdd1959606a1b6044820152606490fd5b346104435760003660031901126104435760206040516103e88152f35b9181601f84011215610443578235916001600160401b0383116104435760208085019460c0850201011161044357565b602060031982011261044357600435906001600160401b03821161044357610ba091600401610b46565b9091565b3461044357610bb236610b76565b610bba614189565b60005b818110610bcb576001600755005b80610c18610be4610bdf6001948688612dc0565b613fb0565b610bfc61ac1d610bf48333612bf2565b921833612bf2565b90610c08848789612dc0565b9180821015610c1e5750906141ab565b01610bbd565b9050906141ab565b634e487b7160e01b600052604160045260246000fd5b61016081019081106001600160401b03821117610c5857604052565b610c26565b60e081019081106001600160401b03821117610c5857604052565b60c081019081106001600160401b03821117610c5857604052565b90601f801991011681019081106001600160401b03821117610c5857604052565b6040519061045361016083610c93565b6001600160401b038111610c585760051b60200190565b9080601f83011215610443578135610cf281610cc4565b92610d006040519485610c93565b81845260208085019260051b82010192831161044357602001905b828210610d285750505090565b8135815260209182019101610d1b565b6001600160401b038111610c5857601f01601f191660200190565b929192610d5f82610d38565b91610d6d6040519384610c93565b829481845281830111610443578281602093846000960137010152565b9080601f8301121561044357816020610da593359101610d53565b90565b346104435760a036600319011261044357600435610dc581610432565b60243590610dd282610432565b6044356001600160401b03811161044357610df1903690600401610cdb565b6064356001600160401b03811161044357610e10903690600401610cdb565b90608435936001600160401b03851161044357610e34610e3a953690600401610d8a565b93612dd0565b005b3461044357600036600319011261044357610e55614094565b6011805461ff001916610100179055005b346104435760c036600319011261044357610e8036610698565b610e88614094565b60408101908135610e9881610432565b6001600160a01b03166000908152600d6020526040902054610ebc9060ff16612cde565b610ec581613fb0565b91610ee6610728610ee085600052600a602052604060002090565b92612cd4565b90600281019165ffffffffffff610f07845465ffffffffffff9060301c1690565b166111365760808401610f1c61074582612d2f565b421061110b57506040516316d3df1560e31b815292906001600160a01b0316602084600481845afa9384156109d5576000946110ea575b50600460018401546020610f77610f6a8360801c90565b926001600160801b031690565b936040519384809263313ce56760e01b82525afa9687156109d5576108df6110a9966108d861072860a0611090956110408f9a7fafeed4501a6753eefb924ea0eeb9a58b8d2ad05c8610190cd5f2c7160341a2559f8f6110969b61100e9261101a946000805160206155388339815191529f6000926110c9575b50610ffb88612da0565b9261100860208a01612da0565b946142de565b6001600160801b031690565b8c54600160601b600160e01b03191660609190911b600160601b600160e01b0316178c55565b8a546bffffffffffff00000000000019164260301b6bffffffffffff00000000000016178b5561106f81614409565b9687956108966001600160801b03881661089183546001600160801b031690565b01612cd4565b0390a25460601c6001600160801b031690565b604080519283526001600160801b039091166020830152819081016109a1565b6110e391925060203d6020116109ce576109c08183610c93565b9038610ff1565b61110491945060203d6020116109ce576109c08183610c93565b9238610f53565b611117610a0c91612d2f565b63bd7d315f60e01b6000524260045265ffffffffffff16602452604490565b6366ddd3a160e11b600052600485905260246000fd5b6102a090600319011261044357600490565b34610443576102a0366003190112610443576111793661114c565b61118161444b565b906102a081360312610443576105c591611261916112566102806111a3610cb4565b926111ad81610448565b84526111bb60208201610448565b60208501526111cc60408201612e2d565b60408501526111dd60608201610448565b60608501526111ee60808201612e38565b60808501526112003660a08301612e43565b60a08501526112126101608201612e38565b60c08501526112246101808201610448565b60e08501526112366101a08201612e38565b61010085015261124a366101c08301612e43565b61012085015201612e38565b6101408201526145f8565b6040519081529081906020820190565b346104435760c036600319011261044357610e3a61128e36610698565b612f69565b906020808351928381520192019060005b8181106112b15750505090565b82518452602093840193909201916001016112a4565b906020610da5928181520190611293565b34610443576112e636610b76565b906112f082613069565b9160005b81811061131157604051602080825281906105c590820187611293565b806113276113226001938587612dc0565b614409565b611331828761309b565b52016112f4565b3461044357600036600319011261044357602060ff60115460081c166040519015158152f35b9181601f84011215610443578235916001600160401b038311610443576020808501946102a0850201011161044357565b9181601f84011215610443578235916001600160401b038311610443576020808501948460051b01011161044357565b34610443576060366003190112610443576004356001600160401b038111610443576113ef90369060040161135e565b6024356001600160401b0381116104435761140e90369060040161138f565b6044356001600160401b0381116104435761142d90369060040161138f565b9490928285148015906114d0575b6114bf57909336829003601e1901919060005b81811061145757005b6114628183896130af565b90858110156114ba578060051b84013585811215610443578401918235926001600160401b03841161044357602001908336038213610443576001936114b4926114ad858e8d6130c0565b359261325b565b0161144e565b612daa565b633009a29d60e01b60005260046000fd5b508585141561143b565b34610443576000366003190112610443576114f3614094565b60ff19601154166011557ff9b5d9ff43c04557eb813158a432098c5d195947516dd9795ef5a11ecb047f36600080a1005b346104435760e03660031901126104435761153e36610698565b60c4359061154b82610432565b61155481613fb0565b9182600052600a60205260406000209065ffffffffffff600283015460301c16156115aa57906115a461159e611596611261959461ac1d6105c5981890612bf2565b933690612e43565b91612ec7565b906146e7565b83631fd4ba0360e01b60005260045260246000fd5b34610443576040366003190112610443576004356001600160401b0381116104435736602382011215610443578060040135906115fb82610cc4565b916116096040519384610c93565b8083526024602084019160051b8301019136831161044357602401905b82821061166657836024356001600160401b038111610443576105c59161165461165a923690600401610cdb565b906130d0565b604051918291826112c7565b60208091833561167581610432565b815201910190611626565b346104435760c036600319011261044357610e3a61169d36610698565b613143565b34610443576020366003190112610443576004356116bf81610432565b6116c7614094565b60018060a01b031680600052600d602052600160ff60406000205416151503611731576001600160a01b0381166000908152600d60205260409020805460ff191690557fdfb945e5b80afc93bd56261ec23d264f7bdefcb9dee18ba4781ec206fe7a1dc7600080a2005b60405162461bcd60e51b8152602060048201526013602482015272185b1c9958591e48189b1858dadb1a5cdd1959606a1b6044820152606490fd5b3461044357602036600319011261044357600435600052600b602052602060ff604060002054166040519015158152f35b34610443576117ab36610b76565b906117b582613069565b9160005b8181106117d657604051602080825281906105c590820187611293565b806117ec6117e76001938587612dc0565b6140a8565b6117f6828761309b565b52016117b9565b3461044357600036600319011261044357602060ff601154166040519015158152f35b346104435760203660031901126104435760043561183d81610432565b611845614094565b6001600160a01b03168015611895576020817f2c8741c51ef15572035be75af521ed4878a6e3406c7fdea3494b5fbffdc107c6926001600160601b0360a01b6009541617600955604051908152a1005b634e487b7160e01b600052600160045260246000fd5b34610443576000366003190112610443576020600f54604051908152f35b34610443576000366003190112610443576118e2614094565b600680546001600160a01b03199081169091556005805491821690556000906001600160a01b03167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08280a3005b3461044357600036600319011261044357602061194b61444b565b604051908152f35b3461044357600036600319011261044357600654336001600160a01b03909116036119c857600680546001600160a01b0319908116909155600580543392811683179091556001600160a01b03167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0600080a3005b63118cdaa760e01b6000523360045260246000fd5b34610443576119eb36610b76565b4265ffffffffffff16919060005b818110611a0257005b611a0d818385612dc0565b90611a16614094565b60408201918235611a2681610432565b6001600160a01b03166000908152600d6020526040902054611a4a9060ff16612cde565b611a5381613fb0565b90611a74610728611a6e84600052600a602052604060002090565b95612cd4565b90600285019165ffffffffffff611a95845465ffffffffffff9060301c1690565b16611c7d5760808201611aaa61074582612d2f565b421061110b57506040516316d3df1560e31b81526001600160a01b03919091169590926020846004818a5afa9283156109d557600494600094611c5d575b5060018301546020611afd610f6a8360801c90565b996040519788809263313ce56760e01b82525afa9081156109d557611c086108df611c1d968f95611bde8c9760019f611b8e61100e7fafeed4501a6753eefb924ea0eeb9a58b8d2ad05c8610190cd5f2c7160341a2559f8f909a6000805160206155388339815191529c611bb4956110969d600092611c3d575b50611b818a612da0565b9261100860208c01612da0565b8b54600160601b600160e01b03191660609190911b600160601b600160e01b0316178b55565b89546bffffffffffff000000000000191660309190911b6bffffffffffff00000000000016178955565b611be781614409565b9384926108966001600160801b03851661089183546001600160801b031690565b611c1861072860a0339301612cd4565b614149565b604080519283526001600160801b0391909116602083015290a2016119f9565b611c5691925060203d81116109ce576109c08183610c93565b9038611b77565b611c7691945060203d81116109ce576109c08183610c93565b9238611ae8565b6366ddd3a160e11b600052600484905260246000fd5b346104435761012036600319011261044357611cae36610698565b60c4359060e435611cbe81610432565b6101043591611ccc83610432565b60ff60115416611d5757610e3a93611d50604051611ce981610c3c565b6000815260006020820152600060408201526000606082015260006080820152611d116131f7565b60a0820152600060c0820152600060e08201526000610100820152611d346131f7565b6101208201526000610140820152611d4a61444b565b906145f8565b339261494b565b634815836b60e11b60005260046000fd5b3461044357600036600319011261044357611d81614094565b600160ff1960115416176011557f05204c23a38d23799ab593b867a0a8f7bb23ba80aa8308107716de014e257d9b600080a1005b3461044357600036600319011261044357611e48611df27f0000000000000000000000000000000000000000000000000000000000000000615084565b6105c5611e1e7f00000000000000000000000000000000000000000000000000000000000000006150e8565b611e56611e2961304d565b91604051958695600f60f81b875260e0602088015260e0870190610526565b908582036040870152610526565b90466060850152306080850152600060a085015283820360c0850152611293565b34610443576020366003190112610443577fa8d4f499ed89ed61915e14bec2bd7bea8fb6c9701f14ce893bbc2e847d920d326020600435611eb6614094565b80600e55604051908152a1005b346104435760e036600319011261044357611edd36610698565b60c435611ee981610432565b611ef282613fb0565b9182600052600a60205260406000209165ffffffffffff600284015460301c16156115aa5790611f32611f2c6105c5956112619594612bf2565b92612ec7565b906148f6565b34610443576000366003190112610443576005546040516001600160a01b039091168152602090f35b6040600319820112610443576004356001600160401b0381116104435781611f8b91600401610b46565b92909291602435906001600160401b03821161044357610ba09160040161138f565b3461044357611fbb36611f61565b80839493036114bf57611fcd84613069565b9360005b818110611fe657604051806105c588826112c7565b80611ff7610bdf6001938589612dc0565b600052600a60205261203660406000205461203061202961201985898b6130c0565b356001600160801b038416613228565b9160801c90565b9061323b565b612040828961309b565b5201611fd1565b346104435761205536611f61565b9061205e614189565b8183036114bf5760005b838110612076576001600755005b806120996120876001938789612dc0565b6120928387876130c0565b35906141ab565b01612068565b34610443576102e0366003190112610443576120ba3661114c565b6102a4356001600160401b03811161044357366023820112156104435780600401356001600160401b03811161044357366024828401011161044357610e3a9260246102c43593019061325b565b34610443576020366003190112610443576004356001600160401b0381116104435761213890369060040161135e565b60005b81811061214457005b61214f8183856130af565b803561215a81610432565b6001600160a01b038116903382036121c55750509061218360019261217d61444b565b90613e0c565b61219a610aba82600052600b602052604060002090565b7fdae6f8929d076546361068a77fbf488bf65e58a76625628ede047a30311456a9600080a20161213b565b6121ce90610432565b6365d0b58b60e11b6000523360045260245260446000fd5b346104435760403660031901126104435760043561220381610432565b6024359081151590818303610443576001600160a01b03811692831561228e5761224f6122609233600052600160205260406000209060018060a01b0316600052602052604060002090565b9060ff801983541691151516179055565b6040519081527f17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c3160203392a3005b62ced3e160e81b600052600060045260246000fd5b34610443576020366003190112610443576004356122bf614094565b6103e881116122f9576020817fd5862782a16cfe1b4efd87aa8ff52fe97b1b3300d25bbf2719b5cbd413cd9cd492600855604051908152a1005b60405162461bcd60e51b815260206004820152601960248201527f43616e6e6f7420657863656564206d61782066656520425053000000000000006044820152606490fd5b3461044357602036600319011261044357602060043561ac1d60405191188152f35b34610443576102c036600319011261044357602061194b6123803661114c565b6102a43590613e0c565b34610443576000366003190112610443576009546040516001600160a01b039091168152602090f35b346104435760c036600319011261044357602061194b610bdf36610698565b346104435760003660031901126104435760206040516127108152f35b34610443576123fd36611f61565b9050819291036114bf5761241082613069565b9160005b81811061242957604051806105c586826112c7565b8061243a610bdf6001938587612dc0565b6124448133612bf2565b61248c61247a3361246361ac1d86186000526000602052604060002090565b9060018060a01b0316600052602052604060002090565b5492600052600a602052604060002090565b91808210156124d6575061203061100e6124bd6124c49454936124b861100e866001600160801b031690565b613228565b9260801c90565b6124ce828761309b565b525b01612414565b905061203061100e6124bd6124fa9454936124b861100e866001600160801b031690565b612504828761309b565b526124d0565b34610443576020366003190112610443577f9ee70d55a8fb5949bbafdc2c166db4f6b56a7f6827fcfc91202d433174fddd0d6020600435612549614094565b80600f55604051908152a1005b34610443576020366003190112610443576020600435604051908152f35b346104435760003660031901126104435761258d614094565b6011805461ff0019169055005b6104539092919260c08060e08301956001600160801b0381511684526001600160801b0360208201511660208501526001600160801b0360408201511660408501526001600160801b03606082015116606085015265ffffffffffff608082015116608085015261261a60a082015160a086019065ffffffffffff169052565b01516001600160801b0316910152565b3461044357602036600319011261044357600435600060c060405161264e81610c5d565b8281528260208201528260408201528260608201528260808201528260a08201520152600052600a6020526105c56126896040600020612ec7565b6040519182918261259a565b34610443576000366003190112610443576020600e54604051908152f35b34610443576000366003190112610443576006546040516001600160a01b039091168152602090f35b3461044357604036600319011261044357602060ff61273860043561270081610432565b6024359061270d82610432565b60018060a01b03166000526001845260406000209060018060a01b0316600052602052604060002090565b54166040519015158152f35b3461044357600036600319011261044357602060405161ac1d8152f35b34610443576040366003190112610443576004356001600160401b03811161044357612791903690600401610b46565b6024356001600160401b038111610443576127b0903690600401610b46565b92909160005b8181106127e35750505060005b8281106127cc57005b806127dd61128e6001938686612dc0565b016127c3565b806127f461169d6001938587612dc0565b016127b6565b346104435760a03660031901126104435760043561281781610432565b60243561282381610432565b60443590606435926084356001600160401b0381116104435761284a903690600401610d8a565b926001600160a01b03821633811415806128ed575b6128d5576001600160a01b038416156128bf57156128aa57610e3a946128a260405192600184526020840152604083019160018352606084015260808301604052565b929091614d56565b626a0d4560e21b600052600060045260246000fd5b632bfa23e760e11b600052600060045260246000fd5b63711bec9160e11b6000523360045260245260446000fd5b50600081815260016020908152604080832033845290915290205460ff161561285f565b346104435760203660031901126104435760043561292e81610432565b612936614094565b600680546001600160a01b0319166001600160a01b039283169081179091556005549091167f38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e22700600080a3005b346104435761299036610b76565b4265ffffffffffff16919060005b8181106129a757005b6129b2818385612dc0565b906129bb614094565b604082019182356129cb81610432565b6001600160a01b03166000908152600d60205260409020546129ef9060ff16612cde565b6129f881613fb0565b90612a13610728611a6e84600052600a602052604060002090565b906060810191612a2561074584612d2f565b4210612bc8576002860165ffffffffffff612a46825465ffffffffffff1690565b16612bb257805465ffffffffffff191665ffffffffffff8b16179055604051630198a77d60e11b81526001600160a01b03919091169290602081600481875afa9081156109d557600091612b94575b50612ac36001600160801b0360018901921682906001600160801b03166001600160801b0319825416179055565b6040516316d3df1560e31b815290602082600481885afa9182156109d5576001987f8da731be8204f25f24740734bc94894e24bf5606c951e71acc15bff0e1a68a9f96612b3e6001600160801b03612b73968b95600091612b7c575086546001600160801b0316911660801b6001600160801b031916178555565b612b4a610872886140a8565b826000805160206155388339815191526108f560a08a01946108df8133611c186107288a612cd4565b0390a20161299e565b6109c8915060203d81116109ce576109c08183610c93565b612bac915060203d81116109ce576109c08183610c93565b38612a95565b6309ed6f7160e11b600052600485905260246000fd5b610a0c610a1c84612d2f565b34610443576000366003190112610443576020600854604051908152f35b6000918252602082815260408084206001600160a01b03909316845291905290205490565b90600182811c92168015612c47575b6020831014612c3157565b634e487b7160e01b600052602260045260246000fd5b91607f1691612c26565b60009291815491612c6183612c17565b8083529260018116908115612cb75750600114612c7d57505050565b60009081526020812093945091925b838310612c9d575060209250010190565b600181602092949394548385870101520191019190612c8c565b915050602093945060ff929192191683830152151560051b010190565b35610da581610432565b15612ce557565b60405162461bcd60e51b8152602060048201526012602482015271092dcecc2d8d2c8a6d2d8d2c6c292dcc8caf60731b6044820152606490fd5b65ffffffffffff81160361044357565b35610da581612d1f565b90816020910312610443575190565b6040513d6000823e3d90fd5b634e487b7160e01b600052601160045260246000fd5b906001600160801b03809116911603906001600160801b038211612d8a57565b612d54565b6001600160801b0381160361044357565b35610da581612d8f565b634e487b7160e01b600052603260045260246000fd5b91908110156114ba5760c0020190565b939291906001600160a01b0385163381141580612e09575b6128d5576001600160a01b038216156128bf57156128aa5761045394614d56565b50600081815260016020908152604080832033845290915290205460ff1615612de8565b359061045382612d1f565b359061045382612d8f565b91908260c091031261044357604051612e5b81610c78565b60a0612ec28183958035612e6e81612d8f565b85526020810135612e7e81612d8f565b60208601526040810135612e9181610432565b60408601526060810135612ea481612d1f565b60608601526080810135612eb781612d1f565b608086015201610448565b910152565b90610453604051612ed781610c5d565b60c0612f5b600283966001600160801b038154818116875260801c166020860152612f2a612f1a60018301546001600160801b0380821616604089015260801c90565b6001600160801b03166060870152565b015465ffffffffffff8116608085015265ffffffffffff603082901c1660a085015260601c6001600160801b031690565b6001600160801b0316910152565b612f7281613fb0565b80600052600a60205260406000209065ffffffffffff80600284015460301c161615613039577ff1e780e78d89d283caba1fefbe6d85a112fb930e5cb9544301096a011c7bafb461ac1d82189361301260a0612fef612fdf336124638a6000526000602052604060002090565b5480976115a461159e3688612e43565b92612ffb87893361475c565b0161300d8333611c1861072885612cd4565b612cd4565b604080519586526001600160a01b039091166020860152840152339280606081015b0390a4565b631fd4ba0360e01b60005260045260246000fd5b6040519061305c602083610c93565b6000808352366020840137565b9061307382610cc4565b6130806040519182610c93565b8281528092613091601f1991610cc4565b0190602036910137565b80518210156114ba5760209160051b010190565b91908110156114ba576102a0020190565b91908110156114ba5760051b0190565b9190918051835180820361312c5750506130ea8151613069565b9060005b8151811015613125578061311460019260051b6020808287010151918901015190612bf2565b61311e828661309b565b52016130ee565b5090925050565b635b05999160e01b60005260045260245260446000fd5b61314c81613fb0565b9081600052600a602052604060002065ffffffffffff600282015460301c16156131e2577ff1e780e78d89d283caba1fefbe6d85a112fb930e5cb9544301096a011c7bafb46131d09261301260a06131d687958660005260006020526131c760406000203360018060a01b0316600052602052604060002090565b54978891612ec7565b856148f6565b92612ffb87873361475c565b82631fd4ba0360e01b60005260045260246000fd5b6040519061320482610c78565b600060a0838281528260208201528260408201528260608201528260808201520152565b81810292918115918404141715612d8a57565b8115613245570490565b634e487b7160e01b600052601260045260246000fd5b91613264614189565b6011549160ff8316611d575761328e61328461327e61444b565b86613e0c565b9360081c60ff1690565b1580613cb3575b613c9d576132b76132b084600052600b602052604060002090565b5460ff1690565b613c87576132cf6132c9368484610d53565b84614c55565b6132db61072886612cd4565b6001600160a01b0390911603613c67575050602082016001600160a01b0361330282612cd4565b16151580613c4c575b613c2057506040820161331d81612d2f565b65ffffffffffff42911610613bf5575060a082019265ffffffffffff61336a600261335a61334a88613fb0565b600052600a602052604060002090565b015460301c65ffffffffffff1690565b16613bd6576101c0830192613389610745600261335a61334a88613fb0565b613bd657608081016001600160801b036133a282612da0565b16613aec575b6101a08201916133ba61100e84612da0565b6139cf575b6101608101926133d161100e85612da0565b61375a575b506102808101916133e961100e84612da0565b6134ce575b5061345c8461347a61347461346e61346e6134686134626134c1988d6134497f40e693fe7b2f0b2982286c4522e2b45296dfb9b66206b5bc1551a29dbcc538619e61344383600052600c602052604060002090565b54613d2e565b998a91600052600c602052604060002090565b55612cd4565b9d613fb0565b9b613fb0565b96612da0565b92613d05565b91604051958695339b60018060a01b03169a8792936001600160801b0360a09581939998979460c087019a8752602087015216604085015216606083015260808201520152565b0390a46104536001600755565b60046020613511610728610728610200870161300d61350c6132b06134f284612cd4565b6001600160a01b03166000908152600d6020526040902090565b613ced565b60405163313ce56760e01b815292839182905afa9081156109d55760009161373b575b5061353e88612da0565b9061354c6101e08501612da0565b8761355687612da0565b6001600160801b03169061356991613228565b670de0b6b3a764000090049061357e93614cbd565b908660085461358d9084613228565b61271090046102608501906135a182612cd4565b6001600160a01b031660095482906001600160a01b0316336135c293614c6b565b6135cb8b613fb0565b6135d48c613fb0565b926135de90612cd4565b604080519283526001600160a01b0391909116602083015281019190915233907fd251a84f70b303473d1a800f3bee17030d3936ce3f7c39e96744648d7490641190606090a48561362e85612da0565b6001600160801b03169061364191613228565b670de0b6b3a764000090043361365685612cd4565b33613662938b8d61494b565b61366b88613fb0565b61367484612cd4565b9161367e8a613fb0565b61ac1d1892898961368e89612da0565b6001600160801b0316906136a191613228565b670de0b6b3a76400009004958a6136ba60608a01612cd4565b946136c490612da0565b6001600160801b0316906136d791613228565b670de0b6b3a764000090046136eb91613d21565b604080519283526020830196909652948101959095526001600160a01b039182166060860152608085019390935291909116913391906000805160206155588339815191529060a090a4386133ee565b613754915060203d6020116109ce576109c08183610c93565b38613534565b6004602061377d61072861072860e0870161300d61350c6132b06134f284612cd4565b60405163313ce56760e01b815292839182905afa9081156109d5576000916139b0575b506137aa89612da0565b906137b760c08501612da0565b876137c188612da0565b6001600160801b0316906137d491613228565b670de0b6b3a76400009004906137e993614cbd565b866008546137f79083613228565b612710900461014085019061380b82612cd4565b6001600160a01b031660095482906001600160a01b03163361382c93614c6b565b6138358c613fb0565b61ac1d186138428d613fb0565b9261384c90612cd4565b604080519283526001600160a01b0391909116602083015281019190915233907fd251a84f70b303473d1a800f3bee17030d3936ce3f7c39e96744648d7490641190606090a4888661389d87612da0565b6001600160801b0316906138b091613228565b670de0b6b3a76400009004886138c586612cd4565b6138ce87612cd4565b9233926138da9561494b565b6138e389613fb0565b6138ec84612cd4565b926138f68b613fb0565b61ac1d189289896139068a612da0565b6001600160801b03169061391991613228565b670de0b6b3a76400009004918a6139336101808a01612cd4565b9461393d90612da0565b6001600160801b03169061395091613228565b670de0b6b3a7640000900461396491613d21565b604080519283526020830196909652948101919091526001600160a01b0391821660608201526080810193909352339316916000805160206155588339815191529060a090a4386133d6565b6139c9915060203d6020116109ce576109c08183610c93565b386137a0565b61018081016139dd81612cd4565b6001600160a01b03166139ef83612cd4565b866139f987612da0565b6001600160801b031690613a0c91613228565b670de0b6b3a764000090049033613a2293614c6b565b613a2b88613fb0565b613a3483612cd4565b90613a3e8a613fb0565b9187613a4d6101608701612da0565b6001600160801b031690613a6091613228565b670de0b6b3a7640000900493613a7590612cd4565b908989613a818a612da0565b6001600160801b031690613a9491613228565b604080519283526020830196909652948101959095526001600160a01b039182166060860152670de0b6b3a7640000909304608085015291909116913391906000805160206155588339815191529060a090a46133bf565b848460608401613b34613b0161072883612cd4565b613b0a87612cd4565b90613b2c613b1e8a6124b861100e8b612da0565b670de0b6b3a7640000900490565b913391614c6b565b600080516020615558833981519152613b4c84613fb0565b9186613bce613b7d610722613b1e8c6124b861100e610280613b76613b708a612cd4565b9e613fb0565b9801612da0565b613b90613b1e8c6124b861100e8d612da0565b604080519889526020890194909452928701939093526001600160a01b039283166060870152608086019190915233959091169390819060a0820190565b0390a46133a8565b610a0c613be285613fb0565b6366ddd3a160e11b600052600452602490565b613c01610a0c91612d2f565b632676a8cd60e21b60005265ffffffffffff1660045242602452604490565b613c2c610a0c91612cd4565b6365d0b58b60e11b600052336004526001600160a01b0316602452604490565b50613c5681612cd4565b6001600160a01b031633141561330b565b613c83604051928392634f11230760e01b845260048401613cc5565b0390fd5b63310cc63360e21b600052600483905260246000fd5b6318f8b05760e21b600052600483905260246000fd5b50670de0b6b3a7640000851415613295565b90918060409360208452816020850152848401376000828201840152601f01601f1916010190565b15613cf457565b637209d83160e11b60005260046000fd5b670de0b6b3a76400000390670de0b6b3a76400008211612d8a57565b91908203918211612d8a57565b91908201809211612d8a57565b6104539092919260c0613dfe60a060e08401967f25036ae61bfc8d8512539bb2b64fb5ba7dcad72dca292e53cbc1b911b11a73e085526001600160801b038135613d8481612d8f565b1660208601526001600160801b036020820135613da081612d8f565b1660408601526040810135613db481610432565b600180841b0316606086015265ffffffffffff6060820135613dd581612d1f565b166080860152613df8613dea60808301612e2d565b65ffffffffffff1686840152565b01610448565b6001600160a01b0316910152565b90610da5916040516020810190613e3881613e2a60a0860185613d3b565b03601f198101835282610c93565b51902090613f8f6040516020810190613e5981613e2a6101c0870185613d3b565b51902092613e2a613e6984612cd4565b94613e7660208601612cd4565b92613e8360408701612d2f565b95613e9060608201612cd4565b91613e9d60808301612da0565b90613eab6101608401612da0565b613eb86101808501612cd4565b92613ed3610280613ecc6101a08801612da0565b9601612da0565b956040519b8c9a60208c019e8f7fe150cacb97f549f136b51aebe10986dc8bb73d35181d725b8a20dac1ac0c26b781526001600160a01b039182166020820152918116604083015265ffffffffffff9092166060820152911660808201526001600160801b0391821660a0820152911660c0820152610180810196959490939092909160e08501526001600160a01b03166101008401526001600160801b03166101208301526001600160801b03166101408201526101600152565b519020906042916040519161190160f01b8352600283015260228201522090565b803590613fbc82612d8f565b602081013590613fcb82612d8f565b604081013590613fda82610432565b6060810135613fe881612d1f565b60a0608083013592613ff984612d1f565b01359261400584610432565b6040519460208601966001600160801b03199060801b1687526001600160801b03199060801b1660308601526001600160601b03199060601b16604085015265ffffffffffff60d01b9060d01b16605484015265ffffffffffff60d01b9060d01b16605a8301526001600160601b03199060601b1660608201526054815261408e607482610c93565b51902090565b6005546001600160a01b031633036119c857565b613b1e610da5916140b881613fb0565b600052600a60205265ffffffffffff60606001600160801b0380604060002054161692016140f681356140ea81612d1f565b600e5493849116613d2e565b421115614140576141279161411961411361074561411e94612d2f565b42613d21565b613d21565b60105490613228565b600f5490818111156141395750613228565b9050613228565b50506000614127565b60405163a9059cbb60e01b60208201526001600160a01b03909216602483015260448083019390935291815261045391614184606483610c93565b614cfb565b60026007541461419a576002600755565b633ee5aeb560e01b60005260046000fd5b6141b481613fb0565b80600052600a6020527f12f5b4ba74ddf6fb0dac562f2e5020a8bb1172bdf51f14af3e551439d249354860406000209260a084549161425261423261422161421161420a8b6001600160801b03808a1616613228565b9660801c90565b956001600160801b038716612030565b946001600160801b038a1690612d6a565b87546001600160801b031660809190911b6001600160801b031916178755565b61428f61ac1d86189661426689883361475c565b61427189893361475c565b6108966001600160801b03861661089183546001600160801b031690565b016142a18233611c1861072885612cd4565b6001600160a01b03906142b390612cd4565b1694613034604051928392339787859094939260609260808301968352602083015260408201520152565b9194906001600160801b0380911695169283156143b55785831061433f576143316001600160801b039461432c8693614326614320610da59b61433899613d21565b91614caf565b90613228565b61323b565b911661548f565b91166154a1565b60405162461bcd60e51b815260206004820152604260248201527f496e6465782062616c616e6365206d757374206265206772656174657220746860448201527f616e206f7220657175616c20746f2074686520696e697469616c2062616c616e606482015261636560f01b608482015260a490fd5b60405162461bcd60e51b815260206004820152602660248201527f496e64657820736861726573206d7573742062652067726561746572207468616044820152656e207a65726f60d01b6064820152608490fd5b613b1e610da59161441981613fb0565b600052600a60205265ffffffffffff60806001600160801b0380604060002054161692016140f681356140ea81612d1f565b307f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03161480614538575b156144a6577f000000000000000000000000000000000000000000000000000000000000000090565b60405160208101907f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f82527f000000000000000000000000000000000000000000000000000000000000000060408201527f000000000000000000000000000000000000000000000000000000000000000060608201524660808201523060a082015260a0815261408e60c082610c93565b507f0000000000000000000000000000000000000000000000000000000000000000461461447d565b91909160c060e08201937f25036ae61bfc8d8512539bb2b64fb5ba7dcad72dca292e53cbc1b911b11a73e083526001600160801b0381511660208401526001600160801b03602082015116604084015260018060a01b03604082015116606084015265ffffffffffff606082015116608084015265ffffffffffff60808201511660a084015260a0600180821b0391015116910152565b90610da59160a081015160405161461781613e2a602082019485614561565b51902090613f8f61012082015160405161463981613e2a602082019485614561565b5190208251909390613e2a906001600160a01b031660208501519095906001600160a01b031692614673604087015165ffffffffffff1690565b60608701519096906001600160a01b03169161469960808301516001600160801b031690565b906146ae60c08401516001600160801b031690565b60e08401516001600160a01b031692613ed36101406146d86101008801516001600160801b031690565b9601516001600160801b031690565b602061473d610da5946124b86001600160801b03948561473686830192828061472a8c8280614720818b51168260c08601511690612d6a565b1691511690613228565b95511691511690612d6a565b169061323b565b920151169061323b565b60405190614756602083610c93565b60008252565b926001600160a01b0384169290919083156128aa5761479860405192600184526020840152604083019160018352606084015260808301604052565b919060209160006040516147ac8582610c93565b5281518451908181036148df57505060005b8251811015614854578060051b8480828601015191870101516147ef89612463846000526000602052604060002090565b5481811061481d578961246360019594936148169303936000526000602052604060002090565b55016147be565b6040516303dee4c560e01b81526001600160a01b038b16600482015260248101919091526044810182905260648101839052608490fd5b509450909160009392600183511485146148ab579182015191015160408051928352602083019190915233917fc3d58168c5ae7397731d063d5bbf3d657854427343f4c083240f7aacaa2d0f629181908101613034565b506130347f4a39dc06d4c0dbc64b70af90fd698a233a518aa5d07e595d983b8c0526c8f7fb916040519182913395836151fd565b635b05999160e01b60005260045260245260446000fd5b602061473d610da5946124b86001600160801b0394856147368160c08a015116876149368461492b8735809561089182612d8f565b16858d511690613228565b94013561494281612d8f565b61089182612d8f565b949290946040810194853561495f81610432565b6001600160a01b03166000908152600d60205260409020546149839060ff16612cde565b8493816149996001600160801b03831115614be9565b6149a284613fb0565b9765ffffffffffff6149c3600261335a8c600052600a602052604060002090565b16614bd357906149da610728600496959493612cd4565b966149ef8a600052600a602052604060002090565b6149f886612da0565b996020614a06818901612da0565b60405163313ce56760e01b8152909b90998a9182906001600160a01b03165afa998a156109d557614a6a8d9b8760a0937f3226776085fb473b91e74f4a2b3e96cd425fcc3e1bc0ee18410353c435a7e9d39f614b9d9d600094614bb2575b50614cbd565b97614aad614a916001600160801b038b16614a8c87546001600160801b031690565b614c35565b85546001600160801b0319166001600160801b03909116178555565b0195614ac788614abf6107288a612cd4565b8c3091614c6b565b6001600160a01b031615614baa575b6001600160a01b031615614ba2575b614b2190614b016001600160801b038616614a8c835460801c90565b81546001600160801b031660809190911b6001600160801b031916179055565b614b5061ac1d891894614b3d614b35614747565b868c87614f3f565b61300d614b48614747565b868886614f3f565b604080519c8d5260208d0199909952978b01939093526001600160a01b0392831660608b0152821660808a015260a089015293841660c088015260e0870152911693908190610100820190565b0390a3565b339150614ae5565b339350614ad6565b614bcc91945060203d6020116109ce576109c08183610c93565b9238614a64565b6366ddd3a160e11b600052600489905260246000fd5b15614bf057565b60405162461bcd60e51b815260206004820152601960248201527f536861726573206578636565642075696e74313238206d6178000000000000006044820152606490fd5b906001600160801b03809116911601906001600160801b038211612d8a57565b610da591614c629161511f565b9092919261517b565b6040516323b872dd60e01b60208201526001600160a01b03928316602482015292909116604483015260648083019390935291815261045391614184608483610c93565b604d8111612d8a57600a0a90565b916001600160801b03614cd6614cdc9461432094612d6a565b16613228565b8015614ced57808204910615150190565b6365244e4e6000526004601cfd5b906000602091828151910182855af115612d48576000513d614d4d57506001600160a01b0381163b155b614d2c5750565b635274afe760e01b60009081526001600160a01b0391909116600452602490fd5b60011415614d25565b94939290919384518251908181036148df5750506001600160a01b0386811695861515959185168015159391929060005b8451811015614e71578060051b90898988602080868b010151958c01015192614dea575b93600194614dbd575b50505001614d87565b614de091612463614dd8926000526000602052604060002090565b918254613d2e565b9055388981614db4565b50509091614e068d612463836000526000602052604060002090565b54828110614e3a578291898f614e31600197968f950391612463856000526000602052604060002090565b55909450614dab565b6040516303dee4c560e01b81526001600160a01b038f16600482015260248101919091526044810183905260648101829052608490fd5b509198959392979096506001885114600014614f055760208881015186820151604080519283529282015233917fc3d58168c5ae7397731d063d5bbf3d657854427343f4c083240f7aacaa2d0f6291a45b614ece575b5050505050565b8451600103614ef457602080614eea96015192015192336153ef565b3880808080614ec7565b614f00949192336152ba565b614eea565b6040517f4a39dc06d4c0dbc64b70af90fd698a233a518aa5d07e595d983b8c0526c8f7fb339180614f37898d836151fd565b0390a4614ec2565b6001600160a01b038116939290919084156128bf57614f7b60405192600184526020840152604083019160018352606084015260808301604052565b9281518451908181036148df57505060005b8251811015614fcd578060019160051b614fc5614dd887612463602080868b010151958c010151946000526000602052604060002090565b905501614f8d565b5092919360018251146000146150485760208281015184820151604080519283529282015260009133917fc3d58168c5ae7397731d063d5bbf3d657854427343f4c083240f7aacaa2d0f629190a45b805160010361503c579060208061045395930151910151916000336153ef565b610453936000336152ba565b60006040517f4a39dc06d4c0dbc64b70af90fd698a233a518aa5d07e595d983b8c0526c8f7fb33918061507c8888836151fd565b0390a461501c565b60ff81146150ce5760ff811690601f82116150bd5760408051926150a88285610c93565b6020808552840191601f190136833783525290565b632cd44ac360e21b60005260046000fd5b50604051610da5816150e1816003612c51565b0382610c93565b60ff811461510c5760ff811690601f82116150bd5760408051926150a88285610c93565b50604051610da5816150e1816004612c51565b81519190604183036151505761514992506020820151906060604084015193015160001a906154ae565b9192909190565b505060009160029190565b6004111561516557565b634e487b7160e01b600052602160045260246000fd5b6151848161515b565b8061518d575050565b6151968161515b565b600181036151af5763f645eedf60e01b60005260046000fd5b6151b88161515b565b600281036151d5575063fce698f760e01b60005260045260246000fd5b806151e160039261515b565b146151e95750565b6335e2f38360e21b60005260045260246000fd5b9091615214610da593604084526040840190611293565b916020818403910152611293565b908160209103126104435751610da5816104a6565b6001600160a01b0391821681529116602082015260a060408201819052610da5949193919261527c929161526e9190860190611293565b908482036060860152611293565b916080818403910152610526565b3d156152b5573d9061529b82610d38565b916152a96040519384610c93565b82523d6000602084013e565b606090565b9091949293853b6152ce575b505050505050565b6020936152f091604051968795869563bc197c8160e01b875260048701615237565b038160006001600160a01b0387165af160009181615385575b50615345575061531761528a565b805191908261533e57632bfa23e760e11b6000526001600160a01b03821660045260246000fd5b9050602001fd5b6001600160e01b0319166343e6837f60e01b0161536857503880808080806152c6565b632bfa23e760e11b6000526001600160a01b031660045260246000fd5b6153a891925060203d6020116153af575b6153a08183610c93565b810190615222565b9038615309565b503d615396565b6001600160a01b039182168152911660208201526040810191909152606081019190915260a060808201819052610da592910190610526565b9091949293853b61540257505050505050565b60209361542491604051968795869563f23a6e6160e01b8752600487016153b6565b038160006001600160a01b0387165af16000918161546e575b5061544b575061531761528a565b6001600160e01b031916630dc5919f60e01b0161536857503880808080806152c6565b61548891925060203d6020116153af576153a08183610c93565b903861543d565b908082101561549c575090565b905090565b908082111561549c575090565b91907f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0841161552b579160209360809260ff60009560405194855216868401526040830152606082015282805260015afa156109d5576000516001600160a01b0381161561551f5790600090600090565b50600090600190600090565b5050506000916003919056fe39cc814c3df1705a9d1bd4ec3a061f6fb23cb831bb8bc16c733ea10f0228624b25dfd61dc56aaa80d21af2bec91e32accf54e832ae0150840f23119063ce2dfea264697066735822122082582ebda6478cd5ed894c9ba3a5d83a076a37f96ac5fcd2aff2d0cb746d75b064736f6c634300081b003300000000000000000000000000000000000000000000000000000000000000000000000000000000000000009cf99d917fb1a5538aa4316c03b5c57293c97c8f00000000000000000000000062e30d1969faf92dc8a3c22a1552eb83763eb372000000000000000000000000000000000000000000000000000000000000012c00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
Deployed Bytecode
0x6080604052600436101561001257600080fd5b60003560e01c8062fdd58e1461042d57806301ffc9a7146104285780630e89341c1461042357806313208d1b1461041e57806319b87556146104195780631d0fa9cf1461036a57806324b3e7ec146104145780632556bc151461040f57806329fa8b871461040a5780632eb2c2d6146104055780632fece5ae14610400578063312f14ba146103fb57806332afed8f146103f65780633305d6b1146103f157806334d2efe5146103ec57806337d59827146103e75780633ba1a0df146103e25780633f4ba83a146103dd5780634cd21543146103d85780634e1273f4146103d357806351594173146103ce5780635396fae5146103c95780635889bf5e146103c45780635b72928c146103bf5780635c975abb146103ba5780636605bfda146103b55780636c0dc97914610383578063715018a6146103b057806378e890ba146103ab57806379ba5097146103a65780637d1a7558146103a15780637e28c0521461039c5780638456cb591461039757806384b0196e14610392578063880185401461038d5780638ac86f1a146103885780638c8c29ce146103835780638da5cb5b1461037e5780638f409d2614610379578063934ed73214610374578063992cc7cb1461036f5780639c9b381c1461036a578063a0fadc3514610365578063a22cb46514610360578063a2b597ee1461035b578063bda9f38614610310578063c4cde46b14610356578063c5f956af14610351578063c837a9411461034c578063cae6047f14610347578063ccaaa52014610342578063d6dc6b041461033d578063d7e5ae9f14610329578063de30f4a714610338578063e0b01bac14610333578063e1c6709114610306578063e30c39781461032e578063e5c168a814610329578063e985e9c514610324578063ec9f8ae81461031f578063f0cd67511461031a578063f242432a14610315578063f249958514610310578063f2fde38b1461030b578063f50ec60214610306578063f5d213f2146103015763fe2de08c146102fc57600080fd5b612bd4565b612982565b612695565b612911565b61233e565b6127fa565b612761565b612744565b6126dc565b612556565b6126b3565b61262a565b612574565b61250a565b6123ef565b6123d2565b6123b3565b61238a565b612360565b6122a3565b6121e6565b612108565b610a3b565b61209f565b612047565b611fad565b611f38565b6118ab565b611ec3565b611e77565b611db5565b611d68565b611c93565b6119dd565b611953565b611930565b6118c9565b611820565b6117fd565b61179d565b61176c565b6116a2565b611680565b6115bf565b611524565b6114da565b6113bf565b611338565b6112d8565b611271565b61115e565b610e66565b610e3c565b610da8565b610ba4565b610b29565b610a59565b6106a9565b61064c565b610567565b6104b8565b610455565b6001600160a01b0381160361044357565b600080fd5b359061045382610432565b565b3461044357604036600319011261044357602061049d60043561047781610432565b6024356000526000835260406000209060018060a01b0316600052602052604060002090565b54604051908152f35b6001600160e01b031981160361044357565b346104435760203660031901126104435760206004356104d7816104a6565b63ffffffff60e01b16636cdb3d1360e11b8114908115610515575b8115610504575b506040519015158152f35b6301ffc9a760e01b149050386104f9565b6303a24d0760e21b811491506104f2565b919082519283825260005b848110610552575050826000602080949584010152601f8019910116010190565b80602080928401015182828601015201610531565b3461044357602036600319011261044357604051600060025461058981612c17565b808452906001811690811561062857506001146105c9575b6105c5836105b181850382610c93565b604051918291602083526020830190610526565b0390f35b600260009081527f405787fa12a823e0f2b7631cc41b3ba8828b3321ca811111fa75cd3aa3bb5ace939250905b80821061060e575090915081016020016105b16105a1565b9192600181602092548385880101520191019092916105f6565b60ff191660208086019190915291151560051b840190910191506105b190506105a1565b34610443576020366003190112610443577f2e54a66023bd119d7da51cb6619e461b9f2d33f3749d492dcec52d5c6ce5f34b602060043561068b614094565b80601055604051908152a1005b60c090600319011261044357600490565b346104435760c0366003190112610443576106c336610698565b6106cb614094565b6040810180356106da81610432565b6001600160a01b03166000908152600d60205260409020546106fe9060ff16612cde565b61070782613fb0565b9161073461072861072285600052600a602052604060002090565b93612cd4565b6001600160a01b031690565b606082019061075061074583612d2f565b65ffffffffffff1690565b4210610a10576002840165ffffffffffff610771825465ffffffffffff1690565b166109f957805465ffffffffffff19164265ffffffffffff16179055604051630198a77d60e11b81526001600160a01b03919091169390602081600481885afa9081156109d5576000916109da575b506107ee6001600160801b0360018401921682906001600160801b03166001600160801b0319825416179055565b6040516316d3df1560e31b8152602081600481895afa9283156109d5577f8da731be8204f25f24740734bc94894e24bf5606c951e71acc15bff0e1a68a9f966108666001600160801b036109a1968b956000916109a6575b5086546001600160801b0316911660801b6001600160801b031916178555565b6108b0610872886140a8565b926108966001600160801b03851661089183546001600160801b031690565b612d6a565b6001600160801b03166001600160801b0319825416179055565b826000805160206155388339815191526108f560a08a01946108df816108d861072889612cd4565b3390614149565b6040805191825233602083015290918291820190565b0390a261090187612da0565b93610926610722608061091f61091960208d01612da0565b9a612d2f565b9a01612d2f565b9054604080516001600160801b03978816815298871660208a015265ffffffffffff998a16908901529290971660608701526001600160a01b03908116608087810191909152961660a086015291821660c0850152931c60e0830152610100820183905261ac1d909218610120820152908190610140820190565b0390a2005b6109c8915060203d6020116109ce575b6109c08183610c93565b810190612d39565b38610846565b503d6109b6565b612d48565b6109f3915060203d6020116109ce576109c08183610c93565b386107c0565b6309ed6f7160e11b600052600486905260245b6000fd5b610a0c610a1c83612d2f565b63c7b7b42d60e01b6000524260045265ffffffffffff16602452604490565b34610443576000366003190112610443576020601054604051908152f35b3461044357602036600319011261044357600435610a7681610432565b610a7e614094565b6001600160a01b03166000818152600d602052604090205460ff16610aee576001600160a01b0381166000908152600d60205260409020610ac7905b805460ff19166001179055565b7f5d30d9fe66d95241fa9d52d043504e452639553b3156d29d5c2df6625a246db2600080a2005b60405162461bcd60e51b8152602060048201526013602482015272185b1c9958591e481dda1a5d195b1a5cdd1959606a1b6044820152606490fd5b346104435760003660031901126104435760206040516103e88152f35b9181601f84011215610443578235916001600160401b0383116104435760208085019460c0850201011161044357565b602060031982011261044357600435906001600160401b03821161044357610ba091600401610b46565b9091565b3461044357610bb236610b76565b610bba614189565b60005b818110610bcb576001600755005b80610c18610be4610bdf6001948688612dc0565b613fb0565b610bfc61ac1d610bf48333612bf2565b921833612bf2565b90610c08848789612dc0565b9180821015610c1e5750906141ab565b01610bbd565b9050906141ab565b634e487b7160e01b600052604160045260246000fd5b61016081019081106001600160401b03821117610c5857604052565b610c26565b60e081019081106001600160401b03821117610c5857604052565b60c081019081106001600160401b03821117610c5857604052565b90601f801991011681019081106001600160401b03821117610c5857604052565b6040519061045361016083610c93565b6001600160401b038111610c585760051b60200190565b9080601f83011215610443578135610cf281610cc4565b92610d006040519485610c93565b81845260208085019260051b82010192831161044357602001905b828210610d285750505090565b8135815260209182019101610d1b565b6001600160401b038111610c5857601f01601f191660200190565b929192610d5f82610d38565b91610d6d6040519384610c93565b829481845281830111610443578281602093846000960137010152565b9080601f8301121561044357816020610da593359101610d53565b90565b346104435760a036600319011261044357600435610dc581610432565b60243590610dd282610432565b6044356001600160401b03811161044357610df1903690600401610cdb565b6064356001600160401b03811161044357610e10903690600401610cdb565b90608435936001600160401b03851161044357610e34610e3a953690600401610d8a565b93612dd0565b005b3461044357600036600319011261044357610e55614094565b6011805461ff001916610100179055005b346104435760c036600319011261044357610e8036610698565b610e88614094565b60408101908135610e9881610432565b6001600160a01b03166000908152600d6020526040902054610ebc9060ff16612cde565b610ec581613fb0565b91610ee6610728610ee085600052600a602052604060002090565b92612cd4565b90600281019165ffffffffffff610f07845465ffffffffffff9060301c1690565b166111365760808401610f1c61074582612d2f565b421061110b57506040516316d3df1560e31b815292906001600160a01b0316602084600481845afa9384156109d5576000946110ea575b50600460018401546020610f77610f6a8360801c90565b926001600160801b031690565b936040519384809263313ce56760e01b82525afa9687156109d5576108df6110a9966108d861072860a0611090956110408f9a7fafeed4501a6753eefb924ea0eeb9a58b8d2ad05c8610190cd5f2c7160341a2559f8f6110969b61100e9261101a946000805160206155388339815191529f6000926110c9575b50610ffb88612da0565b9261100860208a01612da0565b946142de565b6001600160801b031690565b8c54600160601b600160e01b03191660609190911b600160601b600160e01b0316178c55565b8a546bffffffffffff00000000000019164260301b6bffffffffffff00000000000016178b5561106f81614409565b9687956108966001600160801b03881661089183546001600160801b031690565b01612cd4565b0390a25460601c6001600160801b031690565b604080519283526001600160801b039091166020830152819081016109a1565b6110e391925060203d6020116109ce576109c08183610c93565b9038610ff1565b61110491945060203d6020116109ce576109c08183610c93565b9238610f53565b611117610a0c91612d2f565b63bd7d315f60e01b6000524260045265ffffffffffff16602452604490565b6366ddd3a160e11b600052600485905260246000fd5b6102a090600319011261044357600490565b34610443576102a0366003190112610443576111793661114c565b61118161444b565b906102a081360312610443576105c591611261916112566102806111a3610cb4565b926111ad81610448565b84526111bb60208201610448565b60208501526111cc60408201612e2d565b60408501526111dd60608201610448565b60608501526111ee60808201612e38565b60808501526112003660a08301612e43565b60a08501526112126101608201612e38565b60c08501526112246101808201610448565b60e08501526112366101a08201612e38565b61010085015261124a366101c08301612e43565b61012085015201612e38565b6101408201526145f8565b6040519081529081906020820190565b346104435760c036600319011261044357610e3a61128e36610698565b612f69565b906020808351928381520192019060005b8181106112b15750505090565b82518452602093840193909201916001016112a4565b906020610da5928181520190611293565b34610443576112e636610b76565b906112f082613069565b9160005b81811061131157604051602080825281906105c590820187611293565b806113276113226001938587612dc0565b614409565b611331828761309b565b52016112f4565b3461044357600036600319011261044357602060ff60115460081c166040519015158152f35b9181601f84011215610443578235916001600160401b038311610443576020808501946102a0850201011161044357565b9181601f84011215610443578235916001600160401b038311610443576020808501948460051b01011161044357565b34610443576060366003190112610443576004356001600160401b038111610443576113ef90369060040161135e565b6024356001600160401b0381116104435761140e90369060040161138f565b6044356001600160401b0381116104435761142d90369060040161138f565b9490928285148015906114d0575b6114bf57909336829003601e1901919060005b81811061145757005b6114628183896130af565b90858110156114ba578060051b84013585811215610443578401918235926001600160401b03841161044357602001908336038213610443576001936114b4926114ad858e8d6130c0565b359261325b565b0161144e565b612daa565b633009a29d60e01b60005260046000fd5b508585141561143b565b34610443576000366003190112610443576114f3614094565b60ff19601154166011557ff9b5d9ff43c04557eb813158a432098c5d195947516dd9795ef5a11ecb047f36600080a1005b346104435760e03660031901126104435761153e36610698565b60c4359061154b82610432565b61155481613fb0565b9182600052600a60205260406000209065ffffffffffff600283015460301c16156115aa57906115a461159e611596611261959461ac1d6105c5981890612bf2565b933690612e43565b91612ec7565b906146e7565b83631fd4ba0360e01b60005260045260246000fd5b34610443576040366003190112610443576004356001600160401b0381116104435736602382011215610443578060040135906115fb82610cc4565b916116096040519384610c93565b8083526024602084019160051b8301019136831161044357602401905b82821061166657836024356001600160401b038111610443576105c59161165461165a923690600401610cdb565b906130d0565b604051918291826112c7565b60208091833561167581610432565b815201910190611626565b346104435760c036600319011261044357610e3a61169d36610698565b613143565b34610443576020366003190112610443576004356116bf81610432565b6116c7614094565b60018060a01b031680600052600d602052600160ff60406000205416151503611731576001600160a01b0381166000908152600d60205260409020805460ff191690557fdfb945e5b80afc93bd56261ec23d264f7bdefcb9dee18ba4781ec206fe7a1dc7600080a2005b60405162461bcd60e51b8152602060048201526013602482015272185b1c9958591e48189b1858dadb1a5cdd1959606a1b6044820152606490fd5b3461044357602036600319011261044357600435600052600b602052602060ff604060002054166040519015158152f35b34610443576117ab36610b76565b906117b582613069565b9160005b8181106117d657604051602080825281906105c590820187611293565b806117ec6117e76001938587612dc0565b6140a8565b6117f6828761309b565b52016117b9565b3461044357600036600319011261044357602060ff601154166040519015158152f35b346104435760203660031901126104435760043561183d81610432565b611845614094565b6001600160a01b03168015611895576020817f2c8741c51ef15572035be75af521ed4878a6e3406c7fdea3494b5fbffdc107c6926001600160601b0360a01b6009541617600955604051908152a1005b634e487b7160e01b600052600160045260246000fd5b34610443576000366003190112610443576020600f54604051908152f35b34610443576000366003190112610443576118e2614094565b600680546001600160a01b03199081169091556005805491821690556000906001600160a01b03167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08280a3005b3461044357600036600319011261044357602061194b61444b565b604051908152f35b3461044357600036600319011261044357600654336001600160a01b03909116036119c857600680546001600160a01b0319908116909155600580543392811683179091556001600160a01b03167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0600080a3005b63118cdaa760e01b6000523360045260246000fd5b34610443576119eb36610b76565b4265ffffffffffff16919060005b818110611a0257005b611a0d818385612dc0565b90611a16614094565b60408201918235611a2681610432565b6001600160a01b03166000908152600d6020526040902054611a4a9060ff16612cde565b611a5381613fb0565b90611a74610728611a6e84600052600a602052604060002090565b95612cd4565b90600285019165ffffffffffff611a95845465ffffffffffff9060301c1690565b16611c7d5760808201611aaa61074582612d2f565b421061110b57506040516316d3df1560e31b81526001600160a01b03919091169590926020846004818a5afa9283156109d557600494600094611c5d575b5060018301546020611afd610f6a8360801c90565b996040519788809263313ce56760e01b82525afa9081156109d557611c086108df611c1d968f95611bde8c9760019f611b8e61100e7fafeed4501a6753eefb924ea0eeb9a58b8d2ad05c8610190cd5f2c7160341a2559f8f909a6000805160206155388339815191529c611bb4956110969d600092611c3d575b50611b818a612da0565b9261100860208c01612da0565b8b54600160601b600160e01b03191660609190911b600160601b600160e01b0316178b55565b89546bffffffffffff000000000000191660309190911b6bffffffffffff00000000000016178955565b611be781614409565b9384926108966001600160801b03851661089183546001600160801b031690565b611c1861072860a0339301612cd4565b614149565b604080519283526001600160801b0391909116602083015290a2016119f9565b611c5691925060203d81116109ce576109c08183610c93565b9038611b77565b611c7691945060203d81116109ce576109c08183610c93565b9238611ae8565b6366ddd3a160e11b600052600484905260246000fd5b346104435761012036600319011261044357611cae36610698565b60c4359060e435611cbe81610432565b6101043591611ccc83610432565b60ff60115416611d5757610e3a93611d50604051611ce981610c3c565b6000815260006020820152600060408201526000606082015260006080820152611d116131f7565b60a0820152600060c0820152600060e08201526000610100820152611d346131f7565b6101208201526000610140820152611d4a61444b565b906145f8565b339261494b565b634815836b60e11b60005260046000fd5b3461044357600036600319011261044357611d81614094565b600160ff1960115416176011557f05204c23a38d23799ab593b867a0a8f7bb23ba80aa8308107716de014e257d9b600080a1005b3461044357600036600319011261044357611e48611df27f53696c696361506f6f6c7300000000000000000000000000000000000000000b615084565b6105c5611e1e7f31000000000000000000000000000000000000000000000000000000000000016150e8565b611e56611e2961304d565b91604051958695600f60f81b875260e0602088015260e0870190610526565b908582036040870152610526565b90466060850152306080850152600060a085015283820360c0850152611293565b34610443576020366003190112610443577fa8d4f499ed89ed61915e14bec2bd7bea8fb6c9701f14ce893bbc2e847d920d326020600435611eb6614094565b80600e55604051908152a1005b346104435760e036600319011261044357611edd36610698565b60c435611ee981610432565b611ef282613fb0565b9182600052600a60205260406000209165ffffffffffff600284015460301c16156115aa5790611f32611f2c6105c5956112619594612bf2565b92612ec7565b906148f6565b34610443576000366003190112610443576005546040516001600160a01b039091168152602090f35b6040600319820112610443576004356001600160401b0381116104435781611f8b91600401610b46565b92909291602435906001600160401b03821161044357610ba09160040161138f565b3461044357611fbb36611f61565b80839493036114bf57611fcd84613069565b9360005b818110611fe657604051806105c588826112c7565b80611ff7610bdf6001938589612dc0565b600052600a60205261203660406000205461203061202961201985898b6130c0565b356001600160801b038416613228565b9160801c90565b9061323b565b612040828961309b565b5201611fd1565b346104435761205536611f61565b9061205e614189565b8183036114bf5760005b838110612076576001600755005b806120996120876001938789612dc0565b6120928387876130c0565b35906141ab565b01612068565b34610443576102e0366003190112610443576120ba3661114c565b6102a4356001600160401b03811161044357366023820112156104435780600401356001600160401b03811161044357366024828401011161044357610e3a9260246102c43593019061325b565b34610443576020366003190112610443576004356001600160401b0381116104435761213890369060040161135e565b60005b81811061214457005b61214f8183856130af565b803561215a81610432565b6001600160a01b038116903382036121c55750509061218360019261217d61444b565b90613e0c565b61219a610aba82600052600b602052604060002090565b7fdae6f8929d076546361068a77fbf488bf65e58a76625628ede047a30311456a9600080a20161213b565b6121ce90610432565b6365d0b58b60e11b6000523360045260245260446000fd5b346104435760403660031901126104435760043561220381610432565b6024359081151590818303610443576001600160a01b03811692831561228e5761224f6122609233600052600160205260406000209060018060a01b0316600052602052604060002090565b9060ff801983541691151516179055565b6040519081527f17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c3160203392a3005b62ced3e160e81b600052600060045260246000fd5b34610443576020366003190112610443576004356122bf614094565b6103e881116122f9576020817fd5862782a16cfe1b4efd87aa8ff52fe97b1b3300d25bbf2719b5cbd413cd9cd492600855604051908152a1005b60405162461bcd60e51b815260206004820152601960248201527f43616e6e6f7420657863656564206d61782066656520425053000000000000006044820152606490fd5b3461044357602036600319011261044357602060043561ac1d60405191188152f35b34610443576102c036600319011261044357602061194b6123803661114c565b6102a43590613e0c565b34610443576000366003190112610443576009546040516001600160a01b039091168152602090f35b346104435760c036600319011261044357602061194b610bdf36610698565b346104435760003660031901126104435760206040516127108152f35b34610443576123fd36611f61565b9050819291036114bf5761241082613069565b9160005b81811061242957604051806105c586826112c7565b8061243a610bdf6001938587612dc0565b6124448133612bf2565b61248c61247a3361246361ac1d86186000526000602052604060002090565b9060018060a01b0316600052602052604060002090565b5492600052600a602052604060002090565b91808210156124d6575061203061100e6124bd6124c49454936124b861100e866001600160801b031690565b613228565b9260801c90565b6124ce828761309b565b525b01612414565b905061203061100e6124bd6124fa9454936124b861100e866001600160801b031690565b612504828761309b565b526124d0565b34610443576020366003190112610443577f9ee70d55a8fb5949bbafdc2c166db4f6b56a7f6827fcfc91202d433174fddd0d6020600435612549614094565b80600f55604051908152a1005b34610443576020366003190112610443576020600435604051908152f35b346104435760003660031901126104435761258d614094565b6011805461ff0019169055005b6104539092919260c08060e08301956001600160801b0381511684526001600160801b0360208201511660208501526001600160801b0360408201511660408501526001600160801b03606082015116606085015265ffffffffffff608082015116608085015261261a60a082015160a086019065ffffffffffff169052565b01516001600160801b0316910152565b3461044357602036600319011261044357600435600060c060405161264e81610c5d565b8281528260208201528260408201528260608201528260808201528260a08201520152600052600a6020526105c56126896040600020612ec7565b6040519182918261259a565b34610443576000366003190112610443576020600e54604051908152f35b34610443576000366003190112610443576006546040516001600160a01b039091168152602090f35b3461044357604036600319011261044357602060ff61273860043561270081610432565b6024359061270d82610432565b60018060a01b03166000526001845260406000209060018060a01b0316600052602052604060002090565b54166040519015158152f35b3461044357600036600319011261044357602060405161ac1d8152f35b34610443576040366003190112610443576004356001600160401b03811161044357612791903690600401610b46565b6024356001600160401b038111610443576127b0903690600401610b46565b92909160005b8181106127e35750505060005b8281106127cc57005b806127dd61128e6001938686612dc0565b016127c3565b806127f461169d6001938587612dc0565b016127b6565b346104435760a03660031901126104435760043561281781610432565b60243561282381610432565b60443590606435926084356001600160401b0381116104435761284a903690600401610d8a565b926001600160a01b03821633811415806128ed575b6128d5576001600160a01b038416156128bf57156128aa57610e3a946128a260405192600184526020840152604083019160018352606084015260808301604052565b929091614d56565b626a0d4560e21b600052600060045260246000fd5b632bfa23e760e11b600052600060045260246000fd5b63711bec9160e11b6000523360045260245260446000fd5b50600081815260016020908152604080832033845290915290205460ff161561285f565b346104435760203660031901126104435760043561292e81610432565b612936614094565b600680546001600160a01b0319166001600160a01b039283169081179091556005549091167f38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e22700600080a3005b346104435761299036610b76565b4265ffffffffffff16919060005b8181106129a757005b6129b2818385612dc0565b906129bb614094565b604082019182356129cb81610432565b6001600160a01b03166000908152600d60205260409020546129ef9060ff16612cde565b6129f881613fb0565b90612a13610728611a6e84600052600a602052604060002090565b906060810191612a2561074584612d2f565b4210612bc8576002860165ffffffffffff612a46825465ffffffffffff1690565b16612bb257805465ffffffffffff191665ffffffffffff8b16179055604051630198a77d60e11b81526001600160a01b03919091169290602081600481875afa9081156109d557600091612b94575b50612ac36001600160801b0360018901921682906001600160801b03166001600160801b0319825416179055565b6040516316d3df1560e31b815290602082600481885afa9182156109d5576001987f8da731be8204f25f24740734bc94894e24bf5606c951e71acc15bff0e1a68a9f96612b3e6001600160801b03612b73968b95600091612b7c575086546001600160801b0316911660801b6001600160801b031916178555565b612b4a610872886140a8565b826000805160206155388339815191526108f560a08a01946108df8133611c186107288a612cd4565b0390a20161299e565b6109c8915060203d81116109ce576109c08183610c93565b612bac915060203d81116109ce576109c08183610c93565b38612a95565b6309ed6f7160e11b600052600485905260246000fd5b610a0c610a1c84612d2f565b34610443576000366003190112610443576020600854604051908152f35b6000918252602082815260408084206001600160a01b03909316845291905290205490565b90600182811c92168015612c47575b6020831014612c3157565b634e487b7160e01b600052602260045260246000fd5b91607f1691612c26565b60009291815491612c6183612c17565b8083529260018116908115612cb75750600114612c7d57505050565b60009081526020812093945091925b838310612c9d575060209250010190565b600181602092949394548385870101520191019190612c8c565b915050602093945060ff929192191683830152151560051b010190565b35610da581610432565b15612ce557565b60405162461bcd60e51b8152602060048201526012602482015271092dcecc2d8d2c8a6d2d8d2c6c292dcc8caf60731b6044820152606490fd5b65ffffffffffff81160361044357565b35610da581612d1f565b90816020910312610443575190565b6040513d6000823e3d90fd5b634e487b7160e01b600052601160045260246000fd5b906001600160801b03809116911603906001600160801b038211612d8a57565b612d54565b6001600160801b0381160361044357565b35610da581612d8f565b634e487b7160e01b600052603260045260246000fd5b91908110156114ba5760c0020190565b939291906001600160a01b0385163381141580612e09575b6128d5576001600160a01b038216156128bf57156128aa5761045394614d56565b50600081815260016020908152604080832033845290915290205460ff1615612de8565b359061045382612d1f565b359061045382612d8f565b91908260c091031261044357604051612e5b81610c78565b60a0612ec28183958035612e6e81612d8f565b85526020810135612e7e81612d8f565b60208601526040810135612e9181610432565b60408601526060810135612ea481612d1f565b60608601526080810135612eb781612d1f565b608086015201610448565b910152565b90610453604051612ed781610c5d565b60c0612f5b600283966001600160801b038154818116875260801c166020860152612f2a612f1a60018301546001600160801b0380821616604089015260801c90565b6001600160801b03166060870152565b015465ffffffffffff8116608085015265ffffffffffff603082901c1660a085015260601c6001600160801b031690565b6001600160801b0316910152565b612f7281613fb0565b80600052600a60205260406000209065ffffffffffff80600284015460301c161615613039577ff1e780e78d89d283caba1fefbe6d85a112fb930e5cb9544301096a011c7bafb461ac1d82189361301260a0612fef612fdf336124638a6000526000602052604060002090565b5480976115a461159e3688612e43565b92612ffb87893361475c565b0161300d8333611c1861072885612cd4565b612cd4565b604080519586526001600160a01b039091166020860152840152339280606081015b0390a4565b631fd4ba0360e01b60005260045260246000fd5b6040519061305c602083610c93565b6000808352366020840137565b9061307382610cc4565b6130806040519182610c93565b8281528092613091601f1991610cc4565b0190602036910137565b80518210156114ba5760209160051b010190565b91908110156114ba576102a0020190565b91908110156114ba5760051b0190565b9190918051835180820361312c5750506130ea8151613069565b9060005b8151811015613125578061311460019260051b6020808287010151918901015190612bf2565b61311e828661309b565b52016130ee565b5090925050565b635b05999160e01b60005260045260245260446000fd5b61314c81613fb0565b9081600052600a602052604060002065ffffffffffff600282015460301c16156131e2577ff1e780e78d89d283caba1fefbe6d85a112fb930e5cb9544301096a011c7bafb46131d09261301260a06131d687958660005260006020526131c760406000203360018060a01b0316600052602052604060002090565b54978891612ec7565b856148f6565b92612ffb87873361475c565b82631fd4ba0360e01b60005260045260246000fd5b6040519061320482610c78565b600060a0838281528260208201528260408201528260608201528260808201520152565b81810292918115918404141715612d8a57565b8115613245570490565b634e487b7160e01b600052601260045260246000fd5b91613264614189565b6011549160ff8316611d575761328e61328461327e61444b565b86613e0c565b9360081c60ff1690565b1580613cb3575b613c9d576132b76132b084600052600b602052604060002090565b5460ff1690565b613c87576132cf6132c9368484610d53565b84614c55565b6132db61072886612cd4565b6001600160a01b0390911603613c67575050602082016001600160a01b0361330282612cd4565b16151580613c4c575b613c2057506040820161331d81612d2f565b65ffffffffffff42911610613bf5575060a082019265ffffffffffff61336a600261335a61334a88613fb0565b600052600a602052604060002090565b015460301c65ffffffffffff1690565b16613bd6576101c0830192613389610745600261335a61334a88613fb0565b613bd657608081016001600160801b036133a282612da0565b16613aec575b6101a08201916133ba61100e84612da0565b6139cf575b6101608101926133d161100e85612da0565b61375a575b506102808101916133e961100e84612da0565b6134ce575b5061345c8461347a61347461346e61346e6134686134626134c1988d6134497f40e693fe7b2f0b2982286c4522e2b45296dfb9b66206b5bc1551a29dbcc538619e61344383600052600c602052604060002090565b54613d2e565b998a91600052600c602052604060002090565b55612cd4565b9d613fb0565b9b613fb0565b96612da0565b92613d05565b91604051958695339b60018060a01b03169a8792936001600160801b0360a09581939998979460c087019a8752602087015216604085015216606083015260808201520152565b0390a46104536001600755565b60046020613511610728610728610200870161300d61350c6132b06134f284612cd4565b6001600160a01b03166000908152600d6020526040902090565b613ced565b60405163313ce56760e01b815292839182905afa9081156109d55760009161373b575b5061353e88612da0565b9061354c6101e08501612da0565b8761355687612da0565b6001600160801b03169061356991613228565b670de0b6b3a764000090049061357e93614cbd565b908660085461358d9084613228565b61271090046102608501906135a182612cd4565b6001600160a01b031660095482906001600160a01b0316336135c293614c6b565b6135cb8b613fb0565b6135d48c613fb0565b926135de90612cd4565b604080519283526001600160a01b0391909116602083015281019190915233907fd251a84f70b303473d1a800f3bee17030d3936ce3f7c39e96744648d7490641190606090a48561362e85612da0565b6001600160801b03169061364191613228565b670de0b6b3a764000090043361365685612cd4565b33613662938b8d61494b565b61366b88613fb0565b61367484612cd4565b9161367e8a613fb0565b61ac1d1892898961368e89612da0565b6001600160801b0316906136a191613228565b670de0b6b3a76400009004958a6136ba60608a01612cd4565b946136c490612da0565b6001600160801b0316906136d791613228565b670de0b6b3a764000090046136eb91613d21565b604080519283526020830196909652948101959095526001600160a01b039182166060860152608085019390935291909116913391906000805160206155588339815191529060a090a4386133ee565b613754915060203d6020116109ce576109c08183610c93565b38613534565b6004602061377d61072861072860e0870161300d61350c6132b06134f284612cd4565b60405163313ce56760e01b815292839182905afa9081156109d5576000916139b0575b506137aa89612da0565b906137b760c08501612da0565b876137c188612da0565b6001600160801b0316906137d491613228565b670de0b6b3a76400009004906137e993614cbd565b866008546137f79083613228565b612710900461014085019061380b82612cd4565b6001600160a01b031660095482906001600160a01b03163361382c93614c6b565b6138358c613fb0565b61ac1d186138428d613fb0565b9261384c90612cd4565b604080519283526001600160a01b0391909116602083015281019190915233907fd251a84f70b303473d1a800f3bee17030d3936ce3f7c39e96744648d7490641190606090a4888661389d87612da0565b6001600160801b0316906138b091613228565b670de0b6b3a76400009004886138c586612cd4565b6138ce87612cd4565b9233926138da9561494b565b6138e389613fb0565b6138ec84612cd4565b926138f68b613fb0565b61ac1d189289896139068a612da0565b6001600160801b03169061391991613228565b670de0b6b3a76400009004918a6139336101808a01612cd4565b9461393d90612da0565b6001600160801b03169061395091613228565b670de0b6b3a7640000900461396491613d21565b604080519283526020830196909652948101919091526001600160a01b0391821660608201526080810193909352339316916000805160206155588339815191529060a090a4386133d6565b6139c9915060203d6020116109ce576109c08183610c93565b386137a0565b61018081016139dd81612cd4565b6001600160a01b03166139ef83612cd4565b866139f987612da0565b6001600160801b031690613a0c91613228565b670de0b6b3a764000090049033613a2293614c6b565b613a2b88613fb0565b613a3483612cd4565b90613a3e8a613fb0565b9187613a4d6101608701612da0565b6001600160801b031690613a6091613228565b670de0b6b3a7640000900493613a7590612cd4565b908989613a818a612da0565b6001600160801b031690613a9491613228565b604080519283526020830196909652948101959095526001600160a01b039182166060860152670de0b6b3a7640000909304608085015291909116913391906000805160206155588339815191529060a090a46133bf565b848460608401613b34613b0161072883612cd4565b613b0a87612cd4565b90613b2c613b1e8a6124b861100e8b612da0565b670de0b6b3a7640000900490565b913391614c6b565b600080516020615558833981519152613b4c84613fb0565b9186613bce613b7d610722613b1e8c6124b861100e610280613b76613b708a612cd4565b9e613fb0565b9801612da0565b613b90613b1e8c6124b861100e8d612da0565b604080519889526020890194909452928701939093526001600160a01b039283166060870152608086019190915233959091169390819060a0820190565b0390a46133a8565b610a0c613be285613fb0565b6366ddd3a160e11b600052600452602490565b613c01610a0c91612d2f565b632676a8cd60e21b60005265ffffffffffff1660045242602452604490565b613c2c610a0c91612cd4565b6365d0b58b60e11b600052336004526001600160a01b0316602452604490565b50613c5681612cd4565b6001600160a01b031633141561330b565b613c83604051928392634f11230760e01b845260048401613cc5565b0390fd5b63310cc63360e21b600052600483905260246000fd5b6318f8b05760e21b600052600483905260246000fd5b50670de0b6b3a7640000851415613295565b90918060409360208452816020850152848401376000828201840152601f01601f1916010190565b15613cf457565b637209d83160e11b60005260046000fd5b670de0b6b3a76400000390670de0b6b3a76400008211612d8a57565b91908203918211612d8a57565b91908201809211612d8a57565b6104539092919260c0613dfe60a060e08401967f25036ae61bfc8d8512539bb2b64fb5ba7dcad72dca292e53cbc1b911b11a73e085526001600160801b038135613d8481612d8f565b1660208601526001600160801b036020820135613da081612d8f565b1660408601526040810135613db481610432565b600180841b0316606086015265ffffffffffff6060820135613dd581612d1f565b166080860152613df8613dea60808301612e2d565b65ffffffffffff1686840152565b01610448565b6001600160a01b0316910152565b90610da5916040516020810190613e3881613e2a60a0860185613d3b565b03601f198101835282610c93565b51902090613f8f6040516020810190613e5981613e2a6101c0870185613d3b565b51902092613e2a613e6984612cd4565b94613e7660208601612cd4565b92613e8360408701612d2f565b95613e9060608201612cd4565b91613e9d60808301612da0565b90613eab6101608401612da0565b613eb86101808501612cd4565b92613ed3610280613ecc6101a08801612da0565b9601612da0565b956040519b8c9a60208c019e8f7fe150cacb97f549f136b51aebe10986dc8bb73d35181d725b8a20dac1ac0c26b781526001600160a01b039182166020820152918116604083015265ffffffffffff9092166060820152911660808201526001600160801b0391821660a0820152911660c0820152610180810196959490939092909160e08501526001600160a01b03166101008401526001600160801b03166101208301526001600160801b03166101408201526101600152565b519020906042916040519161190160f01b8352600283015260228201522090565b803590613fbc82612d8f565b602081013590613fcb82612d8f565b604081013590613fda82610432565b6060810135613fe881612d1f565b60a0608083013592613ff984612d1f565b01359261400584610432565b6040519460208601966001600160801b03199060801b1687526001600160801b03199060801b1660308601526001600160601b03199060601b16604085015265ffffffffffff60d01b9060d01b16605484015265ffffffffffff60d01b9060d01b16605a8301526001600160601b03199060601b1660608201526054815261408e607482610c93565b51902090565b6005546001600160a01b031633036119c857565b613b1e610da5916140b881613fb0565b600052600a60205265ffffffffffff60606001600160801b0380604060002054161692016140f681356140ea81612d1f565b600e5493849116613d2e565b421115614140576141279161411961411361074561411e94612d2f565b42613d21565b613d21565b60105490613228565b600f5490818111156141395750613228565b9050613228565b50506000614127565b60405163a9059cbb60e01b60208201526001600160a01b03909216602483015260448083019390935291815261045391614184606483610c93565b614cfb565b60026007541461419a576002600755565b633ee5aeb560e01b60005260046000fd5b6141b481613fb0565b80600052600a6020527f12f5b4ba74ddf6fb0dac562f2e5020a8bb1172bdf51f14af3e551439d249354860406000209260a084549161425261423261422161421161420a8b6001600160801b03808a1616613228565b9660801c90565b956001600160801b038716612030565b946001600160801b038a1690612d6a565b87546001600160801b031660809190911b6001600160801b031916178755565b61428f61ac1d86189661426689883361475c565b61427189893361475c565b6108966001600160801b03861661089183546001600160801b031690565b016142a18233611c1861072885612cd4565b6001600160a01b03906142b390612cd4565b1694613034604051928392339787859094939260609260808301968352602083015260408201520152565b9194906001600160801b0380911695169283156143b55785831061433f576143316001600160801b039461432c8693614326614320610da59b61433899613d21565b91614caf565b90613228565b61323b565b911661548f565b91166154a1565b60405162461bcd60e51b815260206004820152604260248201527f496e6465782062616c616e6365206d757374206265206772656174657220746860448201527f616e206f7220657175616c20746f2074686520696e697469616c2062616c616e606482015261636560f01b608482015260a490fd5b60405162461bcd60e51b815260206004820152602660248201527f496e64657820736861726573206d7573742062652067726561746572207468616044820152656e207a65726f60d01b6064820152608490fd5b613b1e610da59161441981613fb0565b600052600a60205265ffffffffffff60806001600160801b0380604060002054161692016140f681356140ea81612d1f565b307f000000000000000000000000a979e1d73f233087d3808cfc02c119f5ea75de366001600160a01b03161480614538575b156144a6577f320f26adc077304999f062fae580e4fd6d692f9495faaf2e66443a4a4f3473f990565b60405160208101907f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f82527f9af5eb6c7b3411798e14119f4f01fa9e89deb420727baaf4d3298ba45ab0df5160408201527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc660608201524660808201523060a082015260a0815261408e60c082610c93565b507f0000000000000000000000000000000000000000000000000000000000002105461461447d565b91909160c060e08201937f25036ae61bfc8d8512539bb2b64fb5ba7dcad72dca292e53cbc1b911b11a73e083526001600160801b0381511660208401526001600160801b03602082015116604084015260018060a01b03604082015116606084015265ffffffffffff606082015116608084015265ffffffffffff60808201511660a084015260a0600180821b0391015116910152565b90610da59160a081015160405161461781613e2a602082019485614561565b51902090613f8f61012082015160405161463981613e2a602082019485614561565b5190208251909390613e2a906001600160a01b031660208501519095906001600160a01b031692614673604087015165ffffffffffff1690565b60608701519096906001600160a01b03169161469960808301516001600160801b031690565b906146ae60c08401516001600160801b031690565b60e08401516001600160a01b031692613ed36101406146d86101008801516001600160801b031690565b9601516001600160801b031690565b602061473d610da5946124b86001600160801b03948561473686830192828061472a8c8280614720818b51168260c08601511690612d6a565b1691511690613228565b95511691511690612d6a565b169061323b565b920151169061323b565b60405190614756602083610c93565b60008252565b926001600160a01b0384169290919083156128aa5761479860405192600184526020840152604083019160018352606084015260808301604052565b919060209160006040516147ac8582610c93565b5281518451908181036148df57505060005b8251811015614854578060051b8480828601015191870101516147ef89612463846000526000602052604060002090565b5481811061481d578961246360019594936148169303936000526000602052604060002090565b55016147be565b6040516303dee4c560e01b81526001600160a01b038b16600482015260248101919091526044810182905260648101839052608490fd5b509450909160009392600183511485146148ab579182015191015160408051928352602083019190915233917fc3d58168c5ae7397731d063d5bbf3d657854427343f4c083240f7aacaa2d0f629181908101613034565b506130347f4a39dc06d4c0dbc64b70af90fd698a233a518aa5d07e595d983b8c0526c8f7fb916040519182913395836151fd565b635b05999160e01b60005260045260245260446000fd5b602061473d610da5946124b86001600160801b0394856147368160c08a015116876149368461492b8735809561089182612d8f565b16858d511690613228565b94013561494281612d8f565b61089182612d8f565b949290946040810194853561495f81610432565b6001600160a01b03166000908152600d60205260409020546149839060ff16612cde565b8493816149996001600160801b03831115614be9565b6149a284613fb0565b9765ffffffffffff6149c3600261335a8c600052600a602052604060002090565b16614bd357906149da610728600496959493612cd4565b966149ef8a600052600a602052604060002090565b6149f886612da0565b996020614a06818901612da0565b60405163313ce56760e01b8152909b90998a9182906001600160a01b03165afa998a156109d557614a6a8d9b8760a0937f3226776085fb473b91e74f4a2b3e96cd425fcc3e1bc0ee18410353c435a7e9d39f614b9d9d600094614bb2575b50614cbd565b97614aad614a916001600160801b038b16614a8c87546001600160801b031690565b614c35565b85546001600160801b0319166001600160801b03909116178555565b0195614ac788614abf6107288a612cd4565b8c3091614c6b565b6001600160a01b031615614baa575b6001600160a01b031615614ba2575b614b2190614b016001600160801b038616614a8c835460801c90565b81546001600160801b031660809190911b6001600160801b031916179055565b614b5061ac1d891894614b3d614b35614747565b868c87614f3f565b61300d614b48614747565b868886614f3f565b604080519c8d5260208d0199909952978b01939093526001600160a01b0392831660608b0152821660808a015260a089015293841660c088015260e0870152911693908190610100820190565b0390a3565b339150614ae5565b339350614ad6565b614bcc91945060203d6020116109ce576109c08183610c93565b9238614a64565b6366ddd3a160e11b600052600489905260246000fd5b15614bf057565b60405162461bcd60e51b815260206004820152601960248201527f536861726573206578636565642075696e74313238206d6178000000000000006044820152606490fd5b906001600160801b03809116911601906001600160801b038211612d8a57565b610da591614c629161511f565b9092919261517b565b6040516323b872dd60e01b60208201526001600160a01b03928316602482015292909116604483015260648083019390935291815261045391614184608483610c93565b604d8111612d8a57600a0a90565b916001600160801b03614cd6614cdc9461432094612d6a565b16613228565b8015614ced57808204910615150190565b6365244e4e6000526004601cfd5b906000602091828151910182855af115612d48576000513d614d4d57506001600160a01b0381163b155b614d2c5750565b635274afe760e01b60009081526001600160a01b0391909116600452602490fd5b60011415614d25565b94939290919384518251908181036148df5750506001600160a01b0386811695861515959185168015159391929060005b8451811015614e71578060051b90898988602080868b010151958c01015192614dea575b93600194614dbd575b50505001614d87565b614de091612463614dd8926000526000602052604060002090565b918254613d2e565b9055388981614db4565b50509091614e068d612463836000526000602052604060002090565b54828110614e3a578291898f614e31600197968f950391612463856000526000602052604060002090565b55909450614dab565b6040516303dee4c560e01b81526001600160a01b038f16600482015260248101919091526044810183905260648101829052608490fd5b509198959392979096506001885114600014614f055760208881015186820151604080519283529282015233917fc3d58168c5ae7397731d063d5bbf3d657854427343f4c083240f7aacaa2d0f6291a45b614ece575b5050505050565b8451600103614ef457602080614eea96015192015192336153ef565b3880808080614ec7565b614f00949192336152ba565b614eea565b6040517f4a39dc06d4c0dbc64b70af90fd698a233a518aa5d07e595d983b8c0526c8f7fb339180614f37898d836151fd565b0390a4614ec2565b6001600160a01b038116939290919084156128bf57614f7b60405192600184526020840152604083019160018352606084015260808301604052565b9281518451908181036148df57505060005b8251811015614fcd578060019160051b614fc5614dd887612463602080868b010151958c010151946000526000602052604060002090565b905501614f8d565b5092919360018251146000146150485760208281015184820151604080519283529282015260009133917fc3d58168c5ae7397731d063d5bbf3d657854427343f4c083240f7aacaa2d0f629190a45b805160010361503c579060208061045395930151910151916000336153ef565b610453936000336152ba565b60006040517f4a39dc06d4c0dbc64b70af90fd698a233a518aa5d07e595d983b8c0526c8f7fb33918061507c8888836151fd565b0390a461501c565b60ff81146150ce5760ff811690601f82116150bd5760408051926150a88285610c93565b6020808552840191601f190136833783525290565b632cd44ac360e21b60005260046000fd5b50604051610da5816150e1816003612c51565b0382610c93565b60ff811461510c5760ff811690601f82116150bd5760408051926150a88285610c93565b50604051610da5816150e1816004612c51565b81519190604183036151505761514992506020820151906060604084015193015160001a906154ae565b9192909190565b505060009160029190565b6004111561516557565b634e487b7160e01b600052602160045260246000fd5b6151848161515b565b8061518d575050565b6151968161515b565b600181036151af5763f645eedf60e01b60005260046000fd5b6151b88161515b565b600281036151d5575063fce698f760e01b60005260045260246000fd5b806151e160039261515b565b146151e95750565b6335e2f38360e21b60005260045260246000fd5b9091615214610da593604084526040840190611293565b916020818403910152611293565b908160209103126104435751610da5816104a6565b6001600160a01b0391821681529116602082015260a060408201819052610da5949193919261527c929161526e9190860190611293565b908482036060860152611293565b916080818403910152610526565b3d156152b5573d9061529b82610d38565b916152a96040519384610c93565b82523d6000602084013e565b606090565b9091949293853b6152ce575b505050505050565b6020936152f091604051968795869563bc197c8160e01b875260048701615237565b038160006001600160a01b0387165af160009181615385575b50615345575061531761528a565b805191908261533e57632bfa23e760e11b6000526001600160a01b03821660045260246000fd5b9050602001fd5b6001600160e01b0319166343e6837f60e01b0161536857503880808080806152c6565b632bfa23e760e11b6000526001600160a01b031660045260246000fd5b6153a891925060203d6020116153af575b6153a08183610c93565b810190615222565b9038615309565b503d615396565b6001600160a01b039182168152911660208201526040810191909152606081019190915260a060808201819052610da592910190610526565b9091949293853b61540257505050505050565b60209361542491604051968795869563f23a6e6160e01b8752600487016153b6565b038160006001600160a01b0387165af16000918161546e575b5061544b575061531761528a565b6001600160e01b031916630dc5919f60e01b0161536857503880808080806152c6565b61548891925060203d6020116153af576153a08183610c93565b903861543d565b908082101561549c575090565b905090565b908082111561549c575090565b91907f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0841161552b579160209360809260ff60009560405194855216868401526040830152606082015282805260015afa156109d5576000516001600160a01b0381161561551f5790600090600090565b50600090600190600090565b5050506000916003919056fe39cc814c3df1705a9d1bd4ec3a061f6fb23cb831bb8bc16c733ea10f0228624b25dfd61dc56aaa80d21af2bec91e32accf54e832ae0150840f23119063ce2dfea264697066735822122082582ebda6478cd5ed894c9ba3a5d83a076a37f96ac5fcd2aff2d0cb746d75b064736f6c634300081b0033
Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)
00000000000000000000000000000000000000000000000000000000000000000000000000000000000000009cf99d917fb1a5538aa4316c03b5c57293c97c8f00000000000000000000000062e30d1969faf92dc8a3c22a1552eb83763eb372000000000000000000000000000000000000000000000000000000000000012c00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
-----Decoded View---------------
Arg [0] : startFeeBps (uint256): 0
Arg [1] : initialOwner (address): 0x9cF99D917fB1A5538Aa4316c03b5c57293c97C8f
Arg [2] : alkimiyaTreasury (address): 0x62E30D1969FAf92dc8a3C22A1552eB83763eb372
Arg [3] : gracePeriod (uint256): 300
Arg [4] : maxBountyFrac (uint256): 0
Arg [5] : bountyIncreasePerSecond (uint256): 0
-----Encoded View---------------
6 Constructor Arguments found :
Arg [0] : 0000000000000000000000000000000000000000000000000000000000000000
Arg [1] : 0000000000000000000000009cf99d917fb1a5538aa4316c03b5c57293c97c8f
Arg [2] : 00000000000000000000000062e30d1969faf92dc8a3c22a1552eb83763eb372
Arg [3] : 000000000000000000000000000000000000000000000000000000000000012c
Arg [4] : 0000000000000000000000000000000000000000000000000000000000000000
Arg [5] : 0000000000000000000000000000000000000000000000000000000000000000
Loading...
Loading
Loading...
Loading
Loading...
Loading
Loading...
Loading
[ Download: CSV Export ]
A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.