Source Code
Overview
ETH Balance
More Info
ContractCreator
Multichain Info
N/A
Transaction Hash |
Method
|
Block
|
From
|
To
|
|||||
---|---|---|---|---|---|---|---|---|---|
Latest 25 internal transactions (View All)
Parent Transaction Hash | Block | From | To | |||
---|---|---|---|---|---|---|
8151834 | 2 mins ago | 0 ETH | ||||
8151801 | 7 mins ago | 0 ETH | ||||
8151726 | 17 mins ago | 0 ETH | ||||
8151696 | 22 mins ago | 0 ETH | ||||
8151538 | 47 mins ago | 0 ETH | ||||
8151508 | 51 mins ago | 0 ETH | ||||
8151431 | 1 hr ago | 0 ETH | ||||
8151369 | 1 hr ago | 0 ETH | ||||
8151139 | 1 hr ago | 0 ETH | ||||
8150985 | 2 hrs ago | 0 ETH | ||||
8150915 | 2 hrs ago | 0 ETH | ||||
8150827 | 2 hrs ago | 0 ETH | ||||
8150796 | 2 hrs ago | 0 ETH | ||||
8150731 | 2 hrs ago | 0 ETH | ||||
8150663 | 3 hrs ago | 0 ETH | ||||
8150631 | 3 hrs ago | 0 ETH | ||||
8150599 | 3 hrs ago | 0 ETH | ||||
8150474 | 3 hrs ago | 0 ETH | ||||
8150444 | 3 hrs ago | 0 ETH | ||||
8150406 | 3 hrs ago | 0 ETH | ||||
8150376 | 3 hrs ago | 0 ETH | ||||
8150340 | 3 hrs ago | 0 ETH | ||||
8150145 | 4 hrs ago | 0 ETH | ||||
8150083 | 4 hrs ago | 0 ETH | ||||
8150015 | 4 hrs ago | 0 ETH |
Loading...
Loading
This contract may be a proxy contract. Click on More Options and select Is this a proxy? to confirm and enable the "Read as Proxy" & "Write as Proxy" tabs.
Contract Source Code Verified (Exact Match)
Contract Name:
Withdrawal
Compiler Version
v0.8.27+commit.40a35a09
Optimization Enabled:
No with 200 runs
Other Settings:
paris EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: MIT pragma solidity 0.8.27; import {IWithdrawal} from "./IWithdrawal.sol"; import {IPlonkVerifier} from "../common/IPlonkVerifier.sol"; import {ILiquidity} from "../liquidity/ILiquidity.sol"; import {IRollup} from "../rollup/IRollup.sol"; import {IContribution} from "../contribution/IContribution.sol"; import {IL2ScrollMessenger} from "@scroll-tech/contracts/L2/IL2ScrollMessenger.sol"; import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import {WithdrawalProofPublicInputsLib} from "./lib/WithdrawalProofPublicInputsLib.sol"; import {ChainedWithdrawalLib} from "./lib/ChainedWithdrawalLib.sol"; import {WithdrawalLib} from "../common/WithdrawalLib.sol"; import {Byte32Lib} from "../common/Byte32Lib.sol"; contract Withdrawal is IWithdrawal, UUPSUpgradeable, OwnableUpgradeable { using EnumerableSet for EnumerableSet.UintSet; using WithdrawalLib for WithdrawalLib.Withdrawal; using ChainedWithdrawalLib for ChainedWithdrawalLib.ChainedWithdrawal[]; using WithdrawalProofPublicInputsLib for WithdrawalProofPublicInputsLib.WithdrawalProofPublicInputs; using Byte32Lib for bytes32; IPlonkVerifier private withdrawalVerifier; IL2ScrollMessenger private l2ScrollMessenger; IRollup private rollup; address private liquidity; IContribution private contribution; mapping(bytes32 => bool) private nullifiers; EnumerableSet.UintSet internal directWithdrawalTokenIndices; /// @custom:oz-upgrades-unsafe-allow constructor constructor() { _disableInitializers(); } function initialize( address _admin, address _scrollMessenger, address _withdrawalVerifier, address _liquidity, address _rollup, address _contribution, uint256[] memory _directWithdrawalTokenIndices ) external initializer { if (_admin == address(0)) { revert AddressZero(); } if (_scrollMessenger == address(0)) { revert AddressZero(); } if (_withdrawalVerifier == address(0)) { revert AddressZero(); } if (_liquidity == address(0)) { revert AddressZero(); } if (_rollup == address(0)) { revert AddressZero(); } if (_contribution == address(0)) { revert AddressZero(); } __Ownable_init(_admin); __UUPSUpgradeable_init(); l2ScrollMessenger = IL2ScrollMessenger(_scrollMessenger); withdrawalVerifier = IPlonkVerifier(_withdrawalVerifier); rollup = IRollup(_rollup); contribution = IContribution(_contribution); liquidity = _liquidity; innerAddDirectWithdrawalTokenIndices(_directWithdrawalTokenIndices); } function updateContractAddresses( address _scrollMessenger, address _withdrawalVerifier, address _liquidity, address _rollup, address _contribution ) external onlyOwner { if (_scrollMessenger != address(0)) { l2ScrollMessenger = IL2ScrollMessenger(_scrollMessenger); } if (_withdrawalVerifier != address(0)) { withdrawalVerifier = IPlonkVerifier(_withdrawalVerifier); } if (_liquidity != address(0)) { liquidity = _liquidity; } if (_rollup != address(0)) { rollup = IRollup(_rollup); } if (_contribution != address(0)) { contribution = IContribution(_contribution); } } function submitWithdrawalProof( ChainedWithdrawalLib.ChainedWithdrawal[] calldata withdrawals, WithdrawalProofPublicInputsLib.WithdrawalProofPublicInputs calldata publicInputs, bytes calldata proof ) external { _validateWithdrawalProof(withdrawals, publicInputs, proof); uint256 directWithdrawalCounter = 0; uint256 claimableWithdrawalCounter = 0; bool[] memory isSkippedFlags = new bool[](withdrawals.length); for (uint256 i = 0; i < withdrawals.length; i++) { ChainedWithdrawalLib.ChainedWithdrawal memory chainedWithdrawal = withdrawals[i]; if (nullifiers[chainedWithdrawal.nullifier]) { isSkippedFlags[i] = true; continue; // already withdrawn } nullifiers[chainedWithdrawal.nullifier] = true; bytes32 expectedBlockHash = rollup.getBlockHash( chainedWithdrawal.blockNumber ); if (expectedBlockHash != chainedWithdrawal.blockHash) { revert BlockHashNotExists(chainedWithdrawal.blockHash); } if (_isDirectWithdrawalToken(chainedWithdrawal.tokenIndex)) { directWithdrawalCounter++; } else { claimableWithdrawalCounter++; } } if (directWithdrawalCounter == 0 && claimableWithdrawalCounter == 0) { return; } WithdrawalLib.Withdrawal[] memory directWithdrawals = new WithdrawalLib.Withdrawal[]( directWithdrawalCounter ); bytes32[] memory claimableWithdrawals = new bytes32[]( claimableWithdrawalCounter ); uint256 directWithdrawalIndex = 0; uint256 claimableWithdrawalIndex = 0; for (uint256 i = 0; i < withdrawals.length; i++) { if (isSkippedFlags[i]) { continue; // skipped withdrawal } ChainedWithdrawalLib.ChainedWithdrawal memory chainedWithdrawal = withdrawals[i]; WithdrawalLib.Withdrawal memory withdrawal = WithdrawalLib .Withdrawal( chainedWithdrawal.recipient, chainedWithdrawal.tokenIndex, chainedWithdrawal.amount, chainedWithdrawal.nullifier ); if (_isDirectWithdrawalToken(chainedWithdrawal.tokenIndex)) { directWithdrawals[directWithdrawalIndex] = withdrawal; emit DirectWithdrawalQueued( withdrawal.getHash(), withdrawal.recipient, withdrawal ); directWithdrawalIndex++; } else { bytes32 withdrawalHash = withdrawal.getHash(); claimableWithdrawals[claimableWithdrawalIndex] = withdrawalHash; emit ClaimableWithdrawalQueued( withdrawalHash, withdrawal.recipient, withdrawal ); claimableWithdrawalIndex++; } } bytes memory message = abi.encodeWithSelector( ILiquidity.processWithdrawals.selector, directWithdrawals, claimableWithdrawals ); _relayMessage(message); contribution.recordContribution( keccak256("WITHDRAWAL"), _msgSender(), directWithdrawalCounter + claimableWithdrawalCounter ); } // The specification of ScrollMessenger may change in the future. // https://docs.scroll.io/en/developers/l1-and-l2-bridging/the-scroll-messenger/ function _relayMessage(bytes memory message) private { uint256 value = 0; // relay to non-payable function // In the current implementation of ScrollMessenger, the `gasLimit` is simply included in the L2 event log // and does not impose any restrictions on the L1 gas limit. However, considering the possibility of // future implementation changes, we will specify a maximum value. uint256 gasLimit = type(uint256).max; l2ScrollMessenger.sendMessage{value: value}( liquidity, value, message, gasLimit, _msgSender() ); } function _isDirectWithdrawalToken( uint32 tokenIndex ) private view returns (bool) { return directWithdrawalTokenIndices.contains(tokenIndex); } function _validateWithdrawalProof( ChainedWithdrawalLib.ChainedWithdrawal[] calldata withdrawals, WithdrawalProofPublicInputsLib.WithdrawalProofPublicInputs calldata publicInputs, bytes calldata proof ) private view { if ( !withdrawals.verifyWithdrawalChain(publicInputs.lastWithdrawalHash) ) { revert WithdrawalChainVerificationFailed(); } if (publicInputs.withdrawalAggregator != _msgSender()) { revert WithdrawalAggregatorMismatch(); } if (!withdrawalVerifier.Verify(proof, publicInputs.getHash().split())) { revert WithdrawalProofVerificationFailed(); } } function getDirectWithdrawalTokenIndices() external view returns (uint256[] memory) { return directWithdrawalTokenIndices.values(); } function addDirectWithdrawalTokenIndices( uint256[] calldata tokenIndices ) external onlyOwner { innerAddDirectWithdrawalTokenIndices(tokenIndices); } function innerAddDirectWithdrawalTokenIndices( uint256[] memory tokenIndices ) private { for (uint256 i = 0; i < tokenIndices.length; i++) { bool result = directWithdrawalTokenIndices.add(tokenIndices[i]); if (!result) { revert TokenAlreadyExist(tokenIndices[i]); } } emit DirectWithdrawalTokenIndicesAdded(tokenIndices); } function removeDirectWithdrawalTokenIndices( uint256[] calldata tokenIndices ) external onlyOwner { for (uint256 i = 0; i < tokenIndices.length; i++) { bool result = directWithdrawalTokenIndices.remove(tokenIndices[i]); if (!result) { revert TokenNotExist(tokenIndices[i]); } } emit DirectWithdrawalTokenIndicesRemoved(tokenIndices); } function _authorizeUpgrade(address) internal override onlyOwner {} }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol) pragma solidity ^0.8.20; import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol"; import {Initializable} from "../proxy/utils/Initializable.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 OwnableUpgradeable is Initializable, ContextUpgradeable { /// @custom:storage-location erc7201:openzeppelin.storage.Ownable struct OwnableStorage { address _owner; } // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Ownable")) - 1)) & ~bytes32(uint256(0xff)) bytes32 private constant OwnableStorageLocation = 0x9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300; function _getOwnableStorage() private pure returns (OwnableStorage storage $) { assembly { $.slot := OwnableStorageLocation } } /** * @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. */ function __Ownable_init(address initialOwner) internal onlyInitializing { __Ownable_init_unchained(initialOwner); } function __Ownable_init_unchained(address initialOwner) internal onlyInitializing { 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) { OwnableStorage storage $ = _getOwnableStorage(); 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 { OwnableStorage storage $ = _getOwnableStorage(); address oldOwner = $._owner; $._owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.20; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in * case an upgrade adds a module that needs to be initialized. * * For example: * * [.hljs-theme-light.nopadding] * ```solidity * contract MyToken is ERC20Upgradeable { * function initialize() initializer public { * __ERC20_init("MyToken", "MTK"); * } * } * * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable { * function initializeV2() reinitializer(2) public { * __ERC20Permit_init("MyToken"); * } * } * ``` * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() { * _disableInitializers(); * } * ``` * ==== */ abstract contract Initializable { /** * @dev Storage of the initializable contract. * * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions * when using with upgradeable contracts. * * @custom:storage-location erc7201:openzeppelin.storage.Initializable */ struct InitializableStorage { /** * @dev Indicates that the contract has been initialized. */ uint64 _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool _initializing; } // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff)) bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00; /** * @dev The contract is already initialized. */ error InvalidInitialization(); /** * @dev The contract is not initializing. */ error NotInitializing(); /** * @dev Triggered when the contract has been initialized or reinitialized. */ event Initialized(uint64 version); /** * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope, * `onlyInitializing` functions can be used to initialize parent contracts. * * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in * production. * * Emits an {Initialized} event. */ modifier initializer() { // solhint-disable-next-line var-name-mixedcase InitializableStorage storage $ = _getInitializableStorage(); // Cache values to avoid duplicated sloads bool isTopLevelCall = !$._initializing; uint64 initialized = $._initialized; // Allowed calls: // - initialSetup: the contract is not in the initializing state and no previous version was // initialized // - construction: the contract is initialized at version 1 (no reininitialization) and the // current contract is just being deployed bool initialSetup = initialized == 0 && isTopLevelCall; bool construction = initialized == 1 && address(this).code.length == 0; if (!initialSetup && !construction) { revert InvalidInitialization(); } $._initialized = 1; if (isTopLevelCall) { $._initializing = true; } _; if (isTopLevelCall) { $._initializing = false; emit Initialized(1); } } /** * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be * used to initialize parent contracts. * * A reinitializer may be used after the original initialization step. This is essential to configure modules that * are added through upgrades and that require initialization. * * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer` * cannot be nested. If one is invoked in the context of another, execution will revert. * * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in * a contract, executing them in the right order is up to the developer or operator. * * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization. * * Emits an {Initialized} event. */ modifier reinitializer(uint64 version) { // solhint-disable-next-line var-name-mixedcase InitializableStorage storage $ = _getInitializableStorage(); if ($._initializing || $._initialized >= version) { revert InvalidInitialization(); } $._initialized = version; $._initializing = true; _; $._initializing = false; emit Initialized(version); } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} and {reinitializer} modifiers, directly or indirectly. */ modifier onlyInitializing() { _checkInitializing(); _; } /** * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}. */ function _checkInitializing() internal view virtual { if (!_isInitializing()) { revert NotInitializing(); } } /** * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call. * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized * to any version. It is recommended to use this to lock implementation contracts that are designed to be called * through proxies. * * Emits an {Initialized} event the first time it is successfully executed. */ function _disableInitializers() internal virtual { // solhint-disable-next-line var-name-mixedcase InitializableStorage storage $ = _getInitializableStorage(); if ($._initializing) { revert InvalidInitialization(); } if ($._initialized != type(uint64).max) { $._initialized = type(uint64).max; emit Initialized(type(uint64).max); } } /** * @dev Returns the highest version that has been initialized. See {reinitializer}. */ function _getInitializedVersion() internal view returns (uint64) { return _getInitializableStorage()._initialized; } /** * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}. */ function _isInitializing() internal view returns (bool) { return _getInitializableStorage()._initializing; } /** * @dev Returns a pointer to the storage namespace. */ // solhint-disable-next-line var-name-mixedcase function _getInitializableStorage() private pure returns (InitializableStorage storage $) { assembly { $.slot := INITIALIZABLE_STORAGE } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (proxy/utils/UUPSUpgradeable.sol) pragma solidity ^0.8.20; import {IERC1822Proxiable} from "@openzeppelin/contracts/interfaces/draft-IERC1822.sol"; import {ERC1967Utils} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol"; import {Initializable} from "./Initializable.sol"; /** * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy. * * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing * `UUPSUpgradeable` with a custom implementation of upgrades. * * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism. */ abstract contract UUPSUpgradeable is Initializable, IERC1822Proxiable { /// @custom:oz-upgrades-unsafe-allow state-variable-immutable address private immutable __self = address(this); /** * @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)` * and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called, * while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string. * If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must * be the empty byte string if no function should be called, making it impossible to invoke the `receive` function * during an upgrade. */ string public constant UPGRADE_INTERFACE_VERSION = "5.0.0"; /** * @dev The call is from an unauthorized context. */ error UUPSUnauthorizedCallContext(); /** * @dev The storage `slot` is unsupported as a UUID. */ error UUPSUnsupportedProxiableUUID(bytes32 slot); /** * @dev Check that the execution is being performed through a delegatecall call and that the execution context is * a proxy contract with an implementation (as defined in ERC-1967) pointing to self. This should only be the case * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a * function through ERC-1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to * fail. */ modifier onlyProxy() { _checkProxy(); _; } /** * @dev Check that the execution is not being performed through a delegate call. This allows a function to be * callable on the implementing contract but not through proxies. */ modifier notDelegated() { _checkNotDelegated(); _; } function __UUPSUpgradeable_init() internal onlyInitializing { } function __UUPSUpgradeable_init_unchained() internal onlyInitializing { } /** * @dev Implementation of the ERC-1822 {proxiableUUID} function. This returns the storage slot used by the * implementation. It is used to validate the implementation's compatibility when performing an upgrade. * * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier. */ function proxiableUUID() external view virtual notDelegated returns (bytes32) { return ERC1967Utils.IMPLEMENTATION_SLOT; } /** * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call * encoded in `data`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. * * @custom:oz-upgrades-unsafe-allow-reachable delegatecall */ function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallUUPS(newImplementation, data); } /** * @dev Reverts if the execution is not performed via delegatecall or the execution * context is not of a proxy with an ERC-1967 compliant implementation pointing to self. * See {_onlyProxy}. */ function _checkProxy() internal view virtual { if ( address(this) == __self || // Must be called through delegatecall ERC1967Utils.getImplementation() != __self // Must be called through an active proxy ) { revert UUPSUnauthorizedCallContext(); } } /** * @dev Reverts if the execution is performed via delegatecall. * See {notDelegated}. */ function _checkNotDelegated() internal view virtual { if (address(this) != __self) { // Must not be called through delegatecall revert UUPSUnauthorizedCallContext(); } } /** * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by * {upgradeToAndCall}. * * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}. * * ```solidity * function _authorizeUpgrade(address) internal onlyOwner {} * ``` */ function _authorizeUpgrade(address newImplementation) internal virtual; /** * @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call. * * As a security check, {proxiableUUID} is invoked in the new implementation, and the return value * is expected to be the implementation slot in ERC-1967. * * Emits an {IERC1967-Upgraded} event. */ function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private { try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) { if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) { revert UUPSUnsupportedProxiableUUID(slot); } ERC1967Utils.upgradeToAndCall(newImplementation, data); } catch { // The implementation is not UUPS revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol) pragma solidity ^0.8.20; import {Initializable} from "../proxy/utils/Initializable.sol"; /** * @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 ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } 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) (interfaces/draft-IERC1822.sol) pragma solidity ^0.8.20; /** * @dev ERC-1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified * proxy whose upgrades are fully controlled by the current implementation. */ interface IERC1822Proxiable { /** * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation * address. * * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this * function revert if invoked through a proxy. */ function proxiableUUID() external view returns (bytes32); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC1967.sol) pragma solidity ^0.8.20; /** * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC. */ interface IERC1967 { /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Emitted when the beacon is changed. */ event BeaconUpgraded(address indexed beacon); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/IBeacon.sol) pragma solidity ^0.8.20; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeacon { /** * @dev Must return an address that can be used as a delegate call target. * * {UpgradeableBeacon} will check that this address is a contract. */ function implementation() external view returns (address); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (proxy/ERC1967/ERC1967Utils.sol) pragma solidity ^0.8.21; import {IBeacon} from "../beacon/IBeacon.sol"; import {IERC1967} from "../../interfaces/IERC1967.sol"; import {Address} from "../../utils/Address.sol"; import {StorageSlot} from "../../utils/StorageSlot.sol"; /** * @dev This library provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots. */ library ERC1967Utils { /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1. */ // solhint-disable-next-line private-vars-leading-underscore bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev The `implementation` of the proxy is invalid. */ error ERC1967InvalidImplementation(address implementation); /** * @dev The `admin` of the proxy is invalid. */ error ERC1967InvalidAdmin(address admin); /** * @dev The `beacon` of the proxy is invalid. */ error ERC1967InvalidBeacon(address beacon); /** * @dev An upgrade function sees `msg.value > 0` that may be lost. */ error ERC1967NonPayable(); /** * @dev Returns the current implementation address. */ function getImplementation() internal view returns (address) { return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the ERC-1967 implementation slot. */ function _setImplementation(address newImplementation) private { if (newImplementation.code.length == 0) { revert ERC1967InvalidImplementation(newImplementation); } StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Performs implementation upgrade with additional setup call if data is nonempty. * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected * to avoid stuck value in the contract. * * Emits an {IERC1967-Upgraded} event. */ function upgradeToAndCall(address newImplementation, bytes memory data) internal { _setImplementation(newImplementation); emit IERC1967.Upgraded(newImplementation); if (data.length > 0) { Address.functionDelegateCall(newImplementation, data); } else { _checkNonPayable(); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1. */ // solhint-disable-next-line private-vars-leading-underscore bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Returns the current admin. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103` */ function getAdmin() internal view returns (address) { return StorageSlot.getAddressSlot(ADMIN_SLOT).value; } /** * @dev Stores a new address in the ERC-1967 admin slot. */ function _setAdmin(address newAdmin) private { if (newAdmin == address(0)) { revert ERC1967InvalidAdmin(address(0)); } StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {IERC1967-AdminChanged} event. */ function changeAdmin(address newAdmin) internal { emit IERC1967.AdminChanged(getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1. */ // solhint-disable-next-line private-vars-leading-underscore bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Returns the current beacon. */ function getBeacon() internal view returns (address) { return StorageSlot.getAddressSlot(BEACON_SLOT).value; } /** * @dev Stores a new beacon in the ERC-1967 beacon slot. */ function _setBeacon(address newBeacon) private { if (newBeacon.code.length == 0) { revert ERC1967InvalidBeacon(newBeacon); } StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon; address beaconImplementation = IBeacon(newBeacon).implementation(); if (beaconImplementation.code.length == 0) { revert ERC1967InvalidImplementation(beaconImplementation); } } /** * @dev Change the beacon and trigger a setup call if data is nonempty. * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected * to avoid stuck value in the contract. * * Emits an {IERC1967-BeaconUpgraded} event. * * CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since * it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for * efficiency. */ function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal { _setBeacon(newBeacon); emit IERC1967.BeaconUpgraded(newBeacon); if (data.length > 0) { Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data); } else { _checkNonPayable(); } } /** * @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract * if an upgrade doesn't perform an initialization call. */ function _checkNonPayable() private { if (msg.value > 0) { revert ERC1967NonPayable(); } } }
// 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/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/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/structs/EnumerableSet.sol) // This file was procedurally generated from scripts/generate/templates/EnumerableSet.js. pragma solidity ^0.8.20; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ```solidity * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. * * [WARNING] * ==== * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure * unusable. * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info. * * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an * array of EnumerableSet. * ==== */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position is the index of the value in the `values` array plus 1. // Position 0 is used to mean a value is not in the set. mapping(bytes32 value => uint256) _positions; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._positions[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We cache the value's position to prevent multiple reads from the same storage slot uint256 position = set._positions[value]; if (position != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 valueIndex = position - 1; uint256 lastIndex = set._values.length - 1; if (valueIndex != lastIndex) { bytes32 lastValue = set._values[lastIndex]; // Move the lastValue to the index where the value to delete is set._values[valueIndex] = lastValue; // Update the tracked position of the lastValue (that was just moved) set._positions[lastValue] = position; } // Delete the slot where the moved value was stored set._values.pop(); // Delete the tracked position for the deleted slot delete set._positions[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._positions[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { bytes32[] memory store = _values(set._inner); bytes32[] memory result; assembly ("memory-safe") { result := store } return result; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly ("memory-safe") { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values in the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly ("memory-safe") { result := store } return result; } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; // Common.sol // // Common mathematical functions used in both SD59x18 and UD60x18. Note that these global functions do not // always operate with SD59x18 and UD60x18 numbers. /*////////////////////////////////////////////////////////////////////////// CUSTOM ERRORS //////////////////////////////////////////////////////////////////////////*/ /// @notice Thrown when the resultant value in {mulDiv} overflows uint256. error PRBMath_MulDiv_Overflow(uint256 x, uint256 y, uint256 denominator); /// @notice Thrown when the resultant value in {mulDiv18} overflows uint256. error PRBMath_MulDiv18_Overflow(uint256 x, uint256 y); /// @notice Thrown when one of the inputs passed to {mulDivSigned} is `type(int256).min`. error PRBMath_MulDivSigned_InputTooSmall(); /// @notice Thrown when the resultant value in {mulDivSigned} overflows int256. error PRBMath_MulDivSigned_Overflow(int256 x, int256 y); /*////////////////////////////////////////////////////////////////////////// CONSTANTS //////////////////////////////////////////////////////////////////////////*/ /// @dev The maximum value a uint128 number can have. uint128 constant MAX_UINT128 = type(uint128).max; /// @dev The maximum value a uint40 number can have. uint40 constant MAX_UINT40 = type(uint40).max; /// @dev The maximum value a uint64 number can have. uint64 constant MAX_UINT64 = type(uint64).max; /// @dev The unit number, which the decimal precision of the fixed-point types. uint256 constant UNIT = 1e18; /// @dev The unit number inverted mod 2^256. uint256 constant UNIT_INVERSE = 78156646155174841979727994598816262306175212592076161876661_508869554232690281; /// @dev The the largest power of two that divides the decimal value of `UNIT`. The logarithm of this value is the least significant /// bit in the binary representation of `UNIT`. uint256 constant UNIT_LPOTD = 262144; /*////////////////////////////////////////////////////////////////////////// FUNCTIONS //////////////////////////////////////////////////////////////////////////*/ /// @notice Calculates the binary exponent of x using the binary fraction method. /// @dev Has to use 192.64-bit fixed-point numbers. See https://ethereum.stackexchange.com/a/96594/24693. /// @param x The exponent as an unsigned 192.64-bit fixed-point number. /// @return result The result as an unsigned 60.18-decimal fixed-point number. /// @custom:smtchecker abstract-function-nondet function exp2(uint256 x) pure returns (uint256 result) { unchecked { // Start from 0.5 in the 192.64-bit fixed-point format. result = 0x800000000000000000000000000000000000000000000000; // The following logic multiplies the result by $\sqrt{2^{-i}}$ when the bit at position i is 1. Key points: // // 1. Intermediate results will not overflow, as the starting point is 2^191 and all magic factors are under 2^65. // 2. The rationale for organizing the if statements into groups of 8 is gas savings. If the result of performing // a bitwise AND operation between x and any value in the array [0x80; 0x40; 0x20; 0x10; 0x08; 0x04; 0x02; 0x01] is 1, // we know that `x & 0xFF` is also 1. if (x & 0xFF00000000000000 > 0) { if (x & 0x8000000000000000 > 0) { result = (result * 0x16A09E667F3BCC909) >> 64; } if (x & 0x4000000000000000 > 0) { result = (result * 0x1306FE0A31B7152DF) >> 64; } if (x & 0x2000000000000000 > 0) { result = (result * 0x1172B83C7D517ADCE) >> 64; } if (x & 0x1000000000000000 > 0) { result = (result * 0x10B5586CF9890F62A) >> 64; } if (x & 0x800000000000000 > 0) { result = (result * 0x1059B0D31585743AE) >> 64; } if (x & 0x400000000000000 > 0) { result = (result * 0x102C9A3E778060EE7) >> 64; } if (x & 0x200000000000000 > 0) { result = (result * 0x10163DA9FB33356D8) >> 64; } if (x & 0x100000000000000 > 0) { result = (result * 0x100B1AFA5ABCBED61) >> 64; } } if (x & 0xFF000000000000 > 0) { if (x & 0x80000000000000 > 0) { result = (result * 0x10058C86DA1C09EA2) >> 64; } if (x & 0x40000000000000 > 0) { result = (result * 0x1002C605E2E8CEC50) >> 64; } if (x & 0x20000000000000 > 0) { result = (result * 0x100162F3904051FA1) >> 64; } if (x & 0x10000000000000 > 0) { result = (result * 0x1000B175EFFDC76BA) >> 64; } if (x & 0x8000000000000 > 0) { result = (result * 0x100058BA01FB9F96D) >> 64; } if (x & 0x4000000000000 > 0) { result = (result * 0x10002C5CC37DA9492) >> 64; } if (x & 0x2000000000000 > 0) { result = (result * 0x1000162E525EE0547) >> 64; } if (x & 0x1000000000000 > 0) { result = (result * 0x10000B17255775C04) >> 64; } } if (x & 0xFF0000000000 > 0) { if (x & 0x800000000000 > 0) { result = (result * 0x1000058B91B5BC9AE) >> 64; } if (x & 0x400000000000 > 0) { result = (result * 0x100002C5C89D5EC6D) >> 64; } if (x & 0x200000000000 > 0) { result = (result * 0x10000162E43F4F831) >> 64; } if (x & 0x100000000000 > 0) { result = (result * 0x100000B1721BCFC9A) >> 64; } if (x & 0x80000000000 > 0) { result = (result * 0x10000058B90CF1E6E) >> 64; } if (x & 0x40000000000 > 0) { result = (result * 0x1000002C5C863B73F) >> 64; } if (x & 0x20000000000 > 0) { result = (result * 0x100000162E430E5A2) >> 64; } if (x & 0x10000000000 > 0) { result = (result * 0x1000000B172183551) >> 64; } } if (x & 0xFF00000000 > 0) { if (x & 0x8000000000 > 0) { result = (result * 0x100000058B90C0B49) >> 64; } if (x & 0x4000000000 > 0) { result = (result * 0x10000002C5C8601CC) >> 64; } if (x & 0x2000000000 > 0) { result = (result * 0x1000000162E42FFF0) >> 64; } if (x & 0x1000000000 > 0) { result = (result * 0x10000000B17217FBB) >> 64; } if (x & 0x800000000 > 0) { result = (result * 0x1000000058B90BFCE) >> 64; } if (x & 0x400000000 > 0) { result = (result * 0x100000002C5C85FE3) >> 64; } if (x & 0x200000000 > 0) { result = (result * 0x10000000162E42FF1) >> 64; } if (x & 0x100000000 > 0) { result = (result * 0x100000000B17217F8) >> 64; } } if (x & 0xFF000000 > 0) { if (x & 0x80000000 > 0) { result = (result * 0x10000000058B90BFC) >> 64; } if (x & 0x40000000 > 0) { result = (result * 0x1000000002C5C85FE) >> 64; } if (x & 0x20000000 > 0) { result = (result * 0x100000000162E42FF) >> 64; } if (x & 0x10000000 > 0) { result = (result * 0x1000000000B17217F) >> 64; } if (x & 0x8000000 > 0) { result = (result * 0x100000000058B90C0) >> 64; } if (x & 0x4000000 > 0) { result = (result * 0x10000000002C5C860) >> 64; } if (x & 0x2000000 > 0) { result = (result * 0x1000000000162E430) >> 64; } if (x & 0x1000000 > 0) { result = (result * 0x10000000000B17218) >> 64; } } if (x & 0xFF0000 > 0) { if (x & 0x800000 > 0) { result = (result * 0x1000000000058B90C) >> 64; } if (x & 0x400000 > 0) { result = (result * 0x100000000002C5C86) >> 64; } if (x & 0x200000 > 0) { result = (result * 0x10000000000162E43) >> 64; } if (x & 0x100000 > 0) { result = (result * 0x100000000000B1721) >> 64; } if (x & 0x80000 > 0) { result = (result * 0x10000000000058B91) >> 64; } if (x & 0x40000 > 0) { result = (result * 0x1000000000002C5C8) >> 64; } if (x & 0x20000 > 0) { result = (result * 0x100000000000162E4) >> 64; } if (x & 0x10000 > 0) { result = (result * 0x1000000000000B172) >> 64; } } if (x & 0xFF00 > 0) { if (x & 0x8000 > 0) { result = (result * 0x100000000000058B9) >> 64; } if (x & 0x4000 > 0) { result = (result * 0x10000000000002C5D) >> 64; } if (x & 0x2000 > 0) { result = (result * 0x1000000000000162E) >> 64; } if (x & 0x1000 > 0) { result = (result * 0x10000000000000B17) >> 64; } if (x & 0x800 > 0) { result = (result * 0x1000000000000058C) >> 64; } if (x & 0x400 > 0) { result = (result * 0x100000000000002C6) >> 64; } if (x & 0x200 > 0) { result = (result * 0x10000000000000163) >> 64; } if (x & 0x100 > 0) { result = (result * 0x100000000000000B1) >> 64; } } if (x & 0xFF > 0) { if (x & 0x80 > 0) { result = (result * 0x10000000000000059) >> 64; } if (x & 0x40 > 0) { result = (result * 0x1000000000000002C) >> 64; } if (x & 0x20 > 0) { result = (result * 0x10000000000000016) >> 64; } if (x & 0x10 > 0) { result = (result * 0x1000000000000000B) >> 64; } if (x & 0x8 > 0) { result = (result * 0x10000000000000006) >> 64; } if (x & 0x4 > 0) { result = (result * 0x10000000000000003) >> 64; } if (x & 0x2 > 0) { result = (result * 0x10000000000000001) >> 64; } if (x & 0x1 > 0) { result = (result * 0x10000000000000001) >> 64; } } // In the code snippet below, two operations are executed simultaneously: // // 1. The result is multiplied by $(2^n + 1)$, where $2^n$ represents the integer part, and the additional 1 // accounts for the initial guess of 0.5. This is achieved by subtracting from 191 instead of 192. // 2. The result is then converted to an unsigned 60.18-decimal fixed-point format. // // The underlying logic is based on the relationship $2^{191-ip} = 2^{ip} / 2^{191}$, where $ip$ denotes the, // integer part, $2^n$. result *= UNIT; result >>= (191 - (x >> 64)); } } /// @notice Finds the zero-based index of the first 1 in the binary representation of x. /// /// @dev See the note on "msb" in this Wikipedia article: https://en.wikipedia.org/wiki/Find_first_set /// /// Each step in this implementation is equivalent to this high-level code: /// /// ```solidity /// if (x >= 2 ** 128) { /// x >>= 128; /// result += 128; /// } /// ``` /// /// Where 128 is replaced with each respective power of two factor. See the full high-level implementation here: /// https://gist.github.com/PaulRBerg/f932f8693f2733e30c4d479e8e980948 /// /// The Yul instructions used below are: /// /// - "gt" is "greater than" /// - "or" is the OR bitwise operator /// - "shl" is "shift left" /// - "shr" is "shift right" /// /// @param x The uint256 number for which to find the index of the most significant bit. /// @return result The index of the most significant bit as a uint256. /// @custom:smtchecker abstract-function-nondet function msb(uint256 x) pure returns (uint256 result) { // 2^128 assembly ("memory-safe") { let factor := shl(7, gt(x, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) x := shr(factor, x) result := or(result, factor) } // 2^64 assembly ("memory-safe") { let factor := shl(6, gt(x, 0xFFFFFFFFFFFFFFFF)) x := shr(factor, x) result := or(result, factor) } // 2^32 assembly ("memory-safe") { let factor := shl(5, gt(x, 0xFFFFFFFF)) x := shr(factor, x) result := or(result, factor) } // 2^16 assembly ("memory-safe") { let factor := shl(4, gt(x, 0xFFFF)) x := shr(factor, x) result := or(result, factor) } // 2^8 assembly ("memory-safe") { let factor := shl(3, gt(x, 0xFF)) x := shr(factor, x) result := or(result, factor) } // 2^4 assembly ("memory-safe") { let factor := shl(2, gt(x, 0xF)) x := shr(factor, x) result := or(result, factor) } // 2^2 assembly ("memory-safe") { let factor := shl(1, gt(x, 0x3)) x := shr(factor, x) result := or(result, factor) } // 2^1 // No need to shift x any more. assembly ("memory-safe") { let factor := gt(x, 0x1) result := or(result, factor) } } /// @notice Calculates x*y÷denominator with 512-bit precision. /// /// @dev Credits to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv. /// /// Notes: /// - The result is rounded toward zero. /// /// Requirements: /// - The denominator must not be zero. /// - The result must fit in uint256. /// /// @param x The multiplicand as a uint256. /// @param y The multiplier as a uint256. /// @param denominator The divisor as a uint256. /// @return result The result as a uint256. /// @custom:smtchecker abstract-function-nondet function mulDiv(uint256 x, uint256 y, uint256 denominator) pure returns (uint256 result) { // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use // use the Chinese Remainder Theorem to reconstruct the 512-bit result. The result is stored in two 256 // variables such that product = prod1 * 2^256 + prod0. uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly ("memory-safe") { let mm := mulmod(x, y, not(0)) prod0 := mul(x, y) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division. if (prod1 == 0) { unchecked { return prod0 / denominator; } } // Make sure the result is less than 2^256. Also prevents denominator == 0. if (prod1 >= denominator) { revert PRBMath_MulDiv_Overflow(x, y, denominator); } //////////////////////////////////////////////////////////////////////////// // 512 by 256 division //////////////////////////////////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0]. uint256 remainder; assembly ("memory-safe") { // Compute remainder using the mulmod Yul instruction. remainder := mulmod(x, y, denominator) // Subtract 256 bit number from 512-bit number. prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } unchecked { // Calculate the largest power of two divisor of the denominator using the unary operator ~. This operation cannot overflow // because the denominator cannot be zero at this point in the function execution. The result is always >= 1. // For more detail, see https://cs.stackexchange.com/q/138556/92363. uint256 lpotdod = denominator & (~denominator + 1); uint256 flippedLpotdod; assembly ("memory-safe") { // Factor powers of two out of denominator. denominator := div(denominator, lpotdod) // Divide [prod1 prod0] by lpotdod. prod0 := div(prod0, lpotdod) // Get the flipped value `2^256 / lpotdod`. If the `lpotdod` is zero, the flipped value is one. // `sub(0, lpotdod)` produces the two's complement version of `lpotdod`, which is equivalent to flipping all the bits. // However, `div` interprets this value as an unsigned value: https://ethereum.stackexchange.com/q/147168/24693 flippedLpotdod := add(div(sub(0, lpotdod), lpotdod), 1) } // Shift in bits from prod1 into prod0. prod0 |= prod1 * flippedLpotdod; // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for // four bits. That is, denominator * inv = 1 mod 2^4. uint256 inverse = (3 * denominator) ^ 2; // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works // in modular arithmetic, doubling the correct bits in each step. inverse *= 2 - denominator * inverse; // inverse mod 2^8 inverse *= 2 - denominator * inverse; // inverse mod 2^16 inverse *= 2 - denominator * inverse; // inverse mod 2^32 inverse *= 2 - denominator * inverse; // inverse mod 2^64 inverse *= 2 - denominator * inverse; // inverse mod 2^128 inverse *= 2 - denominator * inverse; // inverse mod 2^256 // Because the division is now exact we can divide by multiplying with the modular inverse of denominator. // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inverse; } } /// @notice Calculates x*y÷1e18 with 512-bit precision. /// /// @dev A variant of {mulDiv} with constant folding, i.e. in which the denominator is hard coded to 1e18. /// /// Notes: /// - The body is purposely left uncommented; to understand how this works, see the documentation in {mulDiv}. /// - The result is rounded toward zero. /// - We take as an axiom that the result cannot be `MAX_UINT256` when x and y solve the following system of equations: /// /// $$ /// \begin{cases} /// x * y = MAX\_UINT256 * UNIT \\ /// (x * y) \% UNIT \geq \frac{UNIT}{2} /// \end{cases} /// $$ /// /// Requirements: /// - Refer to the requirements in {mulDiv}. /// - The result must fit in uint256. /// /// @param x The multiplicand as an unsigned 60.18-decimal fixed-point number. /// @param y The multiplier as an unsigned 60.18-decimal fixed-point number. /// @return result The result as an unsigned 60.18-decimal fixed-point number. /// @custom:smtchecker abstract-function-nondet function mulDiv18(uint256 x, uint256 y) pure returns (uint256 result) { uint256 prod0; uint256 prod1; assembly ("memory-safe") { let mm := mulmod(x, y, not(0)) prod0 := mul(x, y) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } if (prod1 == 0) { unchecked { return prod0 / UNIT; } } if (prod1 >= UNIT) { revert PRBMath_MulDiv18_Overflow(x, y); } uint256 remainder; assembly ("memory-safe") { remainder := mulmod(x, y, UNIT) result := mul( or( div(sub(prod0, remainder), UNIT_LPOTD), mul(sub(prod1, gt(remainder, prod0)), add(div(sub(0, UNIT_LPOTD), UNIT_LPOTD), 1)) ), UNIT_INVERSE ) } } /// @notice Calculates x*y÷denominator with 512-bit precision. /// /// @dev This is an extension of {mulDiv} for signed numbers, which works by computing the signs and the absolute values separately. /// /// Notes: /// - The result is rounded toward zero. /// /// Requirements: /// - Refer to the requirements in {mulDiv}. /// - None of the inputs can be `type(int256).min`. /// - The result must fit in int256. /// /// @param x The multiplicand as an int256. /// @param y The multiplier as an int256. /// @param denominator The divisor as an int256. /// @return result The result as an int256. /// @custom:smtchecker abstract-function-nondet function mulDivSigned(int256 x, int256 y, int256 denominator) pure returns (int256 result) { if (x == type(int256).min || y == type(int256).min || denominator == type(int256).min) { revert PRBMath_MulDivSigned_InputTooSmall(); } // Get hold of the absolute values of x, y and the denominator. uint256 xAbs; uint256 yAbs; uint256 dAbs; unchecked { xAbs = x < 0 ? uint256(-x) : uint256(x); yAbs = y < 0 ? uint256(-y) : uint256(y); dAbs = denominator < 0 ? uint256(-denominator) : uint256(denominator); } // Compute the absolute value of x*y÷denominator. The result must fit in int256. uint256 resultAbs = mulDiv(xAbs, yAbs, dAbs); if (resultAbs > uint256(type(int256).max)) { revert PRBMath_MulDivSigned_Overflow(x, y); } // Get the signs of x, y and the denominator. uint256 sx; uint256 sy; uint256 sd; assembly ("memory-safe") { // "sgt" is the "signed greater than" assembly instruction and "sub(0,1)" is -1 in two's complement. sx := sgt(x, sub(0, 1)) sy := sgt(y, sub(0, 1)) sd := sgt(denominator, sub(0, 1)) } // XOR over sx, sy and sd. What this does is to check whether there are 1 or 3 negative signs in the inputs. // If there are, the result should be negative. Otherwise, it should be positive. unchecked { result = sx ^ sy ^ sd == 0 ? -int256(resultAbs) : int256(resultAbs); } } /// @notice Calculates the square root of x using the Babylonian method. /// /// @dev See https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method. /// /// Notes: /// - If x is not a perfect square, the result is rounded down. /// - Credits to OpenZeppelin for the explanations in comments below. /// /// @param x The uint256 number for which to calculate the square root. /// @return result The result as a uint256. /// @custom:smtchecker abstract-function-nondet function sqrt(uint256 x) pure returns (uint256 result) { if (x == 0) { return 0; } // For our first guess, we calculate the biggest power of 2 which is smaller than the square root of x. // // We know that the "msb" (most significant bit) of x is a power of 2 such that we have: // // $$ // msb(x) <= x <= 2*msb(x)$ // $$ // // We write $msb(x)$ as $2^k$, and we get: // // $$ // k = log_2(x) // $$ // // Thus, we can write the initial inequality as: // // $$ // 2^{log_2(x)} <= x <= 2*2^{log_2(x)+1} \\ // sqrt(2^k) <= sqrt(x) < sqrt(2^{k+1}) \\ // 2^{k/2} <= sqrt(x) < 2^{(k+1)/2} <= 2^{(k/2)+1} // $$ // // Consequently, $2^{log_2(x) /2} is a good first approximation of sqrt(x) with at least one correct bit. uint256 xAux = uint256(x); result = 1; if (xAux >= 2 ** 128) { xAux >>= 128; result <<= 64; } if (xAux >= 2 ** 64) { xAux >>= 64; result <<= 32; } if (xAux >= 2 ** 32) { xAux >>= 32; result <<= 16; } if (xAux >= 2 ** 16) { xAux >>= 16; result <<= 8; } if (xAux >= 2 ** 8) { xAux >>= 8; result <<= 4; } if (xAux >= 2 ** 4) { xAux >>= 4; result <<= 2; } if (xAux >= 2 ** 2) { result <<= 1; } // At this point, `result` is an estimation with at least one bit of precision. We know the true value has at // most 128 bits, since it is the square root of a uint256. Newton's method converges quadratically (precision // doubles at every iteration). We thus need at most 7 iteration to turn our partial result with one bit of // precision into the expected uint128 result. unchecked { result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; // If x is not a perfect square, round the result toward zero. uint256 roundedResult = x / result; if (result >= roundedResult) { result = roundedResult; } } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; import "../Common.sol" as Common; import "./Errors.sol" as CastingErrors; import { SD59x18 } from "../sd59x18/ValueType.sol"; import { UD60x18 } from "../ud60x18/ValueType.sol"; import { SD1x18 } from "./ValueType.sol"; /// @notice Casts an SD1x18 number into SD59x18. /// @dev There is no overflow check because SD1x18 ⊆ SD59x18. function intoSD59x18(SD1x18 x) pure returns (SD59x18 result) { result = SD59x18.wrap(int256(SD1x18.unwrap(x))); } /// @notice Casts an SD1x18 number into UD60x18. /// @dev Requirements: /// - x ≥ 0 function intoUD60x18(SD1x18 x) pure returns (UD60x18 result) { int64 xInt = SD1x18.unwrap(x); if (xInt < 0) { revert CastingErrors.PRBMath_SD1x18_ToUD60x18_Underflow(x); } result = UD60x18.wrap(uint64(xInt)); } /// @notice Casts an SD1x18 number into uint128. /// @dev Requirements: /// - x ≥ 0 function intoUint128(SD1x18 x) pure returns (uint128 result) { int64 xInt = SD1x18.unwrap(x); if (xInt < 0) { revert CastingErrors.PRBMath_SD1x18_ToUint128_Underflow(x); } result = uint128(uint64(xInt)); } /// @notice Casts an SD1x18 number into uint256. /// @dev Requirements: /// - x ≥ 0 function intoUint256(SD1x18 x) pure returns (uint256 result) { int64 xInt = SD1x18.unwrap(x); if (xInt < 0) { revert CastingErrors.PRBMath_SD1x18_ToUint256_Underflow(x); } result = uint256(uint64(xInt)); } /// @notice Casts an SD1x18 number into uint40. /// @dev Requirements: /// - x ≥ 0 /// - x ≤ MAX_UINT40 function intoUint40(SD1x18 x) pure returns (uint40 result) { int64 xInt = SD1x18.unwrap(x); if (xInt < 0) { revert CastingErrors.PRBMath_SD1x18_ToUint40_Underflow(x); } if (xInt > int64(uint64(Common.MAX_UINT40))) { revert CastingErrors.PRBMath_SD1x18_ToUint40_Overflow(x); } result = uint40(uint64(xInt)); } /// @notice Alias for {wrap}. function sd1x18(int64 x) pure returns (SD1x18 result) { result = SD1x18.wrap(x); } /// @notice Unwraps an SD1x18 number into int64. function unwrap(SD1x18 x) pure returns (int64 result) { result = SD1x18.unwrap(x); } /// @notice Wraps an int64 number into SD1x18. function wrap(int64 x) pure returns (SD1x18 result) { result = SD1x18.wrap(x); }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; import { SD1x18 } from "./ValueType.sol"; /// @dev Euler's number as an SD1x18 number. SD1x18 constant E = SD1x18.wrap(2_718281828459045235); /// @dev The maximum value an SD1x18 number can have. int64 constant uMAX_SD1x18 = 9_223372036854775807; SD1x18 constant MAX_SD1x18 = SD1x18.wrap(uMAX_SD1x18); /// @dev The minimum value an SD1x18 number can have. int64 constant uMIN_SD1x18 = -9_223372036854775808; SD1x18 constant MIN_SD1x18 = SD1x18.wrap(uMIN_SD1x18); /// @dev PI as an SD1x18 number. SD1x18 constant PI = SD1x18.wrap(3_141592653589793238); /// @dev The unit number, which gives the decimal precision of SD1x18. SD1x18 constant UNIT = SD1x18.wrap(1e18); int64 constant uUNIT = 1e18;
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; import { SD1x18 } from "./ValueType.sol"; /// @notice Thrown when trying to cast an SD1x18 number that doesn't fit in UD60x18. error PRBMath_SD1x18_ToUD60x18_Underflow(SD1x18 x); /// @notice Thrown when trying to cast an SD1x18 number that doesn't fit in uint128. error PRBMath_SD1x18_ToUint128_Underflow(SD1x18 x); /// @notice Thrown when trying to cast an SD1x18 number that doesn't fit in uint256. error PRBMath_SD1x18_ToUint256_Underflow(SD1x18 x); /// @notice Thrown when trying to cast an SD1x18 number that doesn't fit in uint40. error PRBMath_SD1x18_ToUint40_Overflow(SD1x18 x); /// @notice Thrown when trying to cast an SD1x18 number that doesn't fit in uint40. error PRBMath_SD1x18_ToUint40_Underflow(SD1x18 x);
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; import "./Casting.sol" as Casting; /// @notice The signed 1.18-decimal fixed-point number representation, which can have up to 1 digit and up to 18 /// decimals. The values of this are bound by the minimum and the maximum values permitted by the underlying Solidity /// type int64. This is useful when end users want to use int64 to save gas, e.g. with tight variable packing in contract /// storage. type SD1x18 is int64; /*////////////////////////////////////////////////////////////////////////// CASTING //////////////////////////////////////////////////////////////////////////*/ using { Casting.intoSD59x18, Casting.intoUD60x18, Casting.intoUint128, Casting.intoUint256, Casting.intoUint40, Casting.unwrap } for SD1x18 global;
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; import "../Common.sol" as Common; import "./Errors.sol" as CastingErrors; import { SD59x18 } from "../sd59x18/ValueType.sol"; import { UD60x18 } from "../ud60x18/ValueType.sol"; import { SD21x18 } from "./ValueType.sol"; /// @notice Casts an SD21x18 number into SD59x18. /// @dev There is no overflow check because SD21x18 ⊆ SD59x18. function intoSD59x18(SD21x18 x) pure returns (SD59x18 result) { result = SD59x18.wrap(int256(SD21x18.unwrap(x))); } /// @notice Casts an SD21x18 number into UD60x18. /// @dev Requirements: /// - x ≥ 0 function intoUD60x18(SD21x18 x) pure returns (UD60x18 result) { int128 xInt = SD21x18.unwrap(x); if (xInt < 0) { revert CastingErrors.PRBMath_SD21x18_ToUD60x18_Underflow(x); } result = UD60x18.wrap(uint128(xInt)); } /// @notice Casts an SD21x18 number into uint128. /// @dev Requirements: /// - x ≥ 0 function intoUint128(SD21x18 x) pure returns (uint128 result) { int128 xInt = SD21x18.unwrap(x); if (xInt < 0) { revert CastingErrors.PRBMath_SD21x18_ToUint128_Underflow(x); } result = uint128(xInt); } /// @notice Casts an SD21x18 number into uint256. /// @dev Requirements: /// - x ≥ 0 function intoUint256(SD21x18 x) pure returns (uint256 result) { int128 xInt = SD21x18.unwrap(x); if (xInt < 0) { revert CastingErrors.PRBMath_SD21x18_ToUint256_Underflow(x); } result = uint256(uint128(xInt)); } /// @notice Casts an SD21x18 number into uint40. /// @dev Requirements: /// - x ≥ 0 /// - x ≤ MAX_UINT40 function intoUint40(SD21x18 x) pure returns (uint40 result) { int128 xInt = SD21x18.unwrap(x); if (xInt < 0) { revert CastingErrors.PRBMath_SD21x18_ToUint40_Underflow(x); } if (xInt > int128(uint128(Common.MAX_UINT40))) { revert CastingErrors.PRBMath_SD21x18_ToUint40_Overflow(x); } result = uint40(uint128(xInt)); } /// @notice Alias for {wrap}. function sd21x18(int128 x) pure returns (SD21x18 result) { result = SD21x18.wrap(x); } /// @notice Unwraps an SD21x18 number into int128. function unwrap(SD21x18 x) pure returns (int128 result) { result = SD21x18.unwrap(x); } /// @notice Wraps an int128 number into SD21x18. function wrap(int128 x) pure returns (SD21x18 result) { result = SD21x18.wrap(x); }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; import { SD21x18 } from "./ValueType.sol"; /// @dev Euler's number as an SD21x18 number. SD21x18 constant E = SD21x18.wrap(2_718281828459045235); /// @dev The maximum value an SD21x18 number can have. int128 constant uMAX_SD21x18 = 170141183460469231731_687303715884105727; SD21x18 constant MAX_SD21x18 = SD21x18.wrap(uMAX_SD21x18); /// @dev The minimum value an SD21x18 number can have. int128 constant uMIN_SD21x18 = -170141183460469231731_687303715884105728; SD21x18 constant MIN_SD21x18 = SD21x18.wrap(uMIN_SD21x18); /// @dev PI as an SD21x18 number. SD21x18 constant PI = SD21x18.wrap(3_141592653589793238); /// @dev The unit number, which gives the decimal precision of SD21x18. SD21x18 constant UNIT = SD21x18.wrap(1e18); int128 constant uUNIT = 1e18;
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; import { SD21x18 } from "./ValueType.sol"; /// @notice Thrown when trying to cast an SD21x18 number that doesn't fit in uint128. error PRBMath_SD21x18_ToUint128_Underflow(SD21x18 x); /// @notice Thrown when trying to cast an SD21x18 number that doesn't fit in UD60x18. error PRBMath_SD21x18_ToUD60x18_Underflow(SD21x18 x); /// @notice Thrown when trying to cast an SD21x18 number that doesn't fit in uint256. error PRBMath_SD21x18_ToUint256_Underflow(SD21x18 x); /// @notice Thrown when trying to cast an SD21x18 number that doesn't fit in uint40. error PRBMath_SD21x18_ToUint40_Overflow(SD21x18 x); /// @notice Thrown when trying to cast an SD21x18 number that doesn't fit in uint40. error PRBMath_SD21x18_ToUint40_Underflow(SD21x18 x);
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; import "./Casting.sol" as Casting; /// @notice The signed 21.18-decimal fixed-point number representation, which can have up to 21 digits and up to 18 /// decimals. The values of this are bound by the minimum and the maximum values permitted by the underlying Solidity /// type int128. This is useful when end users want to use int128 to save gas, e.g. with tight variable packing in contract /// storage. type SD21x18 is int128; /*////////////////////////////////////////////////////////////////////////// CASTING //////////////////////////////////////////////////////////////////////////*/ using { Casting.intoSD59x18, Casting.intoUD60x18, Casting.intoUint128, Casting.intoUint256, Casting.intoUint40, Casting.unwrap } for SD21x18 global;
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; import "./Errors.sol" as CastingErrors; import { MAX_UINT128, MAX_UINT40 } from "../Common.sol"; import { uMAX_SD1x18, uMIN_SD1x18 } from "../sd1x18/Constants.sol"; import { SD1x18 } from "../sd1x18/ValueType.sol"; import { uMAX_SD21x18, uMIN_SD21x18 } from "../sd21x18/Constants.sol"; import { SD21x18 } from "../sd21x18/ValueType.sol"; import { uMAX_UD2x18 } from "../ud2x18/Constants.sol"; import { UD2x18 } from "../ud2x18/ValueType.sol"; import { uMAX_UD21x18 } from "../ud21x18/Constants.sol"; import { UD21x18 } from "../ud21x18/ValueType.sol"; import { UD60x18 } from "../ud60x18/ValueType.sol"; import { SD59x18 } from "./ValueType.sol"; /// @notice Casts an SD59x18 number into int256. /// @dev This is basically a functional alias for {unwrap}. function intoInt256(SD59x18 x) pure returns (int256 result) { result = SD59x18.unwrap(x); } /// @notice Casts an SD59x18 number into SD1x18. /// @dev Requirements: /// - x ≥ uMIN_SD1x18 /// - x ≤ uMAX_SD1x18 function intoSD1x18(SD59x18 x) pure returns (SD1x18 result) { int256 xInt = SD59x18.unwrap(x); if (xInt < uMIN_SD1x18) { revert CastingErrors.PRBMath_SD59x18_IntoSD1x18_Underflow(x); } if (xInt > uMAX_SD1x18) { revert CastingErrors.PRBMath_SD59x18_IntoSD1x18_Overflow(x); } result = SD1x18.wrap(int64(xInt)); } /// @notice Casts an SD59x18 number into SD21x18. /// @dev Requirements: /// - x ≥ uMIN_SD21x18 /// - x ≤ uMAX_SD21x18 function intoSD21x18(SD59x18 x) pure returns (SD21x18 result) { int256 xInt = SD59x18.unwrap(x); if (xInt < uMIN_SD21x18) { revert CastingErrors.PRBMath_SD59x18_IntoSD21x18_Underflow(x); } if (xInt > uMAX_SD21x18) { revert CastingErrors.PRBMath_SD59x18_IntoSD21x18_Overflow(x); } result = SD21x18.wrap(int128(xInt)); } /// @notice Casts an SD59x18 number into UD2x18. /// @dev Requirements: /// - x ≥ 0 /// - x ≤ uMAX_UD2x18 function intoUD2x18(SD59x18 x) pure returns (UD2x18 result) { int256 xInt = SD59x18.unwrap(x); if (xInt < 0) { revert CastingErrors.PRBMath_SD59x18_IntoUD2x18_Underflow(x); } if (xInt > int256(uint256(uMAX_UD2x18))) { revert CastingErrors.PRBMath_SD59x18_IntoUD2x18_Overflow(x); } result = UD2x18.wrap(uint64(uint256(xInt))); } /// @notice Casts an SD59x18 number into UD21x18. /// @dev Requirements: /// - x ≥ 0 /// - x ≤ uMAX_UD21x18 function intoUD21x18(SD59x18 x) pure returns (UD21x18 result) { int256 xInt = SD59x18.unwrap(x); if (xInt < 0) { revert CastingErrors.PRBMath_SD59x18_IntoUD21x18_Underflow(x); } if (xInt > int256(uint256(uMAX_UD21x18))) { revert CastingErrors.PRBMath_SD59x18_IntoUD21x18_Overflow(x); } result = UD21x18.wrap(uint128(uint256(xInt))); } /// @notice Casts an SD59x18 number into UD60x18. /// @dev Requirements: /// - x ≥ 0 function intoUD60x18(SD59x18 x) pure returns (UD60x18 result) { int256 xInt = SD59x18.unwrap(x); if (xInt < 0) { revert CastingErrors.PRBMath_SD59x18_IntoUD60x18_Underflow(x); } result = UD60x18.wrap(uint256(xInt)); } /// @notice Casts an SD59x18 number into uint256. /// @dev Requirements: /// - x ≥ 0 function intoUint256(SD59x18 x) pure returns (uint256 result) { int256 xInt = SD59x18.unwrap(x); if (xInt < 0) { revert CastingErrors.PRBMath_SD59x18_IntoUint256_Underflow(x); } result = uint256(xInt); } /// @notice Casts an SD59x18 number into uint128. /// @dev Requirements: /// - x ≥ 0 /// - x ≤ uMAX_UINT128 function intoUint128(SD59x18 x) pure returns (uint128 result) { int256 xInt = SD59x18.unwrap(x); if (xInt < 0) { revert CastingErrors.PRBMath_SD59x18_IntoUint128_Underflow(x); } if (xInt > int256(uint256(MAX_UINT128))) { revert CastingErrors.PRBMath_SD59x18_IntoUint128_Overflow(x); } result = uint128(uint256(xInt)); } /// @notice Casts an SD59x18 number into uint40. /// @dev Requirements: /// - x ≥ 0 /// - x ≤ MAX_UINT40 function intoUint40(SD59x18 x) pure returns (uint40 result) { int256 xInt = SD59x18.unwrap(x); if (xInt < 0) { revert CastingErrors.PRBMath_SD59x18_IntoUint40_Underflow(x); } if (xInt > int256(uint256(MAX_UINT40))) { revert CastingErrors.PRBMath_SD59x18_IntoUint40_Overflow(x); } result = uint40(uint256(xInt)); } /// @notice Alias for {wrap}. function sd(int256 x) pure returns (SD59x18 result) { result = SD59x18.wrap(x); } /// @notice Alias for {wrap}. function sd59x18(int256 x) pure returns (SD59x18 result) { result = SD59x18.wrap(x); } /// @notice Unwraps an SD59x18 number into int256. function unwrap(SD59x18 x) pure returns (int256 result) { result = SD59x18.unwrap(x); } /// @notice Wraps an int256 number into SD59x18. function wrap(int256 x) pure returns (SD59x18 result) { result = SD59x18.wrap(x); }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; import { SD59x18 } from "./ValueType.sol"; // NOTICE: the "u" prefix stands for "unwrapped". /// @dev Euler's number as an SD59x18 number. SD59x18 constant E = SD59x18.wrap(2_718281828459045235); /// @dev The maximum input permitted in {exp}. int256 constant uEXP_MAX_INPUT = 133_084258667509499440; SD59x18 constant EXP_MAX_INPUT = SD59x18.wrap(uEXP_MAX_INPUT); /// @dev Any value less than this returns 0 in {exp}. int256 constant uEXP_MIN_THRESHOLD = -41_446531673892822322; SD59x18 constant EXP_MIN_THRESHOLD = SD59x18.wrap(uEXP_MIN_THRESHOLD); /// @dev The maximum input permitted in {exp2}. int256 constant uEXP2_MAX_INPUT = 192e18 - 1; SD59x18 constant EXP2_MAX_INPUT = SD59x18.wrap(uEXP2_MAX_INPUT); /// @dev Any value less than this returns 0 in {exp2}. int256 constant uEXP2_MIN_THRESHOLD = -59_794705707972522261; SD59x18 constant EXP2_MIN_THRESHOLD = SD59x18.wrap(uEXP2_MIN_THRESHOLD); /// @dev Half the UNIT number. int256 constant uHALF_UNIT = 0.5e18; SD59x18 constant HALF_UNIT = SD59x18.wrap(uHALF_UNIT); /// @dev $log_2(10)$ as an SD59x18 number. int256 constant uLOG2_10 = 3_321928094887362347; SD59x18 constant LOG2_10 = SD59x18.wrap(uLOG2_10); /// @dev $log_2(e)$ as an SD59x18 number. int256 constant uLOG2_E = 1_442695040888963407; SD59x18 constant LOG2_E = SD59x18.wrap(uLOG2_E); /// @dev The maximum value an SD59x18 number can have. int256 constant uMAX_SD59x18 = 57896044618658097711785492504343953926634992332820282019728_792003956564819967; SD59x18 constant MAX_SD59x18 = SD59x18.wrap(uMAX_SD59x18); /// @dev The maximum whole value an SD59x18 number can have. int256 constant uMAX_WHOLE_SD59x18 = 57896044618658097711785492504343953926634992332820282019728_000000000000000000; SD59x18 constant MAX_WHOLE_SD59x18 = SD59x18.wrap(uMAX_WHOLE_SD59x18); /// @dev The minimum value an SD59x18 number can have. int256 constant uMIN_SD59x18 = -57896044618658097711785492504343953926634992332820282019728_792003956564819968; SD59x18 constant MIN_SD59x18 = SD59x18.wrap(uMIN_SD59x18); /// @dev The minimum whole value an SD59x18 number can have. int256 constant uMIN_WHOLE_SD59x18 = -57896044618658097711785492504343953926634992332820282019728_000000000000000000; SD59x18 constant MIN_WHOLE_SD59x18 = SD59x18.wrap(uMIN_WHOLE_SD59x18); /// @dev PI as an SD59x18 number. SD59x18 constant PI = SD59x18.wrap(3_141592653589793238); /// @dev The unit number, which gives the decimal precision of SD59x18. int256 constant uUNIT = 1e18; SD59x18 constant UNIT = SD59x18.wrap(1e18); /// @dev The unit number squared. int256 constant uUNIT_SQUARED = 1e36; SD59x18 constant UNIT_SQUARED = SD59x18.wrap(uUNIT_SQUARED); /// @dev Zero as an SD59x18 number. SD59x18 constant ZERO = SD59x18.wrap(0);
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; import { SD59x18 } from "./ValueType.sol"; /// @notice Thrown when taking the absolute value of `MIN_SD59x18`. error PRBMath_SD59x18_Abs_MinSD59x18(); /// @notice Thrown when ceiling a number overflows SD59x18. error PRBMath_SD59x18_Ceil_Overflow(SD59x18 x); /// @notice Thrown when converting a basic integer to the fixed-point format overflows SD59x18. error PRBMath_SD59x18_Convert_Overflow(int256 x); /// @notice Thrown when converting a basic integer to the fixed-point format underflows SD59x18. error PRBMath_SD59x18_Convert_Underflow(int256 x); /// @notice Thrown when dividing two numbers and one of them is `MIN_SD59x18`. error PRBMath_SD59x18_Div_InputTooSmall(); /// @notice Thrown when dividing two numbers and one of the intermediary unsigned results overflows SD59x18. error PRBMath_SD59x18_Div_Overflow(SD59x18 x, SD59x18 y); /// @notice Thrown when taking the natural exponent of a base greater than 133_084258667509499441. error PRBMath_SD59x18_Exp_InputTooBig(SD59x18 x); /// @notice Thrown when taking the binary exponent of a base greater than 192e18. error PRBMath_SD59x18_Exp2_InputTooBig(SD59x18 x); /// @notice Thrown when flooring a number underflows SD59x18. error PRBMath_SD59x18_Floor_Underflow(SD59x18 x); /// @notice Thrown when taking the geometric mean of two numbers and their product is negative. error PRBMath_SD59x18_Gm_NegativeProduct(SD59x18 x, SD59x18 y); /// @notice Thrown when taking the geometric mean of two numbers and multiplying them overflows SD59x18. error PRBMath_SD59x18_Gm_Overflow(SD59x18 x, SD59x18 y); /// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in SD1x18. error PRBMath_SD59x18_IntoSD1x18_Overflow(SD59x18 x); /// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in SD1x18. error PRBMath_SD59x18_IntoSD1x18_Underflow(SD59x18 x); /// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in SD21x18. error PRBMath_SD59x18_IntoSD21x18_Overflow(SD59x18 x); /// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in SD21x18. error PRBMath_SD59x18_IntoSD21x18_Underflow(SD59x18 x); /// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in UD2x18. error PRBMath_SD59x18_IntoUD2x18_Overflow(SD59x18 x); /// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in UD2x18. error PRBMath_SD59x18_IntoUD2x18_Underflow(SD59x18 x); /// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in UD21x18. error PRBMath_SD59x18_IntoUD21x18_Overflow(SD59x18 x); /// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in UD21x18. error PRBMath_SD59x18_IntoUD21x18_Underflow(SD59x18 x); /// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in UD60x18. error PRBMath_SD59x18_IntoUD60x18_Underflow(SD59x18 x); /// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in uint128. error PRBMath_SD59x18_IntoUint128_Overflow(SD59x18 x); /// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in uint128. error PRBMath_SD59x18_IntoUint128_Underflow(SD59x18 x); /// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in uint256. error PRBMath_SD59x18_IntoUint256_Underflow(SD59x18 x); /// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in uint40. error PRBMath_SD59x18_IntoUint40_Overflow(SD59x18 x); /// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in uint40. error PRBMath_SD59x18_IntoUint40_Underflow(SD59x18 x); /// @notice Thrown when taking the logarithm of a number less than or equal to zero. error PRBMath_SD59x18_Log_InputTooSmall(SD59x18 x); /// @notice Thrown when multiplying two numbers and one of the inputs is `MIN_SD59x18`. error PRBMath_SD59x18_Mul_InputTooSmall(); /// @notice Thrown when multiplying two numbers and the intermediary absolute result overflows SD59x18. error PRBMath_SD59x18_Mul_Overflow(SD59x18 x, SD59x18 y); /// @notice Thrown when raising a number to a power and the intermediary absolute result overflows SD59x18. error PRBMath_SD59x18_Powu_Overflow(SD59x18 x, uint256 y); /// @notice Thrown when taking the square root of a negative number. error PRBMath_SD59x18_Sqrt_NegativeInput(SD59x18 x); /// @notice Thrown when the calculating the square root overflows SD59x18. error PRBMath_SD59x18_Sqrt_Overflow(SD59x18 x);
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; import { wrap } from "./Casting.sol"; import { SD59x18 } from "./ValueType.sol"; /// @notice Implements the checked addition operation (+) in the SD59x18 type. function add(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) { return wrap(x.unwrap() + y.unwrap()); } /// @notice Implements the AND (&) bitwise operation in the SD59x18 type. function and(SD59x18 x, int256 bits) pure returns (SD59x18 result) { return wrap(x.unwrap() & bits); } /// @notice Implements the AND (&) bitwise operation in the SD59x18 type. function and2(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) { return wrap(x.unwrap() & y.unwrap()); } /// @notice Implements the equal (=) operation in the SD59x18 type. function eq(SD59x18 x, SD59x18 y) pure returns (bool result) { result = x.unwrap() == y.unwrap(); } /// @notice Implements the greater than operation (>) in the SD59x18 type. function gt(SD59x18 x, SD59x18 y) pure returns (bool result) { result = x.unwrap() > y.unwrap(); } /// @notice Implements the greater than or equal to operation (>=) in the SD59x18 type. function gte(SD59x18 x, SD59x18 y) pure returns (bool result) { result = x.unwrap() >= y.unwrap(); } /// @notice Implements a zero comparison check function in the SD59x18 type. function isZero(SD59x18 x) pure returns (bool result) { result = x.unwrap() == 0; } /// @notice Implements the left shift operation (<<) in the SD59x18 type. function lshift(SD59x18 x, uint256 bits) pure returns (SD59x18 result) { result = wrap(x.unwrap() << bits); } /// @notice Implements the lower than operation (<) in the SD59x18 type. function lt(SD59x18 x, SD59x18 y) pure returns (bool result) { result = x.unwrap() < y.unwrap(); } /// @notice Implements the lower than or equal to operation (<=) in the SD59x18 type. function lte(SD59x18 x, SD59x18 y) pure returns (bool result) { result = x.unwrap() <= y.unwrap(); } /// @notice Implements the unchecked modulo operation (%) in the SD59x18 type. function mod(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) { result = wrap(x.unwrap() % y.unwrap()); } /// @notice Implements the not equal operation (!=) in the SD59x18 type. function neq(SD59x18 x, SD59x18 y) pure returns (bool result) { result = x.unwrap() != y.unwrap(); } /// @notice Implements the NOT (~) bitwise operation in the SD59x18 type. function not(SD59x18 x) pure returns (SD59x18 result) { result = wrap(~x.unwrap()); } /// @notice Implements the OR (|) bitwise operation in the SD59x18 type. function or(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) { result = wrap(x.unwrap() | y.unwrap()); } /// @notice Implements the right shift operation (>>) in the SD59x18 type. function rshift(SD59x18 x, uint256 bits) pure returns (SD59x18 result) { result = wrap(x.unwrap() >> bits); } /// @notice Implements the checked subtraction operation (-) in the SD59x18 type. function sub(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) { result = wrap(x.unwrap() - y.unwrap()); } /// @notice Implements the checked unary minus operation (-) in the SD59x18 type. function unary(SD59x18 x) pure returns (SD59x18 result) { result = wrap(-x.unwrap()); } /// @notice Implements the unchecked addition operation (+) in the SD59x18 type. function uncheckedAdd(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) { unchecked { result = wrap(x.unwrap() + y.unwrap()); } } /// @notice Implements the unchecked subtraction operation (-) in the SD59x18 type. function uncheckedSub(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) { unchecked { result = wrap(x.unwrap() - y.unwrap()); } } /// @notice Implements the unchecked unary minus operation (-) in the SD59x18 type. function uncheckedUnary(SD59x18 x) pure returns (SD59x18 result) { unchecked { result = wrap(-x.unwrap()); } } /// @notice Implements the XOR (^) bitwise operation in the SD59x18 type. function xor(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) { result = wrap(x.unwrap() ^ y.unwrap()); }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; import "../Common.sol" as Common; import "./Errors.sol" as Errors; import { uEXP_MAX_INPUT, uEXP2_MAX_INPUT, uEXP_MIN_THRESHOLD, uEXP2_MIN_THRESHOLD, uHALF_UNIT, uLOG2_10, uLOG2_E, uMAX_SD59x18, uMAX_WHOLE_SD59x18, uMIN_SD59x18, uMIN_WHOLE_SD59x18, UNIT, uUNIT, uUNIT_SQUARED, ZERO } from "./Constants.sol"; import { wrap } from "./Helpers.sol"; import { SD59x18 } from "./ValueType.sol"; /// @notice Calculates the absolute value of x. /// /// @dev Requirements: /// - x > MIN_SD59x18. /// /// @param x The SD59x18 number for which to calculate the absolute value. /// @return result The absolute value of x as an SD59x18 number. /// @custom:smtchecker abstract-function-nondet function abs(SD59x18 x) pure returns (SD59x18 result) { int256 xInt = x.unwrap(); if (xInt == uMIN_SD59x18) { revert Errors.PRBMath_SD59x18_Abs_MinSD59x18(); } result = xInt < 0 ? wrap(-xInt) : x; } /// @notice Calculates the arithmetic average of x and y. /// /// @dev Notes: /// - The result is rounded toward zero. /// /// @param x The first operand as an SD59x18 number. /// @param y The second operand as an SD59x18 number. /// @return result The arithmetic average as an SD59x18 number. /// @custom:smtchecker abstract-function-nondet function avg(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) { int256 xInt = x.unwrap(); int256 yInt = y.unwrap(); unchecked { // This operation is equivalent to `x / 2 + y / 2`, and it can never overflow. int256 sum = (xInt >> 1) + (yInt >> 1); if (sum < 0) { // If at least one of x and y is odd, add 1 to the result, because shifting negative numbers to the right // rounds toward negative infinity. The right part is equivalent to `sum + (x % 2 == 1 || y % 2 == 1)`. assembly ("memory-safe") { result := add(sum, and(or(xInt, yInt), 1)) } } else { // Add 1 if both x and y are odd to account for the double 0.5 remainder truncated after shifting. result = wrap(sum + (xInt & yInt & 1)); } } } /// @notice Yields the smallest whole number greater than or equal to x. /// /// @dev Optimized for fractional value inputs, because every whole value has (1e18 - 1) fractional counterparts. /// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions. /// /// Requirements: /// - x ≤ MAX_WHOLE_SD59x18 /// /// @param x The SD59x18 number to ceil. /// @return result The smallest whole number greater than or equal to x, as an SD59x18 number. /// @custom:smtchecker abstract-function-nondet function ceil(SD59x18 x) pure returns (SD59x18 result) { int256 xInt = x.unwrap(); if (xInt > uMAX_WHOLE_SD59x18) { revert Errors.PRBMath_SD59x18_Ceil_Overflow(x); } int256 remainder = xInt % uUNIT; if (remainder == 0) { result = x; } else { unchecked { // Solidity uses C fmod style, which returns a modulus with the same sign as x. int256 resultInt = xInt - remainder; if (xInt > 0) { resultInt += uUNIT; } result = wrap(resultInt); } } } /// @notice Divides two SD59x18 numbers, returning a new SD59x18 number. /// /// @dev This is an extension of {Common.mulDiv} for signed numbers, which works by computing the signs and the absolute /// values separately. /// /// Notes: /// - Refer to the notes in {Common.mulDiv}. /// - The result is rounded toward zero. /// /// Requirements: /// - Refer to the requirements in {Common.mulDiv}. /// - None of the inputs can be `MIN_SD59x18`. /// - The denominator must not be zero. /// - The result must fit in SD59x18. /// /// @param x The numerator as an SD59x18 number. /// @param y The denominator as an SD59x18 number. /// @return result The quotient as an SD59x18 number. /// @custom:smtchecker abstract-function-nondet function div(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) { int256 xInt = x.unwrap(); int256 yInt = y.unwrap(); if (xInt == uMIN_SD59x18 || yInt == uMIN_SD59x18) { revert Errors.PRBMath_SD59x18_Div_InputTooSmall(); } // Get hold of the absolute values of x and y. uint256 xAbs; uint256 yAbs; unchecked { xAbs = xInt < 0 ? uint256(-xInt) : uint256(xInt); yAbs = yInt < 0 ? uint256(-yInt) : uint256(yInt); } // Compute the absolute value (x*UNIT÷y). The resulting value must fit in SD59x18. uint256 resultAbs = Common.mulDiv(xAbs, uint256(uUNIT), yAbs); if (resultAbs > uint256(uMAX_SD59x18)) { revert Errors.PRBMath_SD59x18_Div_Overflow(x, y); } // Check if x and y have the same sign using two's complement representation. The left-most bit represents the sign (1 for // negative, 0 for positive or zero). bool sameSign = (xInt ^ yInt) > -1; // If the inputs have the same sign, the result should be positive. Otherwise, it should be negative. unchecked { result = wrap(sameSign ? int256(resultAbs) : -int256(resultAbs)); } } /// @notice Calculates the natural exponent of x using the following formula: /// /// $$ /// e^x = 2^{x * log_2{e}} /// $$ /// /// @dev Notes: /// - Refer to the notes in {exp2}. /// /// Requirements: /// - Refer to the requirements in {exp2}. /// - x < 133_084258667509499441. /// /// @param x The exponent as an SD59x18 number. /// @return result The result as an SD59x18 number. /// @custom:smtchecker abstract-function-nondet function exp(SD59x18 x) pure returns (SD59x18 result) { int256 xInt = x.unwrap(); // Any input less than the threshold returns zero. // This check also prevents an overflow for very small numbers. if (xInt < uEXP_MIN_THRESHOLD) { return ZERO; } // This check prevents values greater than 192e18 from being passed to {exp2}. if (xInt > uEXP_MAX_INPUT) { revert Errors.PRBMath_SD59x18_Exp_InputTooBig(x); } unchecked { // Inline the fixed-point multiplication to save gas. int256 doubleUnitProduct = xInt * uLOG2_E; result = exp2(wrap(doubleUnitProduct / uUNIT)); } } /// @notice Calculates the binary exponent of x using the binary fraction method using the following formula: /// /// $$ /// 2^{-x} = \frac{1}{2^x} /// $$ /// /// @dev See https://ethereum.stackexchange.com/q/79903/24693. /// /// Notes: /// - If x < -59_794705707972522261, the result is zero. /// /// Requirements: /// - x < 192e18. /// - The result must fit in SD59x18. /// /// @param x The exponent as an SD59x18 number. /// @return result The result as an SD59x18 number. /// @custom:smtchecker abstract-function-nondet function exp2(SD59x18 x) pure returns (SD59x18 result) { int256 xInt = x.unwrap(); if (xInt < 0) { // The inverse of any number less than the threshold is truncated to zero. if (xInt < uEXP2_MIN_THRESHOLD) { return ZERO; } unchecked { // Inline the fixed-point inversion to save gas. result = wrap(uUNIT_SQUARED / exp2(wrap(-xInt)).unwrap()); } } else { // Numbers greater than or equal to 192e18 don't fit in the 192.64-bit format. if (xInt > uEXP2_MAX_INPUT) { revert Errors.PRBMath_SD59x18_Exp2_InputTooBig(x); } unchecked { // Convert x to the 192.64-bit fixed-point format. uint256 x_192x64 = uint256((xInt << 64) / uUNIT); // It is safe to cast the result to int256 due to the checks above. result = wrap(int256(Common.exp2(x_192x64))); } } } /// @notice Yields the greatest whole number less than or equal to x. /// /// @dev Optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional /// counterparts. See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions. /// /// Requirements: /// - x ≥ MIN_WHOLE_SD59x18 /// /// @param x The SD59x18 number to floor. /// @return result The greatest whole number less than or equal to x, as an SD59x18 number. /// @custom:smtchecker abstract-function-nondet function floor(SD59x18 x) pure returns (SD59x18 result) { int256 xInt = x.unwrap(); if (xInt < uMIN_WHOLE_SD59x18) { revert Errors.PRBMath_SD59x18_Floor_Underflow(x); } int256 remainder = xInt % uUNIT; if (remainder == 0) { result = x; } else { unchecked { // Solidity uses C fmod style, which returns a modulus with the same sign as x. int256 resultInt = xInt - remainder; if (xInt < 0) { resultInt -= uUNIT; } result = wrap(resultInt); } } } /// @notice Yields the excess beyond the floor of x for positive numbers and the part of the number to the right. /// of the radix point for negative numbers. /// @dev Based on the odd function definition. https://en.wikipedia.org/wiki/Fractional_part /// @param x The SD59x18 number to get the fractional part of. /// @return result The fractional part of x as an SD59x18 number. function frac(SD59x18 x) pure returns (SD59x18 result) { result = wrap(x.unwrap() % uUNIT); } /// @notice Calculates the geometric mean of x and y, i.e. $\sqrt{x * y}$. /// /// @dev Notes: /// - The result is rounded toward zero. /// /// Requirements: /// - x * y must fit in SD59x18. /// - x * y must not be negative, since complex numbers are not supported. /// /// @param x The first operand as an SD59x18 number. /// @param y The second operand as an SD59x18 number. /// @return result The result as an SD59x18 number. /// @custom:smtchecker abstract-function-nondet function gm(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) { int256 xInt = x.unwrap(); int256 yInt = y.unwrap(); if (xInt == 0 || yInt == 0) { return ZERO; } unchecked { // Equivalent to `xy / x != y`. Checking for overflow this way is faster than letting Solidity do it. int256 xyInt = xInt * yInt; if (xyInt / xInt != yInt) { revert Errors.PRBMath_SD59x18_Gm_Overflow(x, y); } // The product must not be negative, since complex numbers are not supported. if (xyInt < 0) { revert Errors.PRBMath_SD59x18_Gm_NegativeProduct(x, y); } // We don't need to multiply the result by `UNIT` here because the x*y product picked up a factor of `UNIT` // during multiplication. See the comments in {Common.sqrt}. uint256 resultUint = Common.sqrt(uint256(xyInt)); result = wrap(int256(resultUint)); } } /// @notice Calculates the inverse of x. /// /// @dev Notes: /// - The result is rounded toward zero. /// /// Requirements: /// - x must not be zero. /// /// @param x The SD59x18 number for which to calculate the inverse. /// @return result The inverse as an SD59x18 number. /// @custom:smtchecker abstract-function-nondet function inv(SD59x18 x) pure returns (SD59x18 result) { result = wrap(uUNIT_SQUARED / x.unwrap()); } /// @notice Calculates the natural logarithm of x using the following formula: /// /// $$ /// ln{x} = log_2{x} / log_2{e} /// $$ /// /// @dev Notes: /// - Refer to the notes in {log2}. /// - The precision isn't sufficiently fine-grained to return exactly `UNIT` when the input is `E`. /// /// Requirements: /// - Refer to the requirements in {log2}. /// /// @param x The SD59x18 number for which to calculate the natural logarithm. /// @return result The natural logarithm as an SD59x18 number. /// @custom:smtchecker abstract-function-nondet function ln(SD59x18 x) pure returns (SD59x18 result) { // Inline the fixed-point multiplication to save gas. This is overflow-safe because the maximum value that // {log2} can return is ~195_205294292027477728. result = wrap(log2(x).unwrap() * uUNIT / uLOG2_E); } /// @notice Calculates the common logarithm of x using the following formula: /// /// $$ /// log_{10}{x} = log_2{x} / log_2{10} /// $$ /// /// However, if x is an exact power of ten, a hard coded value is returned. /// /// @dev Notes: /// - Refer to the notes in {log2}. /// /// Requirements: /// - Refer to the requirements in {log2}. /// /// @param x The SD59x18 number for which to calculate the common logarithm. /// @return result The common logarithm as an SD59x18 number. /// @custom:smtchecker abstract-function-nondet function log10(SD59x18 x) pure returns (SD59x18 result) { int256 xInt = x.unwrap(); if (xInt < 0) { revert Errors.PRBMath_SD59x18_Log_InputTooSmall(x); } // Note that the `mul` in this block is the standard multiplication operation, not {SD59x18.mul}. // prettier-ignore assembly ("memory-safe") { switch x case 1 { result := mul(uUNIT, sub(0, 18)) } case 10 { result := mul(uUNIT, sub(1, 18)) } case 100 { result := mul(uUNIT, sub(2, 18)) } case 1000 { result := mul(uUNIT, sub(3, 18)) } case 10000 { result := mul(uUNIT, sub(4, 18)) } case 100000 { result := mul(uUNIT, sub(5, 18)) } case 1000000 { result := mul(uUNIT, sub(6, 18)) } case 10000000 { result := mul(uUNIT, sub(7, 18)) } case 100000000 { result := mul(uUNIT, sub(8, 18)) } case 1000000000 { result := mul(uUNIT, sub(9, 18)) } case 10000000000 { result := mul(uUNIT, sub(10, 18)) } case 100000000000 { result := mul(uUNIT, sub(11, 18)) } case 1000000000000 { result := mul(uUNIT, sub(12, 18)) } case 10000000000000 { result := mul(uUNIT, sub(13, 18)) } case 100000000000000 { result := mul(uUNIT, sub(14, 18)) } case 1000000000000000 { result := mul(uUNIT, sub(15, 18)) } case 10000000000000000 { result := mul(uUNIT, sub(16, 18)) } case 100000000000000000 { result := mul(uUNIT, sub(17, 18)) } case 1000000000000000000 { result := 0 } case 10000000000000000000 { result := uUNIT } case 100000000000000000000 { result := mul(uUNIT, 2) } case 1000000000000000000000 { result := mul(uUNIT, 3) } case 10000000000000000000000 { result := mul(uUNIT, 4) } case 100000000000000000000000 { result := mul(uUNIT, 5) } case 1000000000000000000000000 { result := mul(uUNIT, 6) } case 10000000000000000000000000 { result := mul(uUNIT, 7) } case 100000000000000000000000000 { result := mul(uUNIT, 8) } case 1000000000000000000000000000 { result := mul(uUNIT, 9) } case 10000000000000000000000000000 { result := mul(uUNIT, 10) } case 100000000000000000000000000000 { result := mul(uUNIT, 11) } case 1000000000000000000000000000000 { result := mul(uUNIT, 12) } case 10000000000000000000000000000000 { result := mul(uUNIT, 13) } case 100000000000000000000000000000000 { result := mul(uUNIT, 14) } case 1000000000000000000000000000000000 { result := mul(uUNIT, 15) } case 10000000000000000000000000000000000 { result := mul(uUNIT, 16) } case 100000000000000000000000000000000000 { result := mul(uUNIT, 17) } case 1000000000000000000000000000000000000 { result := mul(uUNIT, 18) } case 10000000000000000000000000000000000000 { result := mul(uUNIT, 19) } case 100000000000000000000000000000000000000 { result := mul(uUNIT, 20) } case 1000000000000000000000000000000000000000 { result := mul(uUNIT, 21) } case 10000000000000000000000000000000000000000 { result := mul(uUNIT, 22) } case 100000000000000000000000000000000000000000 { result := mul(uUNIT, 23) } case 1000000000000000000000000000000000000000000 { result := mul(uUNIT, 24) } case 10000000000000000000000000000000000000000000 { result := mul(uUNIT, 25) } case 100000000000000000000000000000000000000000000 { result := mul(uUNIT, 26) } case 1000000000000000000000000000000000000000000000 { result := mul(uUNIT, 27) } case 10000000000000000000000000000000000000000000000 { result := mul(uUNIT, 28) } case 100000000000000000000000000000000000000000000000 { result := mul(uUNIT, 29) } case 1000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 30) } case 10000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 31) } case 100000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 32) } case 1000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 33) } case 10000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 34) } case 100000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 35) } case 1000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 36) } case 10000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 37) } case 100000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 38) } case 1000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 39) } case 10000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 40) } case 100000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 41) } case 1000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 42) } case 10000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 43) } case 100000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 44) } case 1000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 45) } case 10000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 46) } case 100000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 47) } case 1000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 48) } case 10000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 49) } case 100000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 50) } case 1000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 51) } case 10000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 52) } case 100000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 53) } case 1000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 54) } case 10000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 55) } case 100000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 56) } case 1000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 57) } case 10000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 58) } default { result := uMAX_SD59x18 } } if (result.unwrap() == uMAX_SD59x18) { unchecked { // Inline the fixed-point division to save gas. result = wrap(log2(x).unwrap() * uUNIT / uLOG2_10); } } } /// @notice Calculates the binary logarithm of x using the iterative approximation algorithm: /// /// $$ /// log_2{x} = n + log_2{y}, \text{ where } y = x*2^{-n}, \ y \in [1, 2) /// $$ /// /// For $0 \leq x \lt 1$, the input is inverted: /// /// $$ /// log_2{x} = -log_2{\frac{1}{x}} /// $$ /// /// @dev See https://en.wikipedia.org/wiki/Binary_logarithm#Iterative_approximation. /// /// Notes: /// - Due to the lossy precision of the iterative approximation, the results are not perfectly accurate to the last decimal. /// /// Requirements: /// - x > 0 /// /// @param x The SD59x18 number for which to calculate the binary logarithm. /// @return result The binary logarithm as an SD59x18 number. /// @custom:smtchecker abstract-function-nondet function log2(SD59x18 x) pure returns (SD59x18 result) { int256 xInt = x.unwrap(); if (xInt <= 0) { revert Errors.PRBMath_SD59x18_Log_InputTooSmall(x); } unchecked { int256 sign; if (xInt >= uUNIT) { sign = 1; } else { sign = -1; // Inline the fixed-point inversion to save gas. xInt = uUNIT_SQUARED / xInt; } // Calculate the integer part of the logarithm. uint256 n = Common.msb(uint256(xInt / uUNIT)); // This is the integer part of the logarithm as an SD59x18 number. The operation can't overflow // because n is at most 255, `UNIT` is 1e18, and the sign is either 1 or -1. int256 resultInt = int256(n) * uUNIT; // Calculate $y = x * 2^{-n}$. int256 y = xInt >> n; // If y is the unit number, the fractional part is zero. if (y == uUNIT) { return wrap(resultInt * sign); } // Calculate the fractional part via the iterative approximation. // The `delta >>= 1` part is equivalent to `delta /= 2`, but shifting bits is more gas efficient. int256 DOUBLE_UNIT = 2e18; for (int256 delta = uHALF_UNIT; delta > 0; delta >>= 1) { y = (y * y) / uUNIT; // Is y^2 >= 2e18 and so in the range [2e18, 4e18)? if (y >= DOUBLE_UNIT) { // Add the 2^{-m} factor to the logarithm. resultInt = resultInt + delta; // Halve y, which corresponds to z/2 in the Wikipedia article. y >>= 1; } } resultInt *= sign; result = wrap(resultInt); } } /// @notice Multiplies two SD59x18 numbers together, returning a new SD59x18 number. /// /// @dev Notes: /// - Refer to the notes in {Common.mulDiv18}. /// /// Requirements: /// - Refer to the requirements in {Common.mulDiv18}. /// - None of the inputs can be `MIN_SD59x18`. /// - The result must fit in SD59x18. /// /// @param x The multiplicand as an SD59x18 number. /// @param y The multiplier as an SD59x18 number. /// @return result The product as an SD59x18 number. /// @custom:smtchecker abstract-function-nondet function mul(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) { int256 xInt = x.unwrap(); int256 yInt = y.unwrap(); if (xInt == uMIN_SD59x18 || yInt == uMIN_SD59x18) { revert Errors.PRBMath_SD59x18_Mul_InputTooSmall(); } // Get hold of the absolute values of x and y. uint256 xAbs; uint256 yAbs; unchecked { xAbs = xInt < 0 ? uint256(-xInt) : uint256(xInt); yAbs = yInt < 0 ? uint256(-yInt) : uint256(yInt); } // Compute the absolute value (x*y÷UNIT). The resulting value must fit in SD59x18. uint256 resultAbs = Common.mulDiv18(xAbs, yAbs); if (resultAbs > uint256(uMAX_SD59x18)) { revert Errors.PRBMath_SD59x18_Mul_Overflow(x, y); } // Check if x and y have the same sign using two's complement representation. The left-most bit represents the sign (1 for // negative, 0 for positive or zero). bool sameSign = (xInt ^ yInt) > -1; // If the inputs have the same sign, the result should be positive. Otherwise, it should be negative. unchecked { result = wrap(sameSign ? int256(resultAbs) : -int256(resultAbs)); } } /// @notice Raises x to the power of y using the following formula: /// /// $$ /// x^y = 2^{log_2{x} * y} /// $$ /// /// @dev Notes: /// - Refer to the notes in {exp2}, {log2}, and {mul}. /// - Returns `UNIT` for 0^0. /// /// Requirements: /// - Refer to the requirements in {exp2}, {log2}, and {mul}. /// /// @param x The base as an SD59x18 number. /// @param y Exponent to raise x to, as an SD59x18 number /// @return result x raised to power y, as an SD59x18 number. /// @custom:smtchecker abstract-function-nondet function pow(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) { int256 xInt = x.unwrap(); int256 yInt = y.unwrap(); // If both x and y are zero, the result is `UNIT`. If just x is zero, the result is always zero. if (xInt == 0) { return yInt == 0 ? UNIT : ZERO; } // If x is `UNIT`, the result is always `UNIT`. else if (xInt == uUNIT) { return UNIT; } // If y is zero, the result is always `UNIT`. if (yInt == 0) { return UNIT; } // If y is `UNIT`, the result is always x. else if (yInt == uUNIT) { return x; } // Calculate the result using the formula. result = exp2(mul(log2(x), y)); } /// @notice Raises x (an SD59x18 number) to the power y (an unsigned basic integer) using the well-known /// algorithm "exponentiation by squaring". /// /// @dev See https://en.wikipedia.org/wiki/Exponentiation_by_squaring. /// /// Notes: /// - Refer to the notes in {Common.mulDiv18}. /// - Returns `UNIT` for 0^0. /// /// Requirements: /// - Refer to the requirements in {abs} and {Common.mulDiv18}. /// - The result must fit in SD59x18. /// /// @param x The base as an SD59x18 number. /// @param y The exponent as a uint256. /// @return result The result as an SD59x18 number. /// @custom:smtchecker abstract-function-nondet function powu(SD59x18 x, uint256 y) pure returns (SD59x18 result) { uint256 xAbs = uint256(abs(x).unwrap()); // Calculate the first iteration of the loop in advance. uint256 resultAbs = y & 1 > 0 ? xAbs : uint256(uUNIT); // Equivalent to `for(y /= 2; y > 0; y /= 2)`. uint256 yAux = y; for (yAux >>= 1; yAux > 0; yAux >>= 1) { xAbs = Common.mulDiv18(xAbs, xAbs); // Equivalent to `y % 2 == 1`. if (yAux & 1 > 0) { resultAbs = Common.mulDiv18(resultAbs, xAbs); } } // The result must fit in SD59x18. if (resultAbs > uint256(uMAX_SD59x18)) { revert Errors.PRBMath_SD59x18_Powu_Overflow(x, y); } unchecked { // Is the base negative and the exponent odd? If yes, the result should be negative. int256 resultInt = int256(resultAbs); bool isNegative = x.unwrap() < 0 && y & 1 == 1; if (isNegative) { resultInt = -resultInt; } result = wrap(resultInt); } } /// @notice Calculates the square root of x using the Babylonian method. /// /// @dev See https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method. /// /// Notes: /// - Only the positive root is returned. /// - The result is rounded toward zero. /// /// Requirements: /// - x ≥ 0, since complex numbers are not supported. /// - x ≤ MAX_SD59x18 / UNIT /// /// @param x The SD59x18 number for which to calculate the square root. /// @return result The result as an SD59x18 number. /// @custom:smtchecker abstract-function-nondet function sqrt(SD59x18 x) pure returns (SD59x18 result) { int256 xInt = x.unwrap(); if (xInt < 0) { revert Errors.PRBMath_SD59x18_Sqrt_NegativeInput(x); } if (xInt > uMAX_SD59x18 / uUNIT) { revert Errors.PRBMath_SD59x18_Sqrt_Overflow(x); } unchecked { // Multiply x by `UNIT` to account for the factor of `UNIT` picked up when multiplying two SD59x18 numbers. // In this case, the two numbers are both the square root. uint256 resultUint = Common.sqrt(uint256(xInt * uUNIT)); result = wrap(int256(resultUint)); } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; import "./Casting.sol" as Casting; import "./Helpers.sol" as Helpers; import "./Math.sol" as Math; /// @notice The signed 59.18-decimal fixed-point number representation, which can have up to 59 digits and up to 18 /// decimals. The values of this are bound by the minimum and the maximum values permitted by the underlying Solidity /// type int256. type SD59x18 is int256; /*////////////////////////////////////////////////////////////////////////// CASTING //////////////////////////////////////////////////////////////////////////*/ using { Casting.intoInt256, Casting.intoSD1x18, Casting.intoSD21x18, Casting.intoUD2x18, Casting.intoUD21x18, Casting.intoUD60x18, Casting.intoUint256, Casting.intoUint128, Casting.intoUint40, Casting.unwrap } for SD59x18 global; /*////////////////////////////////////////////////////////////////////////// MATHEMATICAL FUNCTIONS //////////////////////////////////////////////////////////////////////////*/ using { Math.abs, Math.avg, Math.ceil, Math.div, Math.exp, Math.exp2, Math.floor, Math.frac, Math.gm, Math.inv, Math.log10, Math.log2, Math.ln, Math.mul, Math.pow, Math.powu, Math.sqrt } for SD59x18 global; /*////////////////////////////////////////////////////////////////////////// HELPER FUNCTIONS //////////////////////////////////////////////////////////////////////////*/ using { Helpers.add, Helpers.and, Helpers.eq, Helpers.gt, Helpers.gte, Helpers.isZero, Helpers.lshift, Helpers.lt, Helpers.lte, Helpers.mod, Helpers.neq, Helpers.not, Helpers.or, Helpers.rshift, Helpers.sub, Helpers.uncheckedAdd, Helpers.uncheckedSub, Helpers.uncheckedUnary, Helpers.xor } for SD59x18 global; /*////////////////////////////////////////////////////////////////////////// OPERATORS //////////////////////////////////////////////////////////////////////////*/ // The global "using for" directive makes it possible to use these operators on the SD59x18 type. using { Helpers.add as +, Helpers.and2 as &, Math.div as /, Helpers.eq as ==, Helpers.gt as >, Helpers.gte as >=, Helpers.lt as <, Helpers.lte as <=, Helpers.mod as %, Math.mul as *, Helpers.neq as !=, Helpers.not as ~, Helpers.or as |, Helpers.sub as -, Helpers.unary as -, Helpers.xor as ^ } for SD59x18 global;
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; import "../Common.sol" as Common; import "./Errors.sol" as Errors; import { SD59x18 } from "../sd59x18/ValueType.sol"; import { UD60x18 } from "../ud60x18/ValueType.sol"; import { UD21x18 } from "./ValueType.sol"; /// @notice Casts a UD21x18 number into SD59x18. /// @dev There is no overflow check because UD21x18 ⊆ SD59x18. function intoSD59x18(UD21x18 x) pure returns (SD59x18 result) { result = SD59x18.wrap(int256(uint256(UD21x18.unwrap(x)))); } /// @notice Casts a UD21x18 number into UD60x18. /// @dev There is no overflow check because UD21x18 ⊆ UD60x18. function intoUD60x18(UD21x18 x) pure returns (UD60x18 result) { result = UD60x18.wrap(UD21x18.unwrap(x)); } /// @notice Casts a UD21x18 number into uint128. /// @dev This is basically an alias for {unwrap}. function intoUint128(UD21x18 x) pure returns (uint128 result) { result = UD21x18.unwrap(x); } /// @notice Casts a UD21x18 number into uint256. /// @dev There is no overflow check because UD21x18 ⊆ uint256. function intoUint256(UD21x18 x) pure returns (uint256 result) { result = uint256(UD21x18.unwrap(x)); } /// @notice Casts a UD21x18 number into uint40. /// @dev Requirements: /// - x ≤ MAX_UINT40 function intoUint40(UD21x18 x) pure returns (uint40 result) { uint128 xUint = UD21x18.unwrap(x); if (xUint > uint128(Common.MAX_UINT40)) { revert Errors.PRBMath_UD21x18_IntoUint40_Overflow(x); } result = uint40(xUint); } /// @notice Alias for {wrap}. function ud21x18(uint128 x) pure returns (UD21x18 result) { result = UD21x18.wrap(x); } /// @notice Unwrap a UD21x18 number into uint128. function unwrap(UD21x18 x) pure returns (uint128 result) { result = UD21x18.unwrap(x); } /// @notice Wraps a uint128 number into UD21x18. function wrap(uint128 x) pure returns (UD21x18 result) { result = UD21x18.wrap(x); }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; import { UD21x18 } from "./ValueType.sol"; /// @dev Euler's number as a UD21x18 number. UD21x18 constant E = UD21x18.wrap(2_718281828459045235); /// @dev The maximum value a UD21x18 number can have. uint128 constant uMAX_UD21x18 = 340282366920938463463_374607431768211455; UD21x18 constant MAX_UD21x18 = UD21x18.wrap(uMAX_UD21x18); /// @dev PI as a UD21x18 number. UD21x18 constant PI = UD21x18.wrap(3_141592653589793238); /// @dev The unit number, which gives the decimal precision of UD21x18. uint256 constant uUNIT = 1e18; UD21x18 constant UNIT = UD21x18.wrap(1e18);
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; import { UD21x18 } from "./ValueType.sol"; /// @notice Thrown when trying to cast a UD21x18 number that doesn't fit in uint40. error PRBMath_UD21x18_IntoUint40_Overflow(UD21x18 x);
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; import "./Casting.sol" as Casting; /// @notice The unsigned 21.18-decimal fixed-point number representation, which can have up to 21 digits and up to 18 /// decimals. The values of this are bound by the minimum and the maximum values permitted by the underlying Solidity /// type uint128. This is useful when end users want to use uint128 to save gas, e.g. with tight variable packing in contract /// storage. type UD21x18 is uint128; /*////////////////////////////////////////////////////////////////////////// CASTING //////////////////////////////////////////////////////////////////////////*/ using { Casting.intoSD59x18, Casting.intoUD60x18, Casting.intoUint128, Casting.intoUint256, Casting.intoUint40, Casting.unwrap } for UD21x18 global;
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; import "../Common.sol" as Common; import "./Errors.sol" as Errors; import { SD59x18 } from "../sd59x18/ValueType.sol"; import { UD60x18 } from "../ud60x18/ValueType.sol"; import { UD2x18 } from "./ValueType.sol"; /// @notice Casts a UD2x18 number into SD59x18. /// @dev There is no overflow check because UD2x18 ⊆ SD59x18. function intoSD59x18(UD2x18 x) pure returns (SD59x18 result) { result = SD59x18.wrap(int256(uint256(UD2x18.unwrap(x)))); } /// @notice Casts a UD2x18 number into UD60x18. /// @dev There is no overflow check because UD2x18 ⊆ UD60x18. function intoUD60x18(UD2x18 x) pure returns (UD60x18 result) { result = UD60x18.wrap(UD2x18.unwrap(x)); } /// @notice Casts a UD2x18 number into uint128. /// @dev There is no overflow check because UD2x18 ⊆ uint128. function intoUint128(UD2x18 x) pure returns (uint128 result) { result = uint128(UD2x18.unwrap(x)); } /// @notice Casts a UD2x18 number into uint256. /// @dev There is no overflow check because UD2x18 ⊆ uint256. function intoUint256(UD2x18 x) pure returns (uint256 result) { result = uint256(UD2x18.unwrap(x)); } /// @notice Casts a UD2x18 number into uint40. /// @dev Requirements: /// - x ≤ MAX_UINT40 function intoUint40(UD2x18 x) pure returns (uint40 result) { uint64 xUint = UD2x18.unwrap(x); if (xUint > uint64(Common.MAX_UINT40)) { revert Errors.PRBMath_UD2x18_IntoUint40_Overflow(x); } result = uint40(xUint); } /// @notice Alias for {wrap}. function ud2x18(uint64 x) pure returns (UD2x18 result) { result = UD2x18.wrap(x); } /// @notice Unwrap a UD2x18 number into uint64. function unwrap(UD2x18 x) pure returns (uint64 result) { result = UD2x18.unwrap(x); } /// @notice Wraps a uint64 number into UD2x18. function wrap(uint64 x) pure returns (UD2x18 result) { result = UD2x18.wrap(x); }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; import { UD2x18 } from "./ValueType.sol"; /// @dev Euler's number as a UD2x18 number. UD2x18 constant E = UD2x18.wrap(2_718281828459045235); /// @dev The maximum value a UD2x18 number can have. uint64 constant uMAX_UD2x18 = 18_446744073709551615; UD2x18 constant MAX_UD2x18 = UD2x18.wrap(uMAX_UD2x18); /// @dev PI as a UD2x18 number. UD2x18 constant PI = UD2x18.wrap(3_141592653589793238); /// @dev The unit number, which gives the decimal precision of UD2x18. UD2x18 constant UNIT = UD2x18.wrap(1e18); uint64 constant uUNIT = 1e18;
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; import { UD2x18 } from "./ValueType.sol"; /// @notice Thrown when trying to cast a UD2x18 number that doesn't fit in uint40. error PRBMath_UD2x18_IntoUint40_Overflow(UD2x18 x);
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; import "./Casting.sol" as Casting; /// @notice The unsigned 2.18-decimal fixed-point number representation, which can have up to 2 digits and up to 18 /// decimals. The values of this are bound by the minimum and the maximum values permitted by the underlying Solidity /// type uint64. This is useful when end users want to use uint64 to save gas, e.g. with tight variable packing in contract /// storage. type UD2x18 is uint64; /*////////////////////////////////////////////////////////////////////////// CASTING //////////////////////////////////////////////////////////////////////////*/ using { Casting.intoSD59x18, Casting.intoUD60x18, Casting.intoUint128, Casting.intoUint256, Casting.intoUint40, Casting.unwrap } for UD2x18 global;
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; /* ██████╗ ██████╗ ██████╗ ███╗ ███╗ █████╗ ████████╗██╗ ██╗ ██╔══██╗██╔══██╗██╔══██╗████╗ ████║██╔══██╗╚══██╔══╝██║ ██║ ██████╔╝██████╔╝██████╔╝██╔████╔██║███████║ ██║ ███████║ ██╔═══╝ ██╔══██╗██╔══██╗██║╚██╔╝██║██╔══██║ ██║ ██╔══██║ ██║ ██║ ██║██████╔╝██║ ╚═╝ ██║██║ ██║ ██║ ██║ ██║ ╚═╝ ╚═╝ ╚═╝╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ██╗ ██╗██████╗ ██████╗ ██████╗ ██╗ ██╗ ██╗ █████╗ ██║ ██║██╔══██╗██╔════╝ ██╔═████╗╚██╗██╔╝███║██╔══██╗ ██║ ██║██║ ██║███████╗ ██║██╔██║ ╚███╔╝ ╚██║╚█████╔╝ ██║ ██║██║ ██║██╔═══██╗████╔╝██║ ██╔██╗ ██║██╔══██╗ ╚██████╔╝██████╔╝╚██████╔╝╚██████╔╝██╔╝ ██╗ ██║╚█████╔╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚════╝ */ import "./ud60x18/Casting.sol"; import "./ud60x18/Constants.sol"; import "./ud60x18/Conversions.sol"; import "./ud60x18/Errors.sol"; import "./ud60x18/Helpers.sol"; import "./ud60x18/Math.sol"; import "./ud60x18/ValueType.sol";
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; import "./Errors.sol" as CastingErrors; import { MAX_UINT128, MAX_UINT40 } from "../Common.sol"; import { uMAX_SD1x18 } from "../sd1x18/Constants.sol"; import { SD1x18 } from "../sd1x18/ValueType.sol"; import { uMAX_SD21x18 } from "../sd21x18/Constants.sol"; import { SD21x18 } from "../sd21x18/ValueType.sol"; import { uMAX_SD59x18 } from "../sd59x18/Constants.sol"; import { SD59x18 } from "../sd59x18/ValueType.sol"; import { uMAX_UD2x18 } from "../ud2x18/Constants.sol"; import { uMAX_UD21x18 } from "../ud21x18/Constants.sol"; import { UD2x18 } from "../ud2x18/ValueType.sol"; import { UD21x18 } from "../ud21x18/ValueType.sol"; import { UD60x18 } from "./ValueType.sol"; /// @notice Casts a UD60x18 number into SD1x18. /// @dev Requirements: /// - x ≤ uMAX_SD1x18 function intoSD1x18(UD60x18 x) pure returns (SD1x18 result) { uint256 xUint = UD60x18.unwrap(x); if (xUint > uint256(int256(uMAX_SD1x18))) { revert CastingErrors.PRBMath_UD60x18_IntoSD1x18_Overflow(x); } result = SD1x18.wrap(int64(uint64(xUint))); } /// @notice Casts a UD60x18 number into SD21x18. /// @dev Requirements: /// - x ≤ uMAX_SD21x18 function intoSD21x18(UD60x18 x) pure returns (SD21x18 result) { uint256 xUint = UD60x18.unwrap(x); if (xUint > uint256(int256(uMAX_SD21x18))) { revert CastingErrors.PRBMath_UD60x18_IntoSD21x18_Overflow(x); } result = SD21x18.wrap(int128(uint128(xUint))); } /// @notice Casts a UD60x18 number into UD2x18. /// @dev Requirements: /// - x ≤ uMAX_UD2x18 function intoUD2x18(UD60x18 x) pure returns (UD2x18 result) { uint256 xUint = UD60x18.unwrap(x); if (xUint > uMAX_UD2x18) { revert CastingErrors.PRBMath_UD60x18_IntoUD2x18_Overflow(x); } result = UD2x18.wrap(uint64(xUint)); } /// @notice Casts a UD60x18 number into UD21x18. /// @dev Requirements: /// - x ≤ uMAX_UD21x18 function intoUD21x18(UD60x18 x) pure returns (UD21x18 result) { uint256 xUint = UD60x18.unwrap(x); if (xUint > uMAX_UD21x18) { revert CastingErrors.PRBMath_UD60x18_IntoUD21x18_Overflow(x); } result = UD21x18.wrap(uint128(xUint)); } /// @notice Casts a UD60x18 number into SD59x18. /// @dev Requirements: /// - x ≤ uMAX_SD59x18 function intoSD59x18(UD60x18 x) pure returns (SD59x18 result) { uint256 xUint = UD60x18.unwrap(x); if (xUint > uint256(uMAX_SD59x18)) { revert CastingErrors.PRBMath_UD60x18_IntoSD59x18_Overflow(x); } result = SD59x18.wrap(int256(xUint)); } /// @notice Casts a UD60x18 number into uint128. /// @dev This is basically an alias for {unwrap}. function intoUint256(UD60x18 x) pure returns (uint256 result) { result = UD60x18.unwrap(x); } /// @notice Casts a UD60x18 number into uint128. /// @dev Requirements: /// - x ≤ MAX_UINT128 function intoUint128(UD60x18 x) pure returns (uint128 result) { uint256 xUint = UD60x18.unwrap(x); if (xUint > MAX_UINT128) { revert CastingErrors.PRBMath_UD60x18_IntoUint128_Overflow(x); } result = uint128(xUint); } /// @notice Casts a UD60x18 number into uint40. /// @dev Requirements: /// - x ≤ MAX_UINT40 function intoUint40(UD60x18 x) pure returns (uint40 result) { uint256 xUint = UD60x18.unwrap(x); if (xUint > MAX_UINT40) { revert CastingErrors.PRBMath_UD60x18_IntoUint40_Overflow(x); } result = uint40(xUint); } /// @notice Alias for {wrap}. function ud(uint256 x) pure returns (UD60x18 result) { result = UD60x18.wrap(x); } /// @notice Alias for {wrap}. function ud60x18(uint256 x) pure returns (UD60x18 result) { result = UD60x18.wrap(x); } /// @notice Unwraps a UD60x18 number into uint256. function unwrap(UD60x18 x) pure returns (uint256 result) { result = UD60x18.unwrap(x); } /// @notice Wraps a uint256 number into the UD60x18 value type. function wrap(uint256 x) pure returns (UD60x18 result) { result = UD60x18.wrap(x); }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; import { UD60x18 } from "./ValueType.sol"; // NOTICE: the "u" prefix stands for "unwrapped". /// @dev Euler's number as a UD60x18 number. UD60x18 constant E = UD60x18.wrap(2_718281828459045235); /// @dev The maximum input permitted in {exp}. uint256 constant uEXP_MAX_INPUT = 133_084258667509499440; UD60x18 constant EXP_MAX_INPUT = UD60x18.wrap(uEXP_MAX_INPUT); /// @dev The maximum input permitted in {exp2}. uint256 constant uEXP2_MAX_INPUT = 192e18 - 1; UD60x18 constant EXP2_MAX_INPUT = UD60x18.wrap(uEXP2_MAX_INPUT); /// @dev Half the UNIT number. uint256 constant uHALF_UNIT = 0.5e18; UD60x18 constant HALF_UNIT = UD60x18.wrap(uHALF_UNIT); /// @dev $log_2(10)$ as a UD60x18 number. uint256 constant uLOG2_10 = 3_321928094887362347; UD60x18 constant LOG2_10 = UD60x18.wrap(uLOG2_10); /// @dev $log_2(e)$ as a UD60x18 number. uint256 constant uLOG2_E = 1_442695040888963407; UD60x18 constant LOG2_E = UD60x18.wrap(uLOG2_E); /// @dev The maximum value a UD60x18 number can have. uint256 constant uMAX_UD60x18 = 115792089237316195423570985008687907853269984665640564039457_584007913129639935; UD60x18 constant MAX_UD60x18 = UD60x18.wrap(uMAX_UD60x18); /// @dev The maximum whole value a UD60x18 number can have. uint256 constant uMAX_WHOLE_UD60x18 = 115792089237316195423570985008687907853269984665640564039457_000000000000000000; UD60x18 constant MAX_WHOLE_UD60x18 = UD60x18.wrap(uMAX_WHOLE_UD60x18); /// @dev PI as a UD60x18 number. UD60x18 constant PI = UD60x18.wrap(3_141592653589793238); /// @dev The unit number, which gives the decimal precision of UD60x18. uint256 constant uUNIT = 1e18; UD60x18 constant UNIT = UD60x18.wrap(uUNIT); /// @dev The unit number squared. uint256 constant uUNIT_SQUARED = 1e36; UD60x18 constant UNIT_SQUARED = UD60x18.wrap(uUNIT_SQUARED); /// @dev Zero as a UD60x18 number. UD60x18 constant ZERO = UD60x18.wrap(0);
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; import { uMAX_UD60x18, uUNIT } from "./Constants.sol"; import { PRBMath_UD60x18_Convert_Overflow } from "./Errors.sol"; import { UD60x18 } from "./ValueType.sol"; /// @notice Converts a UD60x18 number to a simple integer by dividing it by `UNIT`. /// @dev The result is rounded toward zero. /// @param x The UD60x18 number to convert. /// @return result The same number in basic integer form. function convert(UD60x18 x) pure returns (uint256 result) { result = UD60x18.unwrap(x) / uUNIT; } /// @notice Converts a simple integer to UD60x18 by multiplying it by `UNIT`. /// /// @dev Requirements: /// - x ≤ MAX_UD60x18 / UNIT /// /// @param x The basic integer to convert. /// @return result The same number converted to UD60x18. function convert(uint256 x) pure returns (UD60x18 result) { if (x > uMAX_UD60x18 / uUNIT) { revert PRBMath_UD60x18_Convert_Overflow(x); } unchecked { result = UD60x18.wrap(x * uUNIT); } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; import { UD60x18 } from "./ValueType.sol"; /// @notice Thrown when ceiling a number overflows UD60x18. error PRBMath_UD60x18_Ceil_Overflow(UD60x18 x); /// @notice Thrown when converting a basic integer to the fixed-point format overflows UD60x18. error PRBMath_UD60x18_Convert_Overflow(uint256 x); /// @notice Thrown when taking the natural exponent of a base greater than 133_084258667509499441. error PRBMath_UD60x18_Exp_InputTooBig(UD60x18 x); /// @notice Thrown when taking the binary exponent of a base greater than 192e18. error PRBMath_UD60x18_Exp2_InputTooBig(UD60x18 x); /// @notice Thrown when taking the geometric mean of two numbers and multiplying them overflows UD60x18. error PRBMath_UD60x18_Gm_Overflow(UD60x18 x, UD60x18 y); /// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in SD1x18. error PRBMath_UD60x18_IntoSD1x18_Overflow(UD60x18 x); /// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in SD21x18. error PRBMath_UD60x18_IntoSD21x18_Overflow(UD60x18 x); /// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in SD59x18. error PRBMath_UD60x18_IntoSD59x18_Overflow(UD60x18 x); /// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in UD2x18. error PRBMath_UD60x18_IntoUD2x18_Overflow(UD60x18 x); /// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in UD21x18. error PRBMath_UD60x18_IntoUD21x18_Overflow(UD60x18 x); /// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in uint128. error PRBMath_UD60x18_IntoUint128_Overflow(UD60x18 x); /// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in uint40. error PRBMath_UD60x18_IntoUint40_Overflow(UD60x18 x); /// @notice Thrown when taking the logarithm of a number less than UNIT. error PRBMath_UD60x18_Log_InputTooSmall(UD60x18 x); /// @notice Thrown when calculating the square root overflows UD60x18. error PRBMath_UD60x18_Sqrt_Overflow(UD60x18 x);
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; import { wrap } from "./Casting.sol"; import { UD60x18 } from "./ValueType.sol"; /// @notice Implements the checked addition operation (+) in the UD60x18 type. function add(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) { result = wrap(x.unwrap() + y.unwrap()); } /// @notice Implements the AND (&) bitwise operation in the UD60x18 type. function and(UD60x18 x, uint256 bits) pure returns (UD60x18 result) { result = wrap(x.unwrap() & bits); } /// @notice Implements the AND (&) bitwise operation in the UD60x18 type. function and2(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) { result = wrap(x.unwrap() & y.unwrap()); } /// @notice Implements the equal operation (==) in the UD60x18 type. function eq(UD60x18 x, UD60x18 y) pure returns (bool result) { result = x.unwrap() == y.unwrap(); } /// @notice Implements the greater than operation (>) in the UD60x18 type. function gt(UD60x18 x, UD60x18 y) pure returns (bool result) { result = x.unwrap() > y.unwrap(); } /// @notice Implements the greater than or equal to operation (>=) in the UD60x18 type. function gte(UD60x18 x, UD60x18 y) pure returns (bool result) { result = x.unwrap() >= y.unwrap(); } /// @notice Implements a zero comparison check function in the UD60x18 type. function isZero(UD60x18 x) pure returns (bool result) { // This wouldn't work if x could be negative. result = x.unwrap() == 0; } /// @notice Implements the left shift operation (<<) in the UD60x18 type. function lshift(UD60x18 x, uint256 bits) pure returns (UD60x18 result) { result = wrap(x.unwrap() << bits); } /// @notice Implements the lower than operation (<) in the UD60x18 type. function lt(UD60x18 x, UD60x18 y) pure returns (bool result) { result = x.unwrap() < y.unwrap(); } /// @notice Implements the lower than or equal to operation (<=) in the UD60x18 type. function lte(UD60x18 x, UD60x18 y) pure returns (bool result) { result = x.unwrap() <= y.unwrap(); } /// @notice Implements the checked modulo operation (%) in the UD60x18 type. function mod(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) { result = wrap(x.unwrap() % y.unwrap()); } /// @notice Implements the not equal operation (!=) in the UD60x18 type. function neq(UD60x18 x, UD60x18 y) pure returns (bool result) { result = x.unwrap() != y.unwrap(); } /// @notice Implements the NOT (~) bitwise operation in the UD60x18 type. function not(UD60x18 x) pure returns (UD60x18 result) { result = wrap(~x.unwrap()); } /// @notice Implements the OR (|) bitwise operation in the UD60x18 type. function or(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) { result = wrap(x.unwrap() | y.unwrap()); } /// @notice Implements the right shift operation (>>) in the UD60x18 type. function rshift(UD60x18 x, uint256 bits) pure returns (UD60x18 result) { result = wrap(x.unwrap() >> bits); } /// @notice Implements the checked subtraction operation (-) in the UD60x18 type. function sub(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) { result = wrap(x.unwrap() - y.unwrap()); } /// @notice Implements the unchecked addition operation (+) in the UD60x18 type. function uncheckedAdd(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) { unchecked { result = wrap(x.unwrap() + y.unwrap()); } } /// @notice Implements the unchecked subtraction operation (-) in the UD60x18 type. function uncheckedSub(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) { unchecked { result = wrap(x.unwrap() - y.unwrap()); } } /// @notice Implements the XOR (^) bitwise operation in the UD60x18 type. function xor(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) { result = wrap(x.unwrap() ^ y.unwrap()); }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; import "../Common.sol" as Common; import "./Errors.sol" as Errors; import { wrap } from "./Casting.sol"; import { uEXP_MAX_INPUT, uEXP2_MAX_INPUT, uHALF_UNIT, uLOG2_10, uLOG2_E, uMAX_UD60x18, uMAX_WHOLE_UD60x18, UNIT, uUNIT, uUNIT_SQUARED, ZERO } from "./Constants.sol"; import { UD60x18 } from "./ValueType.sol"; /*////////////////////////////////////////////////////////////////////////// MATHEMATICAL FUNCTIONS //////////////////////////////////////////////////////////////////////////*/ /// @notice Calculates the arithmetic average of x and y using the following formula: /// /// $$ /// avg(x, y) = (x & y) + ((xUint ^ yUint) / 2) /// $$ /// /// In English, this is what this formula does: /// /// 1. AND x and y. /// 2. Calculate half of XOR x and y. /// 3. Add the two results together. /// /// This technique is known as SWAR, which stands for "SIMD within a register". You can read more about it here: /// https://devblogs.microsoft.com/oldnewthing/20220207-00/?p=106223 /// /// @dev Notes: /// - The result is rounded toward zero. /// /// @param x The first operand as a UD60x18 number. /// @param y The second operand as a UD60x18 number. /// @return result The arithmetic average as a UD60x18 number. /// @custom:smtchecker abstract-function-nondet function avg(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) { uint256 xUint = x.unwrap(); uint256 yUint = y.unwrap(); unchecked { result = wrap((xUint & yUint) + ((xUint ^ yUint) >> 1)); } } /// @notice Yields the smallest whole number greater than or equal to x. /// /// @dev This is optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional /// counterparts. See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions. /// /// Requirements: /// - x ≤ MAX_WHOLE_UD60x18 /// /// @param x The UD60x18 number to ceil. /// @return result The smallest whole number greater than or equal to x, as a UD60x18 number. /// @custom:smtchecker abstract-function-nondet function ceil(UD60x18 x) pure returns (UD60x18 result) { uint256 xUint = x.unwrap(); if (xUint > uMAX_WHOLE_UD60x18) { revert Errors.PRBMath_UD60x18_Ceil_Overflow(x); } assembly ("memory-safe") { // Equivalent to `x % UNIT`. let remainder := mod(x, uUNIT) // Equivalent to `UNIT - remainder`. let delta := sub(uUNIT, remainder) // Equivalent to `x + remainder > 0 ? delta : 0`. result := add(x, mul(delta, gt(remainder, 0))) } } /// @notice Divides two UD60x18 numbers, returning a new UD60x18 number. /// /// @dev Uses {Common.mulDiv} to enable overflow-safe multiplication and division. /// /// Notes: /// - Refer to the notes in {Common.mulDiv}. /// /// Requirements: /// - Refer to the requirements in {Common.mulDiv}. /// /// @param x The numerator as a UD60x18 number. /// @param y The denominator as a UD60x18 number. /// @return result The quotient as a UD60x18 number. /// @custom:smtchecker abstract-function-nondet function div(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) { result = wrap(Common.mulDiv(x.unwrap(), uUNIT, y.unwrap())); } /// @notice Calculates the natural exponent of x using the following formula: /// /// $$ /// e^x = 2^{x * log_2{e}} /// $$ /// /// @dev Requirements: /// - x ≤ 133_084258667509499440 /// /// @param x The exponent as a UD60x18 number. /// @return result The result as a UD60x18 number. /// @custom:smtchecker abstract-function-nondet function exp(UD60x18 x) pure returns (UD60x18 result) { uint256 xUint = x.unwrap(); // This check prevents values greater than 192e18 from being passed to {exp2}. if (xUint > uEXP_MAX_INPUT) { revert Errors.PRBMath_UD60x18_Exp_InputTooBig(x); } unchecked { // Inline the fixed-point multiplication to save gas. uint256 doubleUnitProduct = xUint * uLOG2_E; result = exp2(wrap(doubleUnitProduct / uUNIT)); } } /// @notice Calculates the binary exponent of x using the binary fraction method. /// /// @dev See https://ethereum.stackexchange.com/q/79903/24693 /// /// Requirements: /// - x < 192e18 /// - The result must fit in UD60x18. /// /// @param x The exponent as a UD60x18 number. /// @return result The result as a UD60x18 number. /// @custom:smtchecker abstract-function-nondet function exp2(UD60x18 x) pure returns (UD60x18 result) { uint256 xUint = x.unwrap(); // Numbers greater than or equal to 192e18 don't fit in the 192.64-bit format. if (xUint > uEXP2_MAX_INPUT) { revert Errors.PRBMath_UD60x18_Exp2_InputTooBig(x); } // Convert x to the 192.64-bit fixed-point format. uint256 x_192x64 = (xUint << 64) / uUNIT; // Pass x to the {Common.exp2} function, which uses the 192.64-bit fixed-point number representation. result = wrap(Common.exp2(x_192x64)); } /// @notice Yields the greatest whole number less than or equal to x. /// @dev Optimized for fractional value inputs, because every whole value has (1e18 - 1) fractional counterparts. /// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions. /// @param x The UD60x18 number to floor. /// @return result The greatest whole number less than or equal to x, as a UD60x18 number. /// @custom:smtchecker abstract-function-nondet function floor(UD60x18 x) pure returns (UD60x18 result) { assembly ("memory-safe") { // Equivalent to `x % UNIT`. let remainder := mod(x, uUNIT) // Equivalent to `x - remainder > 0 ? remainder : 0)`. result := sub(x, mul(remainder, gt(remainder, 0))) } } /// @notice Yields the excess beyond the floor of x using the odd function definition. /// @dev See https://en.wikipedia.org/wiki/Fractional_part. /// @param x The UD60x18 number to get the fractional part of. /// @return result The fractional part of x as a UD60x18 number. /// @custom:smtchecker abstract-function-nondet function frac(UD60x18 x) pure returns (UD60x18 result) { assembly ("memory-safe") { result := mod(x, uUNIT) } } /// @notice Calculates the geometric mean of x and y, i.e. $\sqrt{x * y}$, rounding down. /// /// @dev Requirements: /// - x * y must fit in UD60x18. /// /// @param x The first operand as a UD60x18 number. /// @param y The second operand as a UD60x18 number. /// @return result The result as a UD60x18 number. /// @custom:smtchecker abstract-function-nondet function gm(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) { uint256 xUint = x.unwrap(); uint256 yUint = y.unwrap(); if (xUint == 0 || yUint == 0) { return ZERO; } unchecked { // Checking for overflow this way is faster than letting Solidity do it. uint256 xyUint = xUint * yUint; if (xyUint / xUint != yUint) { revert Errors.PRBMath_UD60x18_Gm_Overflow(x, y); } // We don't need to multiply the result by `UNIT` here because the x*y product picked up a factor of `UNIT` // during multiplication. See the comments in {Common.sqrt}. result = wrap(Common.sqrt(xyUint)); } } /// @notice Calculates the inverse of x. /// /// @dev Notes: /// - The result is rounded toward zero. /// /// Requirements: /// - x must not be zero. /// /// @param x The UD60x18 number for which to calculate the inverse. /// @return result The inverse as a UD60x18 number. /// @custom:smtchecker abstract-function-nondet function inv(UD60x18 x) pure returns (UD60x18 result) { unchecked { result = wrap(uUNIT_SQUARED / x.unwrap()); } } /// @notice Calculates the natural logarithm of x using the following formula: /// /// $$ /// ln{x} = log_2{x} / log_2{e} /// $$ /// /// @dev Notes: /// - Refer to the notes in {log2}. /// - The precision isn't sufficiently fine-grained to return exactly `UNIT` when the input is `E`. /// /// Requirements: /// - Refer to the requirements in {log2}. /// /// @param x The UD60x18 number for which to calculate the natural logarithm. /// @return result The natural logarithm as a UD60x18 number. /// @custom:smtchecker abstract-function-nondet function ln(UD60x18 x) pure returns (UD60x18 result) { unchecked { // Inline the fixed-point multiplication to save gas. This is overflow-safe because the maximum value that // {log2} can return is ~196_205294292027477728. result = wrap(log2(x).unwrap() * uUNIT / uLOG2_E); } } /// @notice Calculates the common logarithm of x using the following formula: /// /// $$ /// log_{10}{x} = log_2{x} / log_2{10} /// $$ /// /// However, if x is an exact power of ten, a hard coded value is returned. /// /// @dev Notes: /// - Refer to the notes in {log2}. /// /// Requirements: /// - Refer to the requirements in {log2}. /// /// @param x The UD60x18 number for which to calculate the common logarithm. /// @return result The common logarithm as a UD60x18 number. /// @custom:smtchecker abstract-function-nondet function log10(UD60x18 x) pure returns (UD60x18 result) { uint256 xUint = x.unwrap(); if (xUint < uUNIT) { revert Errors.PRBMath_UD60x18_Log_InputTooSmall(x); } // Note that the `mul` in this assembly block is the standard multiplication operation, not {UD60x18.mul}. // prettier-ignore assembly ("memory-safe") { switch x case 1 { result := mul(uUNIT, sub(0, 18)) } case 10 { result := mul(uUNIT, sub(1, 18)) } case 100 { result := mul(uUNIT, sub(2, 18)) } case 1000 { result := mul(uUNIT, sub(3, 18)) } case 10000 { result := mul(uUNIT, sub(4, 18)) } case 100000 { result := mul(uUNIT, sub(5, 18)) } case 1000000 { result := mul(uUNIT, sub(6, 18)) } case 10000000 { result := mul(uUNIT, sub(7, 18)) } case 100000000 { result := mul(uUNIT, sub(8, 18)) } case 1000000000 { result := mul(uUNIT, sub(9, 18)) } case 10000000000 { result := mul(uUNIT, sub(10, 18)) } case 100000000000 { result := mul(uUNIT, sub(11, 18)) } case 1000000000000 { result := mul(uUNIT, sub(12, 18)) } case 10000000000000 { result := mul(uUNIT, sub(13, 18)) } case 100000000000000 { result := mul(uUNIT, sub(14, 18)) } case 1000000000000000 { result := mul(uUNIT, sub(15, 18)) } case 10000000000000000 { result := mul(uUNIT, sub(16, 18)) } case 100000000000000000 { result := mul(uUNIT, sub(17, 18)) } case 1000000000000000000 { result := 0 } case 10000000000000000000 { result := uUNIT } case 100000000000000000000 { result := mul(uUNIT, 2) } case 1000000000000000000000 { result := mul(uUNIT, 3) } case 10000000000000000000000 { result := mul(uUNIT, 4) } case 100000000000000000000000 { result := mul(uUNIT, 5) } case 1000000000000000000000000 { result := mul(uUNIT, 6) } case 10000000000000000000000000 { result := mul(uUNIT, 7) } case 100000000000000000000000000 { result := mul(uUNIT, 8) } case 1000000000000000000000000000 { result := mul(uUNIT, 9) } case 10000000000000000000000000000 { result := mul(uUNIT, 10) } case 100000000000000000000000000000 { result := mul(uUNIT, 11) } case 1000000000000000000000000000000 { result := mul(uUNIT, 12) } case 10000000000000000000000000000000 { result := mul(uUNIT, 13) } case 100000000000000000000000000000000 { result := mul(uUNIT, 14) } case 1000000000000000000000000000000000 { result := mul(uUNIT, 15) } case 10000000000000000000000000000000000 { result := mul(uUNIT, 16) } case 100000000000000000000000000000000000 { result := mul(uUNIT, 17) } case 1000000000000000000000000000000000000 { result := mul(uUNIT, 18) } case 10000000000000000000000000000000000000 { result := mul(uUNIT, 19) } case 100000000000000000000000000000000000000 { result := mul(uUNIT, 20) } case 1000000000000000000000000000000000000000 { result := mul(uUNIT, 21) } case 10000000000000000000000000000000000000000 { result := mul(uUNIT, 22) } case 100000000000000000000000000000000000000000 { result := mul(uUNIT, 23) } case 1000000000000000000000000000000000000000000 { result := mul(uUNIT, 24) } case 10000000000000000000000000000000000000000000 { result := mul(uUNIT, 25) } case 100000000000000000000000000000000000000000000 { result := mul(uUNIT, 26) } case 1000000000000000000000000000000000000000000000 { result := mul(uUNIT, 27) } case 10000000000000000000000000000000000000000000000 { result := mul(uUNIT, 28) } case 100000000000000000000000000000000000000000000000 { result := mul(uUNIT, 29) } case 1000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 30) } case 10000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 31) } case 100000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 32) } case 1000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 33) } case 10000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 34) } case 100000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 35) } case 1000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 36) } case 10000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 37) } case 100000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 38) } case 1000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 39) } case 10000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 40) } case 100000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 41) } case 1000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 42) } case 10000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 43) } case 100000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 44) } case 1000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 45) } case 10000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 46) } case 100000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 47) } case 1000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 48) } case 10000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 49) } case 100000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 50) } case 1000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 51) } case 10000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 52) } case 100000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 53) } case 1000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 54) } case 10000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 55) } case 100000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 56) } case 1000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 57) } case 10000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 58) } case 100000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 59) } default { result := uMAX_UD60x18 } } if (result.unwrap() == uMAX_UD60x18) { unchecked { // Inline the fixed-point division to save gas. result = wrap(log2(x).unwrap() * uUNIT / uLOG2_10); } } } /// @notice Calculates the binary logarithm of x using the iterative approximation algorithm: /// /// $$ /// log_2{x} = n + log_2{y}, \text{ where } y = x*2^{-n}, \ y \in [1, 2) /// $$ /// /// For $0 \leq x \lt 1$, the input is inverted: /// /// $$ /// log_2{x} = -log_2{\frac{1}{x}} /// $$ /// /// @dev See https://en.wikipedia.org/wiki/Binary_logarithm#Iterative_approximation /// /// Notes: /// - Due to the lossy precision of the iterative approximation, the results are not perfectly accurate to the last decimal. /// /// Requirements: /// - x ≥ UNIT /// /// @param x The UD60x18 number for which to calculate the binary logarithm. /// @return result The binary logarithm as a UD60x18 number. /// @custom:smtchecker abstract-function-nondet function log2(UD60x18 x) pure returns (UD60x18 result) { uint256 xUint = x.unwrap(); if (xUint < uUNIT) { revert Errors.PRBMath_UD60x18_Log_InputTooSmall(x); } unchecked { // Calculate the integer part of the logarithm. uint256 n = Common.msb(xUint / uUNIT); // This is the integer part of the logarithm as a UD60x18 number. The operation can't overflow because n // n is at most 255 and UNIT is 1e18. uint256 resultUint = n * uUNIT; // Calculate $y = x * 2^{-n}$. uint256 y = xUint >> n; // If y is the unit number, the fractional part is zero. if (y == uUNIT) { return wrap(resultUint); } // Calculate the fractional part via the iterative approximation. // The `delta >>= 1` part is equivalent to `delta /= 2`, but shifting bits is more gas efficient. uint256 DOUBLE_UNIT = 2e18; for (uint256 delta = uHALF_UNIT; delta > 0; delta >>= 1) { y = (y * y) / uUNIT; // Is y^2 >= 2e18 and so in the range [2e18, 4e18)? if (y >= DOUBLE_UNIT) { // Add the 2^{-m} factor to the logarithm. resultUint += delta; // Halve y, which corresponds to z/2 in the Wikipedia article. y >>= 1; } } result = wrap(resultUint); } } /// @notice Multiplies two UD60x18 numbers together, returning a new UD60x18 number. /// /// @dev Uses {Common.mulDiv} to enable overflow-safe multiplication and division. /// /// Notes: /// - Refer to the notes in {Common.mulDiv}. /// /// Requirements: /// - Refer to the requirements in {Common.mulDiv}. /// /// @dev See the documentation in {Common.mulDiv18}. /// @param x The multiplicand as a UD60x18 number. /// @param y The multiplier as a UD60x18 number. /// @return result The product as a UD60x18 number. /// @custom:smtchecker abstract-function-nondet function mul(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) { result = wrap(Common.mulDiv18(x.unwrap(), y.unwrap())); } /// @notice Raises x to the power of y. /// /// For $1 \leq x \leq \infty$, the following standard formula is used: /// /// $$ /// x^y = 2^{log_2{x} * y} /// $$ /// /// For $0 \leq x \lt 1$, since the unsigned {log2} is undefined, an equivalent formula is used: /// /// $$ /// i = \frac{1}{x} /// w = 2^{log_2{i} * y} /// x^y = \frac{1}{w} /// $$ /// /// @dev Notes: /// - Refer to the notes in {log2} and {mul}. /// - Returns `UNIT` for 0^0. /// - It may not perform well with very small values of x. Consider using SD59x18 as an alternative. /// /// Requirements: /// - Refer to the requirements in {exp2}, {log2}, and {mul}. /// /// @param x The base as a UD60x18 number. /// @param y The exponent as a UD60x18 number. /// @return result The result as a UD60x18 number. /// @custom:smtchecker abstract-function-nondet function pow(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) { uint256 xUint = x.unwrap(); uint256 yUint = y.unwrap(); // If both x and y are zero, the result is `UNIT`. If just x is zero, the result is always zero. if (xUint == 0) { return yUint == 0 ? UNIT : ZERO; } // If x is `UNIT`, the result is always `UNIT`. else if (xUint == uUNIT) { return UNIT; } // If y is zero, the result is always `UNIT`. if (yUint == 0) { return UNIT; } // If y is `UNIT`, the result is always x. else if (yUint == uUNIT) { return x; } // If x is > UNIT, use the standard formula. if (xUint > uUNIT) { result = exp2(mul(log2(x), y)); } // Conversely, if x < UNIT, use the equivalent formula. else { UD60x18 i = wrap(uUNIT_SQUARED / xUint); UD60x18 w = exp2(mul(log2(i), y)); result = wrap(uUNIT_SQUARED / w.unwrap()); } } /// @notice Raises x (a UD60x18 number) to the power y (an unsigned basic integer) using the well-known /// algorithm "exponentiation by squaring". /// /// @dev See https://en.wikipedia.org/wiki/Exponentiation_by_squaring. /// /// Notes: /// - Refer to the notes in {Common.mulDiv18}. /// - Returns `UNIT` for 0^0. /// /// Requirements: /// - The result must fit in UD60x18. /// /// @param x The base as a UD60x18 number. /// @param y The exponent as a uint256. /// @return result The result as a UD60x18 number. /// @custom:smtchecker abstract-function-nondet function powu(UD60x18 x, uint256 y) pure returns (UD60x18 result) { // Calculate the first iteration of the loop in advance. uint256 xUint = x.unwrap(); uint256 resultUint = y & 1 > 0 ? xUint : uUNIT; // Equivalent to `for(y /= 2; y > 0; y /= 2)`. for (y >>= 1; y > 0; y >>= 1) { xUint = Common.mulDiv18(xUint, xUint); // Equivalent to `y % 2 == 1`. if (y & 1 > 0) { resultUint = Common.mulDiv18(resultUint, xUint); } } result = wrap(resultUint); } /// @notice Calculates the square root of x using the Babylonian method. /// /// @dev See https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method. /// /// Notes: /// - The result is rounded toward zero. /// /// Requirements: /// - x ≤ MAX_UD60x18 / UNIT /// /// @param x The UD60x18 number for which to calculate the square root. /// @return result The result as a UD60x18 number. /// @custom:smtchecker abstract-function-nondet function sqrt(UD60x18 x) pure returns (UD60x18 result) { uint256 xUint = x.unwrap(); unchecked { if (xUint > uMAX_UD60x18 / uUNIT) { revert Errors.PRBMath_UD60x18_Sqrt_Overflow(x); } // Multiply x by `UNIT` to account for the factor of `UNIT` picked up when multiplying two UD60x18 numbers. // In this case, the two numbers are both the square root. result = wrap(Common.sqrt(xUint * uUNIT)); } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; import "./Casting.sol" as Casting; import "./Helpers.sol" as Helpers; import "./Math.sol" as Math; /// @notice The unsigned 60.18-decimal fixed-point number representation, which can have up to 60 digits and up to 18 /// decimals. The values of this are bound by the minimum and the maximum values permitted by the Solidity type uint256. /// @dev The value type is defined here so it can be imported in all other files. type UD60x18 is uint256; /*////////////////////////////////////////////////////////////////////////// CASTING //////////////////////////////////////////////////////////////////////////*/ using { Casting.intoSD1x18, Casting.intoSD21x18, Casting.intoSD59x18, Casting.intoUD2x18, Casting.intoUD21x18, Casting.intoUint128, Casting.intoUint256, Casting.intoUint40, Casting.unwrap } for UD60x18 global; /*////////////////////////////////////////////////////////////////////////// MATHEMATICAL FUNCTIONS //////////////////////////////////////////////////////////////////////////*/ // The global "using for" directive makes the functions in this library callable on the UD60x18 type. using { Math.avg, Math.ceil, Math.div, Math.exp, Math.exp2, Math.floor, Math.frac, Math.gm, Math.inv, Math.ln, Math.log10, Math.log2, Math.mul, Math.pow, Math.powu, Math.sqrt } for UD60x18 global; /*////////////////////////////////////////////////////////////////////////// HELPER FUNCTIONS //////////////////////////////////////////////////////////////////////////*/ // The global "using for" directive makes the functions in this library callable on the UD60x18 type. using { Helpers.add, Helpers.and, Helpers.eq, Helpers.gt, Helpers.gte, Helpers.isZero, Helpers.lshift, Helpers.lt, Helpers.lte, Helpers.mod, Helpers.neq, Helpers.not, Helpers.or, Helpers.rshift, Helpers.sub, Helpers.uncheckedAdd, Helpers.uncheckedSub, Helpers.xor } for UD60x18 global; /*////////////////////////////////////////////////////////////////////////// OPERATORS //////////////////////////////////////////////////////////////////////////*/ // The global "using for" directive makes it possible to use these operators on the UD60x18 type. using { Helpers.add as +, Helpers.and2 as &, Math.div as /, Helpers.eq as ==, Helpers.gt as >, Helpers.gte as >=, Helpers.lt as <, Helpers.lte as <=, Helpers.or as |, Helpers.mod as %, Math.mul as *, Helpers.neq as !=, Helpers.not as ~, Helpers.sub as -, Helpers.xor as ^ } for UD60x18 global;
// SPDX-License-Identifier: MIT pragma solidity ^0.8.24; import {IScrollMessenger} from "../libraries/IScrollMessenger.sol"; interface IL2ScrollMessenger is IScrollMessenger { /********** * Events * **********/ /// @notice Emitted when the maximum number of times each message can fail in L2 is updated. /// @param oldMaxFailedExecutionTimes The old maximum number of times each message can fail in L2. /// @param newMaxFailedExecutionTimes The new maximum number of times each message can fail in L2. event UpdateMaxFailedExecutionTimes(uint256 oldMaxFailedExecutionTimes, uint256 newMaxFailedExecutionTimes); /***************************** * Public Mutating Functions * *****************************/ /// @notice execute L1 => L2 message /// @dev Make sure this is only called by privileged accounts. /// @param from The address of the sender of the message. /// @param to The address of the recipient of the message. /// @param value The msg.value passed to the message call. /// @param nonce The nonce of the message to avoid replay attack. /// @param message The content of the message. function relayMessage( address from, address to, uint256 value, uint256 nonce, bytes calldata message ) external; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.24; interface IScrollMessenger { /********** * Events * **********/ /// @notice Emitted when a cross domain message is sent. /// @param sender The address of the sender who initiates the message. /// @param target The address of target contract to call. /// @param value The amount of value passed to the target contract. /// @param messageNonce The nonce of the message. /// @param gasLimit The optional gas limit passed to L1 or L2. /// @param message The calldata passed to the target contract. event SentMessage( address indexed sender, address indexed target, uint256 value, uint256 messageNonce, uint256 gasLimit, bytes message ); /// @notice Emitted when a cross domain message is relayed successfully. /// @param messageHash The hash of the message. event RelayedMessage(bytes32 indexed messageHash); /// @notice Emitted when a cross domain message is failed to relay. /// @param messageHash The hash of the message. event FailedRelayedMessage(bytes32 indexed messageHash); /********** * Errors * **********/ /// @dev Thrown when the given address is `address(0)`. error ErrorZeroAddress(); /************************* * Public View Functions * *************************/ /// @notice Return the sender of a cross domain message. function xDomainMessageSender() external view returns (address); /***************************** * Public Mutating Functions * *****************************/ /// @notice Send cross chain message from L1 to L2 or L2 to L1. /// @param target The address of account who receive the message. /// @param value The amount of ether passed when call target contract. /// @param message The content of the message. /// @param gasLimit Gas limit required to complete the message relay on corresponding chain. function sendMessage( address target, uint256 value, bytes calldata message, uint256 gasLimit ) external payable; /// @notice Send cross chain message from L1 to L2 or L2 to L1. /// @param target The address of account who receive the message. /// @param value The amount of ether passed when call target contract. /// @param message The content of the message. /// @param gasLimit Gas limit required to complete the message relay on corresponding chain. /// @param refundAddress The address of account who will receive the refunded fee. function sendMessage( address target, uint256 value, bytes calldata message, uint256 gasLimit, address refundAddress ) external payable; }
// SPDX-License-Identifier: MIT pragma solidity 0.8.27; library Byte32Lib { /// @notice Splits a bytes32 into an array of uint256, each representing 4 bytes /// @param input The bytes32 value to be split /// @return An array of 8 uint256 values, each representing 4 bytes of the input function split(bytes32 input) internal pure returns (uint256[] memory) { uint256[] memory parts = new uint256[](8); for (uint256 i = 0; i < 8; i++) { parts[i] = uint256(uint32(bytes4(input << (i * 32)))); } return parts; } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.27; library DepositLib { /// @dev Represents a leaf in the Deposit tree struct Deposit { /// @notice Hash of the recipient's intmax2 address and a private salt bytes32 recipientSaltHash; /// @notice Index of the token being deposited uint32 tokenIndex; /// @notice Amount of tokens being deposited uint256 amount; } /// @notice Calculates the hash of a Deposit struct /// @param deposit The Deposit struct to be hashed /// @return bytes32 The calculated hash of the Deposit function getHash(Deposit memory deposit) internal pure returns (bytes32) { return keccak256( abi.encodePacked( deposit.recipientSaltHash, deposit.tokenIndex, deposit.amount ) ); } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.27; interface IPlonkVerifier { /// Verify a Plonk proof. /// Reverts if the proof or the public inputs are malformed. /// @param proof serialised plonk proof (using gnark's MarshalSolidity) /// @param publicInputs (must be reduced) /// @return success true if the proof passes false otherwise // solhint-disable-next-line func-name-mixedcase function Verify( bytes calldata proof, uint256[] calldata publicInputs ) external view returns (bool success); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.27; library WithdrawalLib { /// @dev Represents the information for a withdrawal operation struct Withdrawal { /// @notice The address of the recipient of the withdrawal address recipient; /// @notice The index of the token being withdrawn uint32 tokenIndex; /// @notice The amount of tokens being withdrawn uint256 amount; /// @notice The nullifier of the withdrawal, /// which is used to ensure the uniqueness of the withdrawal bytes32 nullifier; } /// @notice Calculates the hash of a Withdrawal struct /// @param withdrawal The Withdrawal struct to be hashed /// @return bytes32 The calculated hash of the Withdrawal function getHash( Withdrawal memory withdrawal ) internal pure returns (bytes32) { return keccak256( abi.encodePacked( withdrawal.recipient, withdrawal.tokenIndex, withdrawal.amount, withdrawal.nullifier ) ); } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.27; import {UD60x18} from "@prb/math/src/UD60x18.sol"; interface IContribution { /// @notice Emitted when the current period is incremented. /// @param newPeriod The new period number. event PeriodIncremented(uint256 indexed newPeriod); /// @notice Emitted when weights are registered for a period. /// @param periodNumber The number of the period. /// @param tags An array of bytes32 representing the tags. /// @param weights An array of uint256 representing the weights. event WeightRegistered( uint256 indexed periodNumber, bytes32[] tags, uint256[] weights ); /// @notice Emitted when a contribution is recorded. /// @param periodNumber The number of the period. /// @param tag The tag associated with the contribution. /// @param user The address of the user making the contribution. /// @param amount The amount of the contribution. event ContributionRecorded( uint256 indexed periodNumber, bytes32 indexed tag, address indexed user, uint256 amount ); /// @notice Error thrown when the input lengths of tags and weights do not match in registerWeights function /// @dev This error is raised to ensure data integrity when registering weights for tags error InvalidInputLength(); /// @notice Get the list of tags registered for a specific period. /// @param periodNumber The number of the period to query. /// @return An array of bytes32 representing the tags. function getTags( uint256 periodNumber ) external view returns (bytes32[] memory); /// @notice Get the weights array for a specified period. /// @param periodNumber The number of the period to query. /// @return An array of uint256 representing the weights. function getWeights( uint256 periodNumber ) external view returns (uint256[] memory); /// @notice Register tags and their corresponding weights for a period. /// @param periodNumber The number of the period to register for. /// @param tags An array of bytes32 representing the tags. /// @param weights An array of uint256 representing the weights corresponding to the tags. function registerWeights( uint256 periodNumber, bytes32[] memory tags, uint256[] memory weights ) external; /// @notice Increment the current period number. function incrementPeriod() external; /// @notice Record a contribution for a specific tag and user. /// @param tag The tag associated with the contribution. /// @param user The address of the user making the contribution. /// @param amount The amount of contribution to record. function recordContribution( bytes32 tag, address user, uint256 amount ) external; /// @notice Returns the current contribution of a user for a specific tag in the current period /// @dev This function does not apply any weighting to the contribution /// @param tag The tag (as bytes32) for which the contribution is being queried /// @param user The address of the user whose contribution is being queried /// @return The unweighted contribution amount as a uint256 function getCurrentContribution( bytes32 tag, address user ) external view returns (uint256); /// @notice Get the contribution rate of a specific user for a given period. /// @param periodNumber The number of the period to query. /// @param user The address of the user to check. /// @return The contribution rate as a UD60x18 value, representing the user's share of the total contribution. function getContributionRate( uint256 periodNumber, address user ) external view returns (UD60x18); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.27; import {DepositLib} from "../common/DepositLib.sol"; import {WithdrawalLib} from "../common/WithdrawalLib.sol"; import {DepositQueueLib} from "./lib/DepositQueueLib.sol"; interface ILiquidity { /// @notice address is zero address error AddressZero(); /// @notice Error thrown when someone other than the original depositor tries to cancel a deposit error OnlySenderCanCancelDeposit(); /// @notice Error thrown when the provided deposit hash doesn't match the calculated hash during cancellation /// @param depositDataHash The hash from the deposit data /// @param calculatedHash The hash calculated from given input error InvalidDepositHash(bytes32 depositDataHash, bytes32 calculatedHash); /// @notice Error thrown when the sender is not the Scroll Messenger in onlyWithdrawal context error SenderIsNotScrollMessenger(); /// @notice Error thrown when the withdrawal contract address is not set error WithdrawalAddressNotSet(); /// @notice Error thrown when the xDomainMessageSender of the Scroll Messenger doesn't match the withdrawal contract address error InvalidWithdrawalAddress(); /// @notice Error thrown when trying to claim a non-existent withdrawal /// @param withdrawalHash The hash of the withdrawal that wasn't found error WithdrawalNotFound(bytes32 withdrawalHash); /// @notice Error thrown when trying to deposit zero amount of native/ERC20/ERC1155 tokens error TriedToDepositZero(); /// @notice Error thrown when already analyzed deposits error AlreadyAnalyzed(); /// @notice Error thrown when the deposit hash already exists error DepositHashAlreadyExists(bytes32 depositHash); /// @notice Event emitted when a deposit is made /// @param depositId The unique identifier for the deposit /// @param sender The address that made the deposit /// @param recipientSaltHash The hash of the recipient's intmax2 address (BLS public key) and a secret salt /// @param tokenIndex The index of the token being deposited /// @param amount The amount of tokens deposited /// @param depositedAt The timestamp of the deposit event Deposited( uint256 indexed depositId, address indexed sender, bytes32 indexed recipientSaltHash, uint32 tokenIndex, uint256 amount, uint256 depositedAt ); /// @notice Event emitted when deposits are analyzed and relayed /// @param upToDepositId The highest deposit ID that was analyzed /// @param rejectedIndices Array of deposit IDs that were rejected /// @param gasLimit The gas limit for the L2 transaction /// @param message Additional message data event DepositsAnalyzedAndRelayed( uint256 indexed upToDepositId, uint256[] rejectedIndices, uint256 gasLimit, bytes message ); /// @notice Event emitted when a deposit is canceled /// @param depositId The ID of the canceled deposit event DepositCanceled(uint256 indexed depositId); /// @notice Event emitted when a withdrawal becomes claimable /// @param withdrawalHash The hash of the claimable withdrawal event WithdrawalClaimable(bytes32 indexed withdrawalHash); /// @notice Event emitted when a direct withdrawal succeeds /// @param withdrawalHash The hash of the successful withdrawal event DirectWithdrawalSuccessed( bytes32 indexed withdrawalHash, address indexed recipient ); /// @notice Event emitted when a direct withdrawal fails, and the funds become claimable /// @param withdrawalHash The hash of the failed withdrawal /// @param withdrawal The withdrawal data event DirectWithdrawalFailed( bytes32 indexed withdrawalHash, WithdrawalLib.Withdrawal withdrawal ); /// @notice Event emitted when a withdrawal is claimed /// @param recipient The address that claimed the withdrawal /// @param withdrawalHash The hash of the claimed withdrawal event ClaimedWithdrawal( address indexed recipient, bytes32 indexed withdrawalHash ); /// @notice Pause deposits function pauseDeposits() external; /// @notice Unpause deposits function unpauseDeposits() external; /// @notice Deposit native token /// @dev recipientSaltHash is the Poseidon hash of the intmax2 address (32 bytes) and a secret salt /// @param recipientSaltHash The hash of the recipient's address and a secret salt function depositNativeToken(bytes32 recipientSaltHash) external payable; /// @notice Deposit a specified amount of ERC20 token /// @dev Requires prior approval for this contract to spend the tokens /// @dev recipientSaltHash is the Poseidon hash of the intmax2 address (32 bytes) and a secret salt /// @param tokenAddress The address of the ERC20 token contract /// @param recipientSaltHash The hash of the recipient's address and a secret salt /// @param amount The amount of tokens to deposit function depositERC20( address tokenAddress, bytes32 recipientSaltHash, uint256 amount ) external; /// @notice Deposit an ERC721 token /// @dev Requires prior approval for this contract to transfer the token /// @param tokenAddress The address of the ERC721 token contract /// @param recipientSaltHash The hash of the recipient's address and a secret salt /// @param tokenId The ID of the token to deposit function depositERC721( address tokenAddress, bytes32 recipientSaltHash, uint256 tokenId ) external; /// @notice Deposit a specified amount of ERC1155 tokens /// @param tokenAddress The address of the ERC1155 token contract /// @param recipientSaltHash The hash of the recipient's address and a secret salt /// @param tokenId The ID of the token to deposit /// @param amount The amount of tokens to deposit function depositERC1155( address tokenAddress, bytes32 recipientSaltHash, uint256 tokenId, uint256 amount ) external; /// @notice Trusted nodes submit the IDs of deposits that do not meet AML standards by this method /// @dev upToDepositId specifies the last deposit id that have been analyzed. It must be greater than lastAnalyzedDeposit and less than or equal to the latest Deposit ID. /// @dev rejectDepositIndices must be greater than lastAnalyzedDeposit and less than or equal to upToDepositId. /// @param upToDepositId The upper limit of the Deposit ID that has been analyzed. It must be greater than lastAnalyzedDeposit and less than or equal to the latest Deposit ID. /// @param rejectDepositIds An array of ids of deposits to exclude. These indices must be greater than lastAnalyzedDeposit and less than or equal to upToDepositId. /// @param gasLimit The gas limit for the l2 transaction. function analyzeAndRelayDeposits( uint256 upToDepositId, uint256[] memory rejectDepositIds, uint256 gasLimit ) external payable; /// @notice Method to cancel a deposit /// @dev The deposit ID and its content should be included in the calldata /// @param depositId The ID of the deposit to cancel /// @param deposit The deposit data function cancelDeposit( uint256 depositId, DepositLib.Deposit calldata deposit ) external; /// @notice Process withdrawals, called by the scroll messenger /// @param withdrawals Array of withdrawals to process /// @param withdrawalHahes Array of withdrawal hashes function processWithdrawals( WithdrawalLib.Withdrawal[] calldata withdrawals, bytes32[] calldata withdrawalHahes ) external; /// @notice Get the ID of the last deposit relayed to L2 /// @return The ID of the last relayed deposit function getLastRelayedDepositId() external view returns (uint256); /// @notice Get the ID of the last deposit to L2 /// @return The ID of the last deposit function getLastDepositId() external view returns (uint256); /// @notice Get deposit data for a given deposit ID /// @param depositId The ID of the deposit /// @return The deposit data function getDepositData( uint256 depositId ) external view returns (DepositQueueLib.DepositData memory); /// @notice Get deposit data list for a given deposit IDs /// @param depositIds The IDs of the deposit /// @return The deposit data list function getDepositDataBatch( uint256[] memory depositIds ) external view returns (DepositQueueLib.DepositData[] memory); /// @notice Get deposit data hash for a given deposit ID /// @param depositId The ID of the deposit /// @return The deposit data hash function getDepositDataHash( uint256 depositId ) external view returns (bytes32); /// @notice Claim withdrawals for tokens that are not direct withdrawals /// @param withdrawals Array of withdrawals to claim function claimWithdrawals( WithdrawalLib.Withdrawal[] calldata withdrawals ) external; /// @notice Check if the deposit is valid /// @param depositId The ID of the deposit /// @param recipientSaltHash The hash of the recipient's intmax2 address (BLS public key) and a secret salt /// @param tokenIndex The index of the token being deposited /// @param amount The amount of tokens deposited /// @param sender The address that made the deposit /// @return if deposit is valid, return true function isDepositValid( uint256 depositId, bytes32 recipientSaltHash, uint32 tokenIndex, uint256 amount, address sender ) external view returns (bool); /// @notice ERC1155 token receiver function /// @return bytes4 The function selector function onERC1155Received( address, address, uint256, uint256, bytes calldata ) external pure returns (bytes4); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.27; /// @title Deposit Queue Library /// @notice A library for managing a queue of pending deposits library DepositQueueLib { /// @notice Error thrown when trying to analyze deposits outside the queue range /// @param upToDepositId The requested deposit ID to analyze up to /// @param firstDepositId The first deposit ID in the queue /// @param lastDepositId The last deposit ID in the queue error TriedAnalyzeOutOfRange( uint256 upToDepositId, uint256 firstDepositId, uint256 lastDepositId ); /// @notice Error thrown when trying to reject a deposit outside the analyzed range /// @param rejectIndex The index of the deposit to be rejected /// @param front The front index of the queue /// @param upToDepositId The upper bound of the analyzed range error TriedToRejectOutOfRange( uint256 rejectIndex, uint256 front, uint256 upToDepositId ); /// @notice Represents a queue of pending deposits struct DepositQueue { DepositData[] depositData; /// Array of deposits that are pending uint256 front; /// Index of the first element in the queue } /// @notice Represents data for a single deposit /// @dev Includes deposit hash, sender address, and rejection status struct DepositData { bytes32 depositHash; address sender; bool isRejected; } /// @notice Initializes the deposit queue /// @dev Pushes a dummy element to make the queue 1-indexed /// @param depositQueue The storage reference to the DepositQueue struct function initialize(DepositQueue storage depositQueue) internal { depositQueue.depositData.push(DepositData(0, address(0), false)); depositQueue.front = 1; } /// @notice Adds a new deposit to the queue /// @param depositQueue The storage reference to the DepositQueue struct /// @param depositHash The hash of the deposit /// @param sender The address of the depositor /// @return depositId The ID of the newly added deposit function enqueue( DepositQueue storage depositQueue, bytes32 depositHash, address sender ) internal returns (uint256 depositId) { depositId = depositQueue.depositData.length; depositQueue.depositData.push(DepositData(depositHash, sender, false)); } /// @notice Deletes a deposit from the queue /// @param depositQueue The storage reference to the DepositQueue struct /// @param depositId The ID of the deposit to be deleted /// @return depositData The data of the deleted deposit function deleteDeposit( DepositQueue storage depositQueue, uint256 depositId ) internal returns (DepositData memory depositData) { depositData = depositQueue.depositData[depositId]; delete depositQueue.depositData[depositId]; } /// @notice Analyzes deposits in the queue, marking some as rejected /// @dev Collects deposit hashes from front to upToDepositId, skipping rejected ones /// @param depositQueue The storage reference to the DepositQueue struct /// @param upToDepositId The upper bound deposit ID for analysis /// @param rejectIndices Array of deposit IDs to be marked as rejected /// @return An array of deposit hashes that were not rejected function analyze( DepositQueue storage depositQueue, uint256 upToDepositId, uint256[] memory rejectIndices ) internal returns (bytes32[] memory) { uint256 front = depositQueue.front; if ( upToDepositId >= depositQueue.depositData.length || upToDepositId < front ) { revert TriedAnalyzeOutOfRange( upToDepositId, front, depositQueue.depositData.length - 1 ); } for (uint256 i = 0; i < rejectIndices.length; i++) { uint256 rejectIndex = rejectIndices[i]; if (rejectIndex > upToDepositId || rejectIndex < front) { revert TriedToRejectOutOfRange( rejectIndex, front, upToDepositId ); } depositQueue.depositData[rejectIndex].isRejected = true; } uint256 counter = 0; for (uint256 i = front; i <= upToDepositId; i++) { if (depositQueue.depositData[i].sender == address(0)) { continue; } if (depositQueue.depositData[i].isRejected) { continue; } counter++; } bytes32[] memory depositHashes = new bytes32[](counter); uint256 depositHashesIndex = 0; for (uint256 i = front; i <= upToDepositId; i++) { if (depositQueue.depositData[i].sender == address(0)) { continue; } if (depositQueue.depositData[i].isRejected) { continue; } depositHashes[depositHashesIndex] = depositQueue .depositData[i] .depositHash; depositHashesIndex++; } depositQueue.front = upToDepositId + 1; return depositHashes; } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.27; /// @title IRollup /// @notice Interface for the Rollup contract interface IRollup { /// @notice address is zero address error AddressZero(); /// @notice Error thrown when a non-ScrollMessenger calls a function restricted to ScrollMessenger error OnlyScrollMessenger(); /// @notice Error thrown when the xDomainMessageSender in ScrollMessenger is not the liquidity contract error OnlyLiquidity(); /// @notice Error thrown when the number of public keys exceeds 128 error TooManySenderPublicKeys(); /// @notice Error thrown when the number of account IDs exceeds 128 error TooManyAccountIds(); /// @notice Error thrown when the length of account IDs bytes is not a multiple of 5 error SenderAccountIdsInvalidLength(); /// @notice Error thrown when the posted block fails the pairing test error PairingCheckFailed(); /// @notice Error thrown when the specified block number is greater than the latest block number error BlockNumberOutOfRange(); /// @notice Error thrown when the fee for the rate limiter is insufficient error InsufficientPenaltyFee(); /// @notice Event emitted when deposits bridged from the liquidity contract are processed /// @param lastProcessedDepositId The ID of the last processed deposit /// @param depositTreeRoot The root of the deposit tree after processing event DepositsProcessed( uint256 indexed lastProcessedDepositId, bytes32 depositTreeRoot ); /// @notice Event emitted when a deposit is inserted into the deposit tree /// @param depositIndex The index of the deposit /// @param depositHash The hash of the deposit event DepositLeafInserted( uint32 indexed depositIndex, bytes32 indexed depositHash ); /// @notice Event emitted when a new block is posted /// @param prevBlockHash The hash of the previous block /// @param blockBuilder The address of the block builder /// @param blockNumber The number of the posted block /// @param depositTreeRoot The root of the deposit tree /// @param signatureHash The hash of the signature event BlockPosted( bytes32 indexed prevBlockHash, address indexed blockBuilder, uint256 blockNumber, bytes32 depositTreeRoot, bytes32 signatureHash ); /// @notice Posts a registration block (for all senders' first transactions, specified by public keys) /// @dev msg.value must be greater than or equal to the penalty fee of the rate limiter /// @param txTreeRoot The root of the transaction tree /// @param senderFlags Flags indicating whether senders' signatures are included in the aggregated signature /// @param aggregatedPublicKey The aggregated public key /// @param aggregatedSignature The aggregated signature /// @param messagePoint The hash of the tx tree root to G2 /// @param senderPublicKeys The public keys of the senders function postRegistrationBlock( bytes32 txTreeRoot, bytes16 senderFlags, bytes32[2] calldata aggregatedPublicKey, bytes32[4] calldata aggregatedSignature, bytes32[4] calldata messagePoint, uint256[] calldata senderPublicKeys ) external payable; /// @notice Posts a non-registration block (for all senders' subsequent transactions, specified by account IDs) /// @dev msg.value must be greater than or equal to the penalty fee of the rate limiter /// @param txTreeRoot The root of the transaction tree /// @param senderFlags Sender flags /// @param aggregatedPublicKey The aggregated public key /// @param aggregatedSignature The aggregated signature /// @param messagePoint The hash of the tx tree root to G2 /// @param publicKeysHash The hash of the public keys /// @param senderAccountIds The account IDs arranged in a byte sequence function postNonRegistrationBlock( bytes32 txTreeRoot, bytes16 senderFlags, bytes32[2] calldata aggregatedPublicKey, bytes32[4] calldata aggregatedSignature, bytes32[4] calldata messagePoint, bytes32 publicKeysHash, bytes calldata senderAccountIds ) external payable; /// @notice Withdraws the penalty fee from the Rollup contract /// @param to The address to which the penalty fee is transferred /// @dev Only the owner can call this function function withdrawPenaltyFee(address to) external; /// @notice Update the deposit tree branch and root /// @dev Only Liquidity contract can call this function via Scroll Messenger /// @param lastProcessedDepositId The ID of the last processed deposit /// @param depositHashes The hashes of the deposits function processDeposits( uint256 lastProcessedDepositId, bytes32[] calldata depositHashes ) external; /// @notice Get the block number of the latest posted block /// @return The latest block number function getLatestBlockNumber() external view returns (uint32); /// @notice Get the block builder for a specific block number /// @param blockNumber The block number to query /// @return The address of the block builder function getBlockBuilder( uint32 blockNumber ) external view returns (address); /// @notice Get the block hash for a specific block number /// @param blockNumber The block number to query /// @return The hash of the specified block function getBlockHash(uint32 blockNumber) external view returns (bytes32); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.27; import {WithdrawalProofPublicInputsLib} from "./lib/WithdrawalProofPublicInputsLib.sol"; import {ChainedWithdrawalLib} from "./lib/ChainedWithdrawalLib.sol"; import {WithdrawalLib} from "../common/WithdrawalLib.sol"; interface IWithdrawal { /// @notice address is zero address error AddressZero(); /// @notice Error thrown when the verification of the withdrawal proof's public input hash chain fails error WithdrawalChainVerificationFailed(); /// @notice Error thrown when the aggregator in the withdrawal proof's public input doesn't match the actual contract executor error WithdrawalAggregatorMismatch(); /// @notice Error thrown when the block hash in the withdrawal proof's public input doesn't exist /// @param blockHash The non-existent block hash error BlockHashNotExists(bytes32 blockHash); /// @notice Error thrown when the ZKP verification of the withdrawal proof fails error WithdrawalProofVerificationFailed(); /// @notice Error thrown when attempting to add a token to direct withdrawal tokens that already exists /// @param tokenIndice The index of the token that already exists error TokenAlreadyExist(uint256 tokenIndice); /// @notice Error thrown when attempting to remove a non-existent token from direct withdrawal tokens /// @param tokenIndice The index of the non-existent token error TokenNotExist(uint256 tokenIndice); /// @notice Emitted when a claimable withdrawal is queued /// @param withdrawalHash The hash of the withdrawal /// @param recipient The address of the recipient /// @param withdrawal The withdrawal details event ClaimableWithdrawalQueued( bytes32 indexed withdrawalHash, address indexed recipient, WithdrawalLib.Withdrawal withdrawal ); /// @notice Emitted when a direct withdrawal is queued /// @param withdrawalHash The hash of the withdrawal /// @param recipient The address of the recipient /// @param withdrawal The withdrawal details event DirectWithdrawalQueued( bytes32 indexed withdrawalHash, address indexed recipient, WithdrawalLib.Withdrawal withdrawal ); /// @notice Emitted when direct withdrawal token indices are added /// @param tokenIndices The token indices that were added event DirectWithdrawalTokenIndicesAdded(uint256[] tokenIndices); /// @notice Emitted when direct withdrawal token indices are removed /// @param tokenIndices The token indices that were removed event DirectWithdrawalTokenIndicesRemoved(uint256[] tokenIndices); /// @notice Submit withdrawal proof from intmax2 /// @param withdrawals List of chained withdrawals /// @param publicInputs Public inputs for the withdrawal proof /// @param proof The proof data function submitWithdrawalProof( ChainedWithdrawalLib.ChainedWithdrawal[] calldata withdrawals, WithdrawalProofPublicInputsLib.WithdrawalProofPublicInputs calldata publicInputs, bytes calldata proof ) external; /// @notice Get the token indices for direct withdrawals /// @return An array of token indices function getDirectWithdrawalTokenIndices() external view returns (uint256[] memory); /// @notice Add token indices to the list of direct withdrawal token indices /// @param tokenIndices The token indices to add /// @notice ERC721 and ERC1155 tokens are not supported for direct withdrawal. /// When transferred to the liquidity contract, they will be converted to claimable withdrawals. function addDirectWithdrawalTokenIndices( uint256[] calldata tokenIndices ) external; /// @notice Remove token indices from the list of direct withdrawal token indices /// @param tokenIndices The token indices to remove function removeDirectWithdrawalTokenIndices( uint256[] calldata tokenIndices ) external; }
// SPDX-License-Identifier: MIT pragma solidity 0.8.27; /// @title ChainedWithdrawalLib /// @notice Library for handling chained withdrawals in a hash chain library ChainedWithdrawalLib { /// @notice Represents a withdrawal linked in a hash chain, used in withdrawal proof public inputs struct ChainedWithdrawal { address recipient; // Address of the withdrawal recipient uint32 tokenIndex; // Index of the token being withdrawn uint256 amount; // Amount of tokens being withdrawn bytes32 nullifier; // Nullifier to prevent double-spending bytes32 blockHash; // Hash of the block containing the withdrawal uint32 blockNumber; // Number of the block containing the withdrawal } /// @notice Hashes a ChainedWithdrawal with the previous hash in the chain /// @param withdrawal The ChainedWithdrawal to be hashed /// @param prevWithdrawalHash The hash of the previous withdrawal in the chain /// @return bytes32 The resulting hash function hashWithPrevHash( ChainedWithdrawal memory withdrawal, bytes32 prevWithdrawalHash ) private pure returns (bytes32) { return keccak256( abi.encodePacked( prevWithdrawalHash, withdrawal.recipient, withdrawal.tokenIndex, withdrawal.amount, withdrawal.nullifier, withdrawal.blockHash, withdrawal.blockNumber ) ); } /// @notice Verifies the integrity of a withdrawal hash chain /// @param withdrawals Array of ChainedWithdrawals to verify /// @param lastWithdrawalHash The expected hash of the last withdrawal in the chain /// @return bool True if the chain is valid, false otherwise function verifyWithdrawalChain( ChainedWithdrawal[] memory withdrawals, bytes32 lastWithdrawalHash ) internal pure returns (bool) { bytes32 prevWithdrawalHash = 0; for (uint256 i = 0; i < withdrawals.length; i++) { ChainedWithdrawal memory withdrawal = withdrawals[i]; prevWithdrawalHash = hashWithPrevHash( withdrawal, prevWithdrawalHash ); } if (prevWithdrawalHash != lastWithdrawalHash) { return false; } return true; } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.27; library WithdrawalProofPublicInputsLib { /// @notice Represents the public inputs for a withdrawal proof struct WithdrawalProofPublicInputs { bytes32 lastWithdrawalHash; // Hash of the last withdrawal in the chain address withdrawalAggregator; // Address of the withdrawal aggregator } /// @notice Computes the hash of the WithdrawalProofPublicInputs /// @param inputs The WithdrawalProofPublicInputs to be hashed /// @return bytes32 The resulting hash function getHash( WithdrawalProofPublicInputs memory inputs ) internal pure returns (bytes32) { return keccak256( abi.encodePacked( inputs.lastWithdrawalHash, inputs.withdrawalAggregator ) ); } }
{ "evmVersion": "paris", "optimizer": { "enabled": false, "runs": 200 }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "libraries": {} }
[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"AddressEmptyCode","type":"error"},{"inputs":[],"name":"AddressZero","type":"error"},{"inputs":[{"internalType":"bytes32","name":"blockHash","type":"bytes32"}],"name":"BlockHashNotExists","type":"error"},{"inputs":[{"internalType":"address","name":"implementation","type":"address"}],"name":"ERC1967InvalidImplementation","type":"error"},{"inputs":[],"name":"ERC1967NonPayable","type":"error"},{"inputs":[],"name":"FailedCall","type":"error"},{"inputs":[],"name":"InvalidInitialization","type":"error"},{"inputs":[],"name":"NotInitializing","type":"error"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"OwnableInvalidOwner","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"OwnableUnauthorizedAccount","type":"error"},{"inputs":[{"internalType":"uint256","name":"tokenIndice","type":"uint256"}],"name":"TokenAlreadyExist","type":"error"},{"inputs":[{"internalType":"uint256","name":"tokenIndice","type":"uint256"}],"name":"TokenNotExist","type":"error"},{"inputs":[],"name":"UUPSUnauthorizedCallContext","type":"error"},{"inputs":[{"internalType":"bytes32","name":"slot","type":"bytes32"}],"name":"UUPSUnsupportedProxiableUUID","type":"error"},{"inputs":[],"name":"WithdrawalAggregatorMismatch","type":"error"},{"inputs":[],"name":"WithdrawalChainVerificationFailed","type":"error"},{"inputs":[],"name":"WithdrawalProofVerificationFailed","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"withdrawalHash","type":"bytes32"},{"indexed":true,"internalType":"address","name":"recipient","type":"address"},{"components":[{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint32","name":"tokenIndex","type":"uint32"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"bytes32","name":"nullifier","type":"bytes32"}],"indexed":false,"internalType":"struct WithdrawalLib.Withdrawal","name":"withdrawal","type":"tuple"}],"name":"ClaimableWithdrawalQueued","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"withdrawalHash","type":"bytes32"},{"indexed":true,"internalType":"address","name":"recipient","type":"address"},{"components":[{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint32","name":"tokenIndex","type":"uint32"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"bytes32","name":"nullifier","type":"bytes32"}],"indexed":false,"internalType":"struct WithdrawalLib.Withdrawal","name":"withdrawal","type":"tuple"}],"name":"DirectWithdrawalQueued","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256[]","name":"tokenIndices","type":"uint256[]"}],"name":"DirectWithdrawalTokenIndicesAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256[]","name":"tokenIndices","type":"uint256[]"}],"name":"DirectWithdrawalTokenIndicesRemoved","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint64","name":"version","type":"uint64"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"implementation","type":"address"}],"name":"Upgraded","type":"event"},{"inputs":[],"name":"UPGRADE_INTERFACE_VERSION","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256[]","name":"tokenIndices","type":"uint256[]"}],"name":"addDirectWithdrawalTokenIndices","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"getDirectWithdrawalTokenIndices","outputs":[{"internalType":"uint256[]","name":"","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_admin","type":"address"},{"internalType":"address","name":"_scrollMessenger","type":"address"},{"internalType":"address","name":"_withdrawalVerifier","type":"address"},{"internalType":"address","name":"_liquidity","type":"address"},{"internalType":"address","name":"_rollup","type":"address"},{"internalType":"address","name":"_contribution","type":"address"},{"internalType":"uint256[]","name":"_directWithdrawalTokenIndices","type":"uint256[]"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"proxiableUUID","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256[]","name":"tokenIndices","type":"uint256[]"}],"name":"removeDirectWithdrawalTokenIndices","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint32","name":"tokenIndex","type":"uint32"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"bytes32","name":"nullifier","type":"bytes32"},{"internalType":"bytes32","name":"blockHash","type":"bytes32"},{"internalType":"uint32","name":"blockNumber","type":"uint32"}],"internalType":"struct ChainedWithdrawalLib.ChainedWithdrawal[]","name":"withdrawals","type":"tuple[]"},{"components":[{"internalType":"bytes32","name":"lastWithdrawalHash","type":"bytes32"},{"internalType":"address","name":"withdrawalAggregator","type":"address"}],"internalType":"struct WithdrawalProofPublicInputsLib.WithdrawalProofPublicInputs","name":"publicInputs","type":"tuple"},{"internalType":"bytes","name":"proof","type":"bytes"}],"name":"submitWithdrawalProof","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_scrollMessenger","type":"address"},{"internalType":"address","name":"_withdrawalVerifier","type":"address"},{"internalType":"address","name":"_liquidity","type":"address"},{"internalType":"address","name":"_rollup","type":"address"},{"internalType":"address","name":"_contribution","type":"address"}],"name":"updateContractAddresses","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newImplementation","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"upgradeToAndCall","outputs":[],"stateMutability":"payable","type":"function"}]
Contract Creation Code
60a06040523073ffffffffffffffffffffffffffffffffffffffff1660809073ffffffffffffffffffffffffffffffffffffffff1681525034801561004357600080fd5b5061005261005760201b60201c565b6101c1565b600061006761015b60201b60201c565b90508060000160089054906101000a900460ff16156100b2576040517ff92ee8a900000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b67ffffffffffffffff80168160000160009054906101000a900467ffffffffffffffff1667ffffffffffffffff16146101585767ffffffffffffffff8160000160006101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055507fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d267ffffffffffffffff60405161014f91906101a6565b60405180910390a15b50565b60007ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00905090565b600067ffffffffffffffff82169050919050565b6101a081610183565b82525050565b60006020820190506101bb6000830184610197565b92915050565b6080516138226101ea6000396000818161133e01528181611393015261154e01526138226000f3fe6080604052600436106100a75760003560e01c80638da5cb5b116100645780638da5cb5b146101855780639a0002a9146101b0578063a7178c37146101d9578063a93e83a614610204578063ad3cb1cc1461022d578063f2fde38b14610258576100a7565b80634f1ef286146100ac57806352d1902d146100c8578063715018a6146100f3578063717641051461010a57806377e88d2c14610133578063871c5fe71461015c575b600080fd5b6100c660048036038101906100c1919061262c565b610281565b005b3480156100d457600080fd5b506100dd6102a0565b6040516100ea91906126a1565b60405180910390f35b3480156100ff57600080fd5b506101086102d3565b005b34801561011657600080fd5b50610131600480360381019061012c91906126bc565b6102e7565b005b34801561013f57600080fd5b5061015a60048036038101906101559190612835565b610543565b005b34801561016857600080fd5b50610183600480360381019061017e919061294e565b610a91565b005b34801561019157600080fd5b5061019a610ae7565b6040516101a791906129aa565b60405180910390f35b3480156101bc57600080fd5b506101d760048036038101906101d2919061294e565b610b1f565b005b3480156101e557600080fd5b506101ee610c0d565b6040516101fb9190612a83565b60405180910390f35b34801561021057600080fd5b5061022b60048036038101906102269190612b75565b610c1e565b005b34801561023957600080fd5b5061024261127d565b60405161024f9190612c89565b60405180910390f35b34801561026457600080fd5b5061027f600480360381019061027a9190612cab565b6112b6565b005b61028961133c565b61029282611422565b61029c828261142d565b5050565b60006102aa61154c565b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc60001b905090565b6102db6115d3565b6102e5600061165a565b565b6102ef6115d3565b600073ffffffffffffffffffffffffffffffffffffffff168573ffffffffffffffffffffffffffffffffffffffff16146103655784600160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505b600073ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff16146103da57836000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505b600073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff16146104505782600360006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff16146104c65781600260006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505b600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff161461053c5780600460006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505b5050505050565b600061054d611731565b905060008160000160089054906101000a900460ff1615905060008260000160009054906101000a900467ffffffffffffffff1690506000808267ffffffffffffffff1614801561059b5750825b9050600060018367ffffffffffffffff161480156105d0575060003073ffffffffffffffffffffffffffffffffffffffff163b145b9050811580156105de575080155b15610615576040517ff92ee8a900000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60018560000160006101000a81548167ffffffffffffffff021916908367ffffffffffffffff16021790555083156106655760018560000160086101000a81548160ff0219169083151502179055505b600073ffffffffffffffffffffffffffffffffffffffff168c73ffffffffffffffffffffffffffffffffffffffff16036106cb576040517f9fabe1c100000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168b73ffffffffffffffffffffffffffffffffffffffff1603610731576040517f9fabe1c100000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168a73ffffffffffffffffffffffffffffffffffffffff1603610797576040517f9fabe1c100000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168973ffffffffffffffffffffffffffffffffffffffff16036107fd576040517f9fabe1c100000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168873ffffffffffffffffffffffffffffffffffffffff1603610863576040517f9fabe1c100000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168773ffffffffffffffffffffffffffffffffffffffff16036108c9576040517f9fabe1c100000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6108d28c611759565b6108da61176d565b8a600160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550896000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555087600260006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555086600460006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555088600360006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550610a2786611777565b8315610a835760008560000160086101000a81548160ff0219169083151502179055507fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d26001604051610a7a9190612d31565b60405180910390a15b505050505050505050505050565b610a996115d3565b610ae3828280806020026020016040519081016040528093929190818152602001838360200280828437600081840152601f19601f82011690508083019250505050505050611777565b5050565b600080610af261185a565b90508060000160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1691505090565b610b276115d3565b60005b82829050811015610bcf576000610b64848484818110610b4d57610b4c612d4c565b5b90506020020135600661188290919063ffffffff16565b905080610bc157838383818110610b7e57610b7d612d4c565b5b905060200201356040517f2a2c67cd000000000000000000000000000000000000000000000000000000008152600401610bb89190612d8a565b60405180910390fd5b508080600101915050610b2a565b507f0e5fb72f67c09578724f25132b948e5fb901741fa3240f11804518dc94799a2b8282604051610c01929190612e0f565b60405180910390a15050565b6060610c19600661189c565b905090565b610c2b85858585856118bd565b60008060008787905067ffffffffffffffff811115610c4d57610c4c612501565b5b604051908082528060200260200182016040528015610c7b5781602001602082028036833780820191505090505b50905060005b88889050811015610e74576000898983818110610ca157610ca0612d4c565b5b905060c00201803603810190610cb79190612f40565b9050600560008260600151815260200190815260200160002060009054906101000a900460ff1615610d10576001838381518110610cf857610cf7612d4c565b5b60200260200101901515908115158152505050610e67565b6001600560008360600151815260200190815260200160002060006101000a81548160ff0219169083151502179055506000600260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663d2b210a18360a001516040518263ffffffff1660e01b8152600401610da19190612f7c565b602060405180830381865afa158015610dbe573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610de29190612fac565b905081608001518114610e305781608001516040517f631b89b0000000000000000000000000000000000000000000000000000000008152600401610e2791906126a1565b60405180910390fd5b610e3d8260200151611ad9565b15610e55578580610e4d90613008565b965050610e64565b8480610e6090613008565b9550505b50505b8080600101915050610c81565b50600083148015610e855750600082145b15610e9257505050611276565b60008367ffffffffffffffff811115610eae57610ead612501565b5b604051908082528060200260200182016040528015610ee757816020015b610ed461242d565b815260200190600190039081610ecc5790505b50905060008367ffffffffffffffff811115610f0657610f05612501565b5b604051908082528060200260200182016040528015610f345781602001602082028036833780820191505090505b50905060008060005b8c8c905081101561112457858181518110610f5b57610f5a612d4c565b5b60200260200101516111175760008d8d83818110610f7c57610f7b612d4c565b5b905060c00201803603810190610f929190612f40565b905060006040518060800160405280836000015173ffffffffffffffffffffffffffffffffffffffff168152602001836020015163ffffffff1681526020018360400151815260200183606001518152509050610ff28260200151611ad9565b15611084578087868151811061100b5761100a612d4c565b5b6020026020010181905250806000015173ffffffffffffffffffffffffffffffffffffffff1661103a82611afc565b7fdbe674c66915823ad8cb90cac7eb482e951adec0311c9cf091da19de527ee9358360405161106991906130d2565b60405180910390a3848061107c90613008565b955050611114565b600061108f82611afc565b9050808786815181106110a5576110a4612d4c565b5b602002602001018181525050816000015173ffffffffffffffffffffffffffffffffffffffff16817f740137a4fd93de42bb435842325e4fad55ea4ba617db0b44125377b94b43249d846040516110fc91906130d2565b60405180910390a3848061110f90613008565b955050505b50505b8080600101915050610f3d565b506000639d6a54cb60e01b85856040516024016111429291906132a0565b604051602081830303815290604052907bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19166020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff838183161783525050505090506111aa81611b42565b600460009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663f099f9f57f738128fe393bef1bcd8a524796fff40618b938cd467c71fcf37850ab0ba4f7d7611211611c2c565b8a8c61121d91906132d7565b6040518463ffffffff1660e01b815260040161123b9392919061330b565b600060405180830381600087803b15801561125557600080fd5b505af1158015611269573d6000803e3d6000fd5b5050505050505050505050505b5050505050565b6040518060400160405280600581526020017f352e302e3000000000000000000000000000000000000000000000000000000081525081565b6112be6115d3565b600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff16036113305760006040517f1e4fbdf700000000000000000000000000000000000000000000000000000000815260040161132791906129aa565b60405180910390fd5b6113398161165a565b50565b7f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff163073ffffffffffffffffffffffffffffffffffffffff1614806113e957507f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff166113d0611c34565b73ffffffffffffffffffffffffffffffffffffffff1614155b15611420576040517fe07c8dba00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b565b61142a6115d3565b50565b8173ffffffffffffffffffffffffffffffffffffffff166352d1902d6040518163ffffffff1660e01b8152600401602060405180830381865afa92505050801561149557506040513d601f19601f820116820180604052508101906114929190612fac565b60015b6114d657816040517f4c9c8ce30000000000000000000000000000000000000000000000000000000081526004016114cd91906129aa565b60405180910390fd5b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc60001b811461153d57806040517faa1d49a400000000000000000000000000000000000000000000000000000000815260040161153491906126a1565b60405180910390fd5b6115478383611c8b565b505050565b7f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff163073ffffffffffffffffffffffffffffffffffffffff16146115d1576040517fe07c8dba00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b565b6115db611c2c565b73ffffffffffffffffffffffffffffffffffffffff166115f9610ae7565b73ffffffffffffffffffffffffffffffffffffffff16146116585761161c611c2c565b6040517f118cdaa700000000000000000000000000000000000000000000000000000000815260040161164f91906129aa565b60405180910390fd5b565b600061166461185a565b905060008160000160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff169050828260000160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055508273ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e060405160405180910390a3505050565b60007ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00905090565b611761611cfe565b61176a81611d3e565b50565b611775611cfe565b565b60005b815181101561181f5760006117b383838151811061179b5761179a612d4c565b5b60200260200101516006611dc490919063ffffffff16565b905080611811578282815181106117cd576117cc612d4c565b5b60200260200101516040517fd1d533d80000000000000000000000000000000000000000000000000000000081526004016118089190612d8a565b60405180910390fd5b50808060010191505061177a565b507f03e4a91d34a2a2419d5513d9814cf5ea9e317e6166670b4b89a97e478541d4b98160405161184f9190612a83565b60405180910390a150565b60007f9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300905090565b6000611894836000018360001b611dde565b905092915050565b606060006118ac83600001611ef2565b905060608190508092505050919050565b61192a83600001358686808060200260200160405190810160405280939291908181526020016000905b8282101561191757848483905060c002018036038101906119089190612f40565b815260200190600101906118e7565b5050505050611f4e90919063ffffffff16565b611960576040517ffbf63aef00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b611968611c2c565b73ffffffffffffffffffffffffffffffffffffffff168360200160208101906119919190612cab565b73ffffffffffffffffffffffffffffffffffffffff16146119de576040517fbe8e6d9600000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16637e4f7a8a8383611a3d611a3888803603810190611a339190613392565b611fba565b611ff4565b6040518463ffffffff1660e01b8152600401611a5b939291906133fd565b602060405180830381865afa158015611a78573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a9c919061346e565b611ad2576040517f38a3efc400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5050505050565b6000611af58263ffffffff16600661209f90919063ffffffff16565b9050919050565b60008160000151826020015183604001518460600151604051602001611b25949392919061355b565b604051602081830303815290604052805190602001209050919050565b6000807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff9050600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16635f7b157783600360009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16858786611bd5611c2c565b6040518763ffffffff1660e01b8152600401611bf59594939291906135ed565b6000604051808303818588803b158015611c0e57600080fd5b505af1158015611c22573d6000803e3d6000fd5b5050505050505050565b600033905090565b6000611c627f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc60001b6120b9565b60000160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16905090565b611c94826120c3565b8173ffffffffffffffffffffffffffffffffffffffff167fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b60405160405180910390a2600081511115611cf157611ceb8282612190565b50611cfa565b611cf9612214565b5b5050565b611d06612251565b611d3c576040517fd7e6bcf800000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b565b611d46611cfe565b600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1603611db85760006040517f1e4fbdf7000000000000000000000000000000000000000000000000000000008152600401611daf91906129aa565b60405180910390fd5b611dc18161165a565b50565b6000611dd6836000018360001b612271565b905092915050565b60008083600101600084815260200190815260200160002054905060008114611ee6576000600182611e109190613647565b9050600060018660000180549050611e289190613647565b9050808214611e97576000866000018281548110611e4957611e48612d4c565b5b9060005260206000200154905080876000018481548110611e6d57611e6c612d4c565b5b90600052602060002001819055508387600101600083815260200190815260200160002081905550505b85600001805480611eab57611eaa61367b565b5b600190038181906000526020600020016000905590558560010160008681526020019081526020016000206000905560019350505050611eec565b60009150505b92915050565b606081600001805480602002602001604051908101604052809291908181526020018280548015611f4257602002820191906000526020600020905b815481526020019060010190808311611f2e575b50505050509050919050565b6000806000801b905060005b8451811015611f9c576000858281518110611f7857611f77612d4c565b5b60200260200101519050611f8c81846122e1565b9250508080600101915050611f5a565b50828114611fae576000915050611fb4565b60019150505b92915050565b600081600001518260200151604051602001611fd79291906136aa565b604051602081830303815290604052805190602001209050919050565b60606000600867ffffffffffffffff81111561201357612012612501565b5b6040519080825280602002602001820160405280156120415781602001602082028036833780820191505090505b50905060005b60088110156120955760208161205d91906136d6565b84901b60e01c63ffffffff1682828151811061207c5761207b612d4c565b5b6020026020010181815250508080600101915050612047565b5080915050919050565b60006120b1836000018360001b612336565b905092915050565b6000819050919050565b60008173ffffffffffffffffffffffffffffffffffffffff163b0361211f57806040517f4c9c8ce300000000000000000000000000000000000000000000000000000000815260040161211691906129aa565b60405180910390fd5b8061214c7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc60001b6120b9565b60000160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555050565b60606000808473ffffffffffffffffffffffffffffffffffffffff16846040516121ba9190613754565b600060405180830381855af49150503d80600081146121f5576040519150601f19603f3d011682016040523d82523d6000602084013e6121fa565b606091505b509150915061220a858383612359565b9250505092915050565b600034111561224f576040517fb398979f00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b565b600061225b611731565b60000160089054906101000a900460ff16905090565b600061227d8383612336565b6122d65782600001829080600181540180825580915050600190039060005260206000200160009091909190915055826000018054905083600101600084815260200190815260200160002081905550600190506122db565b600090505b92915050565b600081836000015184602001518560400151866060015187608001518860a00151604051602001612318979695949392919061376b565b60405160208183030381529060405280519060200120905092915050565b600080836001016000848152602001908152602001600020541415905092915050565b60608261236e57612369826123e8565b6123e0565b60008251148015612396575060008473ffffffffffffffffffffffffffffffffffffffff163b145b156123d857836040517f9996b3150000000000000000000000000000000000000000000000000000000081526004016123cf91906129aa565b60405180910390fd5b8190506123e1565b5b9392505050565b6000815111156123fb5780518082602001fd5b6040517fd6bda27500000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6040518060800160405280600073ffffffffffffffffffffffffffffffffffffffff168152602001600063ffffffff16815260200160008152602001600080191681525090565b6000604051905090565b600080fd5b600080fd5b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b60006124b382612488565b9050919050565b6124c3816124a8565b81146124ce57600080fd5b50565b6000813590506124e0816124ba565b92915050565b600080fd5b600080fd5b6000601f19601f8301169050919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b612539826124f0565b810181811067ffffffffffffffff8211171561255857612557612501565b5b80604052505050565b600061256b612474565b90506125778282612530565b919050565b600067ffffffffffffffff82111561259757612596612501565b5b6125a0826124f0565b9050602081019050919050565b82818337600083830152505050565b60006125cf6125ca8461257c565b612561565b9050828152602081018484840111156125eb576125ea6124eb565b5b6125f68482856125ad565b509392505050565b600082601f830112612613576126126124e6565b5b81356126238482602086016125bc565b91505092915050565b600080604083850312156126435761264261247e565b5b6000612651858286016124d1565b925050602083013567ffffffffffffffff81111561267257612671612483565b5b61267e858286016125fe565b9150509250929050565b6000819050919050565b61269b81612688565b82525050565b60006020820190506126b66000830184612692565b92915050565b600080600080600060a086880312156126d8576126d761247e565b5b60006126e6888289016124d1565b95505060206126f7888289016124d1565b9450506040612708888289016124d1565b9350506060612719888289016124d1565b925050608061272a888289016124d1565b9150509295509295909350565b600067ffffffffffffffff82111561275257612751612501565b5b602082029050602081019050919050565b600080fd5b6000819050919050565b61277b81612768565b811461278657600080fd5b50565b60008135905061279881612772565b92915050565b60006127b16127ac84612737565b612561565b905080838252602082019050602084028301858111156127d4576127d3612763565b5b835b818110156127fd57806127e98882612789565b8452602084019350506020810190506127d6565b5050509392505050565b600082601f83011261281c5761281b6124e6565b5b813561282c84826020860161279e565b91505092915050565b600080600080600080600060e0888a0312156128545761285361247e565b5b60006128628a828b016124d1565b97505060206128738a828b016124d1565b96505060406128848a828b016124d1565b95505060606128958a828b016124d1565b94505060806128a68a828b016124d1565b93505060a06128b78a828b016124d1565b92505060c088013567ffffffffffffffff8111156128d8576128d7612483565b5b6128e48a828b01612807565b91505092959891949750929550565b600080fd5b60008083601f84011261290e5761290d6124e6565b5b8235905067ffffffffffffffff81111561292b5761292a6128f3565b5b60208301915083602082028301111561294757612946612763565b5b9250929050565b600080602083850312156129655761296461247e565b5b600083013567ffffffffffffffff81111561298357612982612483565b5b61298f858286016128f8565b92509250509250929050565b6129a4816124a8565b82525050565b60006020820190506129bf600083018461299b565b92915050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b6129fa81612768565b82525050565b6000612a0c83836129f1565b60208301905092915050565b6000602082019050919050565b6000612a30826129c5565b612a3a81856129d0565b9350612a45836129e1565b8060005b83811015612a76578151612a5d8882612a00565b9750612a6883612a18565b925050600181019050612a49565b5085935050505092915050565b60006020820190508181036000830152612a9d8184612a25565b905092915050565b60008083601f840112612abb57612aba6124e6565b5b8235905067ffffffffffffffff811115612ad857612ad76128f3565b5b6020830191508360c0820283011115612af457612af3612763565b5b9250929050565b600080fd5b600060408284031215612b1657612b15612afb565b5b81905092915050565b60008083601f840112612b3557612b346124e6565b5b8235905067ffffffffffffffff811115612b5257612b516128f3565b5b602083019150836001820283011115612b6e57612b6d612763565b5b9250929050565b600080600080600060808688031215612b9157612b9061247e565b5b600086013567ffffffffffffffff811115612baf57612bae612483565b5b612bbb88828901612aa5565b95509550506020612bce88828901612b00565b935050606086013567ffffffffffffffff811115612bef57612bee612483565b5b612bfb88828901612b1f565b92509250509295509295909350565b600081519050919050565b600082825260208201905092915050565b60005b83811015612c44578082015181840152602081019050612c29565b60008484015250505050565b6000612c5b82612c0a565b612c658185612c15565b9350612c75818560208601612c26565b612c7e816124f0565b840191505092915050565b60006020820190508181036000830152612ca38184612c50565b905092915050565b600060208284031215612cc157612cc061247e565b5b6000612ccf848285016124d1565b91505092915050565b6000819050919050565b600067ffffffffffffffff82169050919050565b6000819050919050565b6000612d1b612d16612d1184612cd8565b612cf6565b612ce2565b9050919050565b612d2b81612d00565b82525050565b6000602082019050612d466000830184612d22565b92915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b612d8481612768565b82525050565b6000602082019050612d9f6000830184612d7b565b92915050565b600080fd5b82818337505050565b6000612dbf83856129d0565b93507f07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff831115612df257612df1612da5565b5b602083029250612e03838584612daa565b82840190509392505050565b60006020820190508181036000830152612e2a818486612db3565b90509392505050565b600080fd5b600063ffffffff82169050919050565b612e5181612e38565b8114612e5c57600080fd5b50565b600081359050612e6e81612e48565b92915050565b612e7d81612688565b8114612e8857600080fd5b50565b600081359050612e9a81612e74565b92915050565b600060c08284031215612eb657612eb5612e33565b5b612ec060c0612561565b90506000612ed0848285016124d1565b6000830152506020612ee484828501612e5f565b6020830152506040612ef884828501612789565b6040830152506060612f0c84828501612e8b565b6060830152506080612f2084828501612e8b565b60808301525060a0612f3484828501612e5f565b60a08301525092915050565b600060c08284031215612f5657612f5561247e565b5b6000612f6484828501612ea0565b91505092915050565b612f7681612e38565b82525050565b6000602082019050612f916000830184612f6d565b92915050565b600081519050612fa681612e74565b92915050565b600060208284031215612fc257612fc161247e565b5b6000612fd084828501612f97565b91505092915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b600061301382612768565b91507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff820361304557613044612fd9565b5b600182019050919050565b613059816124a8565b82525050565b61306881612e38565b82525050565b61307781612688565b82525050565b6080820160008201516130936000850182613050565b5060208201516130a6602085018261305f565b5060408201516130b960408501826129f1565b5060608201516130cc606085018261306e565b50505050565b60006080820190506130e7600083018461307d565b92915050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b60808201600082015161312f6000850182613050565b506020820151613142602085018261305f565b50604082015161315560408501826129f1565b506060820151613168606085018261306e565b50505050565b600061317a8383613119565b60808301905092915050565b6000602082019050919050565b600061319e826130ed565b6131a881856130f8565b93506131b383613109565b8060005b838110156131e45781516131cb888261316e565b97506131d683613186565b9250506001810190506131b7565b5085935050505092915050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b6000613229838361306e565b60208301905092915050565b6000602082019050919050565b600061324d826131f1565b61325781856131fc565b93506132628361320d565b8060005b8381101561329357815161327a888261321d565b975061328583613235565b925050600181019050613266565b5085935050505092915050565b600060408201905081810360008301526132ba8185613193565b905081810360208301526132ce8184613242565b90509392505050565b60006132e282612768565b91506132ed83612768565b925082820190508082111561330557613304612fd9565b5b92915050565b60006060820190506133206000830186612692565b61332d602083018561299b565b61333a6040830184612d7b565b949350505050565b60006040828403121561335857613357612e33565b5b6133626040612561565b9050600061337284828501612e8b565b6000830152506020613386848285016124d1565b60208301525092915050565b6000604082840312156133a8576133a761247e565b5b60006133b684828501613342565b91505092915050565b600082825260208201905092915050565b60006133dc83856133bf565b93506133e98385846125ad565b6133f2836124f0565b840190509392505050565b600060408201905081810360008301526134188185876133d0565b9050818103602083015261342c8184612a25565b9050949350505050565b60008115159050919050565b61344b81613436565b811461345657600080fd5b50565b60008151905061346881613442565b92915050565b6000602082840312156134845761348361247e565b5b600061349284828501613459565b91505092915050565b60008160601b9050919050565b60006134b38261349b565b9050919050565b60006134c5826134a8565b9050919050565b6134dd6134d8826124a8565b6134ba565b82525050565b60008160e01b9050919050565b60006134fb826134e3565b9050919050565b61351361350e82612e38565b6134f0565b82525050565b6000819050919050565b61353461352f82612768565b613519565b82525050565b6000819050919050565b61355561355082612688565b61353a565b82525050565b600061356782876134cc565b6014820191506135778286613502565b6004820191506135878285613523565b6020820191506135978284613544565b60208201915081905095945050505050565b600081519050919050565b60006135bf826135a9565b6135c981856133bf565b93506135d9818560208601612c26565b6135e2816124f0565b840191505092915050565b600060a082019050613602600083018861299b565b61360f6020830187612d7b565b818103604083015261362181866135b4565b90506136306060830185612d7b565b61363d608083018461299b565b9695505050505050565b600061365282612768565b915061365d83612768565b925082820390508181111561367557613674612fd9565b5b92915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603160045260246000fd5b60006136b68285613544565b6020820191506136c682846134cc565b6014820191508190509392505050565b60006136e182612768565b91506136ec83612768565b92508282026136fa81612768565b9150828204841483151761371157613710612fd9565b5b5092915050565b600081905092915050565b600061372e826135a9565b6137388185613718565b9350613748818560208601612c26565b80840191505092915050565b60006137608284613723565b915081905092915050565b6000613777828a613544565b60208201915061378782896134cc565b6014820191506137978288613502565b6004820191506137a78287613523565b6020820191506137b78286613544565b6020820191506137c78285613544565b6020820191506137d78284613502565b6004820191508190509897505050505050505056fea264697066735822122002c244bb3a678e0c7a73da399db78acaab45b87e9fa39037747ff6296ad96bf464736f6c634300081b0033
Deployed Bytecode
0x6080604052600436106100a75760003560e01c80638da5cb5b116100645780638da5cb5b146101855780639a0002a9146101b0578063a7178c37146101d9578063a93e83a614610204578063ad3cb1cc1461022d578063f2fde38b14610258576100a7565b80634f1ef286146100ac57806352d1902d146100c8578063715018a6146100f3578063717641051461010a57806377e88d2c14610133578063871c5fe71461015c575b600080fd5b6100c660048036038101906100c1919061262c565b610281565b005b3480156100d457600080fd5b506100dd6102a0565b6040516100ea91906126a1565b60405180910390f35b3480156100ff57600080fd5b506101086102d3565b005b34801561011657600080fd5b50610131600480360381019061012c91906126bc565b6102e7565b005b34801561013f57600080fd5b5061015a60048036038101906101559190612835565b610543565b005b34801561016857600080fd5b50610183600480360381019061017e919061294e565b610a91565b005b34801561019157600080fd5b5061019a610ae7565b6040516101a791906129aa565b60405180910390f35b3480156101bc57600080fd5b506101d760048036038101906101d2919061294e565b610b1f565b005b3480156101e557600080fd5b506101ee610c0d565b6040516101fb9190612a83565b60405180910390f35b34801561021057600080fd5b5061022b60048036038101906102269190612b75565b610c1e565b005b34801561023957600080fd5b5061024261127d565b60405161024f9190612c89565b60405180910390f35b34801561026457600080fd5b5061027f600480360381019061027a9190612cab565b6112b6565b005b61028961133c565b61029282611422565b61029c828261142d565b5050565b60006102aa61154c565b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc60001b905090565b6102db6115d3565b6102e5600061165a565b565b6102ef6115d3565b600073ffffffffffffffffffffffffffffffffffffffff168573ffffffffffffffffffffffffffffffffffffffff16146103655784600160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505b600073ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff16146103da57836000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505b600073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff16146104505782600360006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff16146104c65781600260006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505b600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff161461053c5780600460006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505b5050505050565b600061054d611731565b905060008160000160089054906101000a900460ff1615905060008260000160009054906101000a900467ffffffffffffffff1690506000808267ffffffffffffffff1614801561059b5750825b9050600060018367ffffffffffffffff161480156105d0575060003073ffffffffffffffffffffffffffffffffffffffff163b145b9050811580156105de575080155b15610615576040517ff92ee8a900000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60018560000160006101000a81548167ffffffffffffffff021916908367ffffffffffffffff16021790555083156106655760018560000160086101000a81548160ff0219169083151502179055505b600073ffffffffffffffffffffffffffffffffffffffff168c73ffffffffffffffffffffffffffffffffffffffff16036106cb576040517f9fabe1c100000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168b73ffffffffffffffffffffffffffffffffffffffff1603610731576040517f9fabe1c100000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168a73ffffffffffffffffffffffffffffffffffffffff1603610797576040517f9fabe1c100000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168973ffffffffffffffffffffffffffffffffffffffff16036107fd576040517f9fabe1c100000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168873ffffffffffffffffffffffffffffffffffffffff1603610863576040517f9fabe1c100000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168773ffffffffffffffffffffffffffffffffffffffff16036108c9576040517f9fabe1c100000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6108d28c611759565b6108da61176d565b8a600160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550896000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555087600260006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555086600460006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555088600360006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550610a2786611777565b8315610a835760008560000160086101000a81548160ff0219169083151502179055507fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d26001604051610a7a9190612d31565b60405180910390a15b505050505050505050505050565b610a996115d3565b610ae3828280806020026020016040519081016040528093929190818152602001838360200280828437600081840152601f19601f82011690508083019250505050505050611777565b5050565b600080610af261185a565b90508060000160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1691505090565b610b276115d3565b60005b82829050811015610bcf576000610b64848484818110610b4d57610b4c612d4c565b5b90506020020135600661188290919063ffffffff16565b905080610bc157838383818110610b7e57610b7d612d4c565b5b905060200201356040517f2a2c67cd000000000000000000000000000000000000000000000000000000008152600401610bb89190612d8a565b60405180910390fd5b508080600101915050610b2a565b507f0e5fb72f67c09578724f25132b948e5fb901741fa3240f11804518dc94799a2b8282604051610c01929190612e0f565b60405180910390a15050565b6060610c19600661189c565b905090565b610c2b85858585856118bd565b60008060008787905067ffffffffffffffff811115610c4d57610c4c612501565b5b604051908082528060200260200182016040528015610c7b5781602001602082028036833780820191505090505b50905060005b88889050811015610e74576000898983818110610ca157610ca0612d4c565b5b905060c00201803603810190610cb79190612f40565b9050600560008260600151815260200190815260200160002060009054906101000a900460ff1615610d10576001838381518110610cf857610cf7612d4c565b5b60200260200101901515908115158152505050610e67565b6001600560008360600151815260200190815260200160002060006101000a81548160ff0219169083151502179055506000600260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663d2b210a18360a001516040518263ffffffff1660e01b8152600401610da19190612f7c565b602060405180830381865afa158015610dbe573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610de29190612fac565b905081608001518114610e305781608001516040517f631b89b0000000000000000000000000000000000000000000000000000000008152600401610e2791906126a1565b60405180910390fd5b610e3d8260200151611ad9565b15610e55578580610e4d90613008565b965050610e64565b8480610e6090613008565b9550505b50505b8080600101915050610c81565b50600083148015610e855750600082145b15610e9257505050611276565b60008367ffffffffffffffff811115610eae57610ead612501565b5b604051908082528060200260200182016040528015610ee757816020015b610ed461242d565b815260200190600190039081610ecc5790505b50905060008367ffffffffffffffff811115610f0657610f05612501565b5b604051908082528060200260200182016040528015610f345781602001602082028036833780820191505090505b50905060008060005b8c8c905081101561112457858181518110610f5b57610f5a612d4c565b5b60200260200101516111175760008d8d83818110610f7c57610f7b612d4c565b5b905060c00201803603810190610f929190612f40565b905060006040518060800160405280836000015173ffffffffffffffffffffffffffffffffffffffff168152602001836020015163ffffffff1681526020018360400151815260200183606001518152509050610ff28260200151611ad9565b15611084578087868151811061100b5761100a612d4c565b5b6020026020010181905250806000015173ffffffffffffffffffffffffffffffffffffffff1661103a82611afc565b7fdbe674c66915823ad8cb90cac7eb482e951adec0311c9cf091da19de527ee9358360405161106991906130d2565b60405180910390a3848061107c90613008565b955050611114565b600061108f82611afc565b9050808786815181106110a5576110a4612d4c565b5b602002602001018181525050816000015173ffffffffffffffffffffffffffffffffffffffff16817f740137a4fd93de42bb435842325e4fad55ea4ba617db0b44125377b94b43249d846040516110fc91906130d2565b60405180910390a3848061110f90613008565b955050505b50505b8080600101915050610f3d565b506000639d6a54cb60e01b85856040516024016111429291906132a0565b604051602081830303815290604052907bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19166020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff838183161783525050505090506111aa81611b42565b600460009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663f099f9f57f738128fe393bef1bcd8a524796fff40618b938cd467c71fcf37850ab0ba4f7d7611211611c2c565b8a8c61121d91906132d7565b6040518463ffffffff1660e01b815260040161123b9392919061330b565b600060405180830381600087803b15801561125557600080fd5b505af1158015611269573d6000803e3d6000fd5b5050505050505050505050505b5050505050565b6040518060400160405280600581526020017f352e302e3000000000000000000000000000000000000000000000000000000081525081565b6112be6115d3565b600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff16036113305760006040517f1e4fbdf700000000000000000000000000000000000000000000000000000000815260040161132791906129aa565b60405180910390fd5b6113398161165a565b50565b7f0000000000000000000000005b6691f39d4a9abb9cc091818b45d0b5aa4ddf0873ffffffffffffffffffffffffffffffffffffffff163073ffffffffffffffffffffffffffffffffffffffff1614806113e957507f0000000000000000000000005b6691f39d4a9abb9cc091818b45d0b5aa4ddf0873ffffffffffffffffffffffffffffffffffffffff166113d0611c34565b73ffffffffffffffffffffffffffffffffffffffff1614155b15611420576040517fe07c8dba00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b565b61142a6115d3565b50565b8173ffffffffffffffffffffffffffffffffffffffff166352d1902d6040518163ffffffff1660e01b8152600401602060405180830381865afa92505050801561149557506040513d601f19601f820116820180604052508101906114929190612fac565b60015b6114d657816040517f4c9c8ce30000000000000000000000000000000000000000000000000000000081526004016114cd91906129aa565b60405180910390fd5b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc60001b811461153d57806040517faa1d49a400000000000000000000000000000000000000000000000000000000815260040161153491906126a1565b60405180910390fd5b6115478383611c8b565b505050565b7f0000000000000000000000005b6691f39d4a9abb9cc091818b45d0b5aa4ddf0873ffffffffffffffffffffffffffffffffffffffff163073ffffffffffffffffffffffffffffffffffffffff16146115d1576040517fe07c8dba00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b565b6115db611c2c565b73ffffffffffffffffffffffffffffffffffffffff166115f9610ae7565b73ffffffffffffffffffffffffffffffffffffffff16146116585761161c611c2c565b6040517f118cdaa700000000000000000000000000000000000000000000000000000000815260040161164f91906129aa565b60405180910390fd5b565b600061166461185a565b905060008160000160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff169050828260000160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055508273ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e060405160405180910390a3505050565b60007ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00905090565b611761611cfe565b61176a81611d3e565b50565b611775611cfe565b565b60005b815181101561181f5760006117b383838151811061179b5761179a612d4c565b5b60200260200101516006611dc490919063ffffffff16565b905080611811578282815181106117cd576117cc612d4c565b5b60200260200101516040517fd1d533d80000000000000000000000000000000000000000000000000000000081526004016118089190612d8a565b60405180910390fd5b50808060010191505061177a565b507f03e4a91d34a2a2419d5513d9814cf5ea9e317e6166670b4b89a97e478541d4b98160405161184f9190612a83565b60405180910390a150565b60007f9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300905090565b6000611894836000018360001b611dde565b905092915050565b606060006118ac83600001611ef2565b905060608190508092505050919050565b61192a83600001358686808060200260200160405190810160405280939291908181526020016000905b8282101561191757848483905060c002018036038101906119089190612f40565b815260200190600101906118e7565b5050505050611f4e90919063ffffffff16565b611960576040517ffbf63aef00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b611968611c2c565b73ffffffffffffffffffffffffffffffffffffffff168360200160208101906119919190612cab565b73ffffffffffffffffffffffffffffffffffffffff16146119de576040517fbe8e6d9600000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16637e4f7a8a8383611a3d611a3888803603810190611a339190613392565b611fba565b611ff4565b6040518463ffffffff1660e01b8152600401611a5b939291906133fd565b602060405180830381865afa158015611a78573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a9c919061346e565b611ad2576040517f38a3efc400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5050505050565b6000611af58263ffffffff16600661209f90919063ffffffff16565b9050919050565b60008160000151826020015183604001518460600151604051602001611b25949392919061355b565b604051602081830303815290604052805190602001209050919050565b6000807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff9050600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16635f7b157783600360009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16858786611bd5611c2c565b6040518763ffffffff1660e01b8152600401611bf59594939291906135ed565b6000604051808303818588803b158015611c0e57600080fd5b505af1158015611c22573d6000803e3d6000fd5b5050505050505050565b600033905090565b6000611c627f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc60001b6120b9565b60000160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16905090565b611c94826120c3565b8173ffffffffffffffffffffffffffffffffffffffff167fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b60405160405180910390a2600081511115611cf157611ceb8282612190565b50611cfa565b611cf9612214565b5b5050565b611d06612251565b611d3c576040517fd7e6bcf800000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b565b611d46611cfe565b600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1603611db85760006040517f1e4fbdf7000000000000000000000000000000000000000000000000000000008152600401611daf91906129aa565b60405180910390fd5b611dc18161165a565b50565b6000611dd6836000018360001b612271565b905092915050565b60008083600101600084815260200190815260200160002054905060008114611ee6576000600182611e109190613647565b9050600060018660000180549050611e289190613647565b9050808214611e97576000866000018281548110611e4957611e48612d4c565b5b9060005260206000200154905080876000018481548110611e6d57611e6c612d4c565b5b90600052602060002001819055508387600101600083815260200190815260200160002081905550505b85600001805480611eab57611eaa61367b565b5b600190038181906000526020600020016000905590558560010160008681526020019081526020016000206000905560019350505050611eec565b60009150505b92915050565b606081600001805480602002602001604051908101604052809291908181526020018280548015611f4257602002820191906000526020600020905b815481526020019060010190808311611f2e575b50505050509050919050565b6000806000801b905060005b8451811015611f9c576000858281518110611f7857611f77612d4c565b5b60200260200101519050611f8c81846122e1565b9250508080600101915050611f5a565b50828114611fae576000915050611fb4565b60019150505b92915050565b600081600001518260200151604051602001611fd79291906136aa565b604051602081830303815290604052805190602001209050919050565b60606000600867ffffffffffffffff81111561201357612012612501565b5b6040519080825280602002602001820160405280156120415781602001602082028036833780820191505090505b50905060005b60088110156120955760208161205d91906136d6565b84901b60e01c63ffffffff1682828151811061207c5761207b612d4c565b5b6020026020010181815250508080600101915050612047565b5080915050919050565b60006120b1836000018360001b612336565b905092915050565b6000819050919050565b60008173ffffffffffffffffffffffffffffffffffffffff163b0361211f57806040517f4c9c8ce300000000000000000000000000000000000000000000000000000000815260040161211691906129aa565b60405180910390fd5b8061214c7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc60001b6120b9565b60000160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555050565b60606000808473ffffffffffffffffffffffffffffffffffffffff16846040516121ba9190613754565b600060405180830381855af49150503d80600081146121f5576040519150601f19603f3d011682016040523d82523d6000602084013e6121fa565b606091505b509150915061220a858383612359565b9250505092915050565b600034111561224f576040517fb398979f00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b565b600061225b611731565b60000160089054906101000a900460ff16905090565b600061227d8383612336565b6122d65782600001829080600181540180825580915050600190039060005260206000200160009091909190915055826000018054905083600101600084815260200190815260200160002081905550600190506122db565b600090505b92915050565b600081836000015184602001518560400151866060015187608001518860a00151604051602001612318979695949392919061376b565b60405160208183030381529060405280519060200120905092915050565b600080836001016000848152602001908152602001600020541415905092915050565b60608261236e57612369826123e8565b6123e0565b60008251148015612396575060008473ffffffffffffffffffffffffffffffffffffffff163b145b156123d857836040517f9996b3150000000000000000000000000000000000000000000000000000000081526004016123cf91906129aa565b60405180910390fd5b8190506123e1565b5b9392505050565b6000815111156123fb5780518082602001fd5b6040517fd6bda27500000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6040518060800160405280600073ffffffffffffffffffffffffffffffffffffffff168152602001600063ffffffff16815260200160008152602001600080191681525090565b6000604051905090565b600080fd5b600080fd5b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b60006124b382612488565b9050919050565b6124c3816124a8565b81146124ce57600080fd5b50565b6000813590506124e0816124ba565b92915050565b600080fd5b600080fd5b6000601f19601f8301169050919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b612539826124f0565b810181811067ffffffffffffffff8211171561255857612557612501565b5b80604052505050565b600061256b612474565b90506125778282612530565b919050565b600067ffffffffffffffff82111561259757612596612501565b5b6125a0826124f0565b9050602081019050919050565b82818337600083830152505050565b60006125cf6125ca8461257c565b612561565b9050828152602081018484840111156125eb576125ea6124eb565b5b6125f68482856125ad565b509392505050565b600082601f830112612613576126126124e6565b5b81356126238482602086016125bc565b91505092915050565b600080604083850312156126435761264261247e565b5b6000612651858286016124d1565b925050602083013567ffffffffffffffff81111561267257612671612483565b5b61267e858286016125fe565b9150509250929050565b6000819050919050565b61269b81612688565b82525050565b60006020820190506126b66000830184612692565b92915050565b600080600080600060a086880312156126d8576126d761247e565b5b60006126e6888289016124d1565b95505060206126f7888289016124d1565b9450506040612708888289016124d1565b9350506060612719888289016124d1565b925050608061272a888289016124d1565b9150509295509295909350565b600067ffffffffffffffff82111561275257612751612501565b5b602082029050602081019050919050565b600080fd5b6000819050919050565b61277b81612768565b811461278657600080fd5b50565b60008135905061279881612772565b92915050565b60006127b16127ac84612737565b612561565b905080838252602082019050602084028301858111156127d4576127d3612763565b5b835b818110156127fd57806127e98882612789565b8452602084019350506020810190506127d6565b5050509392505050565b600082601f83011261281c5761281b6124e6565b5b813561282c84826020860161279e565b91505092915050565b600080600080600080600060e0888a0312156128545761285361247e565b5b60006128628a828b016124d1565b97505060206128738a828b016124d1565b96505060406128848a828b016124d1565b95505060606128958a828b016124d1565b94505060806128a68a828b016124d1565b93505060a06128b78a828b016124d1565b92505060c088013567ffffffffffffffff8111156128d8576128d7612483565b5b6128e48a828b01612807565b91505092959891949750929550565b600080fd5b60008083601f84011261290e5761290d6124e6565b5b8235905067ffffffffffffffff81111561292b5761292a6128f3565b5b60208301915083602082028301111561294757612946612763565b5b9250929050565b600080602083850312156129655761296461247e565b5b600083013567ffffffffffffffff81111561298357612982612483565b5b61298f858286016128f8565b92509250509250929050565b6129a4816124a8565b82525050565b60006020820190506129bf600083018461299b565b92915050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b6129fa81612768565b82525050565b6000612a0c83836129f1565b60208301905092915050565b6000602082019050919050565b6000612a30826129c5565b612a3a81856129d0565b9350612a45836129e1565b8060005b83811015612a76578151612a5d8882612a00565b9750612a6883612a18565b925050600181019050612a49565b5085935050505092915050565b60006020820190508181036000830152612a9d8184612a25565b905092915050565b60008083601f840112612abb57612aba6124e6565b5b8235905067ffffffffffffffff811115612ad857612ad76128f3565b5b6020830191508360c0820283011115612af457612af3612763565b5b9250929050565b600080fd5b600060408284031215612b1657612b15612afb565b5b81905092915050565b60008083601f840112612b3557612b346124e6565b5b8235905067ffffffffffffffff811115612b5257612b516128f3565b5b602083019150836001820283011115612b6e57612b6d612763565b5b9250929050565b600080600080600060808688031215612b9157612b9061247e565b5b600086013567ffffffffffffffff811115612baf57612bae612483565b5b612bbb88828901612aa5565b95509550506020612bce88828901612b00565b935050606086013567ffffffffffffffff811115612bef57612bee612483565b5b612bfb88828901612b1f565b92509250509295509295909350565b600081519050919050565b600082825260208201905092915050565b60005b83811015612c44578082015181840152602081019050612c29565b60008484015250505050565b6000612c5b82612c0a565b612c658185612c15565b9350612c75818560208601612c26565b612c7e816124f0565b840191505092915050565b60006020820190508181036000830152612ca38184612c50565b905092915050565b600060208284031215612cc157612cc061247e565b5b6000612ccf848285016124d1565b91505092915050565b6000819050919050565b600067ffffffffffffffff82169050919050565b6000819050919050565b6000612d1b612d16612d1184612cd8565b612cf6565b612ce2565b9050919050565b612d2b81612d00565b82525050565b6000602082019050612d466000830184612d22565b92915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b612d8481612768565b82525050565b6000602082019050612d9f6000830184612d7b565b92915050565b600080fd5b82818337505050565b6000612dbf83856129d0565b93507f07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff831115612df257612df1612da5565b5b602083029250612e03838584612daa565b82840190509392505050565b60006020820190508181036000830152612e2a818486612db3565b90509392505050565b600080fd5b600063ffffffff82169050919050565b612e5181612e38565b8114612e5c57600080fd5b50565b600081359050612e6e81612e48565b92915050565b612e7d81612688565b8114612e8857600080fd5b50565b600081359050612e9a81612e74565b92915050565b600060c08284031215612eb657612eb5612e33565b5b612ec060c0612561565b90506000612ed0848285016124d1565b6000830152506020612ee484828501612e5f565b6020830152506040612ef884828501612789565b6040830152506060612f0c84828501612e8b565b6060830152506080612f2084828501612e8b565b60808301525060a0612f3484828501612e5f565b60a08301525092915050565b600060c08284031215612f5657612f5561247e565b5b6000612f6484828501612ea0565b91505092915050565b612f7681612e38565b82525050565b6000602082019050612f916000830184612f6d565b92915050565b600081519050612fa681612e74565b92915050565b600060208284031215612fc257612fc161247e565b5b6000612fd084828501612f97565b91505092915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b600061301382612768565b91507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff820361304557613044612fd9565b5b600182019050919050565b613059816124a8565b82525050565b61306881612e38565b82525050565b61307781612688565b82525050565b6080820160008201516130936000850182613050565b5060208201516130a6602085018261305f565b5060408201516130b960408501826129f1565b5060608201516130cc606085018261306e565b50505050565b60006080820190506130e7600083018461307d565b92915050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b60808201600082015161312f6000850182613050565b506020820151613142602085018261305f565b50604082015161315560408501826129f1565b506060820151613168606085018261306e565b50505050565b600061317a8383613119565b60808301905092915050565b6000602082019050919050565b600061319e826130ed565b6131a881856130f8565b93506131b383613109565b8060005b838110156131e45781516131cb888261316e565b97506131d683613186565b9250506001810190506131b7565b5085935050505092915050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b6000613229838361306e565b60208301905092915050565b6000602082019050919050565b600061324d826131f1565b61325781856131fc565b93506132628361320d565b8060005b8381101561329357815161327a888261321d565b975061328583613235565b925050600181019050613266565b5085935050505092915050565b600060408201905081810360008301526132ba8185613193565b905081810360208301526132ce8184613242565b90509392505050565b60006132e282612768565b91506132ed83612768565b925082820190508082111561330557613304612fd9565b5b92915050565b60006060820190506133206000830186612692565b61332d602083018561299b565b61333a6040830184612d7b565b949350505050565b60006040828403121561335857613357612e33565b5b6133626040612561565b9050600061337284828501612e8b565b6000830152506020613386848285016124d1565b60208301525092915050565b6000604082840312156133a8576133a761247e565b5b60006133b684828501613342565b91505092915050565b600082825260208201905092915050565b60006133dc83856133bf565b93506133e98385846125ad565b6133f2836124f0565b840190509392505050565b600060408201905081810360008301526134188185876133d0565b9050818103602083015261342c8184612a25565b9050949350505050565b60008115159050919050565b61344b81613436565b811461345657600080fd5b50565b60008151905061346881613442565b92915050565b6000602082840312156134845761348361247e565b5b600061349284828501613459565b91505092915050565b60008160601b9050919050565b60006134b38261349b565b9050919050565b60006134c5826134a8565b9050919050565b6134dd6134d8826124a8565b6134ba565b82525050565b60008160e01b9050919050565b60006134fb826134e3565b9050919050565b61351361350e82612e38565b6134f0565b82525050565b6000819050919050565b61353461352f82612768565b613519565b82525050565b6000819050919050565b61355561355082612688565b61353a565b82525050565b600061356782876134cc565b6014820191506135778286613502565b6004820191506135878285613523565b6020820191506135978284613544565b60208201915081905095945050505050565b600081519050919050565b60006135bf826135a9565b6135c981856133bf565b93506135d9818560208601612c26565b6135e2816124f0565b840191505092915050565b600060a082019050613602600083018861299b565b61360f6020830187612d7b565b818103604083015261362181866135b4565b90506136306060830185612d7b565b61363d608083018461299b565b9695505050505050565b600061365282612768565b915061365d83612768565b925082820390508181111561367557613674612fd9565b5b92915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603160045260246000fd5b60006136b68285613544565b6020820191506136c682846134cc565b6014820191508190509392505050565b60006136e182612768565b91506136ec83612768565b92508282026136fa81612768565b9150828204841483151761371157613710612fd9565b5b5092915050565b600081905092915050565b600061372e826135a9565b6137388185613718565b9350613748818560208601612c26565b80840191505092915050565b60006137608284613723565b915081905092915050565b6000613777828a613544565b60208201915061378782896134cc565b6014820191506137978288613502565b6004820191506137a78287613523565b6020820191506137b78286613544565b6020820191506137c78285613544565b6020820191506137d78284613502565b6004820191508190509897505050505050505056fea264697066735822122002c244bb3a678e0c7a73da399db78acaab45b87e9fa39037747ff6296ad96bf464736f6c634300081b0033
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.